Skip to content

Commit

Permalink
fix: fix ESLint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
rygine committed Dec 6, 2023
1 parent a0f51b7 commit 00e8569
Show file tree
Hide file tree
Showing 20 changed files with 72 additions and 32 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"scripts": {
"build": "npm run build --workspaces",
"lint": "npm run lint:eslint && npm run lint:misc --check",
"lint:eslint": "eslint . --cache --ext js,ts",
"lint:eslint": "npm run lint:eslint --workspace=site && npm run lint:eslint --workspace=@xmtp/snap",
"lint:fix": "npm run lint:eslint --fix && npm run lint:misc --write",
"lint:misc": "prettier '**/*.md' '!**/CHANGELOG.md' '**/*.yml' --ignore-path .gitignore",
"start": "concurrently \"npm start --workspace=site\" \"npm start --workspace=@xmtp/snap\"",
Expand Down
5 changes: 3 additions & 2 deletions packages/site/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
module.exports = {
extends: ['../../.eslintrc.js'],

parserOptions: {
project: './tsconfig.eslint.json',
},
overrides: [
{
files: ['**/*.{ts,tsx}'],
Expand All @@ -9,6 +11,5 @@ module.exports = {
},
},
],

ignorePatterns: ['!.eslintrc.js', 'build/'],
};
7 changes: 5 additions & 2 deletions packages/site/gatsby-config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { GatsbyConfig } from 'gatsby';
import dotenv from 'dotenv';
import type { GatsbyConfig } from 'gatsby';

dotenv.config({
path: `.env.${process.env.NODE_ENV}`,
// eslint-disable-next-line no-restricted-globals, @typescript-eslint/no-non-null-assertion
path: `.env.${process.env.NODE_ENV!}`,
});

const config: GatsbyConfig = {
Expand All @@ -17,7 +18,9 @@ const config: GatsbyConfig = {
options: {
name: 'Template Snap',
icon: 'src/assets/logo.svg',
// eslint-disable-next-line @typescript-eslint/naming-convention
theme_color: '#6F4CFF',
// eslint-disable-next-line @typescript-eslint/naming-convention
background_color: '#FFFFFF',
display: 'standalone',
},
Expand Down
2 changes: 2 additions & 0 deletions packages/site/src/config/snap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
* Will default to the local hosted snap if no value is provided in environment.
*/
export const defaultSnapOrigin =
// eslint-disable-next-line no-restricted-globals
process.env.SNAP_ORIGIN ?? `local:http://localhost:8080`;

export const getSnapParams = () => {
// eslint-disable-next-line no-restricted-globals
const envSnapVersion = process.env.SNAP_VERSION;
if (defaultSnapOrigin.startsWith('npm:') && envSnapVersion) {
return { version: envSnapVersion };
Expand Down
3 changes: 3 additions & 0 deletions packages/site/src/polyfills.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
// eslint-disable-next-line import/no-nodejs-modules
import { Buffer } from 'buffer';

// eslint-disable-next-line no-restricted-globals
if (typeof window !== 'undefined') {
// eslint-disable-next-line no-restricted-globals
window.Buffer = window.Buffer ?? Buffer;
}
2 changes: 2 additions & 0 deletions packages/site/src/utils/localStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
* @returns The value stored at the key provided if the key exists.
*/
export const getLocalStorage = (key: string) => {
// eslint-disable-next-line no-restricted-globals
const { localStorage: ls } = window;

if (ls !== null) {
Expand All @@ -20,6 +21,7 @@ export const getLocalStorage = (key: string) => {
* @param value - The value to set.
*/
export const setLocalStorage = (key: string, value: string) => {
// eslint-disable-next-line no-restricted-globals
const { localStorage: ls } = window;

if (ls !== null) {
Expand Down
3 changes: 3 additions & 0 deletions packages/site/src/utils/metamask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ethers } from 'ethers';
* @returns True if the MetaMask version is Flask, false otherwise.
*/
export const isFlask = async () => {
// eslint-disable-next-line no-restricted-globals
const provider = window.ethereum;
try {
const clientVersion = await provider?.request({
Expand All @@ -19,9 +20,11 @@ export const isFlask = async () => {
};

export const getSigner = async () => {
// eslint-disable-next-line no-restricted-globals
const provider = new ethers.BrowserProvider(window.ethereum);

// Request account access if needed
// eslint-disable-next-line no-restricted-globals
await window.ethereum.request({ method: 'eth_requestAccounts' });

// Getting the signer from provider
Expand Down
6 changes: 4 additions & 2 deletions packages/site/src/utils/snap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { GetSnapsResponse, Snap } from '../types';
* @returns The snaps installed in MetaMask.
*/
export const getSnaps = async (): Promise<GetSnapsResponse> => {
// eslint-disable-next-line no-restricted-globals
return (await window.ethereum.request({
method: 'wallet_getSnaps',
})) as unknown as GetSnapsResponse;
Expand All @@ -21,6 +22,7 @@ export const connectSnap = async (
snapId: string = defaultSnapOrigin,
params: Record<'version' | string, unknown> = {},
) => {
// eslint-disable-next-line no-restricted-globals
await window.ethereum.request({
method: 'wallet_requestSnaps',
params: {
Expand All @@ -42,8 +44,8 @@ export const getSnap = async (version?: string): Promise<Snap | undefined> => {
(snap) =>
snap.id === defaultSnapOrigin && (!version || snap.version === version),
);
} catch (e) {
console.log('Failed to obtain installed snap', e);
} catch (error) {
console.log('Failed to obtain installed snap', error);
return undefined;
}
};
Expand Down
2 changes: 2 additions & 0 deletions packages/site/src/utils/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import { getLocalStorage, setLocalStorage } from './localStorage';
* @returns True if the theme is "dark" otherwise, false.
*/
export const getThemePreference = () => {
// eslint-disable-next-line no-restricted-globals
if (typeof window === 'undefined') {
return false;
}

// eslint-disable-next-line no-restricted-globals
const darkModeSystem = window?.matchMedia(
'(prefers-color-scheme: dark)',
).matches;
Expand Down
5 changes: 5 additions & 0 deletions packages/site/tsconfig.eslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"include": [".", ".eslintrc.js"],
"exclude": ["public", "node_modules"]
}
4 changes: 3 additions & 1 deletion packages/snap/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
module.exports = {
extends: ['../../.eslintrc.js'],

ignorePatterns: ['!.eslintrc.js', 'dist/'],
parserOptions: {
project: './tsconfig.eslint.json',
},
};
2 changes: 1 addition & 1 deletion packages/snap/snap.manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"url": "https://github.com/xmtp/snap.git"
},
"source": {
"shasum": "r9PCkPbktkhs3W1SdRYzRRLbbBvVviJwF8NWaMOAPkU=",
"shasum": "5SJLhbSi9AD3AfeY+aKYpHlMuqj7sWpYM27NePYm1Wo=",
"location": {
"npm": {
"filePath": "dist/bundle.js",
Expand Down
6 changes: 4 additions & 2 deletions packages/snap/src/authorizer.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { XmtpEnv } from '@xmtp/xmtp-js';
import type { XmtpEnv } from '@xmtp/xmtp-js';

import { Authorizer } from './authorizer';
import { sleep } from './testHelpers';
import { AUTHORIZATION_EXPIRY_MS } from './config';
import { sleep } from './testHelpers';

const WALLET_ADDRESS = '0x1234';
const ENV = 'dev' as XmtpEnv;
Expand Down Expand Up @@ -32,6 +33,7 @@ describe('Authorizer', () => {
throw new Error('unknown operation');
});

// eslint-disable-next-line no-restricted-globals
(global as any).snap = {
request: mockRequest,
};
Expand Down
6 changes: 1 addition & 5 deletions packages/snap/src/authorizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,7 @@ export class Authorizer {
this.cache = noCache ? undefined : new Map();
}

private async getAuthRecord(
walletAddress: string,
env: XmtpEnv,
origin: string,
) {
async getAuthRecord(walletAddress: string, env: XmtpEnv, origin: string) {
const key = buildKey(walletAddress, env, origin);
// If the record exists in the cache, return it
if (this.cache?.has(key)) {
Expand Down
11 changes: 9 additions & 2 deletions packages/snap/src/handlers.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { PrivateKeyBundleV1, XmtpEnv } from '@xmtp/xmtp-js';
import { keystore } from '@xmtp/proto';
import { installSnap } from '@metamask/snaps-jest';
import { keystore } from '@xmtp/proto';
import type { XmtpEnv } from '@xmtp/xmtp-js';
import { PrivateKeyBundleV1 } from '@xmtp/xmtp-js';

import { buildRpcRequest, newWallet } from './testHelpers';
import { base64Encode } from './utils';

Expand Down Expand Up @@ -29,6 +31,7 @@ describe('onRPCRequest', () => {
env: ENV,
};

// eslint-disable-next-line @typescript-eslint/unbound-method
const { request } = await installSnap();

// Check the status of a fresh instance
Expand Down Expand Up @@ -105,6 +108,7 @@ describe('onRPCRequest', () => {
it('can return the public key', async () => {
const wallet = newWallet();
const bundle = await PrivateKeyBundleV1.generate(wallet);
// eslint-disable-next-line @typescript-eslint/unbound-method
const { request } = await installSnap();
await initKeystore(bundle, request);
const meta = {
Expand All @@ -123,6 +127,7 @@ describe('onRPCRequest', () => {
it('returns an error if unknown handler is called', async () => {
const wallet = newWallet();
const bundle = await PrivateKeyBundleV1.generate(wallet);
// eslint-disable-next-line @typescript-eslint/unbound-method
const { request } = await installSnap();
await initKeystore(bundle, request);
const meta = {
Expand All @@ -139,6 +144,7 @@ describe('onRPCRequest', () => {
it('prompts for authorization', async () => {
const wallet = newWallet();
const bundle = await PrivateKeyBundleV1.generate(wallet);
// eslint-disable-next-line @typescript-eslint/unbound-method
const { request } = await installSnap();
await initKeystore(bundle, request);
const meta = {
Expand All @@ -165,6 +171,7 @@ describe('onRPCRequest', () => {
it('throws errors on rejected authorization', async () => {
const wallet = newWallet();
const bundle = await PrivateKeyBundleV1.generate(wallet);
// eslint-disable-next-line @typescript-eslint/unbound-method
const { request } = await installSnap();
await initKeystore(bundle, request);
const meta = {
Expand Down
21 changes: 12 additions & 9 deletions packages/snap/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ export type SnapResponse = {
res: string | string[];
};

type Codec<T> = {
decode(input: Reader | Uint8Array, length?: number): T;
encode(message: T, writer?: Writer): Writer;
type Codec<MessageType> = {
decode(input: Reader | Uint8Array, length?: number): MessageType;
encode(message: MessageType, writer?: Writer): Writer;
};

export type SnapRPC<Req, Res> = {
Expand All @@ -54,15 +54,18 @@ export async function processProtoRequest<Req, Res>(
}

if (typeof request.req !== 'string') {
throw new Error(`Expected string request. Got: ${request.req}`);
throw new Error(`Expected string request. Got: ${typeof request.req}`);
}

const decodedRequest = rpc.req.decode(b64Decode(request.req));
const result = await handler(decodedRequest);
return serializeResponse(rpc.res, result);
}

function serializeResponse<T>(codec: Codec<T>, res: T) {
function serializeResponse<MessageType>(
codec: Codec<MessageType>,
res: MessageType,
) {
const responseBytes = codec.encode(res).finish();
return { res: b64Encode(responseBytes, 0, responseBytes.length) };
}
Expand Down Expand Up @@ -139,10 +142,10 @@ export async function getKeystoreStatus(
return {
status: KeystoreStatus.KEYSTORE_STATUS_INITIALIZED,
};
} catch (e) {
} catch (error) {
// Only swallow KeyNotFoundError and turn into a negative response
if (!(e instanceof KeyNotFoundError)) {
throw e;
if (!(error instanceof KeyNotFoundError)) {
throw error;
}
return {
status: KeystoreStatus.KEYSTORE_STATUS_UNINITIALIZED,
Expand All @@ -152,7 +155,7 @@ export async function getKeystoreStatus(
);
}

export function KeystoreHandler(backingKeystore: InMemoryKeystore) {
export function keystoreHandler(backingKeystore: InMemoryKeystore) {
const out: any = {};
for (const [method, apiDef] of Object.entries(keystoreApiDefs)) {
if (!(method in backingKeystore)) {
Expand Down
4 changes: 3 additions & 1 deletion packages/snap/src/snapPersistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,20 @@ import storage from './storage';
const ENCODING = 'binary';

// Wraps the snap storage in an interface compatible with the XMTP persistence interface
// Main difference is that XMTP persistence asssumes all values are Uint8Arrays
// Main difference is that XMTP persistence assumes all values are Uint8Arrays
// and expects implementations to handle serialization
export default class SnapPersistence implements Persistence {
async getItem(key: string): Promise<Uint8Array | null> {
const value = await storage.getItem(key);
if (typeof value !== 'string') {
return null;
}
// eslint-disable-next-line no-restricted-globals
return value ? Uint8Array.from(Buffer.from(value, ENCODING)) : null;
}

async setItem(key: string, value: Uint8Array): Promise<void> {
// eslint-disable-next-line no-restricted-globals
await storage.setItem(key, Buffer.from(value).toString(ENCODING));
}
}
6 changes: 3 additions & 3 deletions packages/snap/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import {
import type { XmtpEnv, Persistence } from '@xmtp/xmtp-js';

import { KeyNotFoundError } from './errors';
import { type SnapRequest, KeystoreHandler } from './handlers';
import { type SnapRequest, keystoreHandler } from './handlers';
import SnapPersistence from './snapPersistence';

const { b64Encode } = fetcher;

// Mapping of keystore identifiers ($walletAddress/$env) to handlers
const handlers = new Map<string, ReturnType<typeof KeystoreHandler>>();
const handlers = new Map<string, ReturnType<typeof keystoreHandler>>();

// Gets the keys from provided persistence and converts to a class
export async function getKeys(persistence: Persistence) {
Expand Down Expand Up @@ -47,7 +47,7 @@ export async function getHandler(address: string, env: XmtpEnv) {
// This will throw if keys do not exist
const keys = await getKeys(persistence);
const keyStore = await InMemoryKeystore.create(keys, persistence);
handlers.set(key, KeystoreHandler(keyStore));
handlers.set(key, keystoreHandler(keyStore));
}

return handlers.get(key);
Expand Down
5 changes: 5 additions & 0 deletions packages/snap/tsconfig.eslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"include": [".", ".eslintrc.js"],
"exclude": ["dist", "node_modules"]
}
2 changes: 1 addition & 1 deletion packages/snap/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"extends": "../../tsconfig.json",
"include": ["src"]
"include": ["src", "snap.config.ts"]
}

0 comments on commit 00e8569

Please sign in to comment.