diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 398d660c7..000000000 --- a/.eslintrc.js +++ /dev/null @@ -1,39 +0,0 @@ -module.exports = { - env: { - browser: true, - es2021: true, - node: true, - }, - extends: [ - 'eslint:recommended', - 'plugin:react/recommended', - 'plugin:react/jsx-runtime', - 'plugin:react-hooks/recommended', - 'plugin:@typescript-eslint/recommended', - 'prettier', - 'plugin:prettier/recommended', // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. - ], - parser: '@typescript-eslint/parser', - settings: { - react: { - pragma: 'React', - version: 'detect', // Tells eslint-plugin-react to automatically detect the version of React to use - }, - }, - parserOptions: { - ecmaFeatures: { - jsx: true, - }, - ecmaVersion: 12, - sourceType: 'module', - }, - plugins: ['react', '@typescript-eslint'], - rules: { - '@typescript-eslint/explicit-module-boundary-types': 'off', - 'react/prop-types': 'off', - '@typescript-eslint/no-explicit-any': 'off', - '@typescript-eslint/no-var-requires': 'off', - 'no-shadow': 'off', - '@typescript-eslint/no-shadow': 'error', - }, -}; diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 000000000..fa4a47ec7 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,82 @@ +import { fixupConfigRules, fixupPluginRules } from '@eslint/compat'; +import react from 'eslint-plugin-react'; +import typescriptEslint from '@typescript-eslint/eslint-plugin'; +import globals from 'globals'; +import tsParser from '@typescript-eslint/parser'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import js from '@eslint/js'; +import { FlatCompat } from '@eslint/eslintrc'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const compat = new FlatCompat({ + baseDirectory: __dirname, + recommendedConfig: js.configs.recommended, + allConfig: js.configs.all, +}); + +export default [ + ...fixupConfigRules( + compat.extends( + 'eslint:recommended', + 'plugin:react/recommended', + 'plugin:react/jsx-runtime', + 'plugin:react-hooks/recommended', + 'plugin:@typescript-eslint/recommended', + 'prettier', + 'plugin:prettier/recommended', + ), + ), + { + plugins: { + react: fixupPluginRules(react), + '@typescript-eslint': fixupPluginRules(typescriptEslint), + }, + + languageOptions: { + globals: { + ...globals.browser, + ...globals.node, + }, + + parser: tsParser, + ecmaVersion: 12, + sourceType: 'module', + + parserOptions: { + ecmaFeatures: { + jsx: true, + }, + }, + }, + + settings: { + react: { + pragma: 'React', + version: 'detect', + }, + }, + + rules: { + '@typescript-eslint/explicit-module-boundary-types': 'off', + 'react/prop-types': 'off', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-var-requires': 'off', + 'no-shadow': 'off', + '@typescript-eslint/no-shadow': 'error', + '@typescript-eslint/no-unused-vars': [ + 'error', + { + args: 'all', + argsIgnorePattern: '^_', + caughtErrors: 'all', + caughtErrorsIgnorePattern: '^_', + destructuredArrayIgnorePattern: '^_', + varsIgnorePattern: '^_', + ignoreRestSiblings: true, + }, + ], + }, + }, +]; diff --git a/package.json b/package.json index 943c5c189..8b30922f6 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "build": "yarn run build:inpage --mode=production && webpack --config webpack.prod.js", "build:alpha": "yarn run build:inpage --mode=production && webpack --config webpack.alpha.js", "dev": "yarn run build:inpage && webpack -w --config webpack.dev.js", - "lint": "eslint --fix -c ./.eslintrc.js \"src/**/*.ts*\"", + "lint": "eslint --fix \"src/**/*.ts*\"", "typecheck": "yarn tsc --skipLibCheck --noEmit", "postinstall": "husky install && patch-package", "prettify": "prettier --write \"src/**/*.ts*\"", @@ -117,6 +117,9 @@ "@commitlint/cli": "17.0.3", "@commitlint/config-angular": "17.0.3", "@commitlint/config-conventional": "17.0.3", + "@eslint/compat": "1.2.4", + "@eslint/eslintrc": "3.2.0", + "@eslint/js": "9.16.0", "@google/semantic-release-replace-plugin": "1.1.0", "@lavamoat/allow-scripts": "2.0.0", "@lavamoat/preinstall-always-fail": "1.0.0", @@ -145,8 +148,8 @@ "@types/styled-components": "5.1.21", "@types/web3": "1.2.2", "@types/webextension-polyfill": "0.10.0", - "@typescript-eslint/eslint-plugin": "6.11.0", - "@typescript-eslint/parser": "6.11.0", + "@typescript-eslint/eslint-plugin": "8.17.0", + "@typescript-eslint/parser": "8.17.0", "@walletconnect/types": "2.9.1", "babel-jest": "29.7.0", "babel-loader": "9.1.3", @@ -157,13 +160,14 @@ "copy-webpack-plugin": "10.2.1", "css-loader": "5.2.4", "dotenv-webpack": "7.0.3", - "eslint": "8.7.0", - "eslint-config-prettier": "8.3.0", - "eslint-plugin-prettier": "4.0.0", - "eslint-plugin-react": "7.28.0", - "eslint-plugin-react-hooks": "4.3.0", + "eslint": "9.15.0", + "eslint-config-prettier": "9.1.0", + "eslint-plugin-prettier": "5.2.1", + "eslint-plugin-react": "7.37.2", + "eslint-plugin-react-hooks": "5.1.0", "file-loader": "6.2.0", "fs": "0.0.1-security", + "globals": "15.13.0", "husky": "7.0.4", "i18next-scanner": "4.1.1", "i18next-scanner-typescript": "1.1.1", @@ -175,7 +179,7 @@ "patch-package": "8.0.0", "path-browserify": "1.0.1", "postinstall-postinstall": "2.1.0", - "prettier": "2.5.1", + "prettier": "3.4.2", "react-docgen-typescript-loader": "3.7.2", "react-docgen-typescript-webpack-plugin": "1.1.0", "react-scripts": "5.0.1", diff --git a/src/background/connections/RequestProcessorPipeline.ts b/src/background/connections/RequestProcessorPipeline.ts index 07bb3fa6c..f1c8a19f0 100644 --- a/src/background/connections/RequestProcessorPipeline.ts +++ b/src/background/connections/RequestProcessorPipeline.ts @@ -32,7 +32,7 @@ export function RequestProcessorPipeline( (error) => { // error from the middleware, halt execution reject(error); - } + }, ); } else { // no more middlewares, execution finished @@ -40,7 +40,7 @@ export function RequestProcessorPipeline( } }; runner(0); - } + }, ); }; diff --git a/src/background/connections/dAppConnection/DAppConnectionController.ts b/src/background/connections/dAppConnection/DAppConnectionController.ts index 2302279b1..faa67ed58 100644 --- a/src/background/connections/dAppConnection/DAppConnectionController.ts +++ b/src/background/connections/dAppConnection/DAppConnectionController.ts @@ -57,7 +57,7 @@ export class DAppConnectionController implements ConnectionController { private accountsService: AccountsService, private networkService: NetworkService, private lockService: LockService, - private moduleManager: ModuleManager + private moduleManager: ModuleManager, ) { this.onRequest = this.onRequest.bind(this); this.disconnect = this.disconnect.bind(this); @@ -78,11 +78,11 @@ export class DAppConnectionController implements ConnectionController { PermissionMiddleware( this.permissionsService, this.accountsService, - this.lockService + this.lockService, ), ActiveNetworkMiddleware(this.networkService), DAppRequestHandlerMiddleware(this.handlers, this.moduleManager), - LoggerMiddleware(SideToLog.RESPONSE) + LoggerMiddleware(SideToLog.RESPONSE), ); connectionLog('dApp Provider'); @@ -103,13 +103,13 @@ export class DAppConnectionController implements ConnectionController { disconnect() { this.connection?.dispose(); this.eventEmitters.forEach((emitter) => - emitter.removeListener(this.onEvent) + emitter.removeListener(this.onEvent), ); disconnectLog('dApp Provider'); } needToPost( - context: Context | JsonRpcFailure> + context: Context | JsonRpcFailure>, ): boolean { return context.response !== DEFERRED_RESPONSE; } @@ -126,7 +126,7 @@ export class DAppConnectionController implements ConnectionController { request: { ...request, }, - }) + }), ); if (error) { @@ -156,7 +156,7 @@ export class DAppConnectionController implements ConnectionController { } catch (e) { sentryCaptureException( e as Error, - SentryExceptionTypes.DAPP_CONNECTION_EVENT + SentryExceptionTypes.DAPP_CONNECTION_EVENT, ); console.error(e); } diff --git a/src/background/connections/dAppConnection/DAppRequestHandler.ts b/src/background/connections/dAppConnection/DAppRequestHandler.ts index 897778322..e13cfb7aa 100644 --- a/src/background/connections/dAppConnection/DAppRequestHandler.ts +++ b/src/background/connections/dAppConnection/DAppRequestHandler.ts @@ -17,21 +17,21 @@ export interface DAppRequestHandler { result: any, onSuccess: (result: unknown) => Promise, onError: (error: Error) => Promise, - tabId?: number + tabId?: number, ) => Promise; } export abstract class DAppRequestHandler< RequestParams = unknown, - ResponseParams = any + ResponseParams = any, > { abstract methods: DAppProviderRequest[]; abstract handleAuthenticated: ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ) => Promise>; abstract handleUnauthenticated: ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ) => Promise>; } diff --git a/src/background/connections/dAppConnection/models.ts b/src/background/connections/dAppConnection/models.ts index 4ff004cb3..b76ef3473 100644 --- a/src/background/connections/dAppConnection/models.ts +++ b/src/background/connections/dAppConnection/models.ts @@ -63,7 +63,7 @@ export interface JsonRpcRequestParams { export type JsonRpcRequestPayload< Method extends string = any, - Params = unknown + Params = unknown, > = Params extends undefined ? JsonRpcRequestPayloadWithoutParams : JsonRpcRequestPayloadWithParams; @@ -86,7 +86,7 @@ interface JsonRpcRequestPayloadBase { interface JsonRpcRequestPayloadWithParams< Method extends string = any, - Params = unknown + Params = unknown, > extends JsonRpcRequestPayloadBase { readonly params: Params; } diff --git a/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.test.ts b/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.test.ts index acb56167f..d9f2bef76 100644 --- a/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.test.ts +++ b/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.test.ts @@ -65,7 +65,7 @@ describe('src/background/connections/extensionConnection/DappHandlerToExtensionH expect(await transformedHandler!.handle(buildRpcCall(request))).toEqual( expect.objectContaining({ error: 'No request ID provided', - }) + }), ); }); @@ -87,7 +87,7 @@ describe('src/background/connections/extensionConnection/DappHandlerToExtensionH expect(await transformedHandler!.handle(buildRpcCall(request))).toEqual( expect.objectContaining({ error, - }) + }), ); }); @@ -109,7 +109,7 @@ describe('src/background/connections/extensionConnection/DappHandlerToExtensionH expect(await transformedHandler!.handle(buildRpcCall(request))).toEqual( expect.objectContaining({ error, - }) + }), ); }); @@ -144,7 +144,7 @@ describe('src/background/connections/extensionConnection/DappHandlerToExtensionH name: browser.runtime.getManifest().name, }, }, - }) + }), ); }); @@ -166,7 +166,7 @@ describe('src/background/connections/extensionConnection/DappHandlerToExtensionH expect(await transformedHandler!.handle(buildRpcCall(request))).toEqual( expect.objectContaining({ result, - }) + }), ); }); @@ -204,7 +204,7 @@ describe('src/background/connections/extensionConnection/DappHandlerToExtensionH expect(await transformedHandler!.handle(buildRpcCall(request))).toEqual( expect.objectContaining({ result: DEFERRED_RESPONSE, - }) + }), ); }); }); diff --git a/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.ts b/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.ts index 047c4ffcb..c275ef503 100644 --- a/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.ts +++ b/src/background/connections/extensionConnection/DappHandlerToExtensionHandlerTransformer.ts @@ -10,7 +10,7 @@ import { DAppRequestHandler } from '../dAppConnection/DAppRequestHandler'; import { ExtensionRequestHandler } from '../models'; const decorateWithExtensionMetadata = ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ): JsonRpcRequestParams => ({ ...rpcCall, request: { @@ -27,14 +27,14 @@ const decorateWithExtensionMetadata = ( export class DappHandlerToExtensionHandlerTransformer { transform( - handlers: DAppRequestHandler[] + handlers: DAppRequestHandler[], ): ExtensionRequestHandler[] { return handlers.flatMap((handler) => { return handler.methods.map>( (method) => ({ method, handle: async ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ) => { const extRequest = decorateWithExtensionMetadata(rpcCall); @@ -46,7 +46,7 @@ export class DappHandlerToExtensionHandlerTransformer { } const [result, error] = await resolve( - handler.handleAuthenticated(extRequest) // Extension is always authenticated + handler.handleAuthenticated(extRequest), // Extension is always authenticated ); if (error || 'error' in result) { @@ -61,7 +61,7 @@ export class DappHandlerToExtensionHandlerTransformer { result: result.result, }; }, - }) + }), ); }); } diff --git a/src/background/connections/extensionConnection/ExtensionConnectionController.ts b/src/background/connections/extensionConnection/ExtensionConnectionController.ts index 3ad348896..45dcfa214 100644 --- a/src/background/connections/extensionConnection/ExtensionConnectionController.ts +++ b/src/background/connections/extensionConnection/ExtensionConnectionController.ts @@ -49,12 +49,12 @@ export class ExtensionConnectionController implements ConnectionController { private eventEmitters: ExtensionEventEmitter[], @injectAllWithTransform( 'DAppRequestHandler', - DappHandlerToExtensionHandlerTransformer + DappHandlerToExtensionHandlerTransformer, ) private dappHandlers: ExtensionRequestHandler[], @injectAll('DAppEventEmitter') private dappEmitters: DAppEventEmitter[], private networkService: NetworkService, - private moduleManager: ModuleManager + private moduleManager: ModuleManager, ) { this.onMessage = this.onMessage.bind(this); this.disconnect = this.disconnect.bind(this); @@ -68,8 +68,8 @@ export class ExtensionConnectionController implements ConnectionController { ActiveNetworkMiddleware(this.networkService), ExtensionRequestHandlerMiddleware( [...this.handlers, ...this.dappHandlers], - this.moduleManager - ) + this.moduleManager, + ), ); connectionLog('Extension Provider'); @@ -89,10 +89,10 @@ export class ExtensionConnectionController implements ConnectionController { disconnect(): void { this.connection?.onMessage.removeListener(this.onMessage); this.eventEmitters.forEach((emitter) => - emitter.removeListener(this.onEvent) + emitter.removeListener(this.onEvent), ); this.dappEmitters.forEach((emitter) => - emitter.removeListener(this.onEvent) + emitter.removeListener(this.onEvent), ); disconnectLog('Extension Provider'); } @@ -122,7 +122,7 @@ export class ExtensionConnectionController implements ConnectionController { icon: runtime.getManifest().icons?.['192'], name: runtime.getManifest().name, }, - }) + }), ); if (error) { @@ -135,7 +135,7 @@ export class ExtensionConnectionController implements ConnectionController { if (isDevelopment()) { responseLog( `extension reponse (${deserializedRequest.params.request.method})`, - response + response, ); } try { @@ -143,7 +143,7 @@ export class ExtensionConnectionController implements ConnectionController { } catch (e) { sentryCaptureException( e as Error, - SentryExceptionTypes.EXTENSION_CONNECTION_MESSAGE + SentryExceptionTypes.EXTENSION_CONNECTION_MESSAGE, ); console.error(e); } @@ -151,7 +151,7 @@ export class ExtensionConnectionController implements ConnectionController { if (isDevelopment()) { responseLog( `extension reponse (${deserializedRequest.params.request.method})`, - context.response + context.response, ); } @@ -182,7 +182,7 @@ export class ExtensionConnectionController implements ConnectionController { } catch (e) { sentryCaptureException( e as Error, - SentryExceptionTypes.EXTENSION_CONNECTION_EVENT + SentryExceptionTypes.EXTENSION_CONNECTION_EVENT, ); console.error(e); } diff --git a/src/background/connections/middlewares/ActiveNetworkMiddleware.test.ts b/src/background/connections/middlewares/ActiveNetworkMiddleware.test.ts index c18632c45..caba77fcd 100644 --- a/src/background/connections/middlewares/ActiveNetworkMiddleware.test.ts +++ b/src/background/connections/middlewares/ActiveNetworkMiddleware.test.ts @@ -4,7 +4,7 @@ import { RpcMethod } from '@avalabs/vm-module-types'; import getTargetNetworkForTx from '@src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx'; jest.mock( - '@src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx' + '@src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx', ); describe('src/background/connections/middlewares/ActiveNetworkMiddleware', () => { @@ -42,7 +42,7 @@ describe('src/background/connections/middlewares/ActiveNetworkMiddleware', () => }, } as any, next, - onError + onError, ); expect(next).not.toHaveBeenCalled(); diff --git a/src/background/connections/middlewares/ActiveNetworkMiddleware.ts b/src/background/connections/middlewares/ActiveNetworkMiddleware.ts index c22305b16..5663ffced 100644 --- a/src/background/connections/middlewares/ActiveNetworkMiddleware.ts +++ b/src/background/connections/middlewares/ActiveNetworkMiddleware.ts @@ -11,7 +11,7 @@ import { RpcMethod } from '@avalabs/vm-module-types'; import getTargetNetworkForTx from '@src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx'; export function ActiveNetworkMiddleware( - networkService: NetworkService + networkService: NetworkService, ): Middleware< JsonRpcRequest | ExtensionConnectionMessage, JsonRpcResponse | ExtensionConnectionMessageResponse diff --git a/src/background/connections/middlewares/DAppRequestHandlerMiddleware.ts b/src/background/connections/middlewares/DAppRequestHandlerMiddleware.ts index 5b07fceaa..9ddb83b93 100644 --- a/src/background/connections/middlewares/DAppRequestHandlerMiddleware.ts +++ b/src/background/connections/middlewares/DAppRequestHandlerMiddleware.ts @@ -14,7 +14,7 @@ import { ModuleManager } from '@src/background/vmModules/ModuleManager'; export function DAppRequestHandlerMiddleware( handlers: DAppRequestHandler[], - moduleManager: ModuleManager + moduleManager: ModuleManager, ): Middleware> { const handlerMap = handlers.reduce((acc, handler) => { for (const method of handler.methods) { @@ -51,8 +51,8 @@ export function DAppRequestHandlerMiddleware( const [module] = await resolve( moduleManager.loadModule( context.request.params.scope, - context.request.params.request.method - ) + context.request.params.request.method, + ), ); if (!context.network) { @@ -75,7 +75,7 @@ export function DAppRequestHandlerMiddleware( // This field is for our internal use only (only used with extension's direct connection) context: undefined, }, - context.network + context.network, ); } else { promise = engine(context.network).then((e) => @@ -83,7 +83,7 @@ export function DAppRequestHandlerMiddleware( ...context.request.params.request, id: crypto.randomUUID(), jsonrpc: '2.0', - }) + }), ); } } diff --git a/src/background/connections/middlewares/ExtensionRequestHandlerMiddleware.ts b/src/background/connections/middlewares/ExtensionRequestHandlerMiddleware.ts index a61de8a1d..0c195ed30 100644 --- a/src/background/connections/middlewares/ExtensionRequestHandlerMiddleware.ts +++ b/src/background/connections/middlewares/ExtensionRequestHandlerMiddleware.ts @@ -12,7 +12,7 @@ import { runtime } from 'webextension-polyfill'; export function ExtensionRequestHandlerMiddleware( handlers: ExtensionRequestHandler[], - moduleManager: ModuleManager + moduleManager: ModuleManager, ): Middleware< ExtensionConnectionMessage, ExtensionConnectionMessageResponse @@ -32,15 +32,15 @@ export function ExtensionRequestHandlerMiddleware( : await resolve( moduleManager.loadModule( context.request.params.scope, - context.request.params.request.method - ) + context.request.params.request.method, + ), ); if (!handler && !module) { onError( new Error( - 'Unable to handle request: ' + context.request.params.request.method - ) + 'Unable to handle request: ' + context.request.params.request.method, + ), ); return; } @@ -51,10 +51,12 @@ export function ExtensionRequestHandlerMiddleware( const promise = handleRequest(handler ?? module, context); context.response = await resolve(promise).then(([result, error]) => { - error && console.error(error); - error - ? sentryTracker.setStatus('intertal_error') - : sentryTracker.setStatus('ok'); + if (error) { + console.error(error); + sentryTracker.setStatus('intertal_error'); + } else { + sentryTracker.setStatus('ok'); + } return { ...(error ? error : result), @@ -68,7 +70,7 @@ export function ExtensionRequestHandlerMiddleware( const handleRequest = async ( handlerOrModule: ExtensionRequestHandler | Module, - context: Context + context: Context, ) => { if ('handle' in handlerOrModule) { return handlerOrModule.handle({ @@ -94,7 +96,7 @@ const handleRequest = async ( params: context.request.params.request.params, context: context.request.context, }, - context.network + context.network, ); return { diff --git a/src/background/connections/middlewares/PermissionMiddleware.ts b/src/background/connections/middlewares/PermissionMiddleware.ts index 9fdb5f10d..52957fe98 100644 --- a/src/background/connections/middlewares/PermissionMiddleware.ts +++ b/src/background/connections/middlewares/PermissionMiddleware.ts @@ -116,7 +116,7 @@ const CORE_METHODS = Object.freeze([ export function PermissionMiddleware( permissionService: PermissionsService, accountsService: AccountsService, - lockService: LockService + lockService: LockService, ): Middleware< ExtensionConnectionMessage | JsonRpcRequest, ExtensionConnectionMessageResponse | JsonRpcResponse diff --git a/src/background/connections/middlewares/RequestLoggerMiddleware.ts b/src/background/connections/middlewares/RequestLoggerMiddleware.ts index b84cc01ed..c26ae7b7e 100644 --- a/src/background/connections/middlewares/RequestLoggerMiddleware.ts +++ b/src/background/connections/middlewares/RequestLoggerMiddleware.ts @@ -21,7 +21,7 @@ export enum SideToLog { } export function LoggerMiddleware( - sideToLog: SideToLog + sideToLog: SideToLog, ): Middleware< ExtensionConnectionMessage | JsonRpcRequest, ExtensionConnectionMessageResponse | JsonRpcResponse @@ -31,12 +31,12 @@ export function LoggerMiddleware( if (sideToLog === SideToLog.REQUEST) { requestLog( `Web3 request (${context.request.params.request.method})`, - context.request + context.request, ); } else if (sideToLog === SideToLog.RESPONSE) { responseLog( `Web3 response (${context.request.params.request.method})`, - context.response + context.response, ); } } diff --git a/src/background/connections/middlewares/SiteMetadataMiddleware.ts b/src/background/connections/middlewares/SiteMetadataMiddleware.ts index a8fd48f9a..1404cf2c0 100644 --- a/src/background/connections/middlewares/SiteMetadataMiddleware.ts +++ b/src/background/connections/middlewares/SiteMetadataMiddleware.ts @@ -8,20 +8,19 @@ import { } from '../dAppConnection/models'; import { Middleware } from './models'; -interface DomainMetadataRequest - extends JsonRpcRequestPayload< - DAppProviderRequest.DOMAIN_METADATA_METHOD, - DomainMetadata - > {} +type DomainMetadataRequest = JsonRpcRequestPayload< + DAppProviderRequest.DOMAIN_METADATA_METHOD, + DomainMetadata +>; const isMetadataRequest = ( - request: JsonRpcRequestPayload + request: JsonRpcRequestPayload, ): request is DomainMetadataRequest => { return request.method === DAppProviderRequest.DOMAIN_METADATA_METHOD; }; export function SiteMetadataMiddleware( - connection: Runtime.Port + connection: Runtime.Port, ): Middleware { /** * Domain is per connection so this needs to remain an closure to the connection diff --git a/src/background/connections/middlewares/models.ts b/src/background/connections/middlewares/models.ts index ebc3e532f..5762bbe80 100644 --- a/src/background/connections/middlewares/models.ts +++ b/src/background/connections/middlewares/models.ts @@ -17,12 +17,12 @@ export type Context = { export type Middleware = ( context: Context, next: Next, - error: ErrorCallback + error: ErrorCallback, ) => Promise | void; export type Pipeline = { push: (...middlewares: Middleware[]) => void; execute: ( - context: Context + context: Context, ) => Promise>; }; diff --git a/src/background/connections/models.ts b/src/background/connections/models.ts index e2ddcdb2b..ac545fee0 100644 --- a/src/background/connections/models.ts +++ b/src/background/connections/models.ts @@ -15,15 +15,15 @@ import { EthereumProviderError, EthereumRpcError } from 'eth-rpc-errors'; import { SerializedEthereumRpcError } from 'eth-rpc-errors/dist/classes'; import { DAppRequestHandler } from './dAppConnection/DAppRequestHandler'; -export interface ExtensionConnectionMessage< +export type ExtensionConnectionMessage< Method extends ExtensionRequest | DAppProviderRequest | RpcMethod = any, - Params = any -> extends JsonRpcRequest {} + Params = any, +> = JsonRpcRequest; export type ExtensionConnectionMessageResponse< Method extends ExtensionRequest | DAppProviderRequest | RpcMethod = any, Result = any, - Params = any + Params = any, > = ExtensionConnectionMessage['params']['request'] & ( | { @@ -46,13 +46,13 @@ export interface ExtensionConnectionEvent { } export function isConnectionEvent( - message: ExtensionConnectionMessageResponse | ExtensionConnectionEvent + message: ExtensionConnectionMessageResponse | ExtensionConnectionEvent, ): message is ExtensionConnectionEvent { return !message.hasOwnProperty('id') && message.hasOwnProperty('name'); } export function isConnectionResponse( - message: ExtensionConnectionMessageResponse | ExtensionConnectionEvent + message: ExtensionConnectionMessageResponse | ExtensionConnectionEvent, ): message is ExtensionConnectionMessageResponse { return ( message.hasOwnProperty('id') && @@ -72,31 +72,28 @@ export function isConnectionResponse( export interface ExtensionRequestHandler< Method extends ExtensionRequest | DAppProviderRequest | RpcMethod, Result, - Params = undefined + Params = undefined, > { method: Method; handle: ( - rpcCall: ExtensionConnectionMessage['params'] + rpcCall: ExtensionConnectionMessage['params'], ) => Promise>; } -type ExtractHandlerTypes = Type extends ExtensionRequestHandler< - infer M, - infer R, - infer P -> - ? { Method: M; Result: R; Params: P } - : Type extends DAppRequestHandler - ? { - Method: ArrayElement; - Params: P; - Result: R; - } - : { - Method: RpcMethod; - Params: Type; - Result: string; - }; +type ExtractHandlerTypes = + Type extends ExtensionRequestHandler + ? { Method: M; Result: R; Params: P } + : Type extends DAppRequestHandler + ? { + Method: ArrayElement; + Params: P; + Result: R; + } + : { + Method: RpcMethod; + Params: Type; + Result: string; + }; type ModuleRequestPayload = Record; @@ -116,10 +113,10 @@ export type RequestHandlerType = < | DAppProviderRequest | RpcMethod = ExtractHandlerTypes['Method'], Result = Exclude['Result'], symbol>, - Params = ExtractHandlerTypes['Params'] + Params = ExtractHandlerTypes['Params'], >( message: Omit, 'id'>, - context?: Record + context?: Record, ) => Promise; interface ConnectionEventEmitter { diff --git a/src/background/providers/ChainAgnosticProvider.test.ts b/src/background/providers/ChainAgnosticProvider.test.ts index 59fb4715f..cac10f40d 100644 --- a/src/background/providers/ChainAgnosticProvider.test.ts +++ b/src/background/providers/ChainAgnosticProvider.test.ts @@ -75,7 +75,7 @@ describe('src/background/providers/ChainAgnosticProvider', () => { method: DAppProviderRequest.DOMAIN_METADATA_METHOD, }), }), - }) + }), ); }); }); @@ -137,8 +137,8 @@ describe('src/background/providers/ChainAgnosticProvider', () => { expect(firstCallCallback).toHaveBeenCalledWith('success'); expect(secondCallCallback).toHaveBeenCalledWith( ethErrors.rpc.resourceUnavailable( - `Request of type eth_requestAccounts already pending for origin. Please wait.` - ) + `Request of type eth_requestAccounts already pending for origin. Please wait.`, + ), ); }); it('shoud not use the rate limits on `random_method` requests', async () => { diff --git a/src/background/providers/ChainAgnosticProvider.ts b/src/background/providers/ChainAgnosticProvider.ts index 546f7272d..e4797791b 100644 --- a/src/background/providers/ChainAgnosticProvider.ts +++ b/src/background/providers/ChainAgnosticProvider.ts @@ -71,7 +71,7 @@ export class ChainAgnosticProvider extends EventEmitter { jsonrpc: '2.0', params: { scope: chainIdToCaip( - chainId ? parseInt(chainId) : ChainId.AVALANCHE_MAINNET_ID + chainId ? parseInt(chainId) : ChainId.AVALANCHE_MAINNET_ID, ), sessionId, request: { @@ -103,7 +103,7 @@ export class ChainAgnosticProvider extends EventEmitter { }) => { return this.#providerReadyPromise.call(() => { return this.#requestRateLimiter.call(data.method, () => - this.#request({ data, chainId, sessionId }) + this.#request({ data, chainId, sessionId }), ); }); }; diff --git a/src/background/providers/MultiWalletProviderProxy.test.ts b/src/background/providers/MultiWalletProviderProxy.test.ts index 1ba269d5d..2c0153c64 100644 --- a/src/background/providers/MultiWalletProviderProxy.test.ts +++ b/src/background/providers/MultiWalletProviderProxy.test.ts @@ -294,7 +294,7 @@ describe('src/background/providers/MultiWalletProviderProxy', () => { id: '1', params: [], }, - requestAccountsCallback + requestAccountsCallback, ); expect(requestAccountsCallback).not.toHaveBeenCalled(); @@ -346,7 +346,7 @@ describe('src/background/providers/MultiWalletProviderProxy', () => { const requestAccountsCallback = jest.fn(); mwpp.send( { method: 'eth_requestAccounts', id: '1', params: [] }, - requestAccountsCallback + requestAccountsCallback, ); expect(requestAccountsCallback).not.toHaveBeenCalled(); diff --git a/src/background/providers/MultiWalletProviderProxy.ts b/src/background/providers/MultiWalletProviderProxy.ts index ffc1a330f..a09d667d7 100644 --- a/src/background/providers/MultiWalletProviderProxy.ts +++ b/src/background/providers/MultiWalletProviderProxy.ts @@ -114,7 +114,7 @@ export class MultiWalletProviderProxy extends EventEmitter { event, (...args: any[]) => { this.emit(event as string, ...args); - } + }, ); }); } @@ -172,7 +172,10 @@ export class MultiWalletProviderProxy extends EventEmitter { */ sendAsync( payload: JsonRpcRequestPayload, - callback: (error: Error | null, result?: JsonRpcResponse) => void + callback: ( + error: Error | null, + result?: JsonRpcResponse, + ) => void, ): void { this._request(payload) .then((result: any) => { @@ -207,7 +210,7 @@ export class MultiWalletProviderProxy extends EventEmitter { */ send( payload: JsonRpcRequestPayload, - callback: (error: Error | null, result?: JsonRpcResponse) => void + callback: (error: Error | null, result?: JsonRpcResponse) => void, ): void; /** diff --git a/src/background/providers/initializeInpageProvider.test.ts b/src/background/providers/initializeInpageProvider.test.ts index 06cd47928..f46e2670b 100644 --- a/src/background/providers/initializeInpageProvider.test.ts +++ b/src/background/providers/initializeInpageProvider.test.ts @@ -36,7 +36,7 @@ describe('src/background/providers/initializeInpageProvider', () => { it('initializes CoreProvider with the correct channel name', () => { const provider = initializeProvider(connectionMock, 10, windowMock); expect(EVMProvider).toHaveBeenCalledWith( - expect.objectContaining({ maxListeners: 10 }) + expect.objectContaining({ maxListeners: 10 }), ); expect(provider.isAvalanche).toBe(true); }); @@ -64,7 +64,7 @@ describe('src/background/providers/initializeInpageProvider', () => { expect(windowMock.ethereum).toBe(mockMultiWalletProxy); expect(windowMock.dispatchEvent).toHaveBeenCalledWith( - new Event('ethereum#initialized') + new Event('ethereum#initialized'), ); }); @@ -131,7 +131,7 @@ describe('src/background/providers/initializeInpageProvider', () => { expect(windowMock.avalanche).toBe(provider); expect(windowMock.dispatchEvent).toHaveBeenCalledWith( - new Event('avalanche#initialized') + new Event('avalanche#initialized'), ); }); @@ -141,7 +141,7 @@ describe('src/background/providers/initializeInpageProvider', () => { windowMock.avalanche = { isMetaMask: true }; } catch (e) { expect((e as Error).message).toBe( - `Cannot assign to read only property 'avalanche' of object '#'` + `Cannot assign to read only property 'avalanche' of object '#'`, ); } }); @@ -153,13 +153,13 @@ describe('src/background/providers/initializeInpageProvider', () => { expect(windowMock.dispatchEvent).toHaveBeenCalledTimes(4); expect(windowMock.dispatchEvent.mock.calls[2][0].type).toEqual( - 'eip6963:announceProvider' + 'eip6963:announceProvider', ); expect(windowMock.dispatchEvent.mock.calls[2][0].detail).toStrictEqual( expect.objectContaining({ info: provider.info, provider: provider, - }) + }), ); }); it('re-announces on eip6963:requestProvider', () => { @@ -170,7 +170,7 @@ describe('src/background/providers/initializeInpageProvider', () => { expect(windowMock.addEventListener).toHaveBeenCalledTimes(3); expect(windowMock.addEventListener).toHaveBeenCalledWith( 'eip6963:requestProvider', - expect.anything() + expect.anything(), ); windowMock.addEventListener.mock.calls[1][1](); @@ -178,7 +178,7 @@ describe('src/background/providers/initializeInpageProvider', () => { expect(windowMock.dispatchEvent).toHaveBeenCalledTimes(5); expect(windowMock.dispatchEvent.mock.calls[2][0].type).toEqual( - 'eip6963:announceProvider' + 'eip6963:announceProvider', ); }); }); @@ -187,7 +187,7 @@ describe('src/background/providers/initializeInpageProvider', () => { initializeProvider(connectionMock, 10, windowMock); expect(windowMock.dispatchEvent.mock.calls[3][0].type).toEqual( - 'core-wallet:announceProvider' + 'core-wallet:announceProvider', ); }); }); diff --git a/src/background/providers/initializeInpageProvider.ts b/src/background/providers/initializeInpageProvider.ts index d4b76f9d9..9792366a4 100644 --- a/src/background/providers/initializeInpageProvider.ts +++ b/src/background/providers/initializeInpageProvider.ts @@ -15,13 +15,13 @@ import { EVMProvider } from '@avalabs/evm-module/dist/provider'; export function initializeProvider( connection: AbstractConnection, maxListeners = 100, - globalObject = window + globalObject = window, ): EVMProvider { const chainAgnosticProvider = new Proxy( new ChainAgnosticProvider(connection), { deleteProperty: () => true, - } + }, ); const evmProvider = new Proxy( @@ -42,7 +42,7 @@ export function initializeProvider( { // some common libraries, e.g. web3@1.x, mess with our API deleteProperty: () => true, - } + }, ); const multiWalletProxy = createMultiWalletProxy(evmProvider); @@ -56,8 +56,8 @@ export function initializeProvider( { deleteProperty: () => true, set: () => true, - } - ) + }, + ), ); }); @@ -78,7 +78,7 @@ export function initializeProvider( function setGlobalProvider( providerInstance: EVMProvider, globalObject = window, - multiWalletProxy + multiWalletProxy, ): void { try { Object.defineProperty(globalObject, 'ethereum', { @@ -129,7 +129,7 @@ function setGlobalProvider( */ function setAvalancheGlobalProvider( providerInstance: EVMProvider, - globalObject = window + globalObject = window, ): void { Object.defineProperty(globalObject, 'avalanche', { value: providerInstance, @@ -140,7 +140,7 @@ function setAvalancheGlobalProvider( function announceWalletProvider( providerInstance: EVMProvider, - globalObject = window + globalObject = window, ): void { const announceEvent = new CustomEvent( EventNames.EIP6963_ANNOUNCE_PROVIDER, @@ -149,7 +149,7 @@ function announceWalletProvider( info: { ...providerInstance.info }, provider: providerInstance, }), - } + }, ); // The Wallet dispatches an announce event which is heard by @@ -165,7 +165,7 @@ function announceWalletProvider( function announceChainAgnosticProvider( providerInstance: ChainAgnosticProvider, - globalObject = window + globalObject = window, ): void { const announceEvent = new CustomEvent<{ provider: ChainAgnosticProvider }>( EventNames.CORE_WALLET_ANNOUNCE_PROVIDER, @@ -173,7 +173,7 @@ function announceChainAgnosticProvider( detail: Object.freeze({ provider: providerInstance, }), - } + }, ); // The Wallet dispatches an announce event which is heard by diff --git a/src/background/providers/utils/RequestRatelimiter.test.ts b/src/background/providers/utils/RequestRatelimiter.test.ts index 54f4e9388..15c4efd29 100644 --- a/src/background/providers/utils/RequestRatelimiter.test.ts +++ b/src/background/providers/utils/RequestRatelimiter.test.ts @@ -25,8 +25,8 @@ describe('src/background/providers/utils/RequestRatelimiter', () => { } catch (e) { expect(e).toEqual( ethErrors.rpc.resourceUnavailable( - `Request of type eth_requestAccounts already pending for origin. Please wait.` - ) + `Request of type eth_requestAccounts already pending for origin. Please wait.`, + ), ); } diff --git a/src/background/providers/utils/RequestRatelimiter.ts b/src/background/providers/utils/RequestRatelimiter.ts index 1bda046a4..fccf69e3d 100644 --- a/src/background/providers/utils/RequestRatelimiter.ts +++ b/src/background/providers/utils/RequestRatelimiter.ts @@ -11,7 +11,7 @@ class RequestRatelimiter { async call(key: string, defer: () => Promise) { if (this.#rateLimitedMethods.includes(key) && this.#requestsInflight[key]) { throw ethErrors.rpc.resourceUnavailable( - `Request of type ${key} already pending for origin. Please wait.` + `Request of type ${key} already pending for origin. Please wait.`, ); } @@ -24,7 +24,7 @@ class RequestRatelimiter { if (!this.#requestsInflight[key]) { delete this.#requestsInflight[key]; } - }) + }), ); }); } diff --git a/src/background/providers/utils/getSiteMetadata.ts b/src/background/providers/utils/getSiteMetadata.ts index fdd37c679..ce19bcc2a 100644 --- a/src/background/providers/utils/getSiteMetadata.ts +++ b/src/background/providers/utils/getSiteMetadata.ts @@ -19,14 +19,14 @@ function getSiteName(windowObject: typeof window): string { const { document } = windowObject; const siteName: HTMLMetaElement | null = document.querySelector( - 'head > meta[property="og:site_name"]' + 'head > meta[property="og:site_name"]', ); if (siteName) { return siteName.content; } const metaTitle: HTMLMetaElement | null = document.querySelector( - 'head > meta[name="title"]' + 'head > meta[name="title"]', ); if (metaTitle) { return metaTitle.content; @@ -44,12 +44,12 @@ function getSiteName(windowObject: typeof window): string { * @returns an icon URL */ async function getSiteIcon( - windowObject: typeof window + windowObject: typeof window, ): Promise { const { document } = windowObject; const icons: NodeListOf = document.querySelectorAll( - 'head > link[rel~="icon"]' + 'head > link[rel~="icon"]', ); for (const icon of icons as any) { if (icon && (await imgExists(icon.href))) { diff --git a/src/background/providers/utils/onDomReady.test.ts b/src/background/providers/utils/onDomReady.test.ts index 7f9e3b4ad..d785bbcd1 100644 --- a/src/background/providers/utils/onDomReady.test.ts +++ b/src/background/providers/utils/onDomReady.test.ts @@ -34,7 +34,7 @@ describe('src/background/providers/utils/onDomReady', () => { expect(addEventListenerSpy).toHaveBeenCalledWith( 'DOMContentLoaded', expect.anything(), - { once: true } + { once: true }, ); expect(callback).not.toHaveBeenCalled(); @@ -45,7 +45,7 @@ describe('src/background/providers/utils/onDomReady', () => { expect(removeEventListenerSpy).toHaveBeenCalledWith( 'DOMContentLoaded', addEventListenerSpy.mock.calls[0]?.[1], - { once: true } + { once: true }, ); }); }); diff --git a/src/background/providers/utils/onPageActivated.test.ts b/src/background/providers/utils/onPageActivated.test.ts index f6ab20b66..8bde0d088 100644 --- a/src/background/providers/utils/onPageActivated.test.ts +++ b/src/background/providers/utils/onPageActivated.test.ts @@ -27,7 +27,7 @@ describe('src/background/providers/utils/onPageActivated', () => { expect(addEventListenerSpy).toHaveBeenCalledWith( 'prerenderingchange', expect.anything(), - { once: true } + { once: true }, ); expect(callback).not.toHaveBeenCalled(); diff --git a/src/background/runtime/BackgroundRuntime.ts b/src/background/runtime/BackgroundRuntime.ts index 1044ed6e5..872ac2b25 100644 --- a/src/background/runtime/BackgroundRuntime.ts +++ b/src/background/runtime/BackgroundRuntime.ts @@ -15,7 +15,7 @@ export class BackgroundRuntime { private onboardingService: OnboardingService, // we try to fetch the bridge configs as soon as possible private bridgeService: BridgeService, - private moduleManager: ModuleManager + private moduleManager: ModuleManager, ) {} activate() { diff --git a/src/background/runtime/CallbackManager.ts b/src/background/runtime/CallbackManager.ts index 4d8472cb3..b5b77c879 100644 --- a/src/background/runtime/CallbackManager.ts +++ b/src/background/runtime/CallbackManager.ts @@ -43,7 +43,7 @@ export class CallbackManager { onAllExtensionsClosed() { const instances = this.getInstancesForInterface( - 'onAllExtensionsClosed' + 'onAllExtensionsClosed', ); instances.forEach((i) => i.onAllExtensionsClosed()); } diff --git a/src/background/runtime/openApprovalWindow.test.ts b/src/background/runtime/openApprovalWindow.test.ts index fec5a2eaa..5c366fe8a 100644 --- a/src/background/runtime/openApprovalWindow.test.ts +++ b/src/background/runtime/openApprovalWindow.test.ts @@ -20,7 +20,7 @@ describe('src/background/runtime/openApprovalWindow', () => { id: '123', actionId: crypto.randomUUID(), // this is mocked }, - 'approval/screen' + 'approval/screen', ); }); }); diff --git a/src/background/runtime/openApprovalWindow.ts b/src/background/runtime/openApprovalWindow.ts index 62d0ab58b..ff921c206 100644 --- a/src/background/runtime/openApprovalWindow.ts +++ b/src/background/runtime/openApprovalWindow.ts @@ -13,6 +13,6 @@ export const openApprovalWindow = async (action: Action, url: string) => { ...action, actionId, }, - url + url, ); }; diff --git a/src/background/serialization/deserialize.test.ts b/src/background/serialization/deserialize.test.ts index 164694d07..4e15213fb 100644 --- a/src/background/serialization/deserialize.test.ts +++ b/src/background/serialization/deserialize.test.ts @@ -14,7 +14,7 @@ describe('deserialize', () => { const buffer = Buffer.from('This is a text'); const serializableValues: [ value: SerializableValue, - serializedValue: DeserializableValue + serializedValue: DeserializableValue, ][] = [ [new Big(bigString), { type: 'Big', value: bigString }], [new BN(bigString), { type: 'BN', value: bigString }], @@ -31,7 +31,7 @@ describe('deserialize', () => { }; const deserializedRequestJSON = deserializeFromJSON( - JSON.stringify(request) + JSON.stringify(request), ); expect(deserializedRequestJSON).toEqual({ ...request, params: value }); @@ -73,7 +73,7 @@ describe('deserialize', () => { }; const deserializedRequestJSON = deserializeFromJSON( - JSON.stringify(request) + JSON.stringify(request), ); expect(deserializedRequestJSON).toEqual({ @@ -113,7 +113,7 @@ describe('deserialize', () => { }; const deserializedRequestJSON = deserializeFromJSON( - JSON.stringify(request) + JSON.stringify(request), ); expect(deserializedRequestJSON).toEqual({ diff --git a/src/background/serialization/serialize.test.ts b/src/background/serialization/serialize.test.ts index d0df62e13..bffa3ce7b 100644 --- a/src/background/serialization/serialize.test.ts +++ b/src/background/serialization/serialize.test.ts @@ -14,7 +14,7 @@ describe('serialize', () => { const buffer = Buffer.from('This is a text'); const serializableValues: [ value: SerializableValue, - serializedValue: DeserializableValue + serializedValue: DeserializableValue, ][] = [ [new Big(bigString), { type: 'Big', value: bigString }], [new BN(bigString), { type: 'BN', value: bigString }], @@ -33,7 +33,7 @@ describe('serialize', () => { const serializedResponseString = serializeToJSON(response); expect(serializedResponseString).toEqual( - JSON.stringify({ ...request, result: serializedValue }) + JSON.stringify({ ...request, result: serializedValue }), ); }); }); @@ -78,7 +78,7 @@ describe('serialize', () => { JSON.stringify({ ...request, result: expectedResult, - }) + }), ); }); @@ -118,7 +118,7 @@ describe('serialize', () => { JSON.stringify({ ...request, result: expectedResult, - }) + }), ); }); }); diff --git a/src/background/services/accounts/AccountsService.test.ts b/src/background/services/accounts/AccountsService.test.ts index c4ef91ae5..78cb24b57 100644 --- a/src/background/services/accounts/AccountsService.test.ts +++ b/src/background/services/accounts/AccountsService.test.ts @@ -31,12 +31,12 @@ const WALLET_ID = 'wallet-id'; describe('background/services/accounts/AccountsService', () => { const networkService = new NetworkService( {} as any, - { addListener: jest.fn() } as any + { addListener: jest.fn() } as any, ); const storageService = new StorageService({} as any); const ledgerService = new LedgerService(); const walletConnectService = new WalletConnectService( - new WalletConnectStorage(storageService) + new WalletConnectStorage(storageService), ); const secretsService = new SecretsService(storageService); @@ -45,7 +45,7 @@ describe('background/services/accounts/AccountsService', () => { const analyticsServicePosthog = new AnalyticsServicePosthog( {} as any, {} as any, - {} as any + {} as any, ); let accountsService: AccountsService; @@ -77,7 +77,7 @@ describe('background/services/accounts/AccountsService', () => { const mockAccounts = ( withAddresses = false, withOtherAddresses = false, - active: number | string = 0 + active: number | string = 0, ) => { const addresses = withAddresses ? getAllAddresses(withOtherAddresses) : {}; @@ -161,7 +161,7 @@ describe('background/services/accounts/AccountsService', () => { analyticsServicePosthog, secretsService, ledgerService, - walletConnectService + walletConnectService, ); }); @@ -267,13 +267,13 @@ describe('background/services/accounts/AccountsService', () => { 1, 0, walletId, - networkService + networkService, ); expect(secretsService.getAddresses).toHaveBeenNthCalledWith( 2, 1, walletId, - networkService + networkService, ); expect(secretsService.getImportedAddresses).toBeCalledTimes(3); @@ -351,12 +351,12 @@ describe('background/services/accounts/AccountsService', () => { .mocked(secretsService.getImportedAddresses) .mockImplementation((id) => mockedAccounts.imported[id]); await accountsService.refreshAddressesForAccount( - mockedAccounts.primary[walletId][0]?.id as string + mockedAccounts.primary[walletId][0]?.id as string, ); expect(secretsService.getAddresses).toHaveBeenCalledTimes(1); expect(accountsService.getAccounts().primary[0]).toEqual( - mockAccounts(true, true).primary[0] + mockAccounts(true, true).primary[0], ); }); @@ -378,7 +378,7 @@ describe('background/services/accounts/AccountsService', () => { expect(secretsService.getImportedAddresses).toHaveBeenCalledWith( 'fb-acc', - networkService + networkService, ); expect(secretsService.getAddresses).toHaveBeenCalledTimes(0); expect(accountsService.getAccounts().imported['fb-acc']).toEqual({ @@ -424,7 +424,7 @@ describe('background/services/accounts/AccountsService', () => { await accountsService.onUnlock(); const testnetModeListener = jest.mocked( - networkService.developerModeChanged.add + networkService.developerModeChanged.add, ).mock.calls[0]?.[0]; // mocks a change to testnet @@ -433,7 +433,7 @@ describe('background/services/accounts/AccountsService', () => { await new Promise(process.nextTick); expect(accountsService.activateAccount).toHaveBeenCalledWith( - mockedAccounts.primary[walletId][0]?.id + mockedAccounts.primary[walletId][0]?.id, ); }); }); @@ -448,10 +448,10 @@ describe('background/services/accounts/AccountsService', () => { accountsService.onLock(); expect(accountsService.getAccounts()).toStrictEqual(emptyAccounts); expect( - (networkService.developerModeChanged.add as jest.Mock).mock.calls[0][0] + (networkService.developerModeChanged.add as jest.Mock).mock.calls[0][0], ).toBe( (networkService.developerModeChanged.remove as jest.Mock).mock - .calls[0][0] + .calls[0][0], ); }); @@ -462,7 +462,7 @@ describe('background/services/accounts/AccountsService', () => { await accountsService.onUnlock(); accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, - eventListener + eventListener, ); expect(accountsService.getAccounts()).toStrictEqual(mockedAccounts); accountsService.onLock(); @@ -523,14 +523,14 @@ describe('background/services/accounts/AccountsService', () => { }); expect( - analyticsServicePosthog.captureEncryptedEvent + analyticsServicePosthog.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ windowId: uuid, name: 'addedNewPrimaryAccount', properties: { addresses: Object.values(getAllAddresses()) }, - }) + }), ); }); @@ -557,7 +557,7 @@ describe('background/services/accounts/AccountsService', () => { }); expect(permissionsService.addWhitelistDomains).toBeCalledTimes(1); expect(permissionsService.addWhitelistDomains).toBeCalledWith( - '0x000000000' + '0x000000000', ); const accounts = accountsService.getAccounts(); @@ -598,7 +598,7 @@ describe('background/services/accounts/AccountsService', () => { }); expect(permissionsService.addWhitelistDomains).toBeCalledTimes(1); expect(permissionsService.addWhitelistDomains).toBeCalledWith( - '0x000000000' + '0x000000000', ); const accounts = accountsService.getAccounts(); @@ -626,7 +626,7 @@ describe('background/services/accounts/AccountsService', () => { await accountsService.onUnlock(); accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, - eventListener + eventListener, ); await accountsService.addPrimaryAccount({ name: 'New Account', @@ -634,7 +634,7 @@ describe('background/services/accounts/AccountsService', () => { }); expect(permissionsService.addWhitelistDomains).toBeCalledTimes(1); expect(permissionsService.addWhitelistDomains).toBeCalledWith( - '0x000000000' + '0x000000000', ); const newAccounts = { ...mockedAccounts }; @@ -682,12 +682,12 @@ describe('background/services/accounts/AccountsService', () => { expect(secretsService.addImportedWallet).toBeCalledTimes(1); expect(secretsService.addImportedWallet).toBeCalledWith( options, - networkService + networkService, ); expect(commitMock).toHaveBeenCalled(); expect(permissionsService.addWhitelistDomains).toBeCalledTimes(1); expect(permissionsService.addWhitelistDomains).toBeCalledWith( - '0x000000000' + '0x000000000', ); const accounts = accountsService.getAccounts(); @@ -705,13 +705,13 @@ describe('background/services/accounts/AccountsService', () => { }); expect( - analyticsServicePosthog.captureEncryptedEvent + analyticsServicePosthog.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ name: 'addedNewImportedAccount', properties: { addresses: Object.values(getAllAddresses()) }, - }) + }), ); }); @@ -740,12 +740,12 @@ describe('background/services/accounts/AccountsService', () => { expect(secretsService.addImportedWallet).toBeCalledTimes(1); expect(secretsService.addImportedWallet).toBeCalledWith( options, - networkService + networkService, ); expect(commitMock).toHaveBeenCalled(); expect(permissionsService.addWhitelistDomains).toBeCalledTimes(1); expect(permissionsService.addWhitelistDomains).toBeCalledWith( - '0x000000001' + '0x000000001', ); const accounts = accountsService.getAccounts(); @@ -777,7 +777,7 @@ describe('background/services/accounts/AccountsService', () => { await accountsService.onUnlock(); accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, - eventListener + eventListener, ); (secretsService.addImportedWallet as jest.Mock).mockResolvedValueOnce({ @@ -794,7 +794,7 @@ describe('background/services/accounts/AccountsService', () => { }); expect(permissionsService.addWhitelistDomains).toBeCalledTimes(1); expect(permissionsService.addWhitelistDomains).toBeCalledWith( - '0x000000001' + '0x000000001', ); const newAccounts = { @@ -836,12 +836,12 @@ describe('background/services/accounts/AccountsService', () => { }); expect(await accountsService.addImportedAccount({ options })).toEqual( - '0x1' + '0x1', ); expect(secretsService.addImportedWallet).toBeCalledTimes(1); expect(secretsService.addImportedWallet).toBeCalledWith( options, - networkService + networkService, ); expect(commitMock).not.toHaveBeenCalled(); expect(permissionsService.addWhitelistDomains).not.toHaveBeenCalled(); @@ -855,12 +855,12 @@ describe('background/services/accounts/AccountsService', () => { }; (secretsService.addImportedWallet as jest.Mock).mockRejectedValueOnce( - new Error(errorMessage) + new Error(errorMessage), ); expect(permissionsService.addWhitelistDomains).not.toHaveBeenCalled(); await expect( - accountsService.addImportedAccount({ name: 'New Account', options }) + accountsService.addImportedAccount({ name: 'New Account', options }), ).rejects.toThrow(`Account import failed with error: ${errorMessage}`); }); }); @@ -871,7 +871,7 @@ describe('background/services/accounts/AccountsService', () => { expect(accountsService.getAccounts()).toStrictEqual(emptyAccounts); await expect( - accountsService.setAccountName('unknown-uuid', 'updated name') + accountsService.setAccountName('unknown-uuid', 'updated name'), ).rejects.toThrow('Account rename failed: account not found'); }); @@ -886,7 +886,7 @@ describe('background/services/accounts/AccountsService', () => { const accounts = accountsService.getAccounts(); expect(accounts.primary[walletId]).toEqual( - mockedAccounts.primary[walletId] + mockedAccounts.primary[walletId], ); expect(accounts.primary[secondaryWalletId]).toEqual([ @@ -903,7 +903,7 @@ describe('background/services/accounts/AccountsService', () => { await accountsService.setAccountName('uuid2', 'Updated Name'); const accounts = accountsService.getAccounts(); const expectedAccounts = { ...mockedAccounts }; - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + expectedAccounts.primary[walletId][1]!.name = 'Updated Name'; expect(accounts).toStrictEqual(expectedAccounts); }); @@ -931,7 +931,7 @@ describe('background/services/accounts/AccountsService', () => { accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, - eventListener + eventListener, ); await accountsService.setAccountName('uuid2', 'Updated Name'); @@ -940,7 +940,7 @@ describe('background/services/accounts/AccountsService', () => { const result = accountsService.getAccounts(); const expectedAccounts = mockAccounts(true); - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + expectedAccounts.primary[walletId][1]!.name = 'Updated Name'; expect(result).toStrictEqual(expectedAccounts); @@ -957,7 +957,7 @@ describe('background/services/accounts/AccountsService', () => { expect(accountsService.getAccounts()).toStrictEqual(mockedAccounts); await expect( - accountsService.activateAccount('unknow-uuid') + accountsService.activateAccount('unknow-uuid'), ).rejects.toThrow('Account activation failed: account not found'); }); @@ -997,7 +997,7 @@ describe('background/services/accounts/AccountsService', () => { accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, - eventListener + eventListener, ); await accountsService.activateAccount('uuid2'); @@ -1016,7 +1016,7 @@ describe('background/services/accounts/AccountsService', () => { accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, - eventListener + eventListener, ); await accountsService.deleteAccounts(['0x1', '0x2']); @@ -1038,7 +1038,7 @@ describe('background/services/accounts/AccountsService', () => { expect(eventListener).toHaveBeenCalledWith(expectedAccounts); expect(secretsService.deleteImportedWallets).toHaveBeenCalledWith( ['0x1', '0x2'], - walletConnectService + walletConnectService, ); }); @@ -1053,7 +1053,7 @@ describe('background/services/accounts/AccountsService', () => { accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, - eventListener + eventListener, ); await accountsService.deleteAccounts(['0x1']); @@ -1076,20 +1076,20 @@ describe('background/services/accounts/AccountsService', () => { await accountsService.onUnlock(); expect( async () => - await accountsService.deleteAccounts(['uuid1', 'uuid2', 'uuid3']) + await accountsService.deleteAccounts(['uuid1', 'uuid2', 'uuid3']), ).rejects.toThrow('You cannot delete all of your primary accounts'); }); it('should throw an error because a seedles account cannot be deleted', async () => { const mockedAccounts = mockAccounts(true); (secretsService.getWalletType as jest.Mock).mockReturnValue( - SecretType.Seedless + SecretType.Seedless, ); (storageService.load as jest.Mock).mockResolvedValue(mockedAccounts); await accountsService.onUnlock(); expect( - async () => await accountsService.deleteAccounts(['uuid1']) + async () => await accountsService.deleteAccounts(['uuid1']), ).rejects.toThrow('You cannot delete a seedless account!'); }); it('should delete a primary account', async () => { diff --git a/src/background/services/accounts/AccountsService.ts b/src/background/services/accounts/AccountsService.ts index 919e11d82..b74edffc7 100644 --- a/src/background/services/accounts/AccountsService.ts +++ b/src/background/services/accounts/AccountsService.ts @@ -69,7 +69,7 @@ export class AccountsService implements OnLock, OnUnlock { if (activeAccountChanged) { this.eventEmitter.emit( AccountsEvents.ACTIVE_ACCOUNT_CHANGED, - this.accounts.active + this.accounts.active, ); } @@ -91,7 +91,7 @@ export class AccountsService implements OnLock, OnUnlock { private analyticsServicePosthog: AnalyticsServicePosthog, private secretsService: SecretsService, private ledgerService: LedgerService, - private walletConnectService: WalletConnectService + private walletConnectService: WalletConnectService, ) {} async onUnlock(): Promise { @@ -104,7 +104,7 @@ export class AccountsService implements OnLock, OnUnlock { // TODO(@meeh0w): // Remove this listener after E-upgrade activation on Fuji. It will be no longer needed. this.networkService.uiActiveNetworkChanged.add( - this.#onActiveNetworkChanged + this.#onActiveNetworkChanged, ); } @@ -129,10 +129,10 @@ export class AccountsService implements OnLock, OnUnlock { }; this.networkService.developerModeChanged.remove( - this.onDeveloperModeChanged + this.onDeveloperModeChanged, ); this.networkService.uiActiveNetworkChanged.remove( - this.#onActiveNetworkChanged + this.#onActiveNetworkChanged, ); } @@ -167,7 +167,7 @@ export class AccountsService implements OnLock, OnUnlock { } const refreshAccount = async ( - account: T + account: T, ): Promise => { const isUpdated = !updateAddresses && @@ -227,14 +227,14 @@ export class AccountsService implements OnLock, OnUnlock { if (account.type !== AccountType.PRIMARY) { return this.secretsService.getImportedAddresses( account.id, - this.networkService + this.networkService, ); } const addresses = await this.secretsService.getAddresses( account.index, account.walletId, - this.networkService + this.networkService, ); return { @@ -290,9 +290,8 @@ export class AccountsService implements OnLock, OnUnlock { } private async loadAccounts(): Promise { - const accounts = await this.storageService.load( - ACCOUNTS_STORAGE_KEY - ); + const accounts = + await this.storageService.load(ACCOUNTS_STORAGE_KEY); return ( accounts ?? { @@ -329,7 +328,7 @@ export class AccountsService implements OnLock, OnUnlock { #findAccountByAddress(addressC: string) { return Object.values(this.accounts.imported).find( - (acc) => acc.addressC === addressC + (acc) => acc.addressC === addressC, ); } @@ -340,7 +339,7 @@ export class AccountsService implements OnLock, OnUnlock { #buildAccount( accountData, importType: ImportType, - suggestedName?: string + suggestedName?: string, ): ImportedAccount { const type = IMPORT_TYPE_TO_ACCOUNT_TYPE_MAP[importType]; @@ -396,7 +395,7 @@ export class AccountsService implements OnLock, OnUnlock { }, }; await this.permissionsService.addWhitelistDomains( - addresses[NetworkVMType.EVM] + addresses[NetworkVMType.EVM], ); this.analyticsServicePosthog.captureEncryptedEvent({ @@ -417,7 +416,7 @@ export class AccountsService implements OnLock, OnUnlock { try { const { account, commit } = await this.secretsService.addImportedWallet( options, - this.networkService + this.networkService, ); const existingAccount = this.#findAccountByAddress(account.addressC); @@ -433,7 +432,7 @@ export class AccountsService implements OnLock, OnUnlock { const newAccount: ImportedAccount = this.#buildAccount( account, options.importType, - name + name, ); this.accounts = { @@ -452,7 +451,7 @@ export class AccountsService implements OnLock, OnUnlock { return account.id; } catch (err) { throw new Error( - `Account import failed with error: ${(err as Error).message}` + `Account import failed with error: ${(err as Error).message}`, ); } } @@ -485,7 +484,7 @@ export class AccountsService implements OnLock, OnUnlock { if (!walletAccounts) { throw new Error( - 'Updated account does not exist within any of the primary wallets.' + 'Updated account does not exist within any of the primary wallets.', ); } @@ -525,7 +524,7 @@ export class AccountsService implements OnLock, OnUnlock { const accountsCount = Object.values(this.accounts.primary).flat().length; const importedAccountIds = ids.filter((id) => id in this.accounts.imported); const primaryAccountIds = ids.filter( - (id) => !(id in this.accounts.imported) + (id) => !(id in this.accounts.imported), ); if (accountsCount === primaryAccountIds.length) { @@ -596,7 +595,7 @@ export class AccountsService implements OnLock, OnUnlock { await this.secretsService.deleteImportedWallets( ids, - this.walletConnectService + this.walletConnectService, ); this.accounts = { diff --git a/src/background/services/accounts/events/accountsChangedEvent.ts b/src/background/services/accounts/events/accountsChangedEvent.ts index ff54a392f..1a90f1927 100644 --- a/src/background/services/accounts/events/accountsChangedEvent.ts +++ b/src/background/services/accounts/events/accountsChangedEvent.ts @@ -32,7 +32,7 @@ export class AccountsChangedEvents implements DAppEventEmitter { constructor( private accountsService: AccountsService, - private permissionsService: PermissionsService + private permissionsService: PermissionsService, ) { this.permissionsService.addListener( PermissionEvents.PERMISSIONS_STATE_UPDATE, @@ -42,18 +42,18 @@ export class AccountsChangedEvents implements DAppEventEmitter { ? (permissions as Permissions)[this._connectionInfo.domain] : undefined; this.emitAccountsChanged(currentPermissions); - } + }, ); this.accountsService.addListener( AccountsEvents.ACCOUNTS_UPDATED, async () => { const currentPermissions = this._connectionInfo?.domain ? await this.permissionsService.getPermissionsForDomain( - this._connectionInfo.domain + this._connectionInfo.domain, ) : undefined; this.emitAccountsChanged(currentPermissions); - } + }, ); } @@ -87,7 +87,7 @@ export class AccountsChangedEvents implements DAppEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/accounts/events/accountsUpdatedEvent.ts b/src/background/services/accounts/events/accountsUpdatedEvent.ts index ce6dbeb67..56391e4f6 100644 --- a/src/background/services/accounts/events/accountsUpdatedEvent.ts +++ b/src/background/services/accounts/events/accountsUpdatedEvent.ts @@ -18,7 +18,7 @@ export class AccountsUpdatedEvents implements ExtensionEventEmitter { name: AccountsEvents.ACCOUNTS_UPDATED, value: accounts, }); - } + }, ); } @@ -27,7 +27,7 @@ export class AccountsUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/accounts/events/accountsUpdatedEventListener.ts b/src/background/services/accounts/events/accountsUpdatedEventListener.ts index 444f89cd6..354d732a2 100644 --- a/src/background/services/accounts/events/accountsUpdatedEventListener.ts +++ b/src/background/services/accounts/events/accountsUpdatedEventListener.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { Accounts, AccountsEvents } from '../models'; export function accountsUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === AccountsEvents.ACCOUNTS_UPDATED; } diff --git a/src/background/services/accounts/handlers/avalanche_getAccountPubKey.test.ts b/src/background/services/accounts/handlers/avalanche_getAccountPubKey.test.ts index aa05504fe..0b724b0b1 100644 --- a/src/background/services/accounts/handlers/avalanche_getAccountPubKey.test.ts +++ b/src/background/services/accounts/handlers/avalanche_getAccountPubKey.test.ts @@ -30,7 +30,7 @@ describe('background/services/accounts/handlers/avalanche_getAccountPubKey.ts', }, }; const handler = new AvalancheGetAccountPubKeyHandler( - noAccountsMock as any + noAccountsMock as any, ); const result = await handler.handleAuthenticated(buildRpcCall(request)); diff --git a/src/background/services/accounts/handlers/avalanche_getAccounts.test.ts b/src/background/services/accounts/handlers/avalanche_getAccounts.test.ts index c02fca12c..f758116e5 100644 --- a/src/background/services/accounts/handlers/avalanche_getAccounts.test.ts +++ b/src/background/services/accounts/handlers/avalanche_getAccounts.test.ts @@ -56,7 +56,7 @@ describe('background/services/accounts/handlers/avalanche_getAccounts.ts', () => it('handleAuthenticated', async () => { const handler = new AvalancheGetAccountsHandler( accountServiceMock, - secretsService + secretsService, ); const result = await handler.handleAuthenticated(buildRpcCall(request)); @@ -100,7 +100,7 @@ describe('background/services/accounts/handlers/avalanche_getAccounts.ts', () => it('handleUnauthenticated', async () => { const handler = new AvalancheGetAccountsHandler( accountServiceMock, - secretsService + secretsService, ); const result = await handler.handleUnauthenticated(buildRpcCall(request)); diff --git a/src/background/services/accounts/handlers/avalanche_getAccounts.ts b/src/background/services/accounts/handlers/avalanche_getAccounts.ts index 6e1ceccb4..ebfb3801a 100644 --- a/src/background/services/accounts/handlers/avalanche_getAccounts.ts +++ b/src/background/services/accounts/handlers/avalanche_getAccounts.ts @@ -11,7 +11,7 @@ export class AvalancheGetAccountsHandler extends DAppRequestHandler { constructor( private accountsService: AccountsService, - private secretsService: SecretsService + private secretsService: SecretsService, ) { super(); } diff --git a/src/background/services/accounts/handlers/avalanche_getAddressesInRange.test.ts b/src/background/services/accounts/handlers/avalanche_getAddressesInRange.test.ts index 5902be81c..c8dfdc9ad 100644 --- a/src/background/services/accounts/handlers/avalanche_getAddressesInRange.test.ts +++ b/src/background/services/accounts/handlers/avalanche_getAddressesInRange.test.ts @@ -29,7 +29,7 @@ describe('background/services/accounts/handlers/avalanche_getAddressesInRange.ts const handler = new AvalancheGetAddressesInRangeHandler( secretsServiceMock, networkServiceMock, - accountsService + accountsService, ); return handler.handleAuthenticated(request); @@ -44,7 +44,7 @@ describe('background/services/accounts/handlers/avalanche_getAddressesInRange.ts tabId: 3, }, ...payload, - } as const); + }) as const; beforeEach(() => { jest.resetAllMocks(); @@ -83,36 +83,36 @@ describe('background/services/accounts/handlers/avalanche_getAddressesInRange.ts .mocked(Avalanche.getAddressFromXpub) .mockImplementation( (_, index, __, ___, isChange) => - `X-${isChange ? 'internal' : 'external'}_address${index}` + `X-${isChange ? 'internal' : 'external'}_address${index}`, ); }); it('throws if external start index is incorrect', async () => { const { error } = await handleRequest( - buildRpcCall(getPayload({ params: [-1, 0] })) + buildRpcCall(getPayload({ params: [-1, 0] })), ); expect(error).toEqual( ethErrors.rpc.invalidParams({ message: 'Invalid start index', - }) + }), ); }); it('throws if internal start index is incorrect', async () => { const { error } = await handleRequest( - buildRpcCall(getPayload({ params: [0, -1] })) + buildRpcCall(getPayload({ params: [0, -1] })), ); expect(error).toEqual( ethErrors.rpc.invalidParams({ message: 'Invalid start index', - }) + }), ); }); it('returns the address list correctly', async () => { const { result } = await handleRequest( - buildRpcCall(getPayload({ params: [0, 0, 2, 2] })) + buildRpcCall(getPayload({ params: [0, 0, 2, 2] })), ); expect(result).toEqual({ external: getExpectedResult('external', 2), @@ -142,7 +142,7 @@ describe('background/services/accounts/handlers/avalanche_getAddressesInRange.ts }, }), }), - 'getAddressesInRange' + 'getAddressesInRange', ); }); @@ -162,7 +162,7 @@ describe('background/services/accounts/handlers/avalanche_getAddressesInRange.ts it('sets the limit to 0 if not provided', async () => { const { result } = await handleRequest( - buildRpcCall(getPayload({ params: [0, 0] })) + buildRpcCall(getPayload({ params: [0, 0] })), ); expect(result).toStrictEqual({ external: [], @@ -173,7 +173,7 @@ describe('background/services/accounts/handlers/avalanche_getAddressesInRange.ts it('sets the limit to 100 if the provided is over 100', async () => { const { result } = await handleRequest( - buildRpcCall(getPayload({ params: [0, 0, 1000, 1000] })) + buildRpcCall(getPayload({ params: [0, 0, 1000, 1000] })), ); expect(result.external).toHaveLength(100); expect(result.internal).toHaveLength(100); @@ -186,7 +186,7 @@ describe('background/services/accounts/handlers/avalanche_getAddressesInRange.ts const handler = new AvalancheGetAddressesInRangeHandler( secretsServiceMock, networkServiceMock, - accountsService + accountsService, ); const request = getPayload({ params: [0, 0, 10, 10], diff --git a/src/background/services/accounts/handlers/avalanche_getAddressesInRange.ts b/src/background/services/accounts/handlers/avalanche_getAddressesInRange.ts index 80a1c847f..f2b75545f 100644 --- a/src/background/services/accounts/handlers/avalanche_getAddressesInRange.ts +++ b/src/background/services/accounts/handlers/avalanche_getAddressesInRange.ts @@ -17,7 +17,7 @@ type Params = [ externalStart: number, internalStart: number, externalLimit: number, - internalLimit: number + internalLimit: number, ]; import { AccountsService } from '../AccountsService'; import { getAddressesInRange } from '../utils/getAddressesInRange'; @@ -38,7 +38,7 @@ export class AvalancheGetAddressesInRangeHandler extends DAppRequestHandler< constructor( private secretsService: SecretsService, private networkService: NetworkService, - private accountsService: AccountsService + private accountsService: AccountsService, ) { super(); } @@ -61,7 +61,7 @@ export class AvalancheGetAddressesInRangeHandler extends DAppRequestHandler< }) => { const provXP = await this.networkService.getAvalanceProviderXP(); const secrets = await this.secretsService.getPrimaryAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); const addresses: { external: string[]; internal: string[] } = { @@ -76,7 +76,7 @@ export class AvalancheGetAddressesInRangeHandler extends DAppRequestHandler< provXP, false, externalStart, - externalLimit + externalLimit, ); } @@ -86,7 +86,7 @@ export class AvalancheGetAddressesInRangeHandler extends DAppRequestHandler< provXP, true, internalStart, - internalLimit + internalLimit, ); } } @@ -183,7 +183,7 @@ export class AvalancheGetAddressesInRangeHandler extends DAppRequestHandler< onActionApproved = async ( pendingAction: Action, _, - onSuccess + onSuccess, ) => { onSuccess(pendingAction.displayData.addresses); }; diff --git a/src/background/services/accounts/handlers/avalanche_renameAccount.test.ts b/src/background/services/accounts/handlers/avalanche_renameAccount.test.ts index 94c98eeb2..9064d43a5 100644 --- a/src/background/services/accounts/handlers/avalanche_renameAccount.test.ts +++ b/src/background/services/accounts/handlers/avalanche_renameAccount.test.ts @@ -60,7 +60,7 @@ describe('src/background/services/accounts/handlers/avalanche_renameAccount', () expect.objectContaining({ displayData: { account, newName: 'Changed Name' }, }), - 'renameAccount' + 'renameAccount', ); expect(setAccountName).not.toHaveBeenCalled(); expect(result).toEqual({ ...request, result: DEFERRED_RESPONSE }); diff --git a/src/background/services/accounts/handlers/avalanche_renameAccount.ts b/src/background/services/accounts/handlers/avalanche_renameAccount.ts index 0d0cb1045..c70c35918 100644 --- a/src/background/services/accounts/handlers/avalanche_renameAccount.ts +++ b/src/background/services/accounts/handlers/avalanche_renameAccount.ts @@ -28,7 +28,7 @@ export class AvalancheRenameAccountHandler extends DAppRequestHandler< } handleAuthenticated = async ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ) => { const { request, scope } = rpcCall; const [accountId, newName] = request.params; @@ -107,7 +107,7 @@ export class AvalancheRenameAccountHandler extends DAppRequestHandler< pendingAction: Action<{ account: Account; newName: string }>, _, onSuccess, - onError + onError, ) => { try { const { account, newName } = pendingAction.displayData; diff --git a/src/background/services/accounts/handlers/avalanche_selectAccount.test.ts b/src/background/services/accounts/handlers/avalanche_selectAccount.test.ts index ff4ed3032..14adcb0f8 100644 --- a/src/background/services/accounts/handlers/avalanche_selectAccount.test.ts +++ b/src/background/services/accounts/handlers/avalanche_selectAccount.test.ts @@ -47,7 +47,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () const handler = new AvalancheSelectAccountHandler( accountServiceMock, - permissionsServiceMock + permissionsServiceMock, ); const url = 'switchAccount?actionId=uuid'; @@ -89,7 +89,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () accountServiceMock.getAccountList.mockReturnValue([account]); const handler = new AvalancheSelectAccountHandler( accountServiceMock, - permissionsServiceMock + permissionsServiceMock, ); const url = 'switchAccount?actionId=uuid'; @@ -126,7 +126,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () const handler = new AvalancheSelectAccountHandler( accountServiceMock, - permissionsServiceMock + permissionsServiceMock, ); const request = { id: '123', @@ -155,7 +155,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () const handler = new AvalancheSelectAccountHandler( accountServiceMock, - permissionsServiceMock + permissionsServiceMock, ); const request = { @@ -168,7 +168,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () const result = await handler.handleAuthenticated(buildRpcCall(request)); expect(accountServiceMock.activateAccount).toHaveBeenCalledWith( - account.id + account.id, ); expect(openExtensionNewWindow).not.toHaveBeenCalled(); expect(addActionMock).not.toHaveBeenCalled(); @@ -208,7 +208,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () const handler = new AvalancheSelectAccountHandler( accountServiceMock, - permissionsServiceMock + permissionsServiceMock, ); const request = { @@ -224,7 +224,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () displayData: { selectedAccount: accounts[1], }, - }) + }), ); }); }); @@ -233,7 +233,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () it('should return an error', async () => { const handler = new AvalancheSelectAccountHandler( accountServiceMock, - permissionsServiceMock + permissionsServiceMock, ); const request = { id: '123', @@ -245,7 +245,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () expect(result).toEqual({ ...request, error: new Error( - 'The requested account and/or method has not been authorized by the user.' + 'The requested account and/or method has not been authorized by the user.', ), }); }); @@ -261,7 +261,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () { activateAccount: activateAccountMock, } as any, - permissionsServiceMock + permissionsServiceMock, ); await handler.onActionApproved( { @@ -276,11 +276,11 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () } as any, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect( - permissionsServiceMock.setAccountPermissionForDomain + permissionsServiceMock.setAccountPermissionForDomain, ).not.toHaveBeenCalled(); expect(onErrorMock).not.toHaveBeenCalled(); expect(activateAccountMock).toHaveBeenCalledWith('uuid'); @@ -293,7 +293,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () { activateAccount: activateAccountMock, } as any, - permissionsServiceMock + permissionsServiceMock, ); await handler.onActionApproved( { @@ -304,11 +304,11 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () } as any, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect( - permissionsServiceMock.setAccountPermissionForDomain + permissionsServiceMock.setAccountPermissionForDomain, ).not.toHaveBeenCalled(); expect(onErrorMock).not.toHaveBeenCalled(); expect(activateAccountMock).toHaveBeenCalledWith('0x1'); @@ -321,7 +321,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () { activateAccount: activateAccountMock, } as any, - permissionsServiceMock + permissionsServiceMock, ); await handler.onActionApproved( { @@ -338,14 +338,14 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () } as any, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect( - permissionsServiceMock.setAccountPermissionForDomain + permissionsServiceMock.setAccountPermissionForDomain, ).toHaveBeenCalled(); expect( - permissionsServiceMock.setAccountPermissionForDomain + permissionsServiceMock.setAccountPermissionForDomain, ).toHaveBeenCalledWith('core.app', '0x1', true); expect(activateAccountMock).toHaveBeenCalledWith('0x1'); expect(onSuccessMock).toBeCalledWith(null); @@ -357,7 +357,7 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () { activateAccount: jest.fn().mockRejectedValueOnce(mockError), } as any, - permissionsServiceMock + permissionsServiceMock, ); await handler.onActionApproved( @@ -371,10 +371,10 @@ describe('background/services/accounts/handlers/avalanche_selectAccount.ts', () } as any, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect( - permissionsServiceMock.setAccountPermissionForDomain + permissionsServiceMock.setAccountPermissionForDomain, ).not.toHaveBeenCalled(); expect(onSuccessMock).not.toHaveBeenCalled(); expect(onErrorMock).toHaveBeenCalled(); diff --git a/src/background/services/accounts/handlers/avalanche_selectAccount.ts b/src/background/services/accounts/handlers/avalanche_selectAccount.ts index 86e7c5133..67db6943e 100644 --- a/src/background/services/accounts/handlers/avalanche_selectAccount.ts +++ b/src/background/services/accounts/handlers/avalanche_selectAccount.ts @@ -25,13 +25,13 @@ export class AvalancheSelectAccountHandler extends DAppRequestHandler< constructor( private accountsService: AccountsService, - private permissionsService: PermissionsService + private permissionsService: PermissionsService, ) { super(); } handleAuthenticated = async ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ) => { const { request, scope } = rpcCall; const [selectedIndexOrID] = request.params; @@ -48,7 +48,7 @@ export class AvalancheSelectAccountHandler extends DAppRequestHandler< const activeWalletAccounts = activeWalletId ? allAccounts.filter( (account) => - isPrimaryAccount(account) && account.walletId === activeWalletId + isPrimaryAccount(account) && account.walletId === activeWalletId, ) : undefined; @@ -74,7 +74,7 @@ export class AvalancheSelectAccountHandler extends DAppRequestHandler< const skipApproval = await canSkipApproval( request.site?.domain ?? '', - request.site?.tabId ?? -1 + request.site?.tabId ?? -1, ); if (skipApproval) { @@ -106,7 +106,7 @@ export class AvalancheSelectAccountHandler extends DAppRequestHandler< pendingAction: Action<{ selectedAccount: Account }>, _, onSuccess, - onError + onError, ) => { try { const { selectedAccount } = pendingAction.displayData; @@ -115,7 +115,7 @@ export class AvalancheSelectAccountHandler extends DAppRequestHandler< await this.permissionsService.setAccountPermissionForDomain( pendingAction.site.domain, selectedAccount.addressC, - true + true, ); } await this.accountsService.activateAccount(selectedAccount.id); diff --git a/src/background/services/accounts/handlers/getPrivateKey.test.ts b/src/background/services/accounts/handlers/getPrivateKey.test.ts index 03a78ba7e..18290ab97 100644 --- a/src/background/services/accounts/handlers/getPrivateKey.test.ts +++ b/src/background/services/accounts/handlers/getPrivateKey.test.ts @@ -40,7 +40,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { new GetPrivateKeyHandler( secretServiceMock, lockServiceMock, - accountsServiceMock + accountsServiceMock, ); beforeEach(() => { @@ -58,7 +58,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params: [{ password: '' }], - }) + }), ); expect(result).toEqual({ ...request, @@ -76,7 +76,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params: [{ password: '', chain: 'Z' }], - }) + }), ); expect(result).toEqual({ ...request, @@ -94,7 +94,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params: [{ password: '', chain: PrivateKeyChain.C }], - }) + }), ); expect(result).toEqual({ ...request, @@ -114,7 +114,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params: [{ password: 'asd', chain: PrivateKeyChain.C }], - }) + }), ); expect(result).toEqual({ ...request, @@ -147,7 +147,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ @@ -173,7 +173,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ ...request, @@ -203,7 +203,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ ...request, @@ -240,7 +240,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ ...request, @@ -274,7 +274,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ ...request, @@ -284,7 +284,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { expect(accountsServiceMock.getAccountByID).toHaveBeenCalledTimes(1); expect(accountsServiceMock.getAccountByID).toHaveBeenCalledWith( - '123-123-123' + '123-123-123', ); expect(secretServiceMock.getPrimaryAccountSecrets).toHaveBeenCalledTimes(1); expect(secretServiceMock.getPrimaryAccountSecrets).toHaveBeenCalledWith({ @@ -313,7 +313,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ ...request, @@ -341,7 +341,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ ...request, @@ -367,7 +367,7 @@ describe('background/services/accounts/handlers/getPrivateKey.ts', () => { buildRpcCall({ ...request, params, - }) + }), ); expect(result).toEqual({ ...request, diff --git a/src/background/services/accounts/handlers/getPrivateKey.ts b/src/background/services/accounts/handlers/getPrivateKey.ts index 91215340b..3035c7d57 100644 --- a/src/background/services/accounts/handlers/getPrivateKey.ts +++ b/src/background/services/accounts/handlers/getPrivateKey.ts @@ -39,7 +39,7 @@ export class GetPrivateKeyHandler implements HandlerType { constructor( private secretService: SecretsService, private lockService: LockService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -93,9 +93,8 @@ export class GetPrivateKeyHandler implements HandlerType { try { if (type === AccountType.IMPORTED) { - const account = await this.secretService.getImportedAccountSecrets( - accountId - ); + const account = + await this.secretService.getImportedAccountSecrets(accountId); if (account?.secretType === SecretType.PrivateKey) { return { @@ -125,9 +124,8 @@ export class GetPrivateKeyHandler implements HandlerType { }; } - const primaryAccount = await this.secretService.getPrimaryAccountSecrets( - account - ); + const primaryAccount = + await this.secretService.getPrimaryAccountSecrets(account); if ( !primaryAccount || @@ -149,8 +147,8 @@ export class GetPrivateKeyHandler implements HandlerType { getAddressDerivationPath( accountIndex, primaryAccount.derivationPath, - 'PVM' - ) + 'PVM', + ), ); if (!pvmNode.privateKey) { return { @@ -171,7 +169,7 @@ export class GetPrivateKeyHandler implements HandlerType { const signer = getWalletFromMnemonic( primaryAccount.mnemonic, accountIndex, - primaryAccount.derivationPath + primaryAccount.derivationPath, ); if (!signer || !signer.path) { diff --git a/src/background/services/accounts/utils/getAddressesInRange.ts b/src/background/services/accounts/utils/getAddressesInRange.ts index 2ff423ef3..1ae7529ba 100644 --- a/src/background/services/accounts/utils/getAddressesInRange.ts +++ b/src/background/services/accounts/utils/getAddressesInRange.ts @@ -5,15 +5,15 @@ export function getAddressesInRange( providerXP: Avalanche.JsonRpcProvider, internal = false, start = 0, - limit = 64 + limit = 64, ) { const addresses: string[] = []; for (let i = start; i < start + limit; i++) { addresses.push( Avalanche.getAddressFromXpub(xpubXP, i, providerXP, 'P', internal).split( - '-' - )[1] as string + '-', + )[1] as string, ); } diff --git a/src/background/services/accounts/utils/typeGuards.ts b/src/background/services/accounts/utils/typeGuards.ts index b6aa6d703..d0fa38479 100644 --- a/src/background/services/accounts/utils/typeGuards.ts +++ b/src/background/services/accounts/utils/typeGuards.ts @@ -8,18 +8,18 @@ import { } from '../models'; export const isFireblocksAccount = ( - account?: Account + account?: Account, ): account is FireblocksAccount => account?.type === AccountType.FIREBLOCKS; export const isWalletConnectAccount = ( - account?: Account + account?: Account, ): account is WalletConnectAccount => account?.type === AccountType.WALLET_CONNECT; export const isPrimaryAccount = ( - account?: Account + account?: Account, ): account is PrimaryAccount => account?.type === AccountType.PRIMARY; export const isImportedAccount = ( - account?: Account + account?: Account, ): account is ImportedAccount => Boolean(account) && !isPrimaryAccount(account); diff --git a/src/background/services/actions/ActionsService.test.ts b/src/background/services/actions/ActionsService.test.ts index 31800bc9d..f40c8c205 100644 --- a/src/background/services/actions/ActionsService.test.ts +++ b/src/background/services/actions/ActionsService.test.ts @@ -51,7 +51,6 @@ describe('background/services/actions/ActionsService.ts', () => { actionId: 'uuid', } as any; - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { displayData, ...mockActionWithoutDisplaydata } = mockAction; let approvalController: jest.Mocked; @@ -71,7 +70,7 @@ describe('background/services/actions/ActionsService.ts', () => { [handlerWithCallback, handlerWithoutCallback], storageService, lockService, - approvalController + approvalController, ); (filterStaleActions as jest.Mock).mockImplementation((a) => a); }); @@ -79,7 +78,7 @@ describe('background/services/actions/ActionsService.ts', () => { describe('updateTx()', () => { it('throws error if the request does not exist', async () => { await expect(actionsService.updateTx('weird-id', {})).rejects.toThrow( - /No request found with id/ + /No request found with id/, ); }); @@ -128,7 +127,7 @@ describe('background/services/actions/ActionsService.ts', () => { }; (storageService.load as jest.Mock).mockResolvedValue(actions); (storageService.loadFromSessionStorage as jest.Mock).mockResolvedValue( - actions2 + actions2, ); const result = await actionsService.getActions(); @@ -137,7 +136,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.load).toHaveBeenCalledWith(ACTIONS_STORAGE_KEY); expect(storageService.loadFromSessionStorage).toHaveBeenCalledTimes(1); expect(storageService.loadFromSessionStorage).toHaveBeenCalledWith( - ACTIONS_STORAGE_KEY + ACTIONS_STORAGE_KEY, ); }); @@ -149,7 +148,7 @@ describe('background/services/actions/ActionsService.ts', () => { 2: { ...mockAction, id: 2 }, }; (storageService.loadFromSessionStorage as jest.Mock).mockResolvedValue( - actions + actions, ); const result = await actionsService.getActions(); @@ -157,7 +156,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(result).toEqual(actions); expect(storageService.loadFromSessionStorage).toHaveBeenCalledTimes(1); expect(storageService.loadFromSessionStorage).toHaveBeenCalledWith( - ACTIONS_STORAGE_KEY + ACTIONS_STORAGE_KEY, ); expect(storageService.load).not.toHaveBeenCalled(); }); @@ -175,7 +174,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.save).toHaveBeenCalledTimes(1); expect(storageService.save).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - actions + actions, ); expect(storageService.saveToSessionStorage).not.toHaveBeenCalled(); }); @@ -192,7 +191,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.saveToSessionStorage).toHaveBeenCalledTimes(1); expect(storageService.saveToSessionStorage).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - actions + actions, ); expect(storageService.save).not.toHaveBeenCalled(); }); @@ -230,7 +229,7 @@ describe('background/services/actions/ActionsService.ts', () => { }); expect(storageService.removeFromSessionStorage).toHaveBeenCalledWith( - ACTIONS_STORAGE_KEY + ACTIONS_STORAGE_KEY, ); }); }); @@ -332,7 +331,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); const action = { @@ -360,7 +359,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.save).toHaveBeenCalledTimes(1); expect(storageService.save).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - {} + {}, ); }); @@ -368,7 +367,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ @@ -388,7 +387,7 @@ describe('background/services/actions/ActionsService.ts', () => { undefined, expect.any(Function), expect.any(Function), - tabId + tabId, ); }); @@ -396,7 +395,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ @@ -404,9 +403,9 @@ describe('background/services/actions/ActionsService.ts', () => { }); (handlerWithCallback.onActionApproved as jest.Mock).mockImplementation( - async (pendingAction, result, onSuccess, onError) => { + async (_pendingAction, _result, _onSuccess, onError) => { await onError(new Error('someError')); - } + }, ); await actionsService.updateAction({ @@ -423,7 +422,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.save).toHaveBeenCalledTimes(1); expect(storageService.save).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - {} + {}, ); }); @@ -431,7 +430,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ @@ -439,9 +438,9 @@ describe('background/services/actions/ActionsService.ts', () => { }); (handlerWithCallback.onActionApproved as jest.Mock).mockImplementation( - async (pendingAction, result, onSuccess) => { + async (_pendingAction, _result, onSuccess) => { await onSuccess(['ADDRESS']); - } + }, ); await actionsService.updateAction({ @@ -458,7 +457,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.save).toHaveBeenCalledTimes(1); expect(storageService.save).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - {} + {}, ); }); }); @@ -486,7 +485,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ @@ -507,7 +506,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.save).toHaveBeenCalledTimes(1); expect(storageService.save).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - {} + {}, ); }); }); @@ -517,7 +516,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ @@ -539,7 +538,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.save).toHaveBeenCalledTimes(1); expect(storageService.save).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - {} + {}, ); }); }); @@ -549,7 +548,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ @@ -571,7 +570,7 @@ describe('background/services/actions/ActionsService.ts', () => { expect(storageService.save).toHaveBeenCalledTimes(1); expect(storageService.save).toHaveBeenCalledWith( ACTIONS_STORAGE_KEY, - {} + {}, ); }); }); @@ -581,7 +580,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ @@ -610,7 +609,7 @@ describe('background/services/actions/ActionsService.ts', () => { const eventListener = jest.fn(); actionsService.addListener( ActionsEvent.ACTION_COMPLETED, - eventListener + eventListener, ); (storageService.load as jest.Mock).mockResolvedValue({ diff --git a/src/background/services/actions/ActionsService.ts b/src/background/services/actions/ActionsService.ts index e2a91fe47..ebef811ec 100644 --- a/src/background/services/actions/ActionsService.ts +++ b/src/background/services/actions/ActionsService.ts @@ -30,13 +30,13 @@ export class ActionsService implements OnStorageReady { private dAppRequestHandlers: DAppRequestHandler[], private storageService: StorageService, private lockService: LockService, - private approvalController: ApprovalController + private approvalController: ApprovalController, ) {} async onStorageReady() { const acionsInSession = await this.storageService.loadFromSessionStorage( - ACTIONS_STORAGE_KEY + ACTIONS_STORAGE_KEY, ); const actionsInStorage = await this.getActions(); this.storageService.removeFromSessionStorage(ACTIONS_STORAGE_KEY); @@ -50,7 +50,7 @@ export class ActionsService implements OnStorageReady { async getActions(): Promise { const sessionStorageActions = (await this.storageService.loadFromSessionStorage( - ACTIONS_STORAGE_KEY + ACTIONS_STORAGE_KEY, )) ?? {}; if (this.lockService.locked) { return sessionStorageActions; @@ -70,7 +70,7 @@ export class ActionsService implements OnStorageReady { if (this.lockService.locked) { await this.storageService.saveToSessionStorage( ACTIONS_STORAGE_KEY, - actions + actions, ); } else { await this.storageService.save(ACTIONS_STORAGE_KEY, actions); @@ -97,7 +97,7 @@ export class ActionsService implements OnStorageReady { async removeAction(id: string) { const currentPendingActions = await this.getActions(); - // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { [`${id}`]: _removed, ...txs } = currentPendingActions; await this.saveActions(txs); } @@ -106,13 +106,13 @@ export class ActionsService implements OnStorageReady { id: string, action: Action, isSuccess: boolean, - result: any + result: any, ) { await this.removeAction(id); // We dont want display data to be emitted. Sometimes it can not be serialized and it's content is internal to Core // Make sure not to modify the original action object - // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { displayData, ...actionWithoutDisplayData } = action; this.eventEmitter.emit(ActionsEvent.ACTION_COMPLETED, { @@ -146,7 +146,7 @@ export class ActionsService implements OnStorageReady { this.removeAction(id); } else if (status === ActionStatus.SUBMITTING) { const handler = this.dAppRequestHandlers.find((h) => - h.methods.includes(pendingMessage.method as DAppProviderRequest) + h.methods.includes(pendingMessage.method as DAppProviderRequest), ); if (!handler || !handler.onActionApproved) { @@ -154,7 +154,7 @@ export class ActionsService implements OnStorageReady { id, pendingMessage, false, - ethErrors.rpc.internal('Request handler not found') + ethErrors.rpc.internal('Request handler not found'), ); return; } @@ -168,14 +168,14 @@ export class ActionsService implements OnStorageReady { async (failureResult) => { await this.emitResult(id, pendingMessage, false, failureResult); }, - tabId + tabId, ); } else if (status === ActionStatus.ERROR) { await this.emitResult( id, pendingMessage, false, - ethErrors.rpc.internal(error) + ethErrors.rpc.internal(error), ); } else if (status === ActionStatus.COMPLETED) { await this.emitResult(id, pendingMessage, true, result ?? true); @@ -190,7 +190,7 @@ export class ActionsService implements OnStorageReady { id, pendingMessage, false, - ethErrors.provider.userRejectedRequest() + ethErrors.provider.userRejectedRequest(), ); } else { await this.saveActions({ @@ -203,7 +203,7 @@ export class ActionsService implements OnStorageReady { }, signingData: getUpdatedSigningData( pendingMessage.signingData, - signingData + signingData, ), status, result, @@ -215,7 +215,7 @@ export class ActionsService implements OnStorageReady { async updateTx( id: string, - newData: Parameters[0] | Parameters[0] + newData: Parameters[0] | Parameters[0], ) { const currentPendingRequests = await this.getActions(); const pendingRequest = currentPendingRequests[id]; @@ -226,7 +226,7 @@ export class ActionsService implements OnStorageReady { const { signingData, displayData } = this.approvalController.updateTx( id, - newData + newData, ); await this.saveActions({ @@ -245,11 +245,11 @@ export class ActionsService implements OnStorageReady { type: ActionCompletedEventType; action: Action; result: any; - }) => void + }) => void, ); addListener( event: ActionsEvent.ACTION_UPDATED, - callback: (actions: Actions) => void + callback: (actions: Actions) => void, ); addListener(event: ActionsEvent, callback: (data: any) => void) { this.eventEmitter.on(event, callback); diff --git a/src/background/services/actions/events/actionEventFilters.ts b/src/background/services/actions/events/actionEventFilters.ts index 72c3d1836..040d7e908 100644 --- a/src/background/services/actions/events/actionEventFilters.ts +++ b/src/background/services/actions/events/actionEventFilters.ts @@ -2,6 +2,6 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { Actions, ActionsEvent } from '../models'; export const isActionsUpdate = ( - ev: ExtensionConnectionEvent + ev: ExtensionConnectionEvent, ): ev is ExtensionConnectionEvent => ev.name === ActionsEvent.ACTION_UPDATED; diff --git a/src/background/services/actions/events/actionEvents.ts b/src/background/services/actions/events/actionEvents.ts index ab1014a68..9d4bb0a90 100644 --- a/src/background/services/actions/events/actionEvents.ts +++ b/src/background/services/actions/events/actionEvents.ts @@ -37,7 +37,7 @@ export class ActionEvents implements DAppEventEmitter { : { ...action, result: result }; this.eventEmitter.emit('update', response); } - } + }, ); this.actionService.addListener( ActionsEvent.ACTION_UPDATED, @@ -46,7 +46,7 @@ export class ActionEvents implements DAppEventEmitter { name: ActionsEvent.ACTION_UPDATED, value: actions, }); - } + }, ); } @@ -55,7 +55,7 @@ export class ActionEvents implements DAppEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/actions/handlers/updateTxData.test.ts b/src/background/services/actions/handlers/updateTxData.test.ts index 9d3b01964..b0c0012e1 100644 --- a/src/background/services/actions/handlers/updateTxData.test.ts +++ b/src/background/services/actions/handlers/updateTxData.test.ts @@ -36,13 +36,13 @@ describe('src/background/services/actions/handlers/updateTxData', () => { .mockRejectedValueOnce({ message: 'Unable to create transaction' }); expect(await handleRequest(getRequest(['id', { feeRate: 5 }]))).toEqual( - matchingPayload({ error: SendErrorMessage.INSUFFICIENT_BALANCE_FOR_FEE }) + matchingPayload({ error: SendErrorMessage.INSUFFICIENT_BALANCE_FOR_FEE }), ); }); it('validates the request to update exists', async () => { expect(await handleRequest(getRequest(['id', { feeRate: 5 }]))).toEqual( - matchingPayload({ error: 'no pending requests found' }) + matchingPayload({ error: 'no pending requests found' }), ); }); diff --git a/src/background/services/actions/handlers/updateTxData.ts b/src/background/services/actions/handlers/updateTxData.ts index e28d5653e..48cf10af8 100644 --- a/src/background/services/actions/handlers/updateTxData.ts +++ b/src/background/services/actions/handlers/updateTxData.ts @@ -12,7 +12,7 @@ type HandlerType = ExtensionRequestHandler< null, [ id: string, - newData: Parameters[0] | Parameters[0] + newData: Parameters[0] | Parameters[0], ] >; diff --git a/src/background/services/actions/utils.ts b/src/background/services/actions/utils.ts index 7714e0348..70234e220 100644 --- a/src/background/services/actions/utils.ts +++ b/src/background/services/actions/utils.ts @@ -5,7 +5,7 @@ import { Actions } from './models'; * Filters out actions from the actions list without an open window */ export async function filterStaleActions( - actionsInStorage: Actions + actionsInStorage: Actions, ): Promise { const openWindowIds = (await browser.windows.getAll()) .filter((w) => w.type === 'popup') diff --git a/src/background/services/analytics/AnalyticsService.ts b/src/background/services/analytics/AnalyticsService.ts index 18caf706d..862ce3904 100644 --- a/src/background/services/analytics/AnalyticsService.ts +++ b/src/background/services/analytics/AnalyticsService.ts @@ -42,7 +42,7 @@ export class AnalyticsService implements OnStorageReady, OnLock { async getSessionId() { const session = await this.storageService.loadFromSessionStorage( - ANALYTICS_SESSION_KEY + ANALYTICS_SESSION_KEY, ); if (session) { @@ -54,7 +54,7 @@ export class AnalyticsService implements OnStorageReady, OnLock { }; await this.storageService.saveToSessionStorage( ANALYTICS_SESSION_KEY, - newSession + newSession, ); return newSession.sessionId; @@ -64,7 +64,7 @@ export class AnalyticsService implements OnStorageReady, OnLock { // get cache first since it's already decrypted const cachedState = await this.storageService.loadFromSessionStorage( - ANALYTICS_STORAGE_KEY + ANALYTICS_STORAGE_KEY, ); if (cachedState) { return cachedState; @@ -72,13 +72,13 @@ export class AnalyticsService implements OnStorageReady, OnLock { try { const state = await this.storageService.load( - ANALYTICS_STORAGE_KEY + ANALYTICS_STORAGE_KEY, ); if (state) { await this.cacheAnalyticsIds(state); } return state; - } catch (_) { + } catch (_err) { // catch storage not ready errors return; } @@ -87,7 +87,7 @@ export class AnalyticsService implements OnStorageReady, OnLock { async initIds(storeInStorage: boolean) { const analyticsUnencryptedState: AnalyticsUnencryptedState | undefined = await this.storageService.loadUnencrypted( - ANALYTICS_UNENCRYPTED_STORAGE_KEY + ANALYTICS_UNENCRYPTED_STORAGE_KEY, ); const savedDeviceId = analyticsUnencryptedState?.deviceId; @@ -104,7 +104,7 @@ export class AnalyticsService implements OnStorageReady, OnLock { ANALYTICS_UNENCRYPTED_STORAGE_KEY, { deviceId: state.deviceId, - } + }, ); } @@ -118,7 +118,7 @@ export class AnalyticsService implements OnStorageReady, OnLock { async saveTemporaryAnalyticsIds() { const state = await this.storageService.loadFromSessionStorage( - ANALYTICS_STORAGE_KEY + ANALYTICS_STORAGE_KEY, ); if (!state) { throw new Error('temporary analytics Ids not found'); @@ -130,14 +130,14 @@ export class AnalyticsService implements OnStorageReady, OnLock { private async cacheAnalyticsIds(state: AnalyticsState) { await this.storageService.saveToSessionStorage( ANALYTICS_STORAGE_KEY, - state + state, ); } async getUnencryptedDeviceId() { const analyticsUnencryptedState = await this.storageService.loadUnencrypted( - ANALYTICS_UNENCRYPTED_STORAGE_KEY + ANALYTICS_UNENCRYPTED_STORAGE_KEY, ); return analyticsUnencryptedState?.deviceId; @@ -148,7 +148,7 @@ export class AnalyticsService implements OnStorageReady, OnLock { ANALYTICS_UNENCRYPTED_STORAGE_KEY, { deviceId, - } + }, ); } diff --git a/src/background/services/analytics/AnalyticsServicePosthog.test.ts b/src/background/services/analytics/AnalyticsServicePosthog.test.ts index cb9d39395..0e7e14c4d 100644 --- a/src/background/services/analytics/AnalyticsServicePosthog.test.ts +++ b/src/background/services/analytics/AnalyticsServicePosthog.test.ts @@ -44,7 +44,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { featureFlags: { [FeatureGates.EVENTS]: enabled, }, - } as FeatureFlagService); + }) as FeatureFlagService; const buildAnalyticsService = (hasData = true) => ({ @@ -54,10 +54,10 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { deviceId: 'deviceId', userId: 'userId', } - : undefined + : undefined, ), getSessionId: jest.fn().mockResolvedValueOnce('sessionId'), - } as unknown as AnalyticsService); + }) as unknown as AnalyticsService; const buildSettingsService = (hasConsent = true) => ({ @@ -66,7 +66,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { ? AnalyticsConsent.Approved : AnalyticsConsent.Denied, }), - } as unknown as SettingsService); + }) as unknown as SettingsService; describe('.captureEncryptedEvent()', () => { const encryptedData = { @@ -83,7 +83,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { const service = new AnalyticsServicePosthog( buildFlagsService(), buildAnalyticsService(), - buildSettingsService() + buildSettingsService(), ); await service.captureEncryptedEvent(dummyEvent); @@ -94,7 +94,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { // Expect request body to contain encrypted data expect(requestBody.properties).toEqual( - expect.objectContaining(encryptedData) + expect.objectContaining(encryptedData), ); // Expect request body NOT TO contain unencrypted data @@ -112,7 +112,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { service = new AnalyticsServicePosthog( buildFlagsService(), buildAnalyticsService(), - buildSettingsService(false) + buildSettingsService(false), ); }); @@ -137,7 +137,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { service = new AnalyticsServicePosthog( buildFlagsService(false), buildAnalyticsService(), - buildSettingsService() + buildSettingsService(), ); }); @@ -162,7 +162,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { service = new AnalyticsServicePosthog( buildFlagsService(), buildAnalyticsService(false), - buildSettingsService() + buildSettingsService(), ); }); @@ -177,7 +177,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { expect(sentryCaptureException).toHaveBeenCalledWith( new Error('Analytics State is not available.'), - SentryExceptionTypes.ANALYTICS + SentryExceptionTypes.ANALYTICS, ); }); }); @@ -193,7 +193,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { service = new AnalyticsServicePosthog( buildFlagsService(), buildAnalyticsService(false), - buildSettingsService() + buildSettingsService(), ); }); @@ -208,7 +208,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { expect(sentryCaptureException).toHaveBeenCalledWith( new Error('Analytics State is not available.'), - SentryExceptionTypes.ANALYTICS + SentryExceptionTypes.ANALYTICS, ); }); }); @@ -226,7 +226,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { service = new AnalyticsServicePosthog( buildFlagsService(), buildAnalyticsService(), - buildSettingsService() + buildSettingsService(), ); }); @@ -240,7 +240,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { chainId: BlockchainId.P_CHAIN, }), }), - { headers: { 'Content-Type': 'application/json' } } + { headers: { 'Content-Type': 'application/json' } }, ); }); it('should report expected the chainId: AVALANCHE_TEST_P', async () => { @@ -253,7 +253,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { chainId: BlockchainId.P_CHAIN_TESTNET, }), }), - { headers: { 'Content-Type': 'application/json' } } + { headers: { 'Content-Type': 'application/json' } }, ); }); it('should report expected the chainId: AVALANCHE_X', async () => { @@ -266,7 +266,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { chainId: BlockchainId.X_CHAIN, }), }), - { headers: { 'Content-Type': 'application/json' } } + { headers: { 'Content-Type': 'application/json' } }, ); }); it('should report expected the chainId: AVALANCHE_TEST_X', async () => { @@ -279,7 +279,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { chainId: BlockchainId.X_CHAIN_TESTNET, }), }), - { headers: { 'Content-Type': 'application/json' } } + { headers: { 'Content-Type': 'application/json' } }, ); }); it('should report expected the chainId', async () => { @@ -292,7 +292,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { chainId: ChainId.AVALANCHE_MAINNET_ID, }), }), - { headers: { 'Content-Type': 'application/json' } } + { headers: { 'Content-Type': 'application/json' } }, ); }); }); @@ -301,7 +301,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { const service = new AnalyticsServicePosthog( buildFlagsService(), buildAnalyticsService(), - buildSettingsService() + buildSettingsService(), ); await service.captureEvent(dummyEvent); @@ -315,7 +315,7 @@ describe('src/background/services/analytics/AnalyticsServicePosthog', () => { ...dummyEvent.properties, }), }), - { headers: { 'Content-Type': 'application/json' } } + { headers: { 'Content-Type': 'application/json' } }, ); }); }); diff --git a/src/background/services/analytics/AnalyticsServicePosthog.ts b/src/background/services/analytics/AnalyticsServicePosthog.ts index c11e961e5..2eef780d2 100644 --- a/src/background/services/analytics/AnalyticsServicePosthog.ts +++ b/src/background/services/analytics/AnalyticsServicePosthog.ts @@ -16,14 +16,14 @@ import { ChainId } from '@avalabs/core-chains-sdk'; @singleton() export class AnalyticsServicePosthog { private http = new HttpClient( - process.env.POSTHOG_URL || 'https://data-posthog.avax-test.network' + process.env.POSTHOG_URL || 'https://data-posthog.avax-test.network', ); private reportedDeviceId; constructor( private featureFlagService: FeatureFlagService, private analyticsService: AnalyticsService, - private settingsService: SettingsService + private settingsService: SettingsService, ) {} /** @@ -68,7 +68,7 @@ export class AnalyticsServicePosthog { ? await this.prepProperties( event.windowId, event.properties, - useEncryption + useEncryption, ) : {}; @@ -105,7 +105,7 @@ export class AnalyticsServicePosthog { private getFeatureFlagsData() { const activeFeatureFlags = Object.keys( - this.featureFlagService.featureFlags + this.featureFlagService.featureFlags, ); const reducer = (accumulated, current) => { @@ -137,7 +137,7 @@ export class AnalyticsServicePosthog { private async prepProperties( windowId: string, properties: Record, - useEncryption = false + useEncryption = false, ) { const userEnv = await getUserEnvironment(); @@ -147,7 +147,7 @@ export class AnalyticsServicePosthog { if (Object.keys(properties).includes('networkChainId')) { properties.networkChainId = this.updateChainIdIfNeeded( - properties.networkChainId + properties.networkChainId, ); } diff --git a/src/background/services/analytics/events/analyticsStateUpdatedEvent.ts b/src/background/services/analytics/events/analyticsStateUpdatedEvent.ts index 45ba0e866..73e2c2f1d 100644 --- a/src/background/services/analytics/events/analyticsStateUpdatedEvent.ts +++ b/src/background/services/analytics/events/analyticsStateUpdatedEvent.ts @@ -18,7 +18,7 @@ export class AnalyticsUpdatedEvents implements ExtensionEventEmitter { name: AnalyticsEvents.ANALYTICS_STATE_UPDATED, value: contacts, }); - } + }, ); } @@ -27,7 +27,7 @@ export class AnalyticsUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/analytics/events/listeners.ts b/src/background/services/analytics/events/listeners.ts index 914a5fd0f..03b98db3c 100644 --- a/src/background/services/analytics/events/listeners.ts +++ b/src/background/services/analytics/events/listeners.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { AnalyticsState, AnalyticsEvents } from '../models'; export function analyticsStateUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === AnalyticsEvents.ANALYTICS_STATE_UPDATED; } diff --git a/src/background/services/analytics/handlers/captureAnalyticsEvent.test.ts b/src/background/services/analytics/handlers/captureAnalyticsEvent.test.ts index 4dd4f4ebe..4607ae194 100644 --- a/src/background/services/analytics/handlers/captureAnalyticsEvent.test.ts +++ b/src/background/services/analytics/handlers/captureAnalyticsEvent.test.ts @@ -30,7 +30,7 @@ describe('background/services/analytics/handlers/captureAnalyticsEvent', () => { it('captures event', async () => { const handler = new CaptureAnalyticsEventHandler( analyticsServicePosthogMock, - featureFlagServiceMock + featureFlagServiceMock, ); const request = { @@ -44,14 +44,14 @@ describe('background/services/analytics/handlers/captureAnalyticsEvent', () => { expect(result).toEqual({ ...request, result: null }); expect(analyticsServicePosthogMock.captureEvent).toHaveBeenCalledTimes(1); expect(analyticsServicePosthogMock.captureEvent).toHaveBeenCalledWith( - mockEvent + mockEvent, ); }); it('uses encryption when requested', async () => { const handler = new CaptureAnalyticsEventHandler( analyticsServicePosthogMock, - featureFlagServiceMock + featureFlagServiceMock, ); const request = { @@ -64,10 +64,10 @@ describe('background/services/analytics/handlers/captureAnalyticsEvent', () => { expect(result).toEqual({ ...request, result: null }); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenCalledTimes(1); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenCalledWith(mockEvent); }); @@ -80,7 +80,7 @@ describe('background/services/analytics/handlers/captureAnalyticsEvent', () => { ...featureFlagServiceMock.featureFlags, [FeatureGates.EVENTS]: false, }, - } + }, ); const request = { @@ -98,11 +98,11 @@ describe('background/services/analytics/handlers/captureAnalyticsEvent', () => { it('returns error when tracking fails', async () => { const handler = new CaptureAnalyticsEventHandler( analyticsServicePosthogMock, - featureFlagServiceMock + featureFlagServiceMock, ); (analyticsServicePosthogMock.captureEvent as jest.Mock).mockRejectedValue( - new Error('some error') + new Error('some error'), ); const request = { diff --git a/src/background/services/analytics/handlers/captureAnalyticsEvent.ts b/src/background/services/analytics/handlers/captureAnalyticsEvent.ts index eacb0f050..381b61a35 100644 --- a/src/background/services/analytics/handlers/captureAnalyticsEvent.ts +++ b/src/background/services/analytics/handlers/captureAnalyticsEvent.ts @@ -18,7 +18,7 @@ export class CaptureAnalyticsEventHandler implements HandlerType { constructor( private analyticsServicePosthog: AnalyticsServicePosthog, - private featureFlagService: FeatureFlagService + private featureFlagService: FeatureFlagService, ) {} handle: HandlerType['handle'] = async ({ request }) => { diff --git a/src/background/services/analytics/utils/encryptAnalyticsData.test.ts b/src/background/services/analytics/utils/encryptAnalyticsData.test.ts index 7cb621028..2b8d8641d 100644 --- a/src/background/services/analytics/utils/encryptAnalyticsData.test.ts +++ b/src/background/services/analytics/utils/encryptAnalyticsData.test.ts @@ -32,7 +32,7 @@ describe('src/background/services/analytics/utils/encryptAnalyticsData', () => { it('raises an error', async () => { await expect(encryptAnalyticsData('heyo')).rejects.toThrow( - 'Encryption setting missing' + 'Encryption setting missing', ); }); }); @@ -60,7 +60,7 @@ describe('src/background/services/analytics/utils/encryptAnalyticsData', () => { const result = await encryptAnalyticsData('heyo'); expect( - DhkemP521HkdfSha512.prototype.deserializePublicKey + DhkemP521HkdfSha512.prototype.deserializePublicKey, ).toHaveBeenCalledWith(Buffer.from(publicKey, 'base64')); expect(CipherSuite.prototype.createSenderContext).toHaveBeenCalledWith({ diff --git a/src/background/services/analytics/utils/encryptAnalyticsData.ts b/src/background/services/analytics/utils/encryptAnalyticsData.ts index 653ab3264..c2bdc5cad 100644 --- a/src/background/services/analytics/utils/encryptAnalyticsData.ts +++ b/src/background/services/analytics/utils/encryptAnalyticsData.ts @@ -12,7 +12,7 @@ const suite = new CipherSuite({ }); export async function encryptAnalyticsData( - message: string + message: string, ): Promise<{ data: string; enc: string; keyID: string }> { if ( !process.env.ANALYTICS_ENCRYPTION_KEY || @@ -22,7 +22,7 @@ export async function encryptAnalyticsData( } const publicKey = await suite.kem.deserializePublicKey( - Buffer.from(process.env.ANALYTICS_ENCRYPTION_KEY, 'base64') + Buffer.from(process.env.ANALYTICS_ENCRYPTION_KEY, 'base64'), ); const sender = await suite.createSenderContext({ diff --git a/src/background/services/approvals/ApprovalService.test.ts b/src/background/services/approvals/ApprovalService.test.ts index 27775aeae..b0f534cba 100644 --- a/src/background/services/approvals/ApprovalService.test.ts +++ b/src/background/services/approvals/ApprovalService.test.ts @@ -38,7 +38,7 @@ describe('src/background/services/approvals/ApprovalService', () => { await service.requestApproval(action, 'sign/transaction'); expect(openExtensionNewWindow).toHaveBeenCalledWith( - `sign/transaction?actionId=${actionId}` + `sign/transaction?actionId=${actionId}`, ); expect(actionsService.addAction).toHaveBeenCalledWith({ ...action, diff --git a/src/background/services/approvals/events/approvalEventFilters.ts b/src/background/services/approvals/events/approvalEventFilters.ts index b0b4ae607..fa8bca0bb 100644 --- a/src/background/services/approvals/events/approvalEventFilters.ts +++ b/src/background/services/approvals/events/approvalEventFilters.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { ApprovalEvent, ApprovalRequest } from '../models'; export function isApprovalRequest( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return evt?.name === ApprovalEvent.ApprovalRequested; } diff --git a/src/background/services/approvals/events/approvalEvents.ts b/src/background/services/approvals/events/approvalEvents.ts index d024ea637..cdf780148 100644 --- a/src/background/services/approvals/events/approvalEvents.ts +++ b/src/background/services/approvals/events/approvalEvents.ts @@ -20,7 +20,7 @@ export class ApprovalEvents implements ExtensionEventEmitter { name: ApprovalEvent.ApprovalRequested, value, }); - } + }, ); } @@ -29,7 +29,7 @@ export class ApprovalEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/balances/BalanceAggregatorService.test.ts b/src/background/services/balances/BalanceAggregatorService.test.ts index ec715bf1d..f290c5bc6 100644 --- a/src/background/services/balances/BalanceAggregatorService.test.ts +++ b/src/background/services/balances/BalanceAggregatorService.test.ts @@ -23,7 +23,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { () => new Promise((res) => { return res; - }) + }), ); const balancesServiceMock = { getBalancesForNetwork: jest.fn(), @@ -182,7 +182,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { } else if (network.chainId === network2.chainId) { return Promise.resolve(balanceForNetwork2); } - } + }, ); // eslint-disable-next-line @@ -199,7 +199,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { networkServiceMock, lockService, storageService, - settingsServiceMock + settingsServiceMock, ); }); @@ -207,14 +207,14 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { await service.getBalancesForNetworks( [network1.chainId], [account1], - [TokenType.NATIVE] + [TokenType.NATIVE], ); expect(balancesServiceMock.getBalancesForNetwork).toBeCalledTimes(1); expect(balancesServiceMock.getBalancesForNetwork).toBeCalledWith( network1, [account1], [TokenType.NATIVE], - undefined + undefined, ); }); @@ -238,11 +238,11 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { await service.getBalancesForNetworks( [network1.chainId], [account2], - [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721] + [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721], ); expect(balancesServiceMock.getBalancesForNetwork).toHaveBeenCalledTimes( - 1 + 1, ); expect(service.balances).toEqual({ @@ -257,11 +257,11 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { await service.getBalancesForNetworks( [network1.chainId], [account1], - [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721] + [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721], ); expect(balancesServiceMock.getBalancesForNetwork).toHaveBeenCalledTimes( - 2 + 2, ); expect(service.balances).toEqual({ [network1.chainId]: { @@ -279,7 +279,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { const balances = await service.getBalancesForNetworks( [network1.chainId, network2.chainId], [account1], - [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721] + [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721], ); expect(balancesServiceMock.getBalancesForNetwork).toBeCalledTimes(2); const expected = { @@ -309,7 +309,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { const result = await service.getBalancesForNetworks( [network1.chainId, network2.chainId], [account1, account2], - [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721] + [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721], ); const expected = { @@ -344,14 +344,14 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { new Promise((res) => setTimeout(() => { res(balanceForNetwork1); - }, 500) - ) + }, 500), + ), ); const updatePromise = service.getBalancesForNetworks( [network1.chainId], [account1], - [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721] + [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721], ); // eslint-disable-next-line @@ -373,7 +373,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { await service.getBalancesForNetworks( [network1.chainId, network2.chainId], [account1], - [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721] + [TokenType.NATIVE, TokenType.ERC20, TokenType.ERC721], ); expect(balancesServiceMock.getBalancesForNetwork).toBeCalledTimes(2); @@ -426,7 +426,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { networkServiceMock, lockService, storageService, - settingsServiceMock + settingsServiceMock, ); }); @@ -452,7 +452,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { it('should skip the load from the cache because of there are data in the memory', async () => { balancesServiceMock.getBalancesForNetwork.mockResolvedValueOnce( - balanceForNetwork2 + balanceForNetwork2, ); const cachedBalances = { [network2.chainId]: balanceForNetwork1 }; @@ -525,7 +525,7 @@ describe('src/background/services/balances/BalanceAggregatorService.ts', () => { // Fresh balances include only one account (account1) and the values for it DID NOT change balancesServiceMock.getBalancesForNetwork.mockResolvedValueOnce( - balanceForNetwork2 + balanceForNetwork2, ); const updatesListener = jest.fn(); diff --git a/src/background/services/balances/BalanceAggregatorService.ts b/src/background/services/balances/BalanceAggregatorService.ts index e2b87f1ec..0e9502b82 100644 --- a/src/background/services/balances/BalanceAggregatorService.ts +++ b/src/background/services/balances/BalanceAggregatorService.ts @@ -49,21 +49,21 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { private networkService: NetworkService, private lockService: LockService, private storageService: StorageService, - private settingsService: SettingsService + private settingsService: SettingsService, ) {} async getBalancesForNetworks( chainIds: number[], accounts: Account[], tokenTypes: TokenType[], - cacheResponse = true + cacheResponse = true, ): Promise<{ tokens: Balances; nfts: Balances }> { const sentryTracker = Sentry.startTransaction({ name: 'BalanceAggregatorService: getBatchedUpdatedBalancesForNetworks', }); const networks = Object.values( - await this.networkService.activeNetworks.promisify() + await this.networkService.activeNetworks.promisify(), ).filter((network) => chainIds.includes(network.chainId)); const priceChangesData = await this.getPriceChangesData(); @@ -75,14 +75,14 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { network, accounts, tokenTypes, - priceChangesData + priceChangesData, ); return { chainId: network.chainId, networkBalances, }; - }) + }), ); const updatedNetworks = updateRequests @@ -97,7 +97,7 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { const fetchedAddresses = Object.keys(networkBalances); const cachedBalances = pick( this.balances[chainId] ?? {}, - fetchedAddresses + fetchedAddresses, ); return !isEqual(networkBalances, cachedBalances); @@ -117,7 +117,7 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { return balances; }, - { tokens: {}, nfts: {} } + { tokens: {}, nfts: {} }, ); // NFTs don't have balance = 0, if they are sent they should be removed @@ -181,7 +181,7 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { .currency; const changesData = await this.storageService.loadUnencrypted( - `${TOKENS_PRICE_DATA}-${selectedCurrency}` + `${TOKENS_PRICE_DATA}-${selectedCurrency}`, ); const lastUpdated = changesData?.lastUpdatedAt; @@ -195,8 +195,8 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { ) { const [priceChangesResult] = await resolve( fetch( - `${process.env.PROXY_URL}/watchlist/tokens?currency=${selectedCurrency}` - ) + `${process.env.PROXY_URL}/watchlist/tokens?currency=${selectedCurrency}`, + ), ); if (!priceChangesResult) { @@ -213,7 +213,7 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { }, }; }, - {} + {}, ); priceChangesData = { ...tokensData }; @@ -224,7 +224,7 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { priceChanges: tokensData, lastUpdatedAt: Date.now(), currency: selectedCurrency, - } + }, ); } return priceChangesData; @@ -275,7 +275,7 @@ export class BalanceAggregatorService implements OnLock, OnUnlock { addListener( event: BalanceServiceEvents, - callback: (data: T) => void + callback: (data: T) => void, ) { this.#eventEmitter.on(event, callback); } diff --git a/src/background/services/balances/BalancePollingService.test.ts b/src/background/services/balances/BalancePollingService.test.ts index eb376a95b..52c70327c 100644 --- a/src/background/services/balances/BalancePollingService.test.ts +++ b/src/background/services/balances/BalancePollingService.test.ts @@ -43,13 +43,13 @@ describe('src/background/services/balances/BalancePollingService.ts', () => { account, activeNetworkId, roundRobinChainIds, - tokenTypes + tokenTypes, ); }); it('polls for active and favorite networks on the first run', () => { expect( - aggregatorServiceMock.getBalancesForNetworks + aggregatorServiceMock.getBalancesForNetworks, ).toHaveBeenLastCalledWith([1, 2, 3, 4], expect.anything(), tokenTypes); }); @@ -59,7 +59,7 @@ describe('src/background/services/balances/BalancePollingService.ts', () => { expect( ( aggregatorServiceMock.getBalancesForNetworks as jest.Mock - ).mock.calls.every(([chainIds]) => chainIds.includes(1)) + ).mock.calls.every(([chainIds]) => chainIds.includes(1)), ).toBe(true); }); diff --git a/src/background/services/balances/BalancePollingService.ts b/src/background/services/balances/BalancePollingService.ts index f8009c81f..a6f71c57d 100644 --- a/src/background/services/balances/BalancePollingService.ts +++ b/src/background/services/balances/BalancePollingService.ts @@ -30,7 +30,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { account: Account, activeChainId: number, roundRobinChainIds: number[], - tokenTypes: TokenType[] + tokenTypes: TokenType[], ) { // Stop any polling that may be occurring already this.stopPolling(); @@ -39,7 +39,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { account, activeChainId, roundRobinChainIds, - tokenTypes + tokenTypes, ); } @@ -59,7 +59,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { account: Account, activeChainId: number, roundRobinChainIds: number[], - tokenTypes: TokenType[] + tokenTypes: TokenType[], ) { const thisPollingStartedAt = performance.now(); this.#lastPollingStartedAt = thisPollingStartedAt; @@ -69,7 +69,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { ...this.getNetworksToUpdate( roundRobinChainIds, this.#pollingIteration, - 15 + 15, ), ]); @@ -77,7 +77,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { await this.balanceAggregator.getBalancesForNetworks( chainIds, [account], - tokenTypes + tokenTypes, ); } catch { // Do nothing, just schedule another attempt @@ -90,7 +90,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { account, activeChainId, roundRobinChainIds, - tokenTypes + tokenTypes, ); } } @@ -99,7 +99,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { account: Account, activeChainId: number, roundRobinChainIds: number[], - tokenTypes: TokenType[] + tokenTypes: TokenType[], ) { this.#pollingIteration += 1; this.#timer = setTimeout( @@ -108,27 +108,27 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { account, activeChainId, roundRobinChainIds, - tokenTypes + tokenTypes, ), - BalancePollingService.INTERVAL + BalancePollingService.INTERVAL, ); } private getNetworksToUpdate( networkIds: number[], iteration: number, - updatePeriod: number + updatePeriod: number, ) { // Always load all chains for the first request. if (iteration === 0) { return networkIds; } const numberOfNetworksToUpdate = Math.ceil( - networkIds.length / updatePeriod + networkIds.length / updatePeriod, ); const roundsWithUpdates = Math.ceil( - networkIds.length / numberOfNetworksToUpdate + networkIds.length / numberOfNetworksToUpdate, ); if (iteration % updatePeriod < roundsWithUpdates) { @@ -138,7 +138,7 @@ export class BalancePollingService implements OnLock, OnAllExtensionClosed { return networkIds.slice( startIndex, - startIndex + numberOfNetworksToUpdate + startIndex + numberOfNetworksToUpdate, ); } diff --git a/src/background/services/balances/BalancesService.test.ts b/src/background/services/balances/BalancesService.test.ts index a0c1dc2b6..8d522264f 100644 --- a/src/background/services/balances/BalancesService.test.ts +++ b/src/background/services/balances/BalancesService.test.ts @@ -209,7 +209,7 @@ describe('src/background/services/balances/BalancesService.ts', () => { const result = await service.getBalancesForNetwork( network as any, [account], - [] + [], ); expect(result).toEqual({ @@ -240,7 +240,7 @@ describe('src/background/services/balances/BalancesService.ts', () => { const result = await service.getBalancesForNetwork( network, [account], - [] + [], ); expect(result).toEqual({ @@ -293,7 +293,7 @@ describe('src/background/services/balances/BalancesService.ts', () => { const result = await service.getBalancesForNetwork( network, [account], - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); expect(result).toEqual({ @@ -325,7 +325,7 @@ describe('src/background/services/balances/BalancesService.ts', () => { const result = await service.getBalancesForNetwork( network, [account], - [] + [], ); expect(result).toEqual({ @@ -360,7 +360,7 @@ describe('src/background/services/balances/BalancesService.ts', () => { [], { test2: { priceChangePercentage: 25 }, - } + }, ); expect(result).toEqual({ diff --git a/src/background/services/balances/BalancesService.ts b/src/background/services/balances/BalancesService.ts index 361676455..4d4d08044 100644 --- a/src/background/services/balances/BalancesService.ts +++ b/src/background/services/balances/BalancesService.ts @@ -19,14 +19,14 @@ const cacheStorage = new LRUCache({ max: 100, ttl: 60 * 1000 }); export class BalancesService { constructor( private settingsService: SettingsService, - private moduleManager: ModuleManager + private moduleManager: ModuleManager, ) {} async getBalancesForNetwork( network: NetworkWithCaipId, accounts: Account[], tokenTypes: TokenType[], - priceChanges?: TokensPriceShortData + priceChanges?: TokensPriceShortData, ): Promise>> { const sentryTracker = Sentry.startTransaction( { @@ -34,14 +34,14 @@ export class BalancesService { }, { network: network.caipId, - } + }, ); const module = await this.moduleManager.loadModuleByNetwork(network); const settings = await this.settingsService.getSettings(); const currency = settings.currency.toLowerCase(); const customTokens = Object.values( - settings.customTokens[network.chainId] ?? {} + settings.customTokens[network.chainId] ?? {}, ).map((t) => ({ ...t, type: TokenType.ERC20 as const })); const rawBalances = await module.getBalances({ @@ -75,7 +75,7 @@ export class BalancesService { const balances = Object.keys(rawBalances).reduce( ( accountBalances, - accountKey + accountKey, ): Record> => { const rawAccountTokenList = rawBalances[accountKey]; if (!rawAccountTokenList || rawAccountTokenList?.error) { @@ -98,16 +98,16 @@ export class BalancesService { priceChanges: getPriceChangeValues( tokenBalance.symbol, tokenBalance.balanceInCurrency, - priceChanges + priceChanges, ), }, }; }, - {} + {}, ), }; }, - {} + {}, ); sentryTracker.finish(); diff --git a/src/background/services/balances/TokenPricesService.ts b/src/background/services/balances/TokenPricesService.ts index 8c0cda9d9..e9fb08689 100644 --- a/src/background/services/balances/TokenPricesService.ts +++ b/src/background/services/balances/TokenPricesService.ts @@ -33,7 +33,7 @@ export class TokenPricesService { */ async getPriceByCoinId( coinId: string, - selectedCurrency: string + selectedCurrency: string, ): Promise { const currencyCode = selectedCurrency.toLowerCase() as any; const cacheKey = `getPriceByCoinId-${coinId}-${selectedCurrency}`; @@ -58,7 +58,7 @@ export class TokenPricesService { async getTokenPriceByAddress( address: string, assetPlatformId: string, - coinId: string + coinId: string, ): Promise> { const selectedCurrency = (await this.settingsService.getSettings()) .currency; @@ -71,7 +71,7 @@ export class TokenPricesService { [address], selectedCurrency.toLowerCase(), avaxPrice || 0, - assetPlatformId + assetPlatformId, ); tokenPriceResponseCache.set(cacheKey, result); return result; @@ -86,19 +86,19 @@ export class TokenPricesService { async getTokenPricesByAddresses( tokens: { address: string }[], assetPlatformId: string, - coinId: string + coinId: string, ): Promise> { const selectedCurrency = (await this.settingsService.getSettings()) .currency; const cacheKey = `getTokenPricesByAddresses-${coinId}-${selectedCurrency}-${assetPlatformId}-${tokens.map( - ({ address }) => address + ({ address }) => address, )}`; const cacheResult = tokenPriceResponseCache.get>(cacheKey); if (cacheResult) return cacheResult; const nativeTokenPrice = await this.getPriceByCoinId( coinId, - selectedCurrency + selectedCurrency, ); const tokenAddys = tokens.map((token) => token.address); const currency = selectedCurrency.toLocaleLowerCase(); @@ -106,7 +106,7 @@ export class TokenPricesService { tokenAddys, currency, nativeTokenPrice || 0, - assetPlatformId + assetPlatformId, ); tokenPriceResponseCache.set(cacheKey, result); return result; diff --git a/src/background/services/balances/events/balancesUpdatedEvent.ts b/src/background/services/balances/events/balancesUpdatedEvent.ts index 110c2e2c6..dfd4884dd 100644 --- a/src/background/services/balances/events/balancesUpdatedEvent.ts +++ b/src/background/services/balances/events/balancesUpdatedEvent.ts @@ -26,7 +26,7 @@ export class BalancesUpdatedEvents implements ExtensionEventEmitter { name: BalanceServiceEvents.UPDATED, value: balancesData, }); - } + }, ); } @@ -35,7 +35,7 @@ export class BalancesUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/balances/events/balancesUpdatedEventListener.ts b/src/background/services/balances/events/balancesUpdatedEventListener.ts index 411f10b09..599860a08 100644 --- a/src/background/services/balances/events/balancesUpdatedEventListener.ts +++ b/src/background/services/balances/events/balancesUpdatedEventListener.ts @@ -3,7 +3,7 @@ import { BalanceServiceEvents } from '../models'; import { BalancesInfo } from './balancesUpdatedEvent'; export function balancesUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === BalanceServiceEvents.UPDATED; } diff --git a/src/background/services/balances/handlers/getAvaxBalance.ts b/src/background/services/balances/handlers/getAvaxBalance.ts index d49bddf00..a2126e45a 100644 --- a/src/background/services/balances/handlers/getAvaxBalance.ts +++ b/src/background/services/balances/handlers/getAvaxBalance.ts @@ -20,7 +20,7 @@ export class GetAvaxBalanceHandler implements HandlerType { constructor( private networkService: NetworkService, - private balancesService: BalancesService + private balancesService: BalancesService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -51,7 +51,7 @@ export class GetAvaxBalanceHandler implements HandlerType { addressBTC: '', }, ], - [TokenType.NATIVE] + [TokenType.NATIVE], ); const nativeTokenWithBalance = diff --git a/src/background/services/balances/handlers/getTokenPrice.ts b/src/background/services/balances/handlers/getTokenPrice.ts index f694dfb5d..d1a9e2d02 100644 --- a/src/background/services/balances/handlers/getTokenPrice.ts +++ b/src/background/services/balances/handlers/getTokenPrice.ts @@ -16,7 +16,7 @@ export class GetTokenPriceHandler implements HandlerType { constructor( private tokenPricesService: TokenPricesService, - private settingsService: SettingsService + private settingsService: SettingsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -28,7 +28,7 @@ export class GetTokenPriceHandler implements HandlerType { ...request, result: await this.tokenPricesService.getPriceByCoinId( tokenId, - settings.currency + settings.currency, ), }; }; diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.test.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.test.ts index 170786798..71ba1c849 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.test.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.test.ts @@ -80,7 +80,7 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts glacierService, networkService, accountsService, - balanceAggregatorService + balanceAggregatorService, ); const handleRequest = (walletId: string) => @@ -91,7 +91,7 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts params: { walletId, }, - }) + }), ); const mockEnv = (isMainnet = true) => { @@ -125,7 +125,7 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts addressBTC: `${id}-addressBTC`, ...opts, type: opts.type ?? AccountType.PRIMARY, - } as T); + }) as T; const ACCOUNT_IMPORTED_0 = buildAccount({ id: 'imported-0', @@ -182,7 +182,7 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts secondCallBalances?: { P: Balances[keyof Balances]; X: Balances[keyof Balances]; - } + }, ) => { balanceAggregatorService.getBalancesForNetworks.mockResolvedValue({ nfts: {}, @@ -267,14 +267,14 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts const response = await handleRequest(IMPORTED_ACCOUNTS_WALLET_ID); expect(response.error).toBeUndefined(); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledTimes(1); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledWith( expect.any(Array), [ACCOUNT_IMPORTED_0, ACCOUNT_IMPORTED_1], - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); }); @@ -305,14 +305,14 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts const response = await handleRequest('seedless'); expect(response.error).toBeUndefined(); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledTimes(1); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledWith( expect.any(Array), [ACCOUNT_SEEDLESS], - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); }); @@ -342,7 +342,7 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts expect(getAccountsWithActivity).toHaveBeenCalledWith( 'xpubXP', PROVIDER_XP, - expect.any(Function) + expect.any(Function), ); // Let's also make sure the passed activity fetcher actually invokes the Glacier API: @@ -361,10 +361,10 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts const response = await handleRequest('seedphrase'); expect(response.error).toBeUndefined(); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledTimes(1); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledWith( [ ChainId.AVALANCHE_MAINNET_ID, @@ -374,7 +374,7 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts ChainId.ETHEREUM_HOMESTEAD, ], [ACCOUNT_SEED_0, ACCOUNT_SEED_1], - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); expect(response.result).toEqual({ @@ -391,10 +391,10 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts const response = await handleRequest('seedphrase'); expect(response.error).toBeUndefined(); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledTimes(1); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledWith( [ ChainId.AVALANCHE_TESTNET_ID, @@ -404,7 +404,7 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts ChainId.ETHEREUM_TEST_SEPOLIA, ], [ACCOUNT_SEED_0, ACCOUNT_SEED_1], - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); expect(response.result).toEqual({ @@ -435,10 +435,10 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts // Fetching balances of derived accounts expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledTimes(2); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenNthCalledWith( 1, [ @@ -449,21 +449,21 @@ describe('background/services/balances/handlers/getTotalBalanceForWallet.test.ts ChainId.ETHEREUM_HOMESTEAD, ], [ACCOUNT_LEDGER_0, ACCOUNT_LEDGER_1], - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); // Fetching XP balances of underived accounts, without caching expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenCalledTimes(2); expect( - balanceAggregatorService.getBalancesForNetworks + balanceAggregatorService.getBalancesForNetworks, ).toHaveBeenNthCalledWith( 2, [ChainId.AVALANCHE_P, ChainId.AVALANCHE_X], [{ addressPVM: `P-${xpAddress}`, addressAVM: `X-${xpAddress}` }], [TokenType.NATIVE], - false + false, ); expect(response.result).toEqual({ diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.ts index 49288cfd7..4dd53f500 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/getTotalBalanceForWallet.ts @@ -40,7 +40,7 @@ export class GetTotalBalanceForWalletHandler implements HandlerType { private glacierService: GlacierService, private networkService: NetworkService, private accountsService: AccountsService, - private balanceAggregatorService: BalanceAggregatorService + private balanceAggregatorService: BalanceAggregatorService, ) {} #getAddressesActivity = (addresses: string[]) => @@ -50,22 +50,21 @@ export class GetTotalBalanceForWalletHandler implements HandlerType { }); async #findUnderivedAccounts(walletId: string, derivedAccounts: Account[]) { - const secrets = await this.secretService.getWalletAccountsSecretsById( - walletId - ); + const secrets = + await this.secretService.getWalletAccountsSecretsById(walletId); const derivedWalletAddresses = getAllAddressesForAccounts( - derivedAccounts ?? [] + derivedAccounts ?? [], ); const derivedAddressesUnprefixed = derivedWalletAddresses.map((addr) => - addr.replace(/^[PXC]-/i, '') + addr.replace(/^[PXC]-/i, ''), ); const underivedXPChainAddresses = secrets.xpubXP ? ( await getAccountsWithActivity( secrets.xpubXP, await this.networkService.getAvalanceProviderXP(), - this.#getAddressesActivity + this.#getAddressesActivity, ) ).filter((address) => !derivedAddressesUnprefixed.includes(address)) : []; @@ -84,7 +83,7 @@ export class GetTotalBalanceForWalletHandler implements HandlerType { const allAccounts = this.accountsService.getAccounts(); const derivedAccounts = requestsImportedAccounts ? Object.values(allAccounts.imported ?? {}) - : allAccounts.primary[walletId] ?? []; + : (allAccounts.primary[walletId] ?? []); if (!derivedAccounts.length) { return { @@ -103,7 +102,7 @@ export class GetTotalBalanceForWalletHandler implements HandlerType { const networksIncludedInTotal = getIncludedNetworks( this.networkService.isMainnet(), await this.networkService.activeNetworks.promisify(), - await this.networkService.getFavoriteNetworks() + await this.networkService.getFavoriteNetworks(), ); // Get balance for derived addresses @@ -111,13 +110,13 @@ export class GetTotalBalanceForWalletHandler implements HandlerType { await this.balanceAggregatorService.getBalancesForNetworks( networksIncludedInTotal, derivedAccounts, - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); let totalBalanceInCurrency = calculateTotalBalanceForAccounts( derivedAddressesBalances, derivedAccounts, - networksIncludedInTotal + networksIncludedInTotal, ); let hasBalanceOnUnderivedAccounts = false; @@ -131,13 +130,13 @@ export class GetTotalBalanceForWalletHandler implements HandlerType { getXPChainIds(this.networkService.isMainnet()), underivedAccounts as Account[], [TokenType.NATIVE], - false // Don't cache this + false, // Don't cache this ); const underivedAccountsTotal = calculateTotalBalanceForAccounts( underivedAddressesBalances, underivedAccounts, - getXPChainIds(this.networkService.isMainnet()) + getXPChainIds(this.networkService.isMainnet()), ); totalBalanceInCurrency += underivedAccountsTotal; hasBalanceOnUnderivedAccounts = underivedAccountsTotal > 0; diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.test.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.test.ts index 109ca6bfc..ac76c0e28 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.test.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.test.ts @@ -63,7 +63,7 @@ describe('src/background/services/balances/handlers/helpers/calculateTotalBalanc const result = calculateTotalBalanceForAccounts( balances, accounts, - chainIds + chainIds, ); expect(calculateTotalBalance).toHaveBeenCalledTimes(4); @@ -71,25 +71,25 @@ describe('src/background/services/balances/handlers/helpers/calculateTotalBalanc 1, accounts[0], chainIds, - balances + balances, ); expect(calculateTotalBalance).toHaveBeenNthCalledWith( 2, accounts[1], chainIds, - balances + balances, ); expect(calculateTotalBalance).toHaveBeenNthCalledWith( 3, accounts[2], chainIds, - balances + balances, ); expect(calculateTotalBalance).toHaveBeenNthCalledWith( 4, accounts[3], chainIds, - balances + balances, ); expect(result).toEqual(1600); diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.ts index 4b7bdc1a1..4ae728a39 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/calculateTotalBalanceForAccounts.ts @@ -6,7 +6,7 @@ import { Balances } from '../../../models'; export function calculateTotalBalanceForAccounts( balances: Balances, accounts: Partial[], - chainIds: number[] + chainIds: number[], ): number { return accounts.reduce((sum: number, account: Partial) => { const accountBalance = calculateTotalBalance(account, chainIds, balances); diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.test.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.test.ts index 9a9431d9c..cff980c8f 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.test.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.test.ts @@ -18,7 +18,7 @@ describe('src/background/services/balances/handlers/getTotalBalanceForWallet/hel .spyOn(Avalanche, 'getAddressFromXpub') .mockImplementation( (_, index, __, prefix, internal) => - `${prefix}-address${index}/${internal}` + `${prefix}-address${index}/${internal}`, ); jest @@ -55,31 +55,31 @@ describe('src/background/services/balances/handlers/getTotalBalanceForWallet/hel 1, expect.any(Array), mockedActivityFetcher, - 0 + 0, ); expect(processGlacierAddresses).toHaveBeenNthCalledWith( 2, expect.any(Array), mockedActivityFetcher, - 0 + 0, ); expect(processGlacierAddresses).toHaveBeenNthCalledWith( 3, expect.any(Array), mockedActivityFetcher, - 5 + 5, ); expect(processGlacierAddresses).toHaveBeenNthCalledWith( 4, expect.any(Array), mockedActivityFetcher, - 9 + 9, ); }); it('returns the addresses with activity', async () => { expect( - await getAccountsWithActivity(xpubXP, providerXP, mockedActivityFetcher) + await getAccountsWithActivity(xpubXP, providerXP, mockedActivityFetcher), ).toEqual([ 'ext-address-0', 'ext-address-15', diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.ts index 40679ba65..8b2e76469 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getAccountsWithActivity.ts @@ -15,7 +15,7 @@ import { isDone } from './isDone'; export async function getAccountsWithActivity( xpubXP: string, providerXP: Avalanche.JsonRpcProvider, - activityFetcher: AddressActivityFetcher + activityFetcher: AddressActivityFetcher, ) { let externalGap = 0; let internalGap = 0; @@ -30,13 +30,13 @@ export async function getAccountsWithActivity( xpubXP, providerXP, false, - externalStart + externalStart, ); const internal = getAddressesInRange( xpubXP, providerXP, true, - internalStart + internalStart, ); const [externalResult, internalResult] = await Promise.all([ processGlacierAddresses(external, activityFetcher, externalGap), diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getIncludedNetworks.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getIncludedNetworks.ts index fd53907ef..03c972b40 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getIncludedNetworks.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/getIncludedNetworks.ts @@ -6,13 +6,13 @@ import { getDefaultChainIds } from '@src/utils/getDefaultChainIds'; export function getIncludedNetworks( isMainnet: boolean, currentChainList: ChainListWithCaipIds, - favoriteChainIds: number[] + favoriteChainIds: number[], ) { const currentEnvNetworks = Object.keys(currentChainList).map(Number); return uniq( [...getDefaultChainIds(isMainnet), ...favoriteChainIds].filter((chainId) => - currentEnvNetworks.includes(chainId) - ) + currentEnvNetworks.includes(chainId), + ), ); } diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.test.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.test.ts index a91166c04..e3fed294e 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.test.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.test.ts @@ -46,8 +46,8 @@ describe('src/background/services/balances/handlers/getTotalBalanceForWallet/hel await processGlacierAddresses( allAddresses, activityFetcher, - ADDRESS_GAP_LIMIT + 1 - ) + ADDRESS_GAP_LIMIT + 1, + ), ).toEqual({ gap: ADDRESS_GAP_LIMIT + 1, result: [], @@ -76,8 +76,8 @@ describe('src/background/services/balances/handlers/getTotalBalanceForWallet/hel await processGlacierAddresses( allAddresses.slice(-10), mockedActivityFetcher, - currentGap - ) + currentGap, + ), ).toEqual({ gap: currentGap + addressesToProcess.length, result: [], @@ -86,7 +86,7 @@ describe('src/background/services/balances/handlers/getTotalBalanceForWallet/hel it('returns all active addresses and the number of consecutive inactive addresses (gap)', async () => { const activeAddresses = allAddresses.filter((addr) => - startsWith(addr, 'active') + startsWith(addr, 'active'), ); const mockedActivityFetcher = jest.fn().mockResolvedValueOnce({ addresses: activeAddresses.map((address) => ({ @@ -96,7 +96,7 @@ describe('src/background/services/balances/handlers/getTotalBalanceForWallet/hel }); expect( - await processGlacierAddresses(allAddresses, mockedActivityFetcher, 0) + await processGlacierAddresses(allAddresses, mockedActivityFetcher, 0), ).toEqual({ gap: 21, result: activeAddresses, diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.ts index 18cb1c7dc..3ac3cc1bc 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/helpers/processGlacierAddresses.ts @@ -6,7 +6,7 @@ import { isDone } from './isDone'; export async function processGlacierAddresses( addresses: string[], fetchActivity: AddressActivityFetcher, - gap: number + gap: number, ) { if (isDone(gap)) { return { gap, result: [] }; @@ -19,7 +19,7 @@ export async function processGlacierAddresses( ...acc, [addressInfo.address]: addressInfo, }), - {} + {}, ); const result: string[] = []; for (let i = 0; i < addresses.length && !isDone(gap); i++) { diff --git a/src/background/services/balances/handlers/getTotalBalanceForWallet/models.ts b/src/background/services/balances/handlers/getTotalBalanceForWallet/models.ts index 540b7bccb..163dbc6c9 100644 --- a/src/background/services/balances/handlers/getTotalBalanceForWallet/models.ts +++ b/src/background/services/balances/handlers/getTotalBalanceForWallet/models.ts @@ -10,7 +10,7 @@ export type TotalBalanceForWallet = { }; export type AddressActivityFetcher = ( - addresses: string[] + addresses: string[], ) => Promise; export const ITERATION_LIMIT = 10; // Abitrary number to avoid an infinite loop. diff --git a/src/background/services/balances/handlers/refreshNftMetadata.test.ts b/src/background/services/balances/handlers/refreshNftMetadata.test.ts index 8f6726ac9..139dfb746 100644 --- a/src/background/services/balances/handlers/refreshNftMetadata.test.ts +++ b/src/background/services/balances/handlers/refreshNftMetadata.test.ts @@ -24,13 +24,13 @@ describe('background/services/balances/handlers/refreshNftMetadata.ts', () => { id: '123', method: ExtensionRequest.NFT_REFRESH_METADATA, params: ['address', 'chainId', 'tokenId'], - }) + }), ); expect(glacierService.refreshNftMetadata).toHaveBeenCalledWith( 'address', 'chainId', - 'tokenId' + 'tokenId', ); expect(result).toEqual({ diff --git a/src/background/services/balances/handlers/refreshNftMetadata.ts b/src/background/services/balances/handlers/refreshNftMetadata.ts index be81b2ede..e2e37446e 100644 --- a/src/background/services/balances/handlers/refreshNftMetadata.ts +++ b/src/background/services/balances/handlers/refreshNftMetadata.ts @@ -27,7 +27,7 @@ export class RefreshNftMetadataHandler implements HandlerType { const token = await this.glacierService.refreshNftMetadata( address, chainId, - tokenId + tokenId, ); return { diff --git a/src/background/services/balances/handlers/startBalancesPolling.test.ts b/src/background/services/balances/handlers/startBalancesPolling.test.ts index 49455e38d..a6b226292 100644 --- a/src/background/services/balances/handlers/startBalancesPolling.test.ts +++ b/src/background/services/balances/handlers/startBalancesPolling.test.ts @@ -33,7 +33,7 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => it('returns current balances', async () => { const handler = new StartBalancesPollingHandler( balancePollingService, - aggregatorService + aggregatorService, ); const { result } = await handler.handle( @@ -41,7 +41,7 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => id: '123', method: ExtensionRequest.BALANCES_START_POLLING, params: [account, chainIds], - }) + }), ); expect(result).toEqual({ @@ -55,7 +55,7 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => it('starts polling', async () => { const handler = new StartBalancesPollingHandler( balancePollingService, - aggregatorService + aggregatorService, ); const scope = 'eip155:43114'; @@ -67,15 +67,15 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => method: ExtensionRequest.BALANCES_START_POLLING, params: [account, chainIds, [TokenType.ERC20]], }, - scope - ) + scope, + ), ); expect(balancePollingService.startPolling).toHaveBeenCalledWith( account, caipToChainId(scope), chainIds, - [TokenType.ERC20] + [TokenType.ERC20], ); }); }); @@ -95,7 +95,7 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => it('returns current balances', async () => { const handler = new StartBalancesPollingHandler( balancePollingService, - aggregatorService + aggregatorService, ); const { result } = await handler.handle( @@ -103,7 +103,7 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => id: '123', method: ExtensionRequest.BALANCES_START_POLLING, params: [account, chainIds], - }) + }), ); expect(result).toEqual({ @@ -118,7 +118,7 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => it('does not start polling', async () => { const handler = new StartBalancesPollingHandler( balancePollingService, - aggregatorService + aggregatorService, ); await handler.handle( @@ -126,7 +126,7 @@ describe('background/services/balances/handlers/startBalancesPolling.ts', () => id: '123', method: ExtensionRequest.BALANCES_START_POLLING, params: [account, chainIds], - }) + }), ); expect(balancePollingService.startPolling).not.toHaveBeenCalled(); diff --git a/src/background/services/balances/handlers/startBalancesPolling.ts b/src/background/services/balances/handlers/startBalancesPolling.ts index 15ef3fcb1..a493f370e 100644 --- a/src/background/services/balances/handlers/startBalancesPolling.ts +++ b/src/background/services/balances/handlers/startBalancesPolling.ts @@ -26,7 +26,7 @@ export class StartBalancesPollingHandler implements HandlerType { constructor( private pollingService: BalancePollingService, - private aggregatorService: BalanceAggregatorService + private aggregatorService: BalanceAggregatorService, ) {} handle: HandlerType['handle'] = async ({ request, scope }) => { @@ -38,7 +38,7 @@ export class StartBalancesPollingHandler implements HandlerType { account, activeChainId, roundRobinChainIds, - tokenTypes + tokenTypes, ); } diff --git a/src/background/services/balances/handlers/stopBalancesPolling.test.ts b/src/background/services/balances/handlers/stopBalancesPolling.test.ts index c453a429b..9aa3f860b 100644 --- a/src/background/services/balances/handlers/stopBalancesPolling.test.ts +++ b/src/background/services/balances/handlers/stopBalancesPolling.test.ts @@ -19,7 +19,7 @@ describe('background/services/balances/handlers/stopBalancesPolling.ts', () => { buildRpcCall({ id: '123', method: ExtensionRequest.BALANCES_STOP_POLLING, - }) + }), ); expect(balancePollingService.stopPolling).toHaveBeenCalled(); diff --git a/src/background/services/balances/handlers/updateBalancesForNetwork.ts b/src/background/services/balances/handlers/updateBalancesForNetwork.ts index 2e380de9e..469d59aab 100644 --- a/src/background/services/balances/handlers/updateBalancesForNetwork.ts +++ b/src/background/services/balances/handlers/updateBalancesForNetwork.ts @@ -22,7 +22,7 @@ export class UpdateBalancesForNetworkHandler implements HandlerType { constructor( private networkBalancesService: BalanceAggregatorService, private accountsService: AccountsService, - private networkSerice: NetworkService + private networkSerice: NetworkService, ) {} async #getDefaultNetworksToFetch(activeChainId: number) { @@ -63,7 +63,7 @@ export class UpdateBalancesForNetworkHandler implements HandlerType { const balances = await this.networkBalancesService.getBalancesForNetworks( networksToFetch, accountsToFetch, - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ); return { ...request, diff --git a/src/background/services/balances/models.ts b/src/background/services/balances/models.ts index 753814c9c..ad99f9031 100644 --- a/src/background/services/balances/models.ts +++ b/src/background/services/balances/models.ts @@ -69,18 +69,18 @@ export class GlacierUnhealthyError extends Error { } export const hasUnconfirmedBTCBalance = ( - token?: TokenWithBalance + token?: TokenWithBalance, ): token is EnsureDefined => Boolean(token && 'unconfirmedBalance' in token); export const isAvaxWithUnavailableBalance = ( - token?: TokenWithBalance + token?: TokenWithBalance, ): token is TokenWithBalanceAVM | TokenWithBalancePVM => Boolean( token && 'balancePerType' in token && token.available && - token.available !== token.balance + token.available !== token.balance, ); export const getUnconfirmedBalanceInCurrency = (token?: TokenWithBalance) => { diff --git a/src/background/services/balances/nft/utils/getSmallImageForNFT.ts b/src/background/services/balances/nft/utils/getSmallImageForNFT.ts index 79c3cc295..69fde075f 100644 --- a/src/background/services/balances/nft/utils/getSmallImageForNFT.ts +++ b/src/background/services/balances/nft/utils/getSmallImageForNFT.ts @@ -13,7 +13,7 @@ const COVALENT_IMG_SIZER = */ export function getSmallImageForNFT( imgUrl: string, - imageSize: '256' | '512' | '1024' = '256' + imageSize: '256' | '512' | '1024' = '256', ) { const url = ipfsResolverWithFallback(imgUrl); return `${COVALENT_IMG_SIZER}/width=${imageSize},fit/${url}`; diff --git a/src/background/services/balances/nft/utils/nftTypesUtils.ts b/src/background/services/balances/nft/utils/nftTypesUtils.ts index ec7bacdbc..6a79f86d6 100644 --- a/src/background/services/balances/nft/utils/nftTypesUtils.ts +++ b/src/background/services/balances/nft/utils/nftTypesUtils.ts @@ -5,13 +5,13 @@ import { } from '@avalabs/glacier-sdk'; export function is1155Response( - item + item, ): item is PromiseFulfilledResult { return Object.keys(item.value).includes('erc1155TokenBalances'); } export function isErc721TokenBalance( - token: Erc721TokenBalance | Erc1155TokenBalance + token: Erc721TokenBalance | Erc1155TokenBalance, ): token is Erc721TokenBalance { return token.ercType === Erc721TokenBalance.ercType.ERC_721; } diff --git a/src/background/services/balances/utils/getPriceChangeValues.test.ts b/src/background/services/balances/utils/getPriceChangeValues.test.ts index bb68f0736..5276ee4a0 100644 --- a/src/background/services/balances/utils/getPriceChangeValues.test.ts +++ b/src/background/services/balances/utils/getPriceChangeValues.test.ts @@ -31,7 +31,7 @@ describe('utils/getPriceChangeValues', () => { const changes = getPriceChangeValues( network1TokenBalance.symbol, network1TokenBalance.balanceInCurrency, - priceChanges + priceChanges, ); expect(changes).toEqual({ value: 3, @@ -41,7 +41,7 @@ describe('utils/getPriceChangeValues', () => { it('should return an empty calculation because of the missing price changes', () => { const changes = getPriceChangeValues( network1TokenBalance.symbol, - network1TokenBalance.balanceInCurrency + network1TokenBalance.balanceInCurrency, ); expect(changes).toEqual({ value: 0, diff --git a/src/background/services/balances/utils/getPriceChangeValues.ts b/src/background/services/balances/utils/getPriceChangeValues.ts index 178fc83c0..37da9f19f 100644 --- a/src/background/services/balances/utils/getPriceChangeValues.ts +++ b/src/background/services/balances/utils/getPriceChangeValues.ts @@ -3,7 +3,7 @@ import { TokensPriceShortData } from '../../tokens/models'; export function getPriceChangeValues( tokenSymbol: string, balanceInCurrency?: number, - priceChanges?: TokensPriceShortData + priceChanges?: TokensPriceShortData, ) { if (!priceChanges) { return { diff --git a/src/background/services/balances/utils/groupTokensByType.ts b/src/background/services/balances/utils/groupTokensByType.ts index 56811c552..dd0104bf3 100644 --- a/src/background/services/balances/utils/groupTokensByType.ts +++ b/src/background/services/balances/utils/groupTokensByType.ts @@ -5,7 +5,7 @@ import { import { isNFT } from '../nft/utils/isNFT'; export function groupTokensByType( - balances?: Record> + balances?: Record>, ): { nfts: Record>; tokens: Record>; diff --git a/src/background/services/balances/utils/isTokenWithBalanceAVM.ts b/src/background/services/balances/utils/isTokenWithBalanceAVM.ts index abb7b5cce..1bbbad867 100644 --- a/src/background/services/balances/utils/isTokenWithBalanceAVM.ts +++ b/src/background/services/balances/utils/isTokenWithBalanceAVM.ts @@ -4,7 +4,7 @@ import { } from '@avalabs/vm-module-types'; export const isTokenWithBalanceAVM = ( - balance?: TokenWithBalance + balance?: TokenWithBalance, ): balance is TokenWithBalanceAVM => { if (!balance) { return false; diff --git a/src/background/services/balances/utils/isTokenWithBalancePVM.ts b/src/background/services/balances/utils/isTokenWithBalancePVM.ts index bf7a95710..db6083fc0 100644 --- a/src/background/services/balances/utils/isTokenWithBalancePVM.ts +++ b/src/background/services/balances/utils/isTokenWithBalancePVM.ts @@ -4,7 +4,7 @@ import { } from '@avalabs/vm-module-types'; export const isTokenWithBalancePVM = ( - balance?: TokenWithBalance + balance?: TokenWithBalance, ): balance is TokenWithBalancePVM => { if (!balance) { return false; diff --git a/src/background/services/blockaid/BlockaidService.test.ts b/src/background/services/blockaid/BlockaidService.test.ts index a4f6fd928..f14a47da6 100644 --- a/src/background/services/blockaid/BlockaidService.test.ts +++ b/src/background/services/blockaid/BlockaidService.test.ts @@ -146,7 +146,7 @@ describe('background/services/blockaid/BlockaidService', () => { const result = await service.jsonRPCScan( networkMock.chainId.toString(), 'toAddress', - requestMock + requestMock, ); expect(result).toBe(null); }); @@ -156,7 +156,7 @@ describe('background/services/blockaid/BlockaidService', () => { const result = await service.jsonRPCScan( networkMock.chainId.toString(), 'toAddress', - requestMock + requestMock, ); expect(result?.validation).toEqual({ result_type: 'Being', diff --git a/src/background/services/blockaid/BlockaidService.ts b/src/background/services/blockaid/BlockaidService.ts index 3349f9a61..2f4d15682 100644 --- a/src/background/services/blockaid/BlockaidService.ts +++ b/src/background/services/blockaid/BlockaidService.ts @@ -21,7 +21,7 @@ export class BlockaidService { async jsonRPCScan( chainId: string, from: string, - request: JsonRpcRequestPayload + request: JsonRpcRequestPayload, ) { if ( !this.featureFlagService.featureFlags[FeatureGates.BLOCKAID_JSONRPC_SCAN] diff --git a/src/background/services/blockaid/utils.ts b/src/background/services/blockaid/utils.ts index e4e38a589..1c1e13962 100644 --- a/src/background/services/blockaid/utils.ts +++ b/src/background/services/blockaid/utils.ts @@ -2,12 +2,12 @@ import Blockaid from '@blockaid/client'; import { TransactionValidationResponse } from '@blockaid/client/resources'; export const isToken = ( - asset: Asset + asset: Asset, ): asset is Blockaid.Erc20TokenDetails | Blockaid.NativeAssetDetails => asset.type === 'ERC20' || asset.type === 'NATIVE' ? true : false; export const isNft = ( - asset: Asset + asset: Asset, ): asset is Blockaid.Erc1155TokenDetails | Blockaid.Erc721TokenDetails => asset.type === 'ERC1155' || asset.type === 'ERC721' || @@ -30,7 +30,7 @@ export type TokenDetails = | Blockaid.NativeAssetDetails; export const getValidationResultType = ( - validation?: TransactionValidationResponse + validation?: TransactionValidationResponse, ) => ({ isMalicious: validation?.result_type === 'Malicious', isSuspicious: validation?.result_type === 'Warning', diff --git a/src/background/services/bridge/BridgeService.test.ts b/src/background/services/bridge/BridgeService.test.ts index 966687a63..dbe851fc6 100644 --- a/src/background/services/bridge/BridgeService.test.ts +++ b/src/background/services/bridge/BridgeService.test.ts @@ -16,7 +16,7 @@ import { StorageService } from '../storage/StorageService'; import { BridgeService } from './BridgeService'; jest.mock('@avalabs/core-bridge-sdk', () => { - const { mockConfig } = require('./fixtures/mockBridgeConfig'); + const { mockConfig } = jest.requireActual('./fixtures/mockBridgeConfig'); return { ...jest.requireActual('@avalabs/core-bridge-sdk'), @@ -82,7 +82,7 @@ describe('src/background/services/bridge/BridgeService.ts', () => { networkService, accountsService, featureFlagService, - networkBalancesService + networkBalancesService, ); await service.onStorageReady(); }); @@ -98,7 +98,11 @@ describe('src/background/services/bridge/BridgeService.ts', () => { it('uses byteLength as gas limit estimation', async () => { expect( - await service.estimateGas(Blockchain.BITCOIN, new Big('1'), {} as any) + await service.estimateGas( + Blockchain.BITCOIN, + new Big('1'), + {} as any, + ), ).toEqual(10000n); }); }); @@ -110,7 +114,7 @@ describe('src/background/services/bridge/BridgeService.ts', () => { const result = await service.estimateGas( Blockchain.ETHEREUM, new Big('1'), - {} as any + {} as any, ); expect(estimateGas).toHaveBeenCalledWith( @@ -122,7 +126,7 @@ describe('src/background/services/bridge/BridgeService.ts', () => { avalanche: networkService.getAvalancheProvider(), }, service.bridgeConfig.config, - Blockchain.ETHEREUM + Blockchain.ETHEREUM, ); expect(result).toEqual(12345n); diff --git a/src/background/services/bridge/BridgeService.ts b/src/background/services/bridge/BridgeService.ts index 09a1a9f49..9a916f348 100644 --- a/src/background/services/bridge/BridgeService.ts +++ b/src/background/services/bridge/BridgeService.ts @@ -58,7 +58,7 @@ export class BridgeService implements OnLock, OnStorageReady { private networkService: NetworkService, private accountsService: AccountsService, private featureFlagService: FeatureFlagService, - private networkBalancesService: BalanceAggregatorService + private networkBalancesService: BalanceAggregatorService, ) { this.networkService.developerModeChanged.add(() => { this.updateBridgeConfig(); @@ -72,7 +72,7 @@ export class BridgeService implements OnLock, OnStorageReady { DefaultBridgeState; this.eventEmitter.emit( BridgeEvents.BRIDGE_STATE_UPDATE_EVENT, - this.bridgeState + this.bridgeState, ); await this.updateBridgeConfig(); @@ -102,14 +102,14 @@ export class BridgeService implements OnLock, OnStorageReady { this.config = config; this.eventEmitter.emit( BridgeEvents.BRIDGE_CONFIG_UPDATE_EVENT, - this.config + this.config, ); return config; } private async trackBridgeTransaction( bridgeTransaction: BridgeTransaction, - bridgeConfig: BridgeConfig | undefined + bridgeConfig: BridgeConfig | undefined, ) { const config = bridgeConfig?.config; if (!config) { @@ -149,16 +149,13 @@ export class BridgeService implements OnLock, OnStorageReady { await this.storageService.save(BRIDGE_STORAGE_KEY, this.bridgeState); this.eventEmitter.emit( BridgeEvents.BRIDGE_STATE_UPDATE_EVENT, - this.bridgeState + this.bridgeState, ); } async removeBridgeTransaction(sourceTxHash: string) { - const { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - [sourceTxHash]: _removed, - ...bridgeTransactions - } = this.bridgeState.bridgeTransactions; + const { [sourceTxHash]: _removed, ...bridgeTransactions } = + this.bridgeState.bridgeTransactions; this.#subscriptions.get(sourceTxHash)?.unsubscribe(); this.#subscriptions.delete(sourceTxHash); @@ -167,14 +164,14 @@ export class BridgeService implements OnLock, OnStorageReady { await this.storageService.save(BRIDGE_STORAGE_KEY, this.bridgeState); this.eventEmitter.emit( BridgeEvents.BRIDGE_STATE_UPDATE_EVENT, - this.bridgeState + this.bridgeState, ); } async estimateGas( currentBlockchain: Blockchain, amount: Big, - asset: Asset + asset: Asset, ): Promise { if (!this.config?.config) { throw new Error('missing bridge config'); @@ -195,7 +192,7 @@ export class BridgeService implements OnLock, OnStorageReady { const balances = await this.networkBalancesService.getBalancesForNetworks( [btcNetwork.chainId], [this.accountsService.activeAccount], - [TokenType.NATIVE] // We only care about BTC here, which is a native token + [TokenType.NATIVE], // We only care about BTC here, which is a native token ); const token = balances.tokens[btcNetwork.chainId]?.[addressBtc]?.[ @@ -214,7 +211,7 @@ export class BridgeService implements OnLock, OnStorageReady { addressBtc, utxos, btcToSatoshi(amount), - feeRate + feeRate, ); return BigInt(byteLength); @@ -232,7 +229,7 @@ export class BridgeService implements OnLock, OnStorageReady { avalanche: avalancheProvider, }, this.config.config, - currentBlockchain + currentBlockchain, ); } } @@ -243,7 +240,7 @@ export class BridgeService implements OnLock, OnStorageReady { sourceStartedAt: number, targetChain: Blockchain, amount: Big, - symbol: string + symbol: string, ) { const { config } = await this.updateBridgeConfig(); if (!this.accountsService.activeAccount || !config) { @@ -261,7 +258,7 @@ export class BridgeService implements OnLock, OnStorageReady { const requiredConfirmationCount = getMinimumConfirmations( sourceChain, - config + config, ); const environment = this.networkService.isMainnet() ? 'main' : 'test'; const bridgeTransaction: BridgeTransaction = { @@ -292,8 +289,8 @@ export class BridgeService implements OnLock, OnStorageReady { return isMainnet ? Environment.PROD : this.bridgeState.isDevEnv - ? Environment.DEV - : Environment.TEST; + ? Environment.DEV + : Environment.TEST; } /** @@ -311,7 +308,7 @@ export class BridgeService implements OnLock, OnStorageReady { configs[env] = config; } this.trackBridgeTransaction(bridgeTransaction, config); - } + }, ); } } diff --git a/src/background/services/bridge/events/bridgeConfigUpdateEvents.ts b/src/background/services/bridge/events/bridgeConfigUpdateEvents.ts index efba86f0a..9b3f2cc92 100644 --- a/src/background/services/bridge/events/bridgeConfigUpdateEvents.ts +++ b/src/background/services/bridge/events/bridgeConfigUpdateEvents.ts @@ -18,7 +18,7 @@ export class BridgeConfigUpdatedEvents implements ExtensionEventEmitter { name: BridgeEvents.BRIDGE_CONFIG_UPDATE_EVENT, value: config, }); - } + }, ); } @@ -27,7 +27,7 @@ export class BridgeConfigUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/bridge/events/bridgeStateUpdateEvents.ts b/src/background/services/bridge/events/bridgeStateUpdateEvents.ts index 54bdc7300..9db5ff7be 100644 --- a/src/background/services/bridge/events/bridgeStateUpdateEvents.ts +++ b/src/background/services/bridge/events/bridgeStateUpdateEvents.ts @@ -18,7 +18,7 @@ export class BridgeStateUpdateEvents implements ExtensionEventEmitter { name: BridgeEvents.BRIDGE_STATE_UPDATE_EVENT, value: value, }); - } + }, ); } @@ -27,7 +27,7 @@ export class BridgeStateUpdateEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/bridge/events/bridgeTransferEvents.ts b/src/background/services/bridge/events/bridgeTransferEvents.ts index 7a7252a29..dd428b207 100644 --- a/src/background/services/bridge/events/bridgeTransferEvents.ts +++ b/src/background/services/bridge/events/bridgeTransferEvents.ts @@ -18,7 +18,7 @@ export class BridgeTransferEvents implements ExtensionEventEmitter { name: BridgeEvents.BRIDGE_TRANSFER_EVENT, value: status, }); - } + }, ); } @@ -27,7 +27,7 @@ export class BridgeTransferEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/bridge/events/listeners.ts b/src/background/services/bridge/events/listeners.ts index 6caa81ccf..c5aac2921 100644 --- a/src/background/services/bridge/events/listeners.ts +++ b/src/background/services/bridge/events/listeners.ts @@ -3,19 +3,19 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { BridgeEvents, BridgeState, TransferEvent } from '../models'; export function isBridgeStateUpdateEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === BridgeEvents.BRIDGE_STATE_UPDATE_EVENT; } export function isBridgeConfigUpdateEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt?.name === BridgeEvents.BRIDGE_CONFIG_UPDATE_EVENT; } export function isBridgeTransferEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return evt?.name === BridgeEvents.BRIDGE_TRANSFER_EVENT; } diff --git a/src/background/services/bridge/handlers/avalanche_bridgeAsset.test.ts b/src/background/services/bridge/handlers/avalanche_bridgeAsset.test.ts index b64d7dbe5..0353a4a12 100644 --- a/src/background/services/bridge/handlers/avalanche_bridgeAsset.test.ts +++ b/src/background/services/bridge/handlers/avalanche_bridgeAsset.test.ts @@ -185,7 +185,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { analyticsServicePosthogMock, walletServiceMock, featureFlagServiceMock, - networkFeeServiceMock + networkFeeServiceMock, ); (encryptAnalyticsData as jest.Mock).mockResolvedValue(mockedEncryptResult); @@ -214,7 +214,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { buildRpcCall({ ...request, params: ['bitcoin'], - }) + }), ); expect(result).toEqual({ @@ -230,7 +230,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { buildRpcCall({ ...request, params: ['testBlockchain', '1'], - }) + }), ); expect(result).toEqual({ @@ -261,8 +261,8 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { ...request, params: ['bitcoin', '1'], }, - `eip155:${ChainId.BITCOIN}` - ) + `eip155:${ChainId.BITCOIN}`, + ), ); expect(result).toEqual({ @@ -284,7 +284,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { asset: btcAsset, }, }, - `approve` + `approve`, ); }); @@ -307,7 +307,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { ], }; const result = await handler.handleAuthenticated( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); expect(result).toEqual({ @@ -323,7 +323,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { params: [Blockchain.ETHEREUM, '1', btcAsset], }; const result = await handler.handleAuthenticated( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); expect(result).toEqual({ @@ -339,7 +339,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { params: [Blockchain.AVALANCHE, '1', nativeAsset], }; const result = await handler.handleAuthenticated( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); expect(result).toEqual({ @@ -393,7 +393,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { }; const result = await handler.handleAuthenticated( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); expect(result).toEqual({ @@ -402,7 +402,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { }); expect(openApprovalWindow).toHaveBeenCalledWith( expectedAction, - `approve` + `approve`, ); }); @@ -447,7 +447,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { analyticsServicePosthogMock, walletServiceMock, featureFlagServiceMock, - networkFeeServiceMock + networkFeeServiceMock, ); const mockRequest = { @@ -480,7 +480,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { }, }; const result = await handlerToTest.handleAuthenticated( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); expect(result).toEqual({ @@ -489,7 +489,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { }); expect(openApprovalWindow).toHaveBeenCalledWith( expectedAction, - `approve` + `approve`, ); }); }); @@ -520,9 +520,9 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { const amount = bnToBig( stringToBN( ethAction.displayData.amountStr, - ethAction.displayData.asset.denomination + ethAction.displayData.asset.denomination, ), - ethAction.displayData.asset.denomination + ethAction.displayData.asset.denomination, ); const action = { @@ -544,7 +544,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { {}, mockOnSuccess, mockOnError, - frontendTabId + frontendTabId, ); expect(transferAssetEVM).toHaveBeenCalledTimes(1); @@ -553,7 +553,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { currentBlockchain: ethAction.displayData.currentBlockchain, amount, asset: ethAction.displayData.asset, - }) + }), ); // Mock signAndSendEVM callback being called @@ -577,7 +577,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { nonce: 14, }), { chainId: 5 }, - expect.any(Number) + expect.any(Number), ); }); @@ -592,9 +592,9 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { const amount = bnToBig( stringToBN( btcAction.displayData.amountStr, - btcAction.displayData.asset.denomination + btcAction.displayData.asset.denomination, ), - btcAction.displayData.asset.denomination + btcAction.displayData.asset.denomination, ); const now = Date.now(); jest.spyOn(Date, 'now').mockReturnValue(now); @@ -604,14 +604,14 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { {}, mockOnSuccess, mockOnError, - frontendTabId + frontendTabId, ); expect(transferAssetBTC).toHaveBeenCalledTimes(1); expect(transferAssetBTC).toHaveBeenCalledWith( expect.objectContaining({ amount: btcToSatoshi(amount), - }) + }), ); expect(bridgeServiceMock.createTransaction).toHaveBeenCalledTimes(1); @@ -621,13 +621,13 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { now, Blockchain.AVALANCHE, amount, - 'BTC' + 'BTC', ); expect(mockOnSuccess).toHaveBeenCalledWith(btcResult); expect(mockOnError).toHaveBeenCalledTimes(0); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -637,7 +637,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { txHash: btcResult.hash, chainId: ChainId.BITCOIN, }, - }) + }), ); }); @@ -660,7 +660,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { expect(mockOnSuccess).toHaveBeenCalledTimes(0); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -669,7 +669,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { address: testActiveAccount.addressBTC, chainId: ChainId.BITCOIN_TESTNET, }, - }) + }), ); }); @@ -682,9 +682,9 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { const amount = bnToBig( stringToBN( ethAction.displayData.amountStr, - ethAction.displayData.asset.denomination + ethAction.displayData.asset.denomination, ), - ethAction.displayData.asset.denomination + ethAction.displayData.asset.denomination, ); const now = Date.now(); @@ -697,11 +697,11 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { {}, mockOnSuccess, mockOnError, - frontendTabId + frontendTabId, ); expect( - balanceAggregatorServiceMock.getBalancesForNetworks + balanceAggregatorServiceMock.getBalancesForNetworks, ).toHaveBeenCalledTimes(0); expect(transferAssetEVM).toHaveBeenCalledTimes(1); @@ -710,7 +710,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { currentBlockchain: ethAction.displayData.currentBlockchain, amount: amount, asset: ethAction.displayData.asset, - }) + }), ); expect(bridgeServiceMock.createTransaction).toHaveBeenCalledTimes(1); expect(bridgeServiceMock.createTransaction).toHaveBeenCalledWith( @@ -719,13 +719,13 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { now, Blockchain.AVALANCHE, amount, - 'ETH' + 'ETH', ); expect(mockOnSuccess).toHaveBeenCalledWith(ethResult); expect(mockOnError).toHaveBeenCalledTimes(0); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -735,7 +735,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { txHash: ethResult, chainId: ChainId.ETHEREUM_TEST_SEPOLIA, }, - }) + }), ); }); @@ -758,7 +758,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { expect(mockOnSuccess).toHaveBeenCalledTimes(0); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -767,7 +767,7 @@ describe('background/services/bridge/handlers/avalanche_bridgeAsset', () => { address: testActiveAccount.addressC, chainId: ChainId.ETHEREUM_HOMESTEAD, }, - }) + }), ); }); }); diff --git a/src/background/services/bridge/handlers/avalanche_bridgeAsset.ts b/src/background/services/bridge/handlers/avalanche_bridgeAsset.ts index c3fe56139..16b154866 100644 --- a/src/background/services/bridge/handlers/avalanche_bridgeAsset.ts +++ b/src/background/services/bridge/handlers/avalanche_bridgeAsset.ts @@ -49,7 +49,7 @@ import { JsonRpcBatchInternal } from '@avalabs/core-wallets-sdk'; type BridgeActionParams = [ currentBlockchain: Blockchain, amountStr: string, - asset: Asset + asset: Asset, ]; // this is used for core web @@ -65,7 +65,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler private analyticsServicePosthog: AnalyticsServicePosthog, private walletService: WalletService, private featureFlagService: FeatureFlagService, - private networkFeeService: NetworkFeeService + private networkFeeService: NetworkFeeService, ) { super(); } @@ -116,7 +116,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler } const networks = Object.values( - (await this.networkService.allNetworks.promisify()) ?? {} + (await this.networkService.allNetworks.promisify()) ?? {}, ); const activeNetwork = await this.networkService.getNetwork(scope); @@ -125,7 +125,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler currentBlockchain, networks, this.bridgeService.bridgeConfig, - activeNetwork?.isTestnet + activeNetwork?.isTestnet, ); const wrappedNetwork = isNativeAsset(asset) @@ -145,7 +145,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler : asset.nativeNetwork, networks, this.bridgeService.bridgeConfig, - activeNetwork?.isTestnet + activeNetwork?.isTestnet, ); const { activeAccount } = this.accountsService; @@ -172,7 +172,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler asset.assetType === AssetType.ERC20 ? TokenType.ERC20 : TokenType.NATIVE, - ] + ], ); const balanceAddress = @@ -186,7 +186,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler findTokenForAsset( asset.symbol, asset.nativeNetwork, - Object.values(tokens?.[sourceNetwork.chainId]?.[balanceAddress] ?? {}) + Object.values(tokens?.[sourceNetwork.chainId]?.[balanceAddress] ?? {}), ); const action: Action = { @@ -201,7 +201,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler gasLimit: await this.bridgeService.estimateGas( currentBlockchain, new Big(amountStr), - asset + asset, ), }, }; @@ -261,7 +261,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler _result, // Unused onSuccess, onError, - frontendTabId?: number + frontendTabId?: number, ) => { const currentBlockchain = pendingAction?.displayData.currentBlockchain; @@ -296,7 +296,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler if (isWalletConnectAccount(account)) { throw new Error( - 'WalletConnect accounts are not supported by Bridge yet' + 'WalletConnect accounts are not supported by Bridge yet', ); } const { addressBTC } = account; @@ -309,12 +309,12 @@ export class AvalancheBridgeAsset extends DAppRequestHandler await this.balanceAggregatorService.getBalancesForNetworks( [network.chainId], [account], - [TokenType.NATIVE] // We only care about BTC here, which is a native token + [TokenType.NATIVE], // We only care about BTC here, which is a native token ); const highFeeRate = Number( (await this.networkFeeService.getNetworkFee(network))?.high - .maxFeePerGas ?? 0 + .maxFeePerGas ?? 0, ); const token = balances.tokens[network.chainId]?.[addressBTC]?.[ @@ -344,12 +344,12 @@ export class AvalancheBridgeAsset extends DAppRequestHandler token, }, utxos, - !network.isTestnet + !network.isTestnet, ); if (error) { throw new Error( - 'Building BTC transaction for Bridge failed: ' + error + 'Building BTC transaction for Bridge failed: ' + error, ); } @@ -361,7 +361,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler address: to, token, feeRate, - } + }, ); if (!inputs || !outputs) { @@ -371,7 +371,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler const result = await this.walletService.sign( { inputs, outputs }, network, - frontendTabId + frontendTabId, ); return this.networkService.sendTransaction(result, network); @@ -390,7 +390,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler Date.now(), Blockchain.AVALANCHE, amount, - 'BTC' + 'BTC', ); this.analyticsServicePosthog.captureEncryptedEvent({ name: 'avalanche_bridgeAsset_success', @@ -427,11 +427,11 @@ export class AvalancheBridgeAsset extends DAppRequestHandler const tx = txData as ContractTransaction; // TODO: update types in the SDK? const provider = (await getProviderForNetwork( - network + network, )) as JsonRpcBatchInternal; const nonce = await provider.getTransactionCount( - this.#getSourceAccount().addressC + this.#getSourceAccount().addressC, ); // Get fee-related properties from the approval screen first, @@ -455,7 +455,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler maxPriorityFeePerGas, }, network, - frontendTabId + frontendTabId, ); return this.networkService.sendTransaction(signResult, network); @@ -474,7 +474,7 @@ export class AvalancheBridgeAsset extends DAppRequestHandler ? Blockchain.ETHEREUM : Blockchain.AVALANCHE, amount, - asset.symbol + asset.symbol, ); this.analyticsServicePosthog.captureEncryptedEvent({ diff --git a/src/background/services/bridge/handlers/createBridgeTransaction.ts b/src/background/services/bridge/handlers/createBridgeTransaction.ts index 708065d7d..4caf08142 100644 --- a/src/background/services/bridge/handlers/createBridgeTransaction.ts +++ b/src/background/services/bridge/handlers/createBridgeTransaction.ts @@ -46,8 +46,8 @@ export class BridgeCreateTransactionHandler implements HandlerType { sourceStartedAt, targetChain, amount, - symbol - ) + symbol, + ), ); if (error) { diff --git a/src/background/services/bridge/handlers/estimateGasForBridgeTx.test.ts b/src/background/services/bridge/handlers/estimateGasForBridgeTx.test.ts index d014123b5..09983a446 100644 --- a/src/background/services/bridge/handlers/estimateGasForBridgeTx.test.ts +++ b/src/background/services/bridge/handlers/estimateGasForBridgeTx.test.ts @@ -33,7 +33,7 @@ describe('src/background/services/bridge/handlers/estimateGasForBridgeTx', () => expect(bridgeService.estimateGas).toHaveBeenCalledWith( sourceChain, amount, - asset + asset, ); }); diff --git a/src/background/services/bridge/handlers/removeBridgeTransaction.ts b/src/background/services/bridge/handlers/removeBridgeTransaction.ts index d45cf62fc..73edd1bb0 100644 --- a/src/background/services/bridge/handlers/removeBridgeTransaction.ts +++ b/src/background/services/bridge/handlers/removeBridgeTransaction.ts @@ -16,7 +16,7 @@ export class BridgeRemoveTransactionHandler implements HandlerType { constructor( private bridgeService: BridgeService, - private unifiedBridgeService: UnifiedBridgeService + private unifiedBridgeService: UnifiedBridgeService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -29,8 +29,8 @@ export class BridgeRemoveTransactionHandler implements HandlerType { }; } - const legacyBridgeTx = await this.bridgeService.bridgeState - .bridgeTransactions[txHash]; + const legacyBridgeTx = + await this.bridgeService.bridgeState.bridgeTransactions[txHash]; if (legacyBridgeTx) { await this.bridgeService.removeBridgeTransaction(txHash); diff --git a/src/background/services/bridge/utils.ts b/src/background/services/bridge/utils.ts index 235c209b1..abb9eb131 100644 --- a/src/background/services/bridge/utils.ts +++ b/src/background/services/bridge/utils.ts @@ -15,15 +15,15 @@ enum BridgeNetwork { */ export function filterBridgeStateToNetwork( bridge: BridgeState, - network: Network + network: Network, ): BridgeState { const networkNameToCheck = isBitcoinNetwork(network) ? BridgeNetwork.BITCOIN : isAvalancheNetwork(network) - ? BridgeNetwork.AVALANCHE - : isEthereumNetwork(network) - ? BridgeNetwork.ETHEREUM - : null; + ? BridgeNetwork.AVALANCHE + : isEthereumNetwork(network) + ? BridgeNetwork.ETHEREUM + : null; const isMainnet = !network.isTestnet; const bridgeTransactions = Object.values(bridge.bridgeTransactions).reduce< diff --git a/src/background/services/contacts/ContactsService.ts b/src/background/services/contacts/ContactsService.ts index 16a07ff16..c8ce988c8 100644 --- a/src/background/services/contacts/ContactsService.ts +++ b/src/background/services/contacts/ContactsService.ts @@ -12,9 +12,8 @@ export class ContactsService { constructor(private storageService: StorageService) {} async getContacts(): Promise { - const contacts = await this.storageService.load( - CONTACTS_STORAGE_KEY - ); + const contacts = + await this.storageService.load(CONTACTS_STORAGE_KEY); return ( contacts ?? { @@ -49,7 +48,7 @@ export class ContactsService { const updatedContacts = { ...contacts, contacts: contacts.contacts.map((c) => - c.id === contact.id ? contact : c + c.id === contact.id ? contact : c, ), }; diff --git a/src/background/services/contacts/events/contactsUpdatedEvent.ts b/src/background/services/contacts/events/contactsUpdatedEvent.ts index 3fb50f9d3..813b61297 100644 --- a/src/background/services/contacts/events/contactsUpdatedEvent.ts +++ b/src/background/services/contacts/events/contactsUpdatedEvent.ts @@ -18,7 +18,7 @@ export class ContactsUpdatedEvents implements ExtensionEventEmitter { name: ContactsEvents.CONTACTS_UPDATED, value: contacts, }); - } + }, ); } @@ -27,7 +27,7 @@ export class ContactsUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/contacts/events/listeners.ts b/src/background/services/contacts/events/listeners.ts index 58ce1e25c..fa60db658 100644 --- a/src/background/services/contacts/events/listeners.ts +++ b/src/background/services/contacts/events/listeners.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { ContactsState, ContactsEvents } from '../models'; export function contactsUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === ContactsEvents.CONTACTS_UPDATED; } diff --git a/src/background/services/contacts/handlers/avalanche_createContact.ts b/src/background/services/contacts/handlers/avalanche_createContact.ts index b20c109fd..39df6c9c5 100644 --- a/src/background/services/contacts/handlers/avalanche_createContact.ts +++ b/src/background/services/contacts/handlers/avalanche_createContact.ts @@ -50,9 +50,9 @@ export class AvalancheCreateContactHandler extends DAppRequestHandler { onActionApproved = async ( pendingAction: Action, - result, + _result, onSuccess, - onError + onError, ) => { try { const { diff --git a/src/background/services/contacts/handlers/avalanche_removeContact.ts b/src/background/services/contacts/handlers/avalanche_removeContact.ts index df80e8d24..db52229da 100644 --- a/src/background/services/contacts/handlers/avalanche_removeContact.ts +++ b/src/background/services/contacts/handlers/avalanche_removeContact.ts @@ -48,9 +48,9 @@ export class AvalancheRemoveContactHandler extends DAppRequestHandler { onActionApproved = async ( pendingAction: Action, - result, + _result, onSuccess, - onError + onError, ) => { try { const { diff --git a/src/background/services/contacts/handlers/avalanche_updateContact.ts b/src/background/services/contacts/handlers/avalanche_updateContact.ts index 7f21f4435..b5ccea53f 100644 --- a/src/background/services/contacts/handlers/avalanche_updateContact.ts +++ b/src/background/services/contacts/handlers/avalanche_updateContact.ts @@ -52,9 +52,9 @@ export class AvalancheUpdateContactHandler extends DAppRequestHandler { onActionApproved = async ( pendingAction: Action, - result, + _result, onSuccess, - onError + onError, ) => { try { const { diff --git a/src/background/services/currency/CurrencyService.test.ts b/src/background/services/currency/CurrencyService.test.ts index 5f837598e..d3ba77fdf 100644 --- a/src/background/services/currency/CurrencyService.test.ts +++ b/src/background/services/currency/CurrencyService.test.ts @@ -76,13 +76,13 @@ describe('src/background/services/currency/CurrencyService.ts', () => { const testedIntervals = 5; jest.advanceTimersByTime( - (10 + CURRENCY_EXCHANGE_RATES_REFRESH_INTERVAL) * testedIntervals + (10 + CURRENCY_EXCHANGE_RATES_REFRESH_INTERVAL) * testedIntervals, ); for (let i = 1; i <= testedIntervals; i++) { expect(global.fetch).toHaveBeenNthCalledWith( i, - CURRENCY_EXCHANGE_RATES_URL + CURRENCY_EXCHANGE_RATES_URL, ); } }); @@ -99,19 +99,19 @@ describe('src/background/services/currency/CurrencyService.ts', () => { date: '2023-06-15', someOtherField: 'someData', usd: { eur: 1 }, - }) + }), ) .mockResolvedValueOnce( buildResponse({ usd: { eur: 1 }, - }) + }), ) .mockResolvedValueOnce( buildResponse({ date: '2023-06-15', usd: { eur: 'asdasd' }, - }) + }), ) .mockResolvedValue(buildResponse(apiResponse)); @@ -152,13 +152,13 @@ describe('src/background/services/currency/CurrencyService.ts', () => { () => new Promise((resolve) => { setTimeout(() => resolve(cachedResponse), 1000); - }) + }), ); global.fetch = jest.fn().mockImplementationOnce( () => new Promise((resolve) => { setTimeout(() => resolve(buildResponse(apiResponse)), 500); - }) + }), ); service.onUnlock(); @@ -169,7 +169,7 @@ describe('src/background/services/currency/CurrencyService.ts', () => { await jest.runAllTimers(); await jest.runAllTicks(); expect(mockStorageService.loadUnencrypted).toHaveBeenCalledWith( - CURRENCY_EXCHANGE_RATES_STORAGE_KEY + CURRENCY_EXCHANGE_RATES_STORAGE_KEY, ); const { date, ...rates } = apiResponse; @@ -191,13 +191,13 @@ describe('src/background/services/currency/CurrencyService.ts', () => { () => new Promise((resolve) => { setTimeout(() => resolve(cachedResponse), 500); - }) + }), ); global.fetch = jest.fn().mockImplementationOnce( () => new Promise((resolve) => { setTimeout(() => resolve(buildResponse(apiResponse)), 1000); - }) + }), ); service.onUnlock(); @@ -207,7 +207,7 @@ describe('src/background/services/currency/CurrencyService.ts', () => { jest.advanceTimersByTime(600); await jest.runAllTicks(); expect(mockStorageService.loadUnencrypted).toHaveBeenCalledWith( - CURRENCY_EXCHANGE_RATES_STORAGE_KEY + CURRENCY_EXCHANGE_RATES_STORAGE_KEY, ); // Cached rates are set first diff --git a/src/background/services/currency/CurrencyService.ts b/src/background/services/currency/CurrencyService.ts index 5c6761d6a..98d573214 100644 --- a/src/background/services/currency/CurrencyService.ts +++ b/src/background/services/currency/CurrencyService.ts @@ -42,14 +42,14 @@ export class CurrencyService implements OnLock, OnUnlock { #scheduleUpdates() { this.#intervalId = setInterval( () => this.#updateExchangeRates(), - CURRENCY_EXCHANGE_RATES_REFRESH_INTERVAL + CURRENCY_EXCHANGE_RATES_REFRESH_INTERVAL, ); } async #initializeFromStorage() { const cachedState = await this.storageService.loadUnencrypted( - CURRENCY_EXCHANGE_RATES_STORAGE_KEY + CURRENCY_EXCHANGE_RATES_STORAGE_KEY, ); // Only use the cached state if we don't have the data from API yet @@ -57,7 +57,7 @@ export class CurrencyService implements OnLock, OnUnlock { this.state = cachedState; this.#eventEmitter.emit( CurrencyServiceEvents.RatesUpdated, - cachedState.rates + cachedState.rates, ); } } @@ -79,9 +79,9 @@ export class CurrencyService implements OnLock, OnUnlock { this.#eventEmitter.emit(CurrencyServiceEvents.RatesUpdated, rates); this.storageService.saveUnencrypted( CURRENCY_EXCHANGE_RATES_STORAGE_KEY, - this.state + this.state, ); - } catch (err) { + } catch (_err) { // If it fails (i.e. remote service is unreachable), schedule another request in 30 seconds. this.#timerId = setTimeout(() => this.#updateExchangeRates(), 30 * 1000); } diff --git a/src/background/services/currency/events/currencyRatesUpdatedEvent.ts b/src/background/services/currency/events/currencyRatesUpdatedEvent.ts index 94ed54401..ef428b290 100644 --- a/src/background/services/currency/events/currencyRatesUpdatedEvent.ts +++ b/src/background/services/currency/events/currencyRatesUpdatedEvent.ts @@ -20,7 +20,7 @@ export class CurrencyRatesUpdatedEvents implements ExtensionEventEmitter { name: CurrencyServiceEvents.RatesUpdated, value: rates, }); - } + }, ); } @@ -29,7 +29,7 @@ export class CurrencyRatesUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/currency/events/listeners.ts b/src/background/services/currency/events/listeners.ts index 93cf251f7..41371f92a 100644 --- a/src/background/services/currency/events/listeners.ts +++ b/src/background/services/currency/events/listeners.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { CurrencyServiceEvents, CurrencyExchangeRatesState } from '../models'; export function currencyRatesUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === CurrencyServiceEvents.RatesUpdated; } diff --git a/src/background/services/currency/handlers/getCurrencyExchangeRates.test.ts b/src/background/services/currency/handlers/getCurrencyExchangeRates.test.ts index 11246fde0..246422751 100644 --- a/src/background/services/currency/handlers/getCurrencyExchangeRates.test.ts +++ b/src/background/services/currency/handlers/getCurrencyExchangeRates.test.ts @@ -6,7 +6,7 @@ import { buildRpcCall } from '@src/tests/test-utils'; describe('src/background/services/currency/handlers/getCurrencyExchangeRates.ts', () => { const currencyService = (state?: CurrencyExchangeRatesState) => - ({ state } as unknown as CurrencyService); + ({ state }) as unknown as CurrencyService; describe('when exchange rates are known', () => { const service = currencyService({ @@ -27,7 +27,7 @@ describe('src/background/services/currency/handlers/getCurrencyExchangeRates.ts' buildRpcCall({ id: '1', method: ExtensionRequest.CURRENCIES_GET_EXCHANGE_RATES, - }) + }), ); expect(response).toEqual({ @@ -54,7 +54,7 @@ describe('src/background/services/currency/handlers/getCurrencyExchangeRates.ts' buildRpcCall({ id: '1', method: ExtensionRequest.CURRENCIES_GET_EXCHANGE_RATES, - }) + }), ); expect(response).toEqual({ diff --git a/src/background/services/debank/DebankService.test.ts b/src/background/services/debank/DebankService.test.ts index d51c47585..79c30978b 100644 --- a/src/background/services/debank/DebankService.test.ts +++ b/src/background/services/debank/DebankService.test.ts @@ -55,7 +55,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { new DebankService(featureFlagService); expect(global.fetch).toHaveBeenCalledWith( - expect.stringMatching('/chain/list$') + expect.stringMatching('/chain/list$'), ); }); @@ -81,7 +81,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { .fn() .mockRejectedValueOnce(buildResponse()) .mockResolvedValueOnce( - buildResponse(fixture_userAllComplexProtocolList) + buildResponse(fixture_userAllComplexProtocolList), ); }); @@ -100,7 +100,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { await service.getUserProtocols('0x1234'); expect(fetch).toHaveBeenCalledWith( - expect.stringContaining('user/all_complex_protocol_list') + expect.stringContaining('user/all_complex_protocol_list'), ); }); }); @@ -112,7 +112,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { .fn() .mockResolvedValueOnce(buildResponse(fixture_chainList)) .mockResolvedValueOnce( - buildResponse(fixture_userAllComplexProtocolList) + buildResponse(fixture_userAllComplexProtocolList), ); }); @@ -123,7 +123,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { await service.getUserProtocols('0x1234'); expect(fetch).toHaveBeenLastCalledWith( - expect.stringContaining('user/all_complex_protocol_list?id=0x1234') + expect.stringContaining('user/all_complex_protocol_list?id=0x1234'), ); }); @@ -377,7 +377,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { .fn() .mockRejectedValueOnce(buildResponse()) .mockResolvedValueOnce( - buildResponse(fixture_userAllComplexProtocolList) + buildResponse(fixture_userAllComplexProtocolList), ); }); @@ -411,7 +411,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { () => new Promise((res) => { resolveFetch = res; - }) + }), ); const service = new DebankService(featureFlagService); @@ -485,9 +485,9 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { } as any); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).rejects.toStrictEqual( - new Error('debank-transaction-parsing flag disabled') + new Error('debank-transaction-parsing flag disabled'), ); }); @@ -499,7 +499,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { () => new Promise((res) => { resolveFetch = res; - }) + }), ) .mockRejectedValue(new Error('network error')); @@ -538,7 +538,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { } as any); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).rejects.toStrictEqual(new Error('DeBank transaction parsing failed')); expect(global.fetch).toHaveBeenCalledTimes(2); @@ -549,7 +549,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { body: '{"tx":{"from":"0x473B6494E2632ec1c9F90Ce05327e96e30767638","to":"0x473B6494E2632ec1c9F90Ce05327e96e30767638","data":"0x","value":"0x5af3107a4000","chainId":43114,"gas":"0x0","nonce":"0x1"}}', headers: { 'content-type': 'application/json' }, method: 'post', - } + }, ); }); @@ -568,7 +568,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { } as any); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).rejects.toStrictEqual(new Error('DeBank transaction parsing failed')); expect(global.fetch).toHaveBeenCalledTimes(2); @@ -592,7 +592,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { } as any); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).rejects.toStrictEqual(new Error('DeBank transaction parsing failed')); expect(global.fetch).toHaveBeenCalledTimes(2); @@ -656,12 +656,12 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { ensureFlagEnabled: jest .fn() .mockImplementation( - (flag) => flag !== FeatureGates.DEBANK_TRANSACTION_PRE_EXECUTION + (flag) => flag !== FeatureGates.DEBANK_TRANSACTION_PRE_EXECUTION, ), } as any); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).resolves.toStrictEqual({ abi: { func: 'setApprovalForAll', @@ -692,7 +692,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { const service = new DebankService(featureFlagService); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).resolves.toStrictEqual({ abi: { func: 'setApprovalForAll', @@ -726,7 +726,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { const service = new DebankService(featureFlagService); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).resolves.toStrictEqual({ abi: { func: 'setApprovalForAll', @@ -757,7 +757,7 @@ describe('src/background/services/defi/debank/DebankService.ts', () => { const service = new DebankService(featureFlagService); await expect( - service.parseTransaction(networkMock, requestMock) + service.parseTransaction(networkMock, requestMock), ).resolves.toStrictEqual({ abi: { func: 'setApprovalForAll', diff --git a/src/background/services/debank/DebankService.ts b/src/background/services/debank/DebankService.ts index bcaec54f7..8c9a7be96 100644 --- a/src/background/services/debank/DebankService.ts +++ b/src/background/services/debank/DebankService.ts @@ -104,7 +104,7 @@ export class DebankService implements DefiDataProvider { totalUsdValue: this.#calculateTotalValueOfProtocolItems(portfolio_item_list), }; - } + }, ); return protocols; @@ -112,7 +112,7 @@ export class DebankService implements DefiDataProvider { throw new Error( `DebankService: Failed to load user's DeFi portfolio. ${ err instanceof Error ? err.message : err - }` + }`, ); } } @@ -133,10 +133,10 @@ export class DebankService implements DefiDataProvider { async parseTransaction( network: Network, - tx: EthSendTransactionParamsWithGas + tx: EthSendTransactionParamsWithGas, ): Promise { this.featureFlagService.ensureFlagEnabled( - FeatureGates.DEBANK_TRANSACTION_PARSING + FeatureGates.DEBANK_TRANSACTION_PARSING, ); await this.#initializationPromise; @@ -181,19 +181,19 @@ export class DebankService implements DefiDataProvider { usdValueChange: execResult.value.balance_change.usd_value_change, sendTokenList: execResult.value?.balance_change.send_token_list.map( - mapTokenItemToTransactionToken + mapTokenItemToTransactionToken, ) ?? [], receiveTokenList: execResult.value.balance_change.receive_token_list.map( - mapTokenItemToTransactionToken + mapTokenItemToTransactionToken, ) ?? [], sendNftList: execResult.value.balance_change.send_nft_list.map( - mapNftToTransactionNft + mapNftToTransactionNft, ) ?? [], receiveNftList: execResult.value.balance_change.receive_nft_list.map( - mapNftToTransactionNft + mapNftToTransactionNft, ) ?? [], } : undefined, @@ -206,10 +206,10 @@ export class DebankService implements DefiDataProvider { async #explainTx( network: Network, - tx: EthSendTransactionParamsWithGas + tx: EthSendTransactionParamsWithGas, ): Promise { this.featureFlagService.ensureFlagEnabled( - FeatureGates.DEBANK_TRANSACTION_PARSING + FeatureGates.DEBANK_TRANSACTION_PARSING, ); await this.#initializationPromise; @@ -244,20 +244,20 @@ export class DebankService implements DefiDataProvider { throw new Error( `DebankService: Failed to pre-execute transaction. ${ err instanceof Error ? err.message : err - }` + }`, ); } } async #preExecuteTx( network: Network, - tx: EthSendTransactionParamsWithGas + tx: EthSendTransactionParamsWithGas, ): Promise { await this.#initializationPromise; if (!(await this.isPreExecuteTxAvailable(network.chainId))) { throw new Error( - 'DebankService: Transaction pre-execution not supported on network' + 'DebankService: Transaction pre-execution not supported on network', ); } @@ -280,7 +280,7 @@ export class DebankService implements DefiDataProvider { throw new Error( `DebankService: Failed to pre-execute transaction. ${ err instanceof Error ? err.message : err - }` + }`, ); } } @@ -322,7 +322,7 @@ export class DebankService implements DefiDataProvider { return null; } }) - .filter(Boolean) as DefiItem[] // Filter-out the nullish items. + .filter(Boolean) as DefiItem[], // Filter-out the nullish items. ); const groupedByName = allItems.reduce((groups, item) => { @@ -360,10 +360,10 @@ export class DebankService implements DefiDataProvider { // We know the fields below are not supposed to be undefined // for perpetuals, so we can cast safely. positionToken: this.#mapToken( - item.detail.position_token as DebankPortfolioTokenItem + item.detail.position_token as DebankPortfolioTokenItem, ), marginToken: this.#mapToken( - item.detail.margin_token as DebankPortfolioTokenItem + item.detail.margin_token as DebankPortfolioTokenItem, ), profitUsdValue: Number(item.detail.pnl_usd_value), netUsdValue: item.stats.net_usd_value, @@ -448,7 +448,7 @@ export class DebankService implements DefiDataProvider { #sortItems(items: DefiItem[]): DefiItem[] { return [...items].sort( - ({ netUsdValue: valueA }, { netUsdValue: valueB }) => valueB - valueA + ({ netUsdValue: valueA }, { netUsdValue: valueB }) => valueB - valueA, ); } @@ -461,7 +461,7 @@ export class DebankService implements DefiDataProvider { } #calculateTotalValueOfProtocolItems( - items: DebankPortfolioItemObject[] + items: DebankPortfolioItemObject[], ): number { return items.reduce((total, { stats }) => total + stats.net_usd_value, 0); } diff --git a/src/background/services/debank/utils/debankActionsToTransactionActions.ts b/src/background/services/debank/utils/debankActionsToTransactionActions.ts index edc6a5dce..855195956 100644 --- a/src/background/services/debank/utils/debankActionsToTransactionActions.ts +++ b/src/background/services/debank/utils/debankActionsToTransactionActions.ts @@ -8,7 +8,7 @@ import { mapTokenItemToTransactionToken } from './mapTokenItemToTransactionToken import { TokenType } from '@avalabs/vm-module-types'; export function debankActionsToTransactionActions( - actions: TxAction[] + actions: TxAction[], ): TransactionAction[] { return actions?.map((action) => { switch (action.type) { diff --git a/src/background/services/debank/utils/mapTokenItemToTransactionToken.ts b/src/background/services/debank/utils/mapTokenItemToTransactionToken.ts index 1ba3095eb..d63f39668 100644 --- a/src/background/services/debank/utils/mapTokenItemToTransactionToken.ts +++ b/src/background/services/debank/utils/mapTokenItemToTransactionToken.ts @@ -4,7 +4,7 @@ import { bigToBigInt } from '@avalabs/core-utils-sdk'; import { TransactionToken } from '../../wallet/handlers/eth_sendTransaction/models'; export const mapTokenItemToTransactionToken = ( - t: DebankTokenItem + t: DebankTokenItem, ): TransactionToken => ({ address: t.id, decimals: t.decimals, diff --git a/src/background/services/debank/utils/txParamsToTransactionData.ts b/src/background/services/debank/utils/txParamsToTransactionData.ts index 5c8f0d97e..64c924eb3 100644 --- a/src/background/services/debank/utils/txParamsToTransactionData.ts +++ b/src/background/services/debank/utils/txParamsToTransactionData.ts @@ -5,7 +5,7 @@ import { EthSendTransactionParams } from '../../wallet/handlers/eth_sendTransact export function txParamsToTransactionData( network: Network, - tx: EthSendTransactionParams + tx: EthSendTransactionParams, ): DebankTransactionData { return { from: tx.from, diff --git a/src/background/services/defi/DefiService.test.ts b/src/background/services/defi/DefiService.test.ts index 056a27b2e..952a45fd5 100644 --- a/src/background/services/defi/DefiService.test.ts +++ b/src/background/services/defi/DefiService.test.ts @@ -75,7 +75,7 @@ describe('src/background/services/defi/DefiService.ts', () => { .mockRejectedValue(new Error('Failure')); expect(service.getUserPortfolio('0x1234')).rejects.toEqual( - new Error(`DefiService: Unable to fetch user's portfolio: Failure`) + new Error(`DefiService: Unable to fetch user's portfolio: Failure`), ); }); diff --git a/src/background/services/defi/DefiService.ts b/src/background/services/defi/DefiService.ts index 1c7cef9f4..b389a2378 100644 --- a/src/background/services/defi/DefiService.ts +++ b/src/background/services/defi/DefiService.ts @@ -12,7 +12,7 @@ export class DefiService { constructor( private debankService: DebankService, - private storageService: StorageService + private storageService: StorageService, ) {} async getUserPortfolio(address: string): Promise { @@ -40,7 +40,7 @@ export class DefiService { throw new Error( `DefiService: Unable to fetch user's portfolio: ${ err instanceof Error ? err.message : err - }` + }`, ); } } @@ -51,7 +51,7 @@ export class DefiService { #buildPortfolio( liveProtocols: DefiProtocol[], - stalePortfolio?: DefiPortfolio + stalePortfolio?: DefiPortfolio, ) { // We just want to make sure the cached protocols do not suddenly disappear // from the portfolio when their positions are closed. @@ -82,7 +82,7 @@ export class DefiService { try { await this.storageService.saveToSessionStorage( this.#getCacheStorageKey(address), - portfolio + portfolio, ); } catch { // If we didn't manage to cache it - no biggie. @@ -90,10 +90,10 @@ export class DefiService { } async #getCachedPortfolio( - address: string + address: string, ): Promise { return this.storageService.loadFromSessionStorage( - this.#getCacheStorageKey(address) + this.#getCacheStorageKey(address), ); } @@ -104,13 +104,13 @@ export class DefiService { #calculateTotalValueOfUserProtocols(protocols: DefiProtocol[]): number { return protocols.reduce( (total, { totalUsdValue }) => total + totalUsdValue, - 0 + 0, ); } #sortProtocols(protocols: DefiProtocol[]): DefiProtocol[] { return [...protocols].sort( - ({ totalUsdValue: valueA }, { totalUsdValue: valueB }) => valueB - valueA + ({ totalUsdValue: valueA }, { totalUsdValue: valueB }) => valueB - valueA, ); } } diff --git a/src/background/services/defi/events/defiPortfolioUpdatedEvent.ts b/src/background/services/defi/events/defiPortfolioUpdatedEvent.ts index c7ad78e44..6a81e2398 100644 --- a/src/background/services/defi/events/defiPortfolioUpdatedEvent.ts +++ b/src/background/services/defi/events/defiPortfolioUpdatedEvent.ts @@ -20,7 +20,7 @@ export class DefiPortfolioUpdatedEvents implements ExtensionEventEmitter { name: DefiServiceEvents.PortfolioUpdated, value, }); - } + }, ); } @@ -29,7 +29,7 @@ export class DefiPortfolioUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/defi/events/listeners.ts b/src/background/services/defi/events/listeners.ts index a7381bec2..1c1d85ee8 100644 --- a/src/background/services/defi/events/listeners.ts +++ b/src/background/services/defi/events/listeners.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { DefiPortfolioUpdatedEvent, DefiServiceEvents } from '../models'; export function defiPortfolioUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === DefiServiceEvents.PortfolioUpdated; } diff --git a/src/background/services/defi/handlers/getDefiPortfolio.test.ts b/src/background/services/defi/handlers/getDefiPortfolio.test.ts index 641d04ba5..3e51b1658 100644 --- a/src/background/services/defi/handlers/getDefiPortfolio.test.ts +++ b/src/background/services/defi/handlers/getDefiPortfolio.test.ts @@ -30,7 +30,7 @@ describe('src/background/services/defi/handlers/getDefiPortfolio.ts', () => { id: '1', params: ['0x1234'], method: ExtensionRequest.DEFI_GET_PORTFOLIO, - }) + }), ); expect(response).toEqual({ @@ -56,7 +56,7 @@ describe('src/background/services/defi/handlers/getDefiPortfolio.ts', () => { id: '1', params: ['0x1234'], method: ExtensionRequest.DEFI_GET_PORTFOLIO, - }) + }), ); expect(response).toEqual({ diff --git a/src/background/services/featureFlags/FeatureFlagService.test.ts b/src/background/services/featureFlags/FeatureFlagService.test.ts index 593facd86..0cbc73113 100644 --- a/src/background/services/featureFlags/FeatureFlagService.test.ts +++ b/src/background/services/featureFlags/FeatureFlagService.test.ts @@ -47,7 +47,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { const featureFlagsService = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); expect(featureFlagsService.featureFlags).toStrictEqual(DEFAULT_FLAGS); }); @@ -61,7 +61,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -80,7 +80,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -105,7 +105,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -113,7 +113,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { expect(getFeatureFlags).toHaveBeenCalledWith( 'posthogkey', '', - 'https://app.posthog.com' + 'https://app.posthog.com', ); }); @@ -121,7 +121,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -135,7 +135,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -147,7 +147,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -156,7 +156,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { expect(getFeatureFlags).toHaveBeenCalledWith( 'posthogkey', '', - 'posthogurl' + 'posthogurl', ); }); @@ -164,7 +164,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -176,7 +176,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { expect(analyticsServiceMock.addListener).toHaveBeenCalledTimes(1); expect(analyticsServiceMock.addListener).toHaveBeenCalledWith( AnalyticsEvents.ANALYTICS_STATE_UPDATED, - expect.any(Function) + expect.any(Function), ); analyticsServiceMock.getIds.mockReturnValue({ userId: 'userId' }); @@ -193,7 +193,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { expect(getFeatureFlags).toHaveBeenCalledWith( 'posthogkey', 'userId', - 'posthogurl' + 'posthogurl', ); expect(setInterval).toHaveBeenCalledTimes(2); }); @@ -211,11 +211,11 @@ describe('background/services/featureFlags/FeatureFlagService', () => { const featureFlagsService = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); featureFlagsService.addListener( FeatureFlagEvents.FEATURE_FLAG_UPDATED, - eventSubscription + eventSubscription, ); expect(featureFlagsService.featureFlags).toStrictEqual(DEFAULT_FLAGS); @@ -240,11 +240,11 @@ describe('background/services/featureFlags/FeatureFlagService', () => { const featureFlagsService = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); featureFlagsService.addListener( FeatureFlagEvents.FEATURE_FLAG_UPDATED, - eventSubscription + eventSubscription, ); expect(featureFlagsService.featureFlags).toStrictEqual(DEFAULT_FLAGS); @@ -281,7 +281,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { featureFlagsService = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -291,7 +291,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { expect(featureFlagsService.featureFlags).toEqual( expect.objectContaining({ [FeatureGates.DEFI]: false, - }) + }), ); }); @@ -300,7 +300,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { expect.objectContaining({ [FeatureGates.SEND]: true, [FeatureGates.SWAP]: false, - }) + }), ); }); }); @@ -390,7 +390,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { const featureFlagsService = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); @@ -401,7 +401,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { [FeatureGates.SEND]: true, // Comes without a payload, should stay in-tact [FeatureGates.SWAP]: false, // Comes without a payload, should stay in-tact }); - } + }, ); }); }); @@ -432,12 +432,12 @@ describe('background/services/featureFlags/FeatureFlagService', () => { featureFlagsService = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); featureFlagsService.addListener( FeatureFlagEvents.FEATURE_FLAG_UPDATED, - eventSubscription + eventSubscription, ); await new Promise(process.nextTick); }); @@ -467,12 +467,12 @@ describe('background/services/featureFlags/FeatureFlagService', () => { const featureFlagsService = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); featureFlagsService.addListener( FeatureFlagEvents.FEATURE_FLAG_UPDATED, - eventSubscription + eventSubscription, ); expect(lockServiceMock.lock).toHaveBeenCalled(); @@ -495,7 +495,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { service = new FeatureFlagService( analyticsServiceMock, lockServiceMock, - storageServiceMock + storageServiceMock, ); await new Promise(process.nextTick); }); @@ -506,7 +506,7 @@ describe('background/services/featureFlags/FeatureFlagService', () => { it('throws an error if given feature is disabled', () => { expect(() => service.ensureFlagEnabled(FeatureGates.BRIDGE)).toThrow( - `Feature (${FeatureGates.BRIDGE}) is currently unavailable` + `Feature (${FeatureGates.BRIDGE}) is currently unavailable`, ); }); }); diff --git a/src/background/services/featureFlags/FeatureFlagService.ts b/src/background/services/featureFlags/FeatureFlagService.ts index e7507124e..14a7b9f3b 100644 --- a/src/background/services/featureFlags/FeatureFlagService.ts +++ b/src/background/services/featureFlags/FeatureFlagService.ts @@ -37,7 +37,7 @@ export class FeatureFlagService { this.#featureFlags = newFlags; this.#eventEmitter.emit( FeatureFlagEvents.FEATURE_FLAG_UPDATED, - this.#featureFlags + this.#featureFlags, ); // We need to lock the wallet when "everything" flag is disabled. @@ -48,7 +48,7 @@ export class FeatureFlagService { #evaluateFeatureFlags( rawFlags: FeatureFlags, - payloads?: Partial> + payloads?: Partial>, ): FeatureFlags { // If there are no flag payloads to evaluate, just return the bare flags. if (!payloads) { @@ -83,7 +83,7 @@ export class FeatureFlagService { } return [flagName, satisfies(coreVersion, versionRange)]; - }) + }), ); return { @@ -95,7 +95,7 @@ export class FeatureFlagService { private async updateFeatureFlags(newFlags: FeatureFlags) { const overrides = (await this.storageService.loadUnencrypted( - FEATURE_FLAGS_OVERRIDES_KEY + FEATURE_FLAGS_OVERRIDES_KEY, )) || {}; const hasOverrides = Object.keys(overrides).length > 0; @@ -112,7 +112,7 @@ export class FeatureFlagService { constructor( private analyticsService: AnalyticsService, private lockService: LockService, - private storageService: StorageService + private storageService: StorageService, ) { // start fetching feature as early as possible // update requests with unique id after it's available @@ -132,7 +132,7 @@ export class FeatureFlagService { this.initFeatureFlags().catch((e) => { console.error(e); }); - } + }, ); } @@ -154,10 +154,10 @@ export class FeatureFlagService { const { flags, flagPayloads } = await getFeatureFlags( process.env.POSTHOG_KEY, analyticsState?.userId ?? '', - process.env.POSTHOG_URL ?? 'https://app.posthog.com' + process.env.POSTHOG_URL ?? 'https://app.posthog.com', ); await this.updateFeatureFlags( - this.#evaluateFeatureFlags(flags, flagPayloads) + this.#evaluateFeatureFlags(flags, flagPayloads), ); } catch (err) { console.error((err as unknown as Error).message); @@ -168,7 +168,7 @@ export class FeatureFlagService { () => { getAndDispatchFlags(); }, - isProductionBuild() ? 30_000 : 5_000 + isProductionBuild() ? 30_000 : 5_000, ); getAndDispatchFlags(); @@ -176,7 +176,7 @@ export class FeatureFlagService { addListener( event: FeatureFlagEvents, - callback: (data: FeatureFlags) => void + callback: (data: FeatureFlags) => void, ) { this.#eventEmitter.on(event, callback); } diff --git a/src/background/services/featureFlags/events/featureFlagsUpdatedEvent.ts b/src/background/services/featureFlags/events/featureFlagsUpdatedEvent.ts index 03f3a4555..42a936999 100644 --- a/src/background/services/featureFlags/events/featureFlagsUpdatedEvent.ts +++ b/src/background/services/featureFlags/events/featureFlagsUpdatedEvent.ts @@ -18,7 +18,7 @@ export class FeatureFlagsUpdatedEvent implements ExtensionEventEmitter { name: FeatureFlagEvents.FEATURE_FLAG_UPDATED, value: featureFlags, }); - } + }, ); } @@ -27,7 +27,7 @@ export class FeatureFlagsUpdatedEvent implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/featureFlags/events/featureFlagsUpdatedEventListener.ts b/src/background/services/featureFlags/events/featureFlagsUpdatedEventListener.ts index ecefd9703..dc6d04aff 100644 --- a/src/background/services/featureFlags/events/featureFlagsUpdatedEventListener.ts +++ b/src/background/services/featureFlags/events/featureFlagsUpdatedEventListener.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { FeatureFlagEvents, FeatureGates } from '../models'; export function featureFlagsUpdatedEventListener( - evt: ExtensionConnectionEvent> + evt: ExtensionConnectionEvent>, ) { return evt.name === FeatureFlagEvents.FEATURE_FLAG_UPDATED; } diff --git a/src/background/services/featureFlags/utils/getFeatureFlags.test.ts b/src/background/services/featureFlags/utils/getFeatureFlags.test.ts index 5a6180be7..5dab2b56c 100644 --- a/src/background/services/featureFlags/utils/getFeatureFlags.test.ts +++ b/src/background/services/featureFlags/utils/getFeatureFlags.test.ts @@ -36,7 +36,7 @@ describe('src/background/services/featureFlags/utils/getFeatureFlags', () => { const { flags } = await getFeatureFlags( 'token', 'userID', - 'https://example.com' + 'https://example.com', ); expect(flags).toEqual({ @@ -49,13 +49,13 @@ describe('src/background/services/featureFlags/utils/getFeatureFlags', () => { const { flagPayloads } = await getFeatureFlags( 'token', 'userID', - 'https://example.com' + 'https://example.com', ); expect(flagPayloads).toEqual( expect.objectContaining({ [FeatureGates.DEFI]: '>=1.60.0', - }) + }), ); }); }; @@ -63,7 +63,7 @@ describe('src/background/services/featureFlags/utils/getFeatureFlags', () => { it('throws if no token is provided', async () => { await expect(getFeatureFlags()).rejects.toThrow(new Error('Invalid token')); await expect(getFeatureFlags('')).rejects.toThrow( - new Error('Invalid token') + new Error('Invalid token'), ); }); @@ -80,7 +80,7 @@ describe('src/background/services/featureFlags/utils/getFeatureFlags', () => { body: 'data=eyJ0b2tlbiI6InRva2VuIiwiZGlzdGluY3RfaWQiOiJ1c2VySUQiLCJncm91cHMiOnt9fQ%3D%3D', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, method: 'POST', - } + }, ); }); @@ -102,13 +102,13 @@ describe('src/background/services/featureFlags/utils/getFeatureFlags', () => { it('throws if no posthogURL is provided', async () => { await expect(getFeatureFlags('token', undefined)).rejects.toThrow( - new Error('Invalid Posthog URL') + new Error('Invalid Posthog URL'), ); }); it('throws if provided posthogURL is empty', async () => { await expect(getFeatureFlags('token', undefined, '')).rejects.toThrow( - new Error('Invalid Posthog URL') + new Error('Invalid Posthog URL'), ); }); @@ -125,7 +125,7 @@ describe('src/background/services/featureFlags/utils/getFeatureFlags', () => { body: 'data=eyJ0b2tlbiI6InRva2VuIiwiZGlzdGluY3RfaWQiOiJ1c2VySUQiLCJncm91cHMiOnt9fQ%3D%3D', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, method: 'POST', - } + }, ); expect(fetch).toHaveBeenNthCalledWith( 2, @@ -134,7 +134,7 @@ describe('src/background/services/featureFlags/utils/getFeatureFlags', () => { body: 'data=eyJ0b2tlbiI6InRva2VuIiwiZGlzdGluY3RfaWQiOiJ1c2VySUQiLCJncm91cHMiOnt9fQ%3D%3D', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, method: 'POST', - } + }, ); }); diff --git a/src/background/services/featureFlags/utils/getFeatureFlags.ts b/src/background/services/featureFlags/utils/getFeatureFlags.ts index 58e92fc86..d6b02528b 100644 --- a/src/background/services/featureFlags/utils/getFeatureFlags.ts +++ b/src/background/services/featureFlags/utils/getFeatureFlags.ts @@ -5,7 +5,7 @@ export async function getFeatureFlags( userId?: string, posthogUrl?: string, ver = '1.20.0', - v = '3' + v = '3', ) { if (!token) { throw new Error('Invalid token'); diff --git a/src/background/services/fireblocks/FireblocksBTCSigner.test.ts b/src/background/services/fireblocks/FireblocksBTCSigner.test.ts index b9c610e83..494bf6859 100644 --- a/src/background/services/fireblocks/FireblocksBTCSigner.test.ts +++ b/src/background/services/fireblocks/FireblocksBTCSigner.test.ts @@ -79,7 +79,7 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { address: knownAddress, value: 1000, }, - ] + ], ) .then((result) => { expect(result).toEqual({ txHash: 'tx-hash' }); @@ -94,7 +94,7 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { await waitForIntervalRuns( expectedNumberOfCalls, - TRANSACTION_POLLING_INTERVAL_MS + TRANSACTION_POLLING_INTERVAL_MS, ); expect(fbService.request).toHaveBeenCalledTimes(expectedNumberOfCalls); }); @@ -117,14 +117,14 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { address: knownAddress, value: 1000, }, - ] + ], ); expect(fbService.request).toHaveBeenCalledWith( expect.objectContaining({ body: expect.objectContaining({ assetId: 'BTC', }), - }) + }), ); }); @@ -138,14 +138,14 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { address: knownAddress, value: 1000, }, - ] + ], ); expect(fbService.request).toHaveBeenCalledWith( expect.objectContaining({ body: expect.objectContaining({ assetId: 'BTC_TEST', }), - }) + }), ); }); @@ -159,7 +159,7 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { address: knownAddress, value: 1000, }, - ] + ], ); expect(fbService.request).toHaveBeenCalledWith( @@ -170,7 +170,7 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { type: PeerType.VAULT_ACCOUNT, }, }), - }) + }), ); }); @@ -192,7 +192,7 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { address: 'source-address', value: 500000, }, - ] + ], ); expect(fbService.request).toHaveBeenCalledWith( @@ -217,7 +217,7 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { }, ], }), - }) + }), ); }); }); @@ -236,10 +236,12 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { address: knownAddress, value: 1000, }, - ] - ) + ], + ), ).rejects.toThrow( - ethErrors.rpc.internal({ data: { reason: CommonError.NetworkError } }) + ethErrors.rpc.internal({ + data: { reason: CommonError.NetworkError }, + }), ); }); }); @@ -268,10 +270,10 @@ describe('src/background/services/fireblocks/FireblocksBTCSigner', () => { address: knownAddress, value: 1000, }, - ] - ) + ], + ), ).rejects.toThrow( - ethErrors.rpc.transactionRejected({ data: { reason: errorCode } }) + ethErrors.rpc.transactionRejected({ data: { reason: errorCode } }), ); }); }); diff --git a/src/background/services/fireblocks/FireblocksBTCSigner.ts b/src/background/services/fireblocks/FireblocksBTCSigner.ts index 463e2344e..809e6db26 100644 --- a/src/background/services/fireblocks/FireblocksBTCSigner.ts +++ b/src/background/services/fireblocks/FireblocksBTCSigner.ts @@ -35,7 +35,7 @@ export class FireblocksBTCSigner { constructor( fireblocksService: FireblocksService, vaultAccountId: string, - isTestnet?: boolean + isTestnet?: boolean, ) { this.#isTestnet = isTestnet; this.#vaultAccountId = vaultAccountId; @@ -44,7 +44,7 @@ export class FireblocksBTCSigner { async signTx( inputs: BtcTransactionRequest['inputs'], - outputs: BtcTransactionRequest['outputs'] + outputs: BtcTransactionRequest['outputs'], ): Promise { /** * TODO: Do we need to handle mutliple inputs? Fireblocks has a way of selecting @@ -111,8 +111,8 @@ export class FireblocksBTCSigner { wrapError( ethErrors.rpc.internal({ data: { reason: FireblocksErrorCode.Unknown }, - }) - ) + }), + ), ); // TODO: Emit an event containing a transaction ID, so we can start @@ -132,7 +132,7 @@ export class FireblocksBTCSigner { * TODO: emit success/failure events to finalize the transaction tracking. */ async #waitForTransaction( - txId: string + txId: string, ): Promise { let continuePolling = true; let tx: TransactionResponse; @@ -190,12 +190,10 @@ export class FireblocksBTCSigner { async #getDestinations( outputs: BtcTransactionRequest['outputs'], - txAssetId: string + txAssetId: string, ): Promise { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const knownAddresses = await this.#client.getAllKnownAddressesForAsset( - txAssetId - ); + const knownAddresses = + await this.#client.getAllKnownAddressesForAsset(txAssetId); // When there are multiple outputs, the last seems to always be the "rest". // Unfortunately, we can't have that rest UTXO here, as Fireblocks "wants to" @@ -225,7 +223,7 @@ export class FireblocksBTCSigner { }, }, }; - } + }, ); } diff --git a/src/background/services/fireblocks/FireblocksSecretsService.ts b/src/background/services/fireblocks/FireblocksSecretsService.ts index 1e7810700..850af6c7c 100644 --- a/src/background/services/fireblocks/FireblocksSecretsService.ts +++ b/src/background/services/fireblocks/FireblocksSecretsService.ts @@ -15,7 +15,7 @@ import { AccountsService } from '../accounts/AccountsService'; export class FireblocksSecretsService implements FireblocksSecretsProvider { constructor( private secretsService: SecretsService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} async getSecrets(): Promise<{ apiKey: string; privateKey: KeyLike }> { @@ -24,18 +24,18 @@ export class FireblocksSecretsService implements FireblocksSecretsProvider { } // By default thought, we'll get the credentials directly from SecretsService const secrets = await this.secretsService.getAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets.secretType !== SecretType.Fireblocks) { throw new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.WrongAccountType + FireblocksBtcAccessErrorCode.WrongAccountType, ); } if (!secrets.api) { throw new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.SecretsNotConfigured + FireblocksBtcAccessErrorCode.SecretsNotConfigured, ); } @@ -48,7 +48,7 @@ export class FireblocksSecretsService implements FireblocksSecretsProvider { }; } catch { throw new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.InvalidSecretKey + FireblocksBtcAccessErrorCode.InvalidSecretKey, ); } } diff --git a/src/background/services/fireblocks/FireblocksService.test.ts b/src/background/services/fireblocks/FireblocksService.test.ts index b6ef5938a..059ba2c96 100644 --- a/src/background/services/fireblocks/FireblocksService.test.ts +++ b/src/background/services/fireblocks/FireblocksService.test.ts @@ -66,7 +66,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { const secretsService = jest.mocked(new SecretsService({} as any)); const secretsProvider = new FireblocksSecretsService( secretsService, - accountsService + accountsService, ); let service: FireblocksService; @@ -111,12 +111,12 @@ describe('src/background/services/fireblocks/FireblocksService', () => { }, ], }, - }) + }), ); const result = await service.getBtcAddressByAccountId( vaultAccount1, - false + false, ); expect(result).toEqual(vaultAcctAddr); expect(global.fetch).toHaveBeenCalledTimes(1); @@ -153,12 +153,12 @@ describe('src/background/services/fireblocks/FireblocksService', () => { }, ], }, - }) + }), ); const result = await service.getBtcAddressByAccountId( vaultAccount1, - false + false, ); expect(result).toEqual(vaultAcctAddr2); expect(global.fetch).toHaveBeenCalledTimes(2); @@ -188,7 +188,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { [`/vault/accounts/${vaultAccount1}/BTC_TEST/addresses_paginated`]: { addresses: [primaryAddress], }, - }) + }), ); const result = await service.getAllAddesses(vaultAccount1, 'BTC_TEST'); @@ -209,7 +209,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { { addresses: [primaryAddress], }, - }) + }), ); const result = await service.getAllAddesses(vaultAccount1, 'BTC_TEST'); @@ -234,7 +234,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { ], }, ], - }) + }), ); }); @@ -263,7 +263,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { ], }, ], - }) + }), ); }); @@ -301,7 +301,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { }, ], }, - }) + }), ); }); @@ -338,7 +338,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { apiErrorCode: 1427, apiErrorMessage: 'Source type of transaction is invalid', }, - }) + }), ); }); @@ -368,7 +368,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { 'Cannot read properties of undefined (reading "type")', }, }), - SentryExceptionTypes.FIREBLOCKS + SentryExceptionTypes.FIREBLOCKS, ); } }); @@ -382,7 +382,7 @@ describe('src/background/services/fireblocks/FireblocksService', () => { data: { reason: CommonError.NetworkError, }, - }) + }), ); }); }); diff --git a/src/background/services/fireblocks/FireblocksService.ts b/src/background/services/fireblocks/FireblocksService.ts index fc00f20ab..73e2e77a4 100644 --- a/src/background/services/fireblocks/FireblocksService.ts +++ b/src/background/services/fireblocks/FireblocksService.ts @@ -45,7 +45,7 @@ import './registry'; export class FireblocksService { constructor( @inject('FireblocksSecretsProvider') - private secretsProvider: FireblocksSecretsProvider + private secretsProvider: FireblocksSecretsProvider, ) {} async fetchVaultAccountByWalletAddress(address: string, assetIds: string[]) { @@ -63,14 +63,14 @@ export class FireblocksService { async getBtcAddressByAccountId( accountId: string, isMainnet: boolean, - nextPaginationToken?: string + nextPaginationToken?: string, ) { const assetId = isMainnet ? 'BTC' : 'BTC_TEST'; const response = await this.getAddresses( accountId, assetId, - nextPaginationToken + nextPaginationToken, ); const permanent = response.addresses.find((address) => { @@ -85,7 +85,7 @@ export class FireblocksService { return await this.getBtcAddressByAccountId( accountId, isMainnet, - response.paging?.after + response.paging?.after, ); } @@ -101,7 +101,7 @@ export class FireblocksService { async getAddresses( accountId: string, assetId: string, - nextPaginationToken?: string + nextPaginationToken?: string, ) { const queryParamKey = '?after='; @@ -121,7 +121,7 @@ export class FireblocksService { const response = await this.getAddresses( accountId, assetId, - nextPaginationToken + nextPaginationToken, ); nextPaginationToken = response.paging?.after; addresses = [...addresses, ...response.addresses]; @@ -155,7 +155,7 @@ export class FireblocksService { vaultAccounts.accounts.map(async ({ id }) => ({ vaultId: id, addresses: await this.getAllAddesses(id, assetId), - })) + })), ); const addressToVaultMap = new Map(); @@ -179,7 +179,7 @@ export class FireblocksService { * TODO: cache this data in storage, with some kind of TTL. */ async getAllKnownAddressesForAsset( - assetId: string + assetId: string, ): Promise { const addressDictionary: KnownAddressDictionary = new Map(); diff --git a/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.test.ts b/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.test.ts index c04e8d985..d6bbb7236 100644 --- a/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.test.ts +++ b/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.test.ts @@ -36,7 +36,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent {} as any, {} as any, {} as any, - {} as any + {} as any, ); const fireblocksServiceMock = new FireblocksService({} as any); @@ -69,11 +69,11 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); expect(handler.method).toBe( - ExtensionRequest.FIREBLOCKS_UPDATE_API_CREDENTIALS + ExtensionRequest.FIREBLOCKS_UPDATE_API_CREDENTIALS, ); }); @@ -81,7 +81,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); expect(await handler.handle(mockRequest)).toEqual({ @@ -90,11 +90,11 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent }); expect( - fireblocksServiceMock.fetchVaultAccountByWalletAddress + fireblocksServiceMock.fetchVaultAccountByWalletAddress, ).toHaveBeenCalledWith('0x000', MAINNET_LOOKUP_ASSETS); expect(fireblocksServiceMock.getBtcAddressByAccountId).toHaveBeenCalledWith( 'VAULT_ACCOUNT_ID', - true + true, ); expect(importPKCS8).toHaveBeenCalledWith('SECRET_KEY', 'RS256'); @@ -112,14 +112,14 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent vaultAccountId: 'VAULT_ACCOUNT_ID', }, secretType: SecretType.Fireblocks, - } + }, ); expect(accountServiceMock.refreshAddressesForAccount).toHaveBeenCalledTimes( - 1 + 1, ); expect(accountServiceMock.refreshAddressesForAccount).toHaveBeenCalledWith( - 'ACCOUNT_ID' + 'ACCOUNT_ID', ); }); @@ -127,7 +127,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); jest.mocked(networkServiceMock.isMainnet).mockReturnValue(false); @@ -138,12 +138,12 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent }); expect( - fireblocksServiceMock.fetchVaultAccountByWalletAddress + fireblocksServiceMock.fetchVaultAccountByWalletAddress, ).toHaveBeenCalledWith('0x000', TESTNET_LOOKUP_ASSETS); expect(fireblocksServiceMock.getBtcAddressByAccountId).toHaveBeenCalledWith( 'VAULT_ACCOUNT_ID', - false + false, ); }); @@ -151,7 +151,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); jest.mocked(accountServiceMock.getAccountByID).mockReturnValue({ type: AccountType.WALLET_CONNECT, @@ -163,7 +163,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent expect(await handler.handle(mockRequest)).toEqual({ ...mockRequest.request, error: new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.WrongAccountType + FireblocksBtcAccessErrorCode.WrongAccountType, ).message, }); }); @@ -172,7 +172,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); jest.mocked(accountServiceMock.getAccountByID).mockReturnValue(undefined); @@ -186,7 +186,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); jest .mocked(fireblocksServiceMock.fetchVaultAccountByWalletAddress) @@ -195,7 +195,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent expect(await handler.handle(mockRequest)).toEqual({ ...mockRequest.request, error: new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.VaultAccountNotFound + FireblocksBtcAccessErrorCode.VaultAccountNotFound, ).message, }); }); @@ -204,14 +204,14 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); jest.mocked(importPKCS8).mockRejectedValue('Invalid key'); expect(await handler.handle(mockRequest)).toEqual({ ...mockRequest.request, error: new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.InvalidSecretKey + FireblocksBtcAccessErrorCode.InvalidSecretKey, ).message, }); }); @@ -220,7 +220,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent const handler = new FireblocksUpdateApiCredentialsHandler( accountServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); jest .mocked(fireblocksServiceMock.getBtcAddressByAccountId) @@ -229,7 +229,7 @@ describe('src/background/services/fireblocks/handlers/fireblocksUpdateApiCredent expect(await handler.handle(mockRequest)).toEqual({ ...mockRequest.request, error: new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.BTCAddressNotFound + FireblocksBtcAccessErrorCode.BTCAddressNotFound, ).message, }); }); diff --git a/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.ts b/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.ts index 0649076fd..9fac07bd4 100644 --- a/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.ts +++ b/src/background/services/fireblocks/handlers/fireblocksUpdateApiCredentials.ts @@ -31,7 +31,7 @@ export class FireblocksUpdateApiCredentialsHandler implements HandlerType { constructor( private accountsService: AccountsService, private networkService: NetworkService, - private secretsService: SecretsService + private secretsService: SecretsService, ) {} async #getVaultAccountId(address: string) { @@ -45,12 +45,12 @@ export class FireblocksUpdateApiCredentialsHandler implements HandlerType { const id = await this.#fireblocksService.fetchVaultAccountByWalletAddress( address, - assetIds + assetIds, ); if (!id) { throw new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.VaultAccountNotFound + FireblocksBtcAccessErrorCode.VaultAccountNotFound, ); } @@ -64,12 +64,12 @@ export class FireblocksUpdateApiCredentialsHandler implements HandlerType { const address = await this.#fireblocksService.getBtcAddressByAccountId( vaultAccountId, - this.networkService.isMainnet() + this.networkService.isMainnet(), ); if (!address) { throw new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.BTCAddressNotFound + FireblocksBtcAccessErrorCode.BTCAddressNotFound, ); } @@ -78,7 +78,7 @@ export class FireblocksUpdateApiCredentialsHandler implements HandlerType { async #getSecretsProvider( apiKey: string, - secretKey: string + secretKey: string, ): Promise { try { const privateKey = await importPKCS8(secretKey, 'RS256'); @@ -92,7 +92,7 @@ export class FireblocksUpdateApiCredentialsHandler implements HandlerType { }; } catch { throw new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.InvalidSecretKey + FireblocksBtcAccessErrorCode.InvalidSecretKey, ); } } @@ -102,7 +102,7 @@ export class FireblocksUpdateApiCredentialsHandler implements HandlerType { try { this.#fireblocksService = new FireblocksService( - await this.#getSecretsProvider(apiKey, secretKey) + await this.#getSecretsProvider(apiKey, secretKey), ); const account = this.accountsService.getAccountByID(coreAccountId); @@ -113,7 +113,7 @@ export class FireblocksUpdateApiCredentialsHandler implements HandlerType { if (account.type !== AccountType.FIREBLOCKS) { throw new FireblocksBtcAccessError( - FireblocksBtcAccessErrorCode.WrongAccountType + FireblocksBtcAccessErrorCode.WrongAccountType, ); } diff --git a/src/background/services/glacier/GlacierService.test.ts b/src/background/services/glacier/GlacierService.test.ts index 807db1c6d..f9bb287a8 100644 --- a/src/background/services/glacier/GlacierService.test.ts +++ b/src/background/services/glacier/GlacierService.test.ts @@ -152,7 +152,7 @@ describe('src/background/services/glacier/GlacierService.ts', () => { await glacierService.refreshNftMetadata( 'address', 'chainId', - 'tokenId' + 'tokenId', ); } catch (err) { expect(err).toEqual('request-timeout'); diff --git a/src/background/services/history/HistoryService.test.ts b/src/background/services/history/HistoryService.test.ts index a6cdf3897..a9aff4cb8 100644 --- a/src/background/services/history/HistoryService.test.ts +++ b/src/background/services/history/HistoryService.test.ts @@ -102,7 +102,7 @@ describe('src/background/services/history/HistoryService.ts', () => { service = new HistoryService( moduleManagereMock, accountsServiceMock, - unifiedBridgeServiceMock + unifiedBridgeServiceMock, ); jest diff --git a/src/background/services/history/HistoryService.ts b/src/background/services/history/HistoryService.ts index d44b474fb..a33afe2e5 100644 --- a/src/background/services/history/HistoryService.ts +++ b/src/background/services/history/HistoryService.ts @@ -17,12 +17,12 @@ export class HistoryService { constructor( private moduleManager: ModuleManager, private accountsService: AccountsService, - private unifiedBridgeService: UnifiedBridgeService + private unifiedBridgeService: UnifiedBridgeService, ) {} async getTxHistory( network: NetworkWithCaipId, - otherAddress?: string + otherAddress?: string, ): Promise { const address = otherAddress ?? this.#getAddress(network); @@ -31,15 +31,15 @@ export class HistoryService { } const [module] = await resolve( - this.moduleManager.loadModuleByNetwork(network) + this.moduleManager.loadModuleByNetwork(network), ); if (!module) { sentryCaptureException( new Error( - `Fetching history failed. Module not found for ${network.caipId}` + `Fetching history failed. Module not found for ${network.caipId}`, ), - SentryExceptionTypes.VM_MODULES + SentryExceptionTypes.VM_MODULES, ); return []; } diff --git a/src/background/services/history/handlers/getHistory.ts b/src/background/services/history/handlers/getHistory.ts index 6a9d47b47..57f763a9a 100644 --- a/src/background/services/history/handlers/getHistory.ts +++ b/src/background/services/history/handlers/getHistory.ts @@ -16,7 +16,7 @@ export class GetHistoryHandler implements HandlerType { constructor( private historyService: HistoryService, - private networkService: NetworkService + private networkService: NetworkService, ) {} handle: HandlerType['handle'] = async ({ request, scope }) => { diff --git a/src/background/services/history/utils/isTxHistoryItem.ts b/src/background/services/history/utils/isTxHistoryItem.ts index 8cab02a96..f12b82cae 100644 --- a/src/background/services/history/utils/isTxHistoryItem.ts +++ b/src/background/services/history/utils/isTxHistoryItem.ts @@ -2,7 +2,7 @@ import { NetworkVMType } from '@avalabs/vm-module-types'; import { TxHistoryItem } from '../models'; export function isNonXPHistoryItem( - tx: TxHistoryItem + tx: TxHistoryItem, ): tx is TxHistoryItem< Exclude > { @@ -10,7 +10,7 @@ export function isNonXPHistoryItem( } export function isPchainTxHistoryItem( - tx: TxHistoryItem + tx: TxHistoryItem, ): tx is TxHistoryItem { return tx.vmType === 'PVM'; } diff --git a/src/background/services/keystone/BitcoinKeystoneWallet.test.ts b/src/background/services/keystone/BitcoinKeystoneWallet.test.ts index 323cec823..a56cc3a96 100644 --- a/src/background/services/keystone/BitcoinKeystoneWallet.test.ts +++ b/src/background/services/keystone/BitcoinKeystoneWallet.test.ts @@ -9,7 +9,7 @@ jest.mock('@avalabs/core-wallets-sdk'); const FIXTURES = { MOCKED_PSBT: Buffer.from( '70736274ff0100520200000001a571b1112b5ce00487e5d3531f168ace50834675898766f96ad55d19374d28770000000000ffffffff0110270000000000001600142f1687421b7b090e42918332b16f4a81d74c4ad7000000000001011f6d3300000000000016001405bd27f4c353c4dc49af121439b810828bc15ab4220602457a4e0160c6e5c553436f1f77ec59f09d1a93e1639578657eea995dcb3907b51880d3bb222c0000803c0000800000008000000000000000000000', - 'hex' + 'hex', ), TRANSACTION_REQUEST: { inputs: [{}, {}] as WalletsSDK.BitcoinInputUTXO[], @@ -21,11 +21,11 @@ const FIXTURES = { }, SIGNATURE_RESPONSE: Buffer.from( '58ed70736274ff0100520200000001a571b1112b5ce00487e5d3531f168ace50834675898766f96ad55d19374d28770000000000ffffffff0110270000000000001600142f1687421b7b090e42918332b16f4a81d74c4ad7000000000001011f6d3300000000000016001405bd27f4c353c4dc49af121439b810828bc15ab401086b0247304402206cc7fb01a93e7277f19f71cf1610761ee038db9ea7e91e4b923a8dbc4420f062022043341566f0b122e11e7ed636e8acfab4c4b53312fab10bb4375375ec10344ab5012102457a4e0160c6e5c553436f1f77ec59f09d1a93e1639578657eea995dcb3907b50000', - 'hex' + 'hex', ), SIGNED_TX: Buffer.from( '70736274ff0100520200000001a571b1112b5ce00487e5d3531f168ace50834675898766f96ad55d19374d28770000000000ffffffff0110270000000000001600142f1687421b7b090e42918332b16f4a81d74c4ad7000000000001011f6d3300000000000016001405bd27f4c353c4dc49af121439b810828bc15ab401086b0247304402206cc7fb01a93e7277f19f71cf1610761ee038db9ea7e91e4b923a8dbc4420f062022043341566f0b122e11e7ed636e8acfab4c4b53312fab10bb4375375ec10344ab5012102457a4e0160c6e5c553436f1f77ec59f09d1a93e1639578657eea995dcb3907b50000', - 'hex' + 'hex', ), }; @@ -39,7 +39,7 @@ const keystoneTransport = { } as unknown as KeystoneTransport; const fingerprint = '80d3bb22'; const pubKey = Buffer.from( - '02457a4e0160c6e5c553436f1f77ec59f09d1a93e1639578657eea995dcb3907b5' + '02457a4e0160c6e5c553436f1f77ec59f09d1a93e1639578657eea995dcb3907b5', ); const keyPath = `m/44'/9000'/0'/0/0`; const network = { bech32: 'tb' } as Network; @@ -74,7 +74,7 @@ describe('src/background/services/keystone/BitcoinKeystoneWallet.ts', () => { keyPath, keystoneTransport, provider, - tabId + tabId, ); }); @@ -85,7 +85,7 @@ describe('src/background/services/keystone/BitcoinKeystoneWallet.ts', () => { expect(WalletsSDK.createPsbt).toHaveBeenCalledWith( inputs, outputs, - network + network, ); }); @@ -112,7 +112,7 @@ describe('src/background/services/keystone/BitcoinKeystoneWallet.ts', () => { expect(keystoneTransport.requestSignature).toHaveBeenCalledWith( FIXTURES.SIGNATURE_REQUEST, - tabId + tabId, ); }); @@ -129,7 +129,7 @@ describe('src/background/services/keystone/BitcoinKeystoneWallet.ts', () => { const result = await wallet.signTx(inputs, outputs); expect(CryptoPSBT.fromCBOR).toHaveBeenCalledWith( - FIXTURES.SIGNATURE_RESPONSE + FIXTURES.SIGNATURE_RESPONSE, ); expect(result).toEqual('signed-tx'); }); diff --git a/src/background/services/keystone/BitcoinKeystoneWallet.ts b/src/background/services/keystone/BitcoinKeystoneWallet.ts index 58203c8fe..266c4f391 100644 --- a/src/background/services/keystone/BitcoinKeystoneWallet.ts +++ b/src/background/services/keystone/BitcoinKeystoneWallet.ts @@ -12,12 +12,12 @@ export class BitcoinKeystoneWallet { private keyPath: string, private keystoneTransport: KeystoneTransport, private provider: BitcoinProviderAbstract, - private tabId?: number + private tabId?: number, ) {} async signTx( inputs: BtcTransactionRequest['inputs'], - outputs: BtcTransactionRequest['outputs'] + outputs: BtcTransactionRequest['outputs'], ): Promise { const psbt = createPsbt(inputs, outputs, this.provider.getNetwork()); @@ -41,7 +41,7 @@ export class BitcoinKeystoneWallet { type, cbor: cbor.toString('hex'), }, - this.tabId + this.tabId, ); const signedTx = CryptoPSBT.fromCBOR(signedCborBuffer).getPSBT(); diff --git a/src/background/services/keystone/KeystoneService.test.ts b/src/background/services/keystone/KeystoneService.test.ts index 0300becd9..245fc86d9 100644 --- a/src/background/services/keystone/KeystoneService.test.ts +++ b/src/background/services/keystone/KeystoneService.test.ts @@ -43,7 +43,7 @@ describe('background/services/keystone/KeystoneService.ts', () => { ({ getRegistryType: jest.fn().mockReturnValue(mockRegistryType), getSignature: jest.fn().mockReturnValue(signatureBuffer), - } as any as ETHSignature) + }) as any as ETHSignature, ); mockedRequest.toUR.mockReturnValue(mockedUR); jest @@ -69,7 +69,7 @@ describe('background/services/keystone/KeystoneService.ts', () => { expect( // @ts-expect-error keystoneRequestSubscription is private - service.keystoneRequestSubscription?.unsubscribe + service.keystoneRequestSubscription?.unsubscribe, ).toHaveBeenCalled(); }); }); diff --git a/src/background/services/keystone/KeystoneService.ts b/src/background/services/keystone/KeystoneService.ts index 1c2b9df39..fcb32eec1 100644 --- a/src/background/services/keystone/KeystoneService.ts +++ b/src/background/services/keystone/KeystoneService.ts @@ -22,7 +22,7 @@ export class KeystoneService implements KeystoneTransport, OnUnlock { this.keystoneRequestSubscription = this.keystoneDeviceRequest$.subscribe( (request) => { this.eventEmitter.emit(KeystoneEvent.DEVICE_REQUEST, request); - } + }, ); } @@ -50,8 +50,8 @@ export class KeystoneService implements KeystoneTransport, OnUnlock { filter((response) => response.requestId === requestId), map((response: DeviceResponseData) => { return Buffer.from(response.cbor, 'hex'); - }) - ) + }), + ), ); } diff --git a/src/background/services/keystone/KeystoneWallet.test.ts b/src/background/services/keystone/KeystoneWallet.test.ts index a80ba04d5..6bf9b7f9a 100644 --- a/src/background/services/keystone/KeystoneWallet.test.ts +++ b/src/background/services/keystone/KeystoneWallet.test.ts @@ -36,7 +36,7 @@ const FIXTURES = { }, SIGNATURE_RESPONSE: Buffer.from( 'a201d8255095a1762eef6e41bdb339c2a15b5d8d70025841c60a745b056a2851dbfd28cdfa7e7069ebb76cebb4a18adb9b715db37f955d85659cd1b54ea949317aa685831bcf241bc58089747437a8e49759158b5982cc082e', - 'hex' + 'hex', ), }; @@ -66,7 +66,7 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { 0, keystoneTransport, currentChainId, - tabId + tabId, ); }); @@ -75,12 +75,12 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { await wallet.signTransaction(FIXTURES.LEGACY_TRANSACTION_REQUEST); expect(keystoneTransport.requestSignature).toHaveBeenCalledWith( FIXTURES.LEGACY_SIGNATURE_REQUEST, - tabId + tabId, ); }); describe('when transaction does not set chainId explicitly', () => { - const { chainId, ...txRequest } = FIXTURES.LEGACY_TRANSACTION_REQUEST; // eslint-disable-line @typescript-eslint/no-unused-vars + const { chainId, ...txRequest } = FIXTURES.LEGACY_TRANSACTION_REQUEST; it(`falls back to the current network's chainId if not explicitly set in the transaction`, async () => { wallet = new KeystoneWallet( @@ -88,7 +88,7 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { 0, keystoneTransport, chainId, - tabId + tabId, ); await wallet.signTransaction(txRequest); @@ -99,7 +99,7 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { common: expect.objectContaining({ _chainParams: expect.objectContaining({ chainId: chainId }), }), - }) + }), ); }); }); @@ -108,7 +108,7 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { await wallet.signTransaction(FIXTURES.LEGACY_TRANSACTION_REQUEST); expect(ETHSignature.fromCBOR).toHaveBeenCalledWith( - FIXTURES.SIGNATURE_RESPONSE + FIXTURES.SIGNATURE_RESPONSE, ); }); @@ -135,7 +135,7 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { s, v, }, - expect.anything() + expect.anything(), ); }); @@ -157,7 +157,7 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { expect.anything(), expect.anything(), expect.anything(), - expect.anything() + expect.anything(), ); }); }); @@ -180,7 +180,7 @@ describe('src/background/services/keystone/KeystoneWallet.ts', () => { expect.anything(), expect.anything(), expect.anything(), - expect.anything() + expect.anything(), ); }); }); diff --git a/src/background/services/keystone/KeystoneWallet.ts b/src/background/services/keystone/KeystoneWallet.ts index 7aa95ca8a..a6a7a559a 100644 --- a/src/background/services/keystone/KeystoneWallet.ts +++ b/src/background/services/keystone/KeystoneWallet.ts @@ -24,7 +24,7 @@ export class KeystoneWallet { private activeAccountIndex: number, private keystoneTransport: KeystoneTransport, private chainId?: number, - private tabId?: number + private tabId?: number, ) {} async signTransaction(txRequest: TransactionRequest): Promise { @@ -32,9 +32,9 @@ export class KeystoneWallet { await this.buildSignatureRequest( txRequest, this.fingerprint, - this.activeAccountIndex + this.activeAccountIndex, ), - this.tabId + this.tabId, ); const signature = ETHSignature.fromCBOR(cborBuffer).getSignature(); @@ -54,7 +54,7 @@ export class KeystoneWallet { private async buildSignatureRequest( txRequest: TransactionRequest, fingerprint: string, - activeAccountIndex: number + activeAccountIndex: number, ): Promise { const chainId = txRequest.chainId ?? this.chainId; const isLegacyTx = typeof txRequest.gasPrice !== 'undefined'; @@ -80,7 +80,7 @@ export class KeystoneWallet { keyPath, fingerprint, crypto.randomUUID(), - Number(chainId) + Number(chainId), ); const ur = ethSignRequest.toUR(); @@ -93,7 +93,7 @@ export class KeystoneWallet { private async getTxFromTransactionRequest( txRequest: TransactionRequest, - signature?: { r: string; s: string; v: number } + signature?: { r: string; s: string; v: number }, ) { return typeof txRequest.gasPrice !== 'undefined' ? Transaction.fromTxData( @@ -105,7 +105,7 @@ export class KeystoneWallet { common: Common.custom({ chainId: Number(txRequest.chainId ?? this.chainId), }), - } + }, ) : FeeMarketEIP1559Transaction.fromTxData( { ...this.txRequestToFeeMarketTxData(txRequest), ...signature }, @@ -117,14 +117,14 @@ export class KeystoneWallet { // to use the new TX props (maxFeePerGas and maxPriorityFeePerGas) in combination // with the custom chainId. hardfork: Hardfork.London, - } + }, ), - } + }, ); } private txRequestToFeeMarketTxData( - txRequest: TransactionRequest + txRequest: TransactionRequest, ): FeeMarketEIP1559TxData { const { to, diff --git a/src/background/services/keystone/events/keystoneDeviceRequest.ts b/src/background/services/keystone/events/keystoneDeviceRequest.ts index c971f601f..b904d5f8b 100644 --- a/src/background/services/keystone/events/keystoneDeviceRequest.ts +++ b/src/background/services/keystone/events/keystoneDeviceRequest.ts @@ -24,7 +24,7 @@ export class KeystoneRequestEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/ledger/LedgerService.test.ts b/src/background/services/ledger/LedgerService.test.ts index 9381b4dcc..3e372e299 100644 --- a/src/background/services/ledger/LedgerService.test.ts +++ b/src/background/services/ledger/LedgerService.test.ts @@ -34,7 +34,7 @@ describe('src/background/services/ledger/LedgerService.ts', () => { jest.resetAllMocks(); ledgerDeviceRequestMock.subscribe.mockReturnValue( - ledgerRequestSubscriptionMock + ledgerRequestSubscriptionMock, ); (Subject as unknown as jest.Mock) @@ -49,21 +49,21 @@ describe('src/background/services/ledger/LedgerService.ts', () => { it('handles events correctly on unlock', () => { expect(ledgerDeviceRequestMock.subscribe).toBeCalledWith( - expect.any(Function) // we test the actual callback below + expect.any(Function), // we test the actual callback below ); expect(eventEmitterMock.emit).toBeCalledWith( - LedgerEvent.DISCOVER_TRANSPORTS + LedgerEvent.DISCOVER_TRANSPORTS, ); expect(eventEmitterMock.emit).not.toBeCalledWith( LedgerEvent.TRANSPORT_REQUEST, - undefined + undefined, ); // execute ledger request callback manually ledgerDeviceRequestMock.subscribe.mock.calls[0][0](); expect(eventEmitterMock.emit).toBeCalledWith( LedgerEvent.TRANSPORT_REQUEST, - undefined + undefined, ); }); @@ -87,7 +87,7 @@ describe('src/background/services/ledger/LedgerService.ts', () => { lruCacheMock.get.mockReturnValueOnce(transportMock); expect(ledgerService.getTransport(transportId)).toStrictEqual( - transportMock + transportMock, ); expect(lruCacheMock.get).toBeCalledWith(transportId); }); @@ -120,7 +120,7 @@ describe('src/background/services/ledger/LedgerService.ts', () => { await expect(promise).resolves.toBe(true); expect(eventEmitterMock.emit).toHaveBeenCalledWith( LedgerEvent.TRANSPORT_CLOSE_REQUEST, - {} + {}, ); jest.useRealTimers(); }); @@ -140,12 +140,12 @@ describe('src/background/services/ledger/LedgerService.ts', () => { ledgerService.initTransport(transportId); expect(lruCacheMock.set).toBeCalledWith( transportId, - expect.any(LedgerTransport) + expect.any(LedgerTransport), ); expect(LedgerTransport).toBeCalledWith( ledgerDeviceRequestMock, ledgerDeviceResponseMock, - transportId + transportId, ); }); diff --git a/src/background/services/ledger/LedgerService.ts b/src/background/services/ledger/LedgerService.ts index d11e50bd0..c2c40e2f1 100644 --- a/src/background/services/ledger/LedgerService.ts +++ b/src/background/services/ledger/LedgerService.ts @@ -25,7 +25,7 @@ export class LedgerService implements OnLock, OnUnlock { this.ledgerRequestSubscription = this.ledgerDeviceRequest$.subscribe( (request) => { this.eventEmitter.emit(LedgerEvent.TRANSPORT_REQUEST, request); - } + }, ); /** * Request all active frontend LedgerProviders to notify the background after a background script restart. @@ -98,8 +98,8 @@ export class LedgerService implements OnLock, OnUnlock { new LedgerTransport( this.ledgerDeviceRequest$, this.ledgerDeviceResponse$, - ledgerTransportUUID - ) + ledgerTransportUUID, + ), ); } diff --git a/src/background/services/ledger/LedgerTransport.test.ts b/src/background/services/ledger/LedgerTransport.test.ts index 351e943e7..f6128978b 100644 --- a/src/background/services/ledger/LedgerTransport.test.ts +++ b/src/background/services/ledger/LedgerTransport.test.ts @@ -19,7 +19,7 @@ describe('src/background/services/ledger/LedgerTransport.ts', () => { ledgerTransport = new LedgerTransport( ledgerDeviceRequest$, ledgerDeviceResponse$, - uuid + uuid, ); }); @@ -27,13 +27,13 @@ describe('src/background/services/ledger/LedgerTransport.ts', () => { const dataLength = 257; const data = Buffer.alloc(dataLength); await expect( - ledgerTransport.send(1, 2, 3, 4, data, [StatusCodes.OK]) + ledgerTransport.send(1, 2, 3, 4, data, [StatusCodes.OK]), ).rejects.toThrow( expect.objectContaining({ id: 'DataLengthTooBig', name: 'TransportError', message: `data.length exceed 256 bytes limit. Got: ${dataLength}`, - }) + }), ); }); @@ -50,7 +50,7 @@ describe('src/background/services/ledger/LedgerTransport.ts', () => { expect.objectContaining({ name: 'TransportStatusError', message: 'Ledger device: UNKNOWN_ERROR (0x111)', - }) + }), ); }); diff --git a/src/background/services/ledger/LedgerTransport.ts b/src/background/services/ledger/LedgerTransport.ts index 0f1e2e13b..ced23e678 100644 --- a/src/background/services/ledger/LedgerTransport.ts +++ b/src/background/services/ledger/LedgerTransport.ts @@ -10,7 +10,7 @@ export class LedgerTransport extends Transport { constructor( private deviceRequest: Subject, private deviceResponse: Subject, - private connectionUUID: string + private connectionUUID: string, ) { super(); } @@ -21,12 +21,12 @@ export class LedgerTransport extends Transport { p1: number, p2: number, data: Buffer = Buffer.alloc(0), - statusList: Array = [StatusCodes.OK] + statusList: Array = [StatusCodes.OK], ): Promise => { if (data.length >= 256) { throw new TransportError( 'data.length exceed 256 bytes limit. Got: ' + data.length, - 'DataLengthTooBig' + 'DataLengthTooBig', ); } @@ -53,8 +53,8 @@ export class LedgerTransport extends Transport { throw new TransportStatusError(response.error); } return Buffer.from(response.result ?? []); - }) - ) + }), + ), ); }; } diff --git a/src/background/services/ledger/events/ledgerCloseTransport.ts b/src/background/services/ledger/events/ledgerCloseTransport.ts index 6066feed2..4603e7831 100644 --- a/src/background/services/ledger/events/ledgerCloseTransport.ts +++ b/src/background/services/ledger/events/ledgerCloseTransport.ts @@ -24,7 +24,7 @@ export class LedgerCloseTransportEvent implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/ledger/events/ledgerDeviceRequest.ts b/src/background/services/ledger/events/ledgerDeviceRequest.ts index 18be90287..1d57847c1 100644 --- a/src/background/services/ledger/events/ledgerDeviceRequest.ts +++ b/src/background/services/ledger/events/ledgerDeviceRequest.ts @@ -23,7 +23,7 @@ export class LedgerTransportRequestEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/ledger/events/ledgerDiscoverTransports.ts b/src/background/services/ledger/events/ledgerDiscoverTransports.ts index edff0c880..460cf3b44 100644 --- a/src/background/services/ledger/events/ledgerDiscoverTransports.ts +++ b/src/background/services/ledger/events/ledgerDiscoverTransports.ts @@ -24,7 +24,7 @@ export class LedgerDiscoverTransportsEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/ledger/events/ledgerDiscoverTransportsEventListener.ts b/src/background/services/ledger/events/ledgerDiscoverTransportsEventListener.ts index abe269c99..c034eb044 100644 --- a/src/background/services/ledger/events/ledgerDiscoverTransportsEventListener.ts +++ b/src/background/services/ledger/events/ledgerDiscoverTransportsEventListener.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { LedgerEvent } from '../models'; export function ledgerDiscoverTransportsEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === LedgerEvent.DISCOVER_TRANSPORTS; } diff --git a/src/background/services/ledger/handlers/getLedgerVersionWarning.test.ts b/src/background/services/ledger/handlers/getLedgerVersionWarning.test.ts index e239cc97a..4196a2958 100644 --- a/src/background/services/ledger/handlers/getLedgerVersionWarning.test.ts +++ b/src/background/services/ledger/handlers/getLedgerVersionWarning.test.ts @@ -24,7 +24,7 @@ describe('src/background/services/ledger/handlers/getLedgerVersionWarning.ts', ( expect(result).toEqual({ ...request, result: false }); expect(storageServiceMock.loadFromSessionStorage).toHaveBeenCalledWith( - LEDGER_VERSION_WARNING_WAS_CLOSED + LEDGER_VERSION_WARNING_WAS_CLOSED, ); }); }); diff --git a/src/background/services/ledger/handlers/getLedgerVersionWarning.ts b/src/background/services/ledger/handlers/getLedgerVersionWarning.ts index 82602300f..d4618c1b7 100644 --- a/src/background/services/ledger/handlers/getLedgerVersionWarning.ts +++ b/src/background/services/ledger/handlers/getLedgerVersionWarning.ts @@ -17,7 +17,7 @@ export class GetLedgerVersionWarningHandler implements HandlerType { handle: HandlerType['handle'] = async ({ request }) => { const result = await this.storageService.loadFromSessionStorage( - LEDGER_VERSION_WARNING_WAS_CLOSED + LEDGER_VERSION_WARNING_WAS_CLOSED, ); return { diff --git a/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.test.ts b/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.test.ts index 692d298aa..c9bff7104 100644 --- a/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.test.ts +++ b/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.test.ts @@ -31,7 +31,7 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe const handler = new MigrateMissingPublicKeysFromLedgerHandler( secretsService, ledgerService, - accountsService + accountsService, ); return handler.handle(buildRpcCall(request)); }; @@ -43,7 +43,7 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe it('returns error if storage is empty', async () => { secretsService.getAccountSecrets.mockRejectedValue( - new Error('Wallet is not initialized') + new Error('Wallet is not initialized'), ); const result = await handleRequest(); @@ -105,7 +105,7 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe { xpubXP: 'xpubXP', }, - WALLET_ID + WALLET_ID, ); }); }); @@ -144,7 +144,7 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe const { error } = await handleRequest(); expect(error).toEqual( - 'Error while searching for missing public keys: incomplete migration.' + 'Error while searching for missing public keys: incomplete migration.', ); expect(secretsService.updateSecrets).toHaveBeenCalledWith( @@ -158,7 +158,7 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe { evm: 'evm3', xp: '' }, ], }, - WALLET_ID + WALLET_ID, ); expect(getPubKeyFromTransport).toHaveBeenNthCalledWith( @@ -166,14 +166,14 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe {}, 1, DerivationPath.LedgerLive, - 'AVM' + 'AVM', ); expect(getPubKeyFromTransport).toHaveBeenNthCalledWith( 2, {}, 2, DerivationPath.LedgerLive, - 'AVM' + 'AVM', ); }); @@ -209,7 +209,7 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe { evm: 'evm3', xp: '5678' }, ], }, - WALLET_ID + WALLET_ID, ); expect(getPubKeyFromTransport).toHaveBeenNthCalledWith( @@ -217,14 +217,14 @@ describe('src/background/services/ledger/handlers/migrateMissingPublicKeysFromLe {}, 1, DerivationPath.LedgerLive, - 'AVM' + 'AVM', ); expect(getPubKeyFromTransport).toHaveBeenNthCalledWith( 2, {}, 2, DerivationPath.LedgerLive, - 'AVM' + 'AVM', ); }); }); diff --git a/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.ts b/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.ts index 2e2fc65c2..14faea6ac 100644 --- a/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.ts +++ b/src/background/services/ledger/handlers/migrateMissingPublicKeysFromLedger.ts @@ -25,7 +25,7 @@ export class MigrateMissingPublicKeysFromLedgerHandler implements HandlerType { constructor( private secretsService: SecretsService, private ledgerService: LedgerService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -34,7 +34,7 @@ export class MigrateMissingPublicKeysFromLedgerHandler implements HandlerType { throw new Error('There is no active account'); } const secrets = await this.secretsService.getAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if ( secrets.secretType !== SecretType.Ledger && @@ -70,13 +70,13 @@ export class MigrateMissingPublicKeysFromLedgerHandler implements HandlerType { const xpubXP = await getLedgerExtendedPublicKey( transport, false, - Avalanche.LedgerWallet.getAccountPath('X') + Avalanche.LedgerWallet.getAccountPath('X'), ); await this.secretsService.updateSecrets({ xpubXP }, walletId); } else if (secrets.secretType === SecretType.LedgerLive) { const hasMissingXPPublicKey = (secrets.pubKeys ?? []).some( - (pubKey) => !pubKey.xp + (pubKey) => !pubKey.xp, ); // nothing to migrate, exit early @@ -102,14 +102,14 @@ export class MigrateMissingPublicKeysFromLedgerHandler implements HandlerType { transport, index, DerivationPath.LedgerLive, - 'AVM' + 'AVM', ); migrationResult.updatedPubKeys.push({ ...pubKey, xp: addressPublicKeyXP.toString('hex'), }); - } catch (err) { + } catch (_err) { migrationResult.updatedPubKeys.push(pubKey); migrationResult.hasError = true; } @@ -122,12 +122,12 @@ export class MigrateMissingPublicKeysFromLedgerHandler implements HandlerType { { pubKeys: migrationResult.updatedPubKeys, }, - walletId + walletId, ); if (migrationResult.hasError) { throw new Error( - 'Error while searching for missing public keys: incomplete migration.' + 'Error while searching for missing public keys: incomplete migration.', ); } } diff --git a/src/background/services/ledger/handlers/removeLedgerTransport.test.ts b/src/background/services/ledger/handlers/removeLedgerTransport.test.ts index 6ca303b2c..8ba80768c 100644 --- a/src/background/services/ledger/handlers/removeLedgerTransport.test.ts +++ b/src/background/services/ledger/handlers/removeLedgerTransport.test.ts @@ -36,7 +36,7 @@ describe('src/background/services/ledger/handlers/removeLedgerTransport.ts', () expect(result).toEqual({ ...request, result: true }); expect(ledgerServiceMock.getTransport).toHaveBeenCalledWith(transportId); expect(ledgerServiceMock.removeTransportFromCache).toHaveBeenCalledWith( - transportId + transportId, ); }); }); diff --git a/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.test.ts b/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.test.ts index 95ff984f1..ff2e9d7a7 100644 --- a/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.test.ts +++ b/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.test.ts @@ -24,7 +24,7 @@ describe('src/background/services/ledger/handlers/setLedgerVersionWarningClosed. expect(result).toEqual({ ...request, result: true }); expect(storageServiceMock.saveToSessionStorage).toHaveBeenCalledWith( LEDGER_VERSION_WARNING_WAS_CLOSED, - true + true, ); }); }); diff --git a/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.ts b/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.ts index 9de64bfef..6a0597eed 100644 --- a/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.ts +++ b/src/background/services/ledger/handlers/setLedgerVersionWarningClosed.ts @@ -18,7 +18,7 @@ export class LedgerVersionWarningClosedHandler implements HandlerType { handle: HandlerType['handle'] = async ({ request }) => { await this.storageService.saveToSessionStorage( LEDGER_VERSION_WARNING_WAS_CLOSED, - true + true, ); return { diff --git a/src/background/services/lock/LockService.ts b/src/background/services/lock/LockService.ts index 4082cede5..bade7c6ad 100644 --- a/src/background/services/lock/LockService.ts +++ b/src/background/services/lock/LockService.ts @@ -24,13 +24,13 @@ export class LockService { constructor( private callbackManager: CallbackManager, - private storageService: StorageService + private storageService: StorageService, ) {} async activate() { const authData = await this.storageService.loadFromSessionStorage( - SESSION_AUTH_DATA_KEY + SESSION_AUTH_DATA_KEY, ); if ( @@ -61,7 +61,7 @@ export class LockService { this.eventEmitter.emit(LockEvents.LOCK_STATE_CHANGED, { isUnlocked: true, }); - } catch (e) { + } catch (_err) { throw new Error('invalid password'); } } @@ -69,7 +69,7 @@ export class LockService { async changePassword(oldPassword: string, newPassword: string) { const authData = await this.storageService.loadFromSessionStorage( - SESSION_AUTH_DATA_KEY + SESSION_AUTH_DATA_KEY, ); if (!authData || oldPassword !== authData.password) { @@ -91,7 +91,7 @@ export class LockService { async verifyPassword(password: string): Promise { const authData = await this.storageService.loadFromSessionStorage( - SESSION_AUTH_DATA_KEY + SESSION_AUTH_DATA_KEY, ); return authData && password === authData.password; @@ -108,14 +108,14 @@ export class LockService { addListener( event: LockEvents.LOCK_STATE_CHANGED, - callback: (data: LockStateChangedEventPayload) => void + callback: (data: LockStateChangedEventPayload) => void, ) { this.eventEmitter.addListener(event, callback); } removeListener( event: LockEvents.LOCK_STATE_CHANGED, - callback: (data: LockStateChangedEventPayload) => void + callback: (data: LockStateChangedEventPayload) => void, ) { this.eventEmitter.removeListener(event, callback); } diff --git a/src/background/services/lock/events/lockStateChangedEvent.ts b/src/background/services/lock/events/lockStateChangedEvent.ts index c43378e28..8f82110c7 100644 --- a/src/background/services/lock/events/lockStateChangedEvent.ts +++ b/src/background/services/lock/events/lockStateChangedEvent.ts @@ -32,7 +32,7 @@ export class LockStateChangedEvents } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/lock/events/lockStateChangedEventListener.ts b/src/background/services/lock/events/lockStateChangedEventListener.ts index 21d4d341b..1087f3d3d 100644 --- a/src/background/services/lock/events/lockStateChangedEventListener.ts +++ b/src/background/services/lock/events/lockStateChangedEventListener.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { LockEvents } from '../models'; export function lockStateChangedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === LockEvents.LOCK_STATE_CHANGED; } diff --git a/src/background/services/lock/handlers/changeWalletPassword.ts b/src/background/services/lock/handlers/changeWalletPassword.ts index ba6bf72e9..4b74a781a 100644 --- a/src/background/services/lock/handlers/changeWalletPassword.ts +++ b/src/background/services/lock/handlers/changeWalletPassword.ts @@ -27,7 +27,7 @@ export class LockChangePasswordHandler implements HandlerType { } const [, err] = await resolve( - this.lockService.changePassword(oldPassword, newPassword) + this.lockService.changePassword(oldPassword, newPassword), ); if (err) { diff --git a/src/background/services/messages/handlers/avalanche_signMessage.test.ts b/src/background/services/messages/handlers/avalanche_signMessage.test.ts index 1f31c7d89..2a2dd506c 100644 --- a/src/background/services/messages/handlers/avalanche_signMessage.test.ts +++ b/src/background/services/messages/handlers/avalanche_signMessage.test.ts @@ -36,7 +36,7 @@ describe('avalanche_signMessage', function () { it('returns error when no message', async () => { const handler = new AvalancheSignMessageHandler(walletServiceMock as any); const res = await handler.handleAuthenticated( - buildRpcCall({ ...request, params: [] }) + buildRpcCall({ ...request, params: [] }), ); expect(res).toHaveProperty('error'); @@ -49,12 +49,12 @@ describe('avalanche_signMessage', function () { buildRpcCall({ ...request, params: ['hello', 'accountIndex'], - }) + }), ); expect(res).toHaveProperty('error'); expect(res.error.message).toMatch( - 'Invalid account index provided: accountIndex' + 'Invalid account index provided: accountIndex', ); }); @@ -78,7 +78,7 @@ describe('avalanche_signMessage', function () { validationError: undefined, }, }, - 'sign' + 'sign', ); }); @@ -110,7 +110,7 @@ describe('avalanche_signMessage', function () { validationError: undefined, }, }, - 'sign' + 'sign', ); }); @@ -138,7 +138,7 @@ describe('avalanche_signMessage', function () { pendingActionMock, {}, onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).toBeCalled(); @@ -154,7 +154,7 @@ describe('avalanche_signMessage', function () { pendingActionMock, {}, onSuccessMock, - onErrorMock + onErrorMock, ); expect(onSuccessMock).toBeCalledWith('encoded'); diff --git a/src/background/services/messages/handlers/avalanche_signMessage.ts b/src/background/services/messages/handlers/avalanche_signMessage.ts index 752db8148..0778cec9d 100644 --- a/src/background/services/messages/handlers/avalanche_signMessage.ts +++ b/src/background/services/messages/handlers/avalanche_signMessage.ts @@ -85,12 +85,12 @@ export class AvalancheSignMessageHandler extends DAppRequestHandler { pendingAction: Action, _, onSuccess, - onError + onError, ) => { try { const res = (await this.walletService.signMessage( MessageType.AVALANCHE_SIGN, - pendingAction + pendingAction, )) as Buffer; if (!res) throw new Error('Failed to sign message'); diff --git a/src/background/services/messages/handlers/signMessage.test.ts b/src/background/services/messages/handlers/signMessage.test.ts index b017353d2..2aba9a221 100644 --- a/src/background/services/messages/handlers/signMessage.test.ts +++ b/src/background/services/messages/handlers/signMessage.test.ts @@ -73,7 +73,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); const request = { @@ -96,7 +96,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); expect(handler.methods).toStrictEqual([ @@ -116,7 +116,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); const request = { @@ -128,7 +128,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { } as any; await expect( - handler.handleAuthenticated(buildRpcCall(request)) + handler.handleAuthenticated(buildRpcCall(request)), ).resolves.toStrictEqual({ ...request, error: 'wallet undefined', @@ -141,7 +141,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); const request = { @@ -153,7 +153,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { } as any; await expect( - handler.handleAuthenticated(buildRpcCall(request)) + handler.handleAuthenticated(buildRpcCall(request)), ).resolves.toStrictEqual({ ...request, error: ethErrors.rpc.invalidRequest({ @@ -168,7 +168,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); const request = { @@ -185,7 +185,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { }); await expect( - handler.handleAuthenticated(buildRpcCall(request)) + handler.handleAuthenticated(buildRpcCall(request)), ).resolves.toStrictEqual({ ...request, error: ethErrors.rpc.invalidParams({ @@ -195,7 +195,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( DAppProviderRequest.ETH_SIGN, { foo: 'bar' }, - 1 + 1, ); }); @@ -205,7 +205,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); const methodsWithoutTypeCheck = [ @@ -231,7 +231,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { .mockResolvedValue({ validation: { result_type: 'Being' } }); await expect( - handler.handleAuthenticated(buildRpcCall(request)) + handler.handleAuthenticated(buildRpcCall(request)), ).resolves.toStrictEqual({ ...request, result: DEFERRED_RESPONSE, @@ -250,7 +250,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { }, tabId: 1, }, - `sign` + `sign`, ); } }); @@ -261,7 +261,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); const messageParamsMock: MessageParams = { @@ -304,7 +304,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { }); await expect( - handler.handleAuthenticated(buildRpcCall(request)) + handler.handleAuthenticated(buildRpcCall(request)), ).resolves.toStrictEqual({ ...request, result: DEFERRED_RESPONSE, @@ -316,7 +316,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { chainId: 1, }, { Mail: [{ name: 'name', type: 'string' }] }, - { name: 'asdasd' } + { name: 'asdasd' }, ); expect(openApprovalWindow).toHaveBeenCalledWith( @@ -332,7 +332,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { tabId: 1, scope: 'eip155:43113', }, - `sign` + `sign`, ); } }); @@ -342,7 +342,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); const request = { @@ -362,7 +362,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( request.method, displayDataMock.data, - activeNetworkMock.chainId + activeNetworkMock.chainId, ); expect(result).toStrictEqual({ ...request, @@ -382,7 +382,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { tabId: 1, scope: 'eip155:43113', }, - `sign` + `sign`, ); }); }); @@ -397,11 +397,11 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); (walletServiceMock.signMessage as jest.Mock).mockResolvedValueOnce( - result + result, ); await handler.onActionApproved( @@ -413,7 +413,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { } as any, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect(onSuccessMock).toHaveBeenCalledWith(result); @@ -425,7 +425,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { walletServiceMock, networkServiceMock, blockaidServiceMock, - secretsServiceMock + secretsServiceMock, ); (walletServiceMock.signMessage as jest.Mock).mockRejectedValueOnce(error); @@ -441,7 +441,7 @@ describe('src/background/services/messages/handlers/signMessage.ts', () => { } as any, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).toHaveBeenCalledWith(error); diff --git a/src/background/services/messages/handlers/signMessage.ts b/src/background/services/messages/handlers/signMessage.ts index af187ec54..bbb18ddb4 100644 --- a/src/background/services/messages/handlers/signMessage.ts +++ b/src/background/services/messages/handlers/signMessage.ts @@ -30,7 +30,7 @@ export class PersonalSignHandler extends DAppRequestHandler { private walletService: WalletService, private networkService: NetworkService, private blockaidService: BlockaidService, - private secretsService: SecretsService + private secretsService: SecretsService, ) { super(); } @@ -67,12 +67,12 @@ export class PersonalSignHandler extends DAppRequestHandler { ensureMessageFormatIsValid( request.method, messageParams.data, - activeNetwork.chainId + activeNetwork.chainId, ); const scanResult = await this.blockaidService.jsonRPCScan( activeNetwork.chainId.toString(), messageParams.from, - request + request, ); const validation = scanResult?.validation ?? undefined; @@ -95,12 +95,12 @@ export class PersonalSignHandler extends DAppRequestHandler { // in which cases we should be able to continue just like other wallets do (even if it's technically incorrect). // remove EIP712Domain from types since ethers.js handles it separately - // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { EIP712Domain, ...types } = messageParams.data.types; TypedDataEncoder.getPayload( messageParams.data.domain, types, - messageParams.data.message + messageParams.data.message, ); } catch (e) { validationError = (e as Error).toString(); @@ -138,12 +138,12 @@ export class PersonalSignHandler extends DAppRequestHandler { pendingAction: Action, _result, onSuccess, - onError + onError, ) => { try { const result = await this.walletService.signMessage( pendingAction.method as unknown as MessageType, - pendingAction + pendingAction, ); onSuccess(result); } catch (e) { diff --git a/src/background/services/messages/utils/messageParamsParser.ts b/src/background/services/messages/utils/messageParamsParser.ts index e29c230a7..d2b275c2b 100644 --- a/src/background/services/messages/utils/messageParamsParser.ts +++ b/src/background/services/messages/utils/messageParamsParser.ts @@ -2,7 +2,7 @@ import { JsonRpcRequestPayload } from '@src/background/connections/dAppConnectio import { MessageParams, MessageType } from '../models'; export function paramsToMessageParams( - data: JsonRpcRequestPayload + data: JsonRpcRequestPayload, ): MessageParams { const { params, method } = data; switch (method) { @@ -20,7 +20,7 @@ export function paramsToMessageParams( return { data: params.find((param) => Array.isArray(param)), from: params.find( - (param: any) => typeof param === 'string' || param instanceof String + (param: any) => typeof param === 'string' || param instanceof String, ), }; case MessageType.ETH_SIGN: diff --git a/src/background/services/navigationHistory/NavigationHistoryService.ts b/src/background/services/navigationHistory/NavigationHistoryService.ts index f18affd7c..34413e6f9 100644 --- a/src/background/services/navigationHistory/NavigationHistoryService.ts +++ b/src/background/services/navigationHistory/NavigationHistoryService.ts @@ -21,7 +21,7 @@ export class NavigationHistoryService { private async loadFromStorage(): Promise { return ( (await this.storageService.load( - NAVIGATION_HISTORY_STORAGE_KEY + NAVIGATION_HISTORY_STORAGE_KEY, )) ?? { state: {}, data: {} } ); } @@ -29,7 +29,7 @@ export class NavigationHistoryService { private async saveToStorage(data: NavigationHistoryStorage) { await this.storageService.save( NAVIGATION_HISTORY_STORAGE_KEY, - data + data, ); } @@ -40,7 +40,7 @@ export class NavigationHistoryService { } async setHistory( - state: NavigationHistoryState + state: NavigationHistoryState, ): Promise { const current = await this.loadFromStorage(); if (this.excludedPathNames.includes(state.location.pathname)) { @@ -59,7 +59,7 @@ export class NavigationHistoryService { ...historyData, }; }, - {} + {}, ); await this.saveToStorage({ @@ -76,7 +76,7 @@ export class NavigationHistoryService { } async setHistoryData( - data: NavigationHistoryDataState + data: NavigationHistoryDataState, ): Promise { const current = await this.loadFromStorage(); diff --git a/src/background/services/navigationHistory/handlers/getNavigationHistory.ts b/src/background/services/navigationHistory/handlers/getNavigationHistory.ts index 39632b5b5..3eaefa8d7 100644 --- a/src/background/services/navigationHistory/handlers/getNavigationHistory.ts +++ b/src/background/services/navigationHistory/handlers/getNavigationHistory.ts @@ -22,7 +22,7 @@ export class GetNavigationHistoryHandler implements HandlerType { ...request, result: navigationHistory, }; - } catch (e) { + } catch (_err) { return { ...request, result: {}, diff --git a/src/background/services/navigationHistory/handlers/getNavigationHistoryData.ts b/src/background/services/navigationHistory/handlers/getNavigationHistoryData.ts index b685f7a52..27786b5cd 100644 --- a/src/background/services/navigationHistory/handlers/getNavigationHistoryData.ts +++ b/src/background/services/navigationHistory/handlers/getNavigationHistoryData.ts @@ -24,7 +24,7 @@ export class GetNavigationHistoryDataHandler implements HandlerType { ...request, result: navigationHistoryData ?? {}, }; - } catch (e) { + } catch (_err) { return { ...request, result: {}, diff --git a/src/background/services/navigationHistory/handlers/setNavigationHistory.ts b/src/background/services/navigationHistory/handlers/setNavigationHistory.ts index baecce9dd..a4fc2cc37 100644 --- a/src/background/services/navigationHistory/handlers/setNavigationHistory.ts +++ b/src/background/services/navigationHistory/handlers/setNavigationHistory.ts @@ -22,9 +22,8 @@ export class SetNavigationHistoryHandler implements HandlerType { return { ...request, - result: await this.navigationHistoryService.setHistory( - newNavigationHistory - ), + result: + await this.navigationHistoryService.setHistory(newNavigationHistory), }; }; } diff --git a/src/background/services/network/NetworkService.test.ts b/src/background/services/network/NetworkService.test.ts index 42f7c7545..16cce0b2a 100644 --- a/src/background/services/network/NetworkService.test.ts +++ b/src/background/services/network/NetworkService.test.ts @@ -56,7 +56,7 @@ jest.mock('@avalabs/core-chains-sdk', () => ({ const mockNetwork = ( vmName: NetworkVMType, isTestnet?: boolean, - overrides = {} + overrides = {}, ) => { const network = { chainName: 'test chain', @@ -123,7 +123,7 @@ describe('background/services/network/NetworkService', () => { [btcNetwork.chainId]: btcNetwork, [leetNetwork.chainId]: leetNetwork, [sepolia.chainId]: sepolia, - }) + }), ); jest.spyOn(instance.allNetworks, 'promisify').mockResolvedValue( Promise.resolve({ @@ -132,7 +132,7 @@ describe('background/services/network/NetworkService', () => { [btcNetwork.chainId]: btcNetwork, [leetNetwork.chainId]: leetNetwork, [sepolia.chainId]: sepolia, - }) + }), ); }; @@ -149,7 +149,7 @@ describe('background/services/network/NetworkService', () => { jest.mocked(getChainsAndTokens).mockResolvedValue({}); - jest.mocked(FetchRequest).mockImplementation((url) => ({ url } as any)); + jest.mocked(FetchRequest).mockImplementation((url) => ({ url }) as any); mockChainList(service); }); @@ -163,7 +163,7 @@ describe('background/services/network/NetworkService', () => { Promise.resolve({ [ethMainnet.chainId]: ethMainnet, [avaxMainnet.chainId]: avaxMainnet, - }) + }), ); }); @@ -284,7 +284,7 @@ describe('background/services/network/NetworkService', () => { dappScopes: expect.objectContaining({ 'test.app': ethMainnet.caipId, }), - }) + }), ); }); @@ -305,7 +305,7 @@ describe('background/services/network/NetworkService', () => { beforeEach(async () => { service = new NetworkService( storageServiceMock, - featureFlagsServiceMock + featureFlagsServiceMock, ); mockChainList(service); // Set Ethereum Mainnet directly for the frontend @@ -324,7 +324,7 @@ describe('background/services/network/NetworkService', () => { dappScopes: expect.objectContaining({ 'app.uniswap.io': sepolia.caipId, }), - }) + }), ); }); @@ -341,7 +341,7 @@ describe('background/services/network/NetworkService', () => { 'app.uniswap.io': sepolia.caipId, [runtime.id]: 'eip155:43113', }), - }) + }), ); }); @@ -367,7 +367,7 @@ describe('background/services/network/NetworkService', () => { dappScopes: expect.objectContaining({ [runtime.id]: ethMainnet.caipId, }), - }) + }), ); }); @@ -376,7 +376,7 @@ describe('background/services/network/NetworkService', () => { Promise.resolve({ [ethMainnet.chainId]: ethMainnet, [avaxMainnet.chainId]: avaxMainnet, - }) + }), ); // Set Ethereum directly for the frontend await service.setNetwork(runtime.id, ethMainnet.caipId); @@ -394,7 +394,7 @@ describe('background/services/network/NetworkService', () => { jest.spyOn(service.allNetworks, 'promisify').mockResolvedValue( Promise.resolve({ [ethMainnet.chainId]: ethMainnet, - }) + }), ); await service.setNetwork('core.app', ethMainnet.caipId); @@ -424,7 +424,7 @@ describe('background/services/network/NetworkService', () => { const networkService = new NetworkService( storageServiceMock, - featureFlagsServiceMock + featureFlagsServiceMock, ); await networkService.updateNetworkOverrides(overrides); @@ -437,7 +437,7 @@ describe('background/services/network/NetworkService', () => { 'X-Glacier-Api-Key': 'my-elite-api-key', }, }, - } + }, ); }); @@ -451,7 +451,7 @@ describe('background/services/network/NetworkService', () => { const networkService = new NetworkService( storageServiceMock, - featureFlagsServiceMock + featureFlagsServiceMock, ); // eslint-disable-next-line @@ -462,7 +462,7 @@ describe('background/services/network/NetworkService', () => { jest.spyOn(networkService.allNetworks, 'promisify').mockResolvedValue( Promise.resolve({ 1337: activeNetwork, - }) + }), ); await networkService.setNetwork(runtime.id, activeNetwork.caipId); @@ -498,14 +498,14 @@ describe('background/services/network/NetworkService', () => { .mockResolvedValueOnce(Promise.resolve(undefined)); await expect(service.saveCustomNetwork(customNetwork)).rejects.toThrow( - 'chainlist failed to load' + 'chainlist failed to load', ); }); it('should throw an error because of duplicated ID', async () => { const newCustomNetwork = { ...customNetwork, chainId: 43114 }; await expect(service.saveCustomNetwork(newCustomNetwork)).rejects.toThrow( - 'chain ID already exists' + 'chain ID already exists', ); }); @@ -526,9 +526,8 @@ describe('background/services/network/NetworkService', () => { ...customNetwork, rpcUrl: newRpcUrl, }; - const savedActiveNetwork = await service.saveCustomNetwork( - newCustomNetwork - ); + const savedActiveNetwork = + await service.saveCustomNetwork(newCustomNetwork); expect(savedActiveNetwork?.rpcUrl).toBe(newRpcUrl); }); @@ -567,7 +566,7 @@ describe('background/services/network/NetworkService', () => { await service.onLock(); expect(storageServiceMock.load).toHaveBeenCalledWith( - NETWORK_LIST_STORAGE_KEY + NETWORK_LIST_STORAGE_KEY, ); expect(dispatchSpy).toHaveBeenCalledWith(cachedChainList); }); @@ -615,7 +614,7 @@ describe('background/services/network/NetworkService', () => { it('applies config overrides to .allNetworks signal', async () => { const networkService = new NetworkService( storageServiceMock, - featureFlagsServiceMock + featureFlagsServiceMock, ); // eslint-disable-next-line @@ -636,7 +635,7 @@ describe('background/services/network/NetworkService', () => { it('applies config overrides to .activeNetworks signal', async () => { const networkService = new NetworkService( storageServiceMock, - featureFlagsServiceMock + featureFlagsServiceMock, ); // eslint-disable-next-line @@ -658,7 +657,7 @@ describe('background/services/network/NetworkService', () => { it('filters networks by .isTestnet for .activeNetworks signal', async () => { const networkService = new NetworkService( storageServiceMock, - featureFlagsServiceMock + featureFlagsServiceMock, ); jest @@ -731,7 +730,7 @@ describe('background/services/network/NetworkService', () => { } as any; const networkService = new NetworkService( storageServiceMock, - featureFlagsServiceMock + featureFlagsServiceMock, ); jest diff --git a/src/background/services/network/NetworkService.ts b/src/background/services/network/NetworkService.ts index 8b1c65f1c..88685c7e5 100644 --- a/src/background/services/network/NetworkService.ts +++ b/src/background/services/network/NetworkService.ts @@ -117,7 +117,7 @@ export class NetworkService implements OnLock, OnStorageReady { constructor( private storageService: StorageService, - private featureFlagService: FeatureFlagService + private featureFlagService: FeatureFlagService, ) { this._initChainList(); @@ -145,8 +145,8 @@ export class NetworkService implements OnLock, OnStorageReady { return Object.fromEntries( Object.entries(flags).filter(([flag]) => - trackedFlags.includes(flag as FeatureGates) - ) + trackedFlags.includes(flag as FeatureGates), + ), ); } @@ -176,16 +176,16 @@ export class NetworkService implements OnLock, OnStorageReady { Object.entries(this.#dappScopes) .filter( ([savedDomain]) => - getSyncDomain(savedDomain) !== getSyncDomain(domain) + getSyncDomain(savedDomain) !== getSyncDomain(domain), ) .map(([savedDomain]) => [ savedDomain, chainIdToCaip( targetNetwork.isTestnet ? ChainId.AVALANCHE_TESTNET_ID - : ChainId.AVALANCHE_MAINNET_ID + : ChainId.AVALANCHE_MAINNET_ID, ), - ]) + ]), ); await this.#updateDappScopes(newScopes); @@ -253,7 +253,7 @@ export class NetworkService implements OnLock, OnStorageReady { if ( !chainId || storedFavoriteNetworks.find( - (storedNetworkChainId) => storedNetworkChainId === chainId + (storedNetworkChainId) => storedNetworkChainId === chainId, ) ) { return storedFavoriteNetworks; @@ -266,7 +266,8 @@ export class NetworkService implements OnLock, OnStorageReady { async removeFavoriteNetwork(chainId: number) { const storedFavoriteNetworks = this._favoriteNetworks; this.favoriteNetworks = storedFavoriteNetworks.filter( - (storedFavoriteNetworkChainId) => storedFavoriteNetworkChainId !== chainId + (storedFavoriteNetworkChainId) => + storedFavoriteNetworkChainId !== chainId, ); this.updateNetworkState(); return this._favoriteNetworks; @@ -302,7 +303,7 @@ export class NetworkService implements OnLock, OnStorageReady { const chainlist = await this._rawNetworks.promisify(); this._allNetworks.dispatch({ ...chainlist }); } - } + }, ); this.activeNetworks.add(async (chainListPromise) => { @@ -325,9 +326,8 @@ export class NetworkService implements OnLock, OnStorageReady { } async init() { - const storedState = await this.storageService.load( - NETWORK_STORAGE_KEY - ); + const storedState = + await this.storageService.load(NETWORK_STORAGE_KEY); this.#dappScopes = storedState?.dappScopes ?? {}; @@ -356,7 +356,7 @@ export class NetworkService implements OnLock, OnStorageReady { : null; this.uiActiveNetwork = decorateWithCaipId( - previouslyActiveNetwork ?? fullChainlist[ChainId.AVALANCHE_MAINNET_ID] + previouslyActiveNetwork ?? fullChainlist[ChainId.AVALANCHE_MAINNET_ID], ); this._allNetworks.dispatch(fullChainlist); @@ -368,7 +368,7 @@ export class NetworkService implements OnLock, OnStorageReady { private async _getCachedChainList(): Promise { const networkList = await this.storageService.load( - NETWORK_LIST_STORAGE_KEY + NETWORK_LIST_STORAGE_KEY, ); if (!networkList) { @@ -436,8 +436,8 @@ export class NetworkService implements OnLock, OnStorageReady { const [result] = await resolve( getChainsAndTokens( process.env.RELEASE === 'production', - process.env.TOKENLIST_OVERRIDE || '' - ) + process.env.TOKENLIST_OVERRIDE || '', + ), ); if (result) { @@ -469,7 +469,7 @@ export class NetworkService implements OnLock, OnStorageReady { async getNetwork(caipScope: string): Promise; async getNetwork(chainId: number): Promise; async getNetwork( - scopeOrChainId: string | number + scopeOrChainId: string | number, ): Promise { const chainId = typeof scopeOrChainId === 'string' @@ -519,7 +519,7 @@ export class NetworkService implements OnLock, OnStorageReady { */ async getAvalanceProviderXP(): Promise { return (await getProviderForNetwork( - this.getAvalancheNetworkXP() + this.getAvalancheNetworkXP(), )) as Avalanche.JsonRpcProvider; } @@ -557,7 +557,7 @@ export class NetworkService implements OnLock, OnStorageReady { */ async sendTransaction( { txHash, signedTx }: SigningResult, - network: Network + network: Network, ): Promise { // Sometimes we'll receive the TX hash directly from the wallet // device that signed the transaction (it's the case for WalletConnect). @@ -584,13 +584,13 @@ export class NetworkService implements OnLock, OnStorageReady { maxCalls: 40, }, url, - new EthersNetwork('', chainId) + new EthersNetwork('', chainId), ); try { const detectedNetwork = await provider.getNetwork(); return detectedNetwork.chainId === BigInt(chainId); - } catch (e) { + } catch (_err) { return false; } } @@ -672,14 +672,14 @@ export class NetworkService implements OnLock, OnStorageReady { const wasTestnet = networkToRemove?.isTestnet; const overrides = await this.storageService.load( - NETWORK_OVERRIDES_STORAGE_KEY + NETWORK_OVERRIDES_STORAGE_KEY, ); if (overrides && overrides[chainID]) { // Remove overrides for deleted network if they were configured await this.storageService.save( NETWORK_OVERRIDES_STORAGE_KEY, - omit(overrides, chainID) + omit(overrides, chainID), ); } @@ -696,7 +696,9 @@ export class NetworkService implements OnLock, OnStorageReady { // Switch to Avalanache Mainnet or Fuji if the active network was removed. if (this.uiActiveNetwork?.chainId === chainID) { const network = await this.getNetwork( - wasTestnet ? ChainId.AVALANCHE_TESTNET_ID : ChainId.AVALANCHE_MAINNET_ID + wasTestnet + ? ChainId.AVALANCHE_TESTNET_ID + : ChainId.AVALANCHE_MAINNET_ID, ); if (network) { @@ -719,14 +721,14 @@ export class NetworkService implements OnLock, OnStorageReady { .filter( (network) => Boolean(this.uiActiveNetwork?.isTestnet) === - Boolean(network.isTestnet) + Boolean(network.isTestnet), ) .reduce( (acc, network) => ({ ...acc, [network.chainId]: network, }), - {} + {}, ); }; @@ -753,7 +755,7 @@ export class NetworkService implements OnLock, OnStorageReady { ...acc, [network.chainId]: network, }), - {} + {}, ); }; @@ -780,11 +782,11 @@ export class NetworkService implements OnLock, OnStorageReady { Object.entries(overrides) // Filter out empty overrides .filter( - ([, networkOverrides]) => Object.keys(networkOverrides).length > 0 + ([, networkOverrides]) => Object.keys(networkOverrides).length > 0, ) // Filter out overrides that do not apply in the current context, // for example if the chain list does not contain the network in question. - .filter(([chainId]) => chainId in chainList) + .filter(([chainId]) => chainId in chainList), ); return merge({}, chainList, applicableOverrides) as ChainList; @@ -797,7 +799,7 @@ export class NetworkService implements OnLock, OnStorageReady { Object.entries(chainList ?? {}).map(([chainId, network]) => [ chainId, decorateWithCaipId(network), - ]) + ]), ); }; } diff --git a/src/background/services/network/events/chainChangedEvent.ts b/src/background/services/network/events/chainChangedEvent.ts index eb7ffb90d..33ab1820f 100644 --- a/src/background/services/network/events/chainChangedEvent.ts +++ b/src/background/services/network/events/chainChangedEvent.ts @@ -33,7 +33,7 @@ export class ChainChangedEvents implements DAppEventEmitter { // Changes triggered by Core suite will contain the extension's ID as the `domain`. const normalizedConnectionDomain = getSyncDomain( - this._connectionInfo?.domain + this._connectionInfo?.domain, ); if (normalizedConnectionDomain !== domain) { @@ -58,7 +58,7 @@ export class ChainChangedEvents implements DAppEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/network/events/developerModeChangedEvent.ts b/src/background/services/network/events/developerModeChangedEvent.ts index a2ce7709e..b011f2e3b 100644 --- a/src/background/services/network/events/developerModeChangedEvent.ts +++ b/src/background/services/network/events/developerModeChangedEvent.ts @@ -24,7 +24,7 @@ export class DeveloperModeChangedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/network/events/isNetworkUpdatedEvent.ts b/src/background/services/network/events/isNetworkUpdatedEvent.ts index d0feb74de..620fb4cde 100644 --- a/src/background/services/network/events/isNetworkUpdatedEvent.ts +++ b/src/background/services/network/events/isNetworkUpdatedEvent.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { NetworkEvents, NetworkWithCaipId } from '../models'; export function isNetworkUpdatedEvent( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === NetworkEvents.NETWORK_UPDATE_EVENT; } diff --git a/src/background/services/network/events/networkUpdatedEvent.ts b/src/background/services/network/events/networkUpdatedEvent.ts index 1eafd343d..eace97bab 100644 --- a/src/background/services/network/events/networkUpdatedEvent.ts +++ b/src/background/services/network/events/networkUpdatedEvent.ts @@ -20,7 +20,6 @@ export class NetworkUpdatedEvents implements ExtensionEventEmitter { return; } - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { tokens: _, ...networkWithoutTokens } = network; this.eventEmitter.emit('update', { @@ -35,7 +34,7 @@ export class NetworkUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/network/events/networkUpdatedEventListener.ts b/src/background/services/network/events/networkUpdatedEventListener.ts index fac03072a..46e0161c9 100644 --- a/src/background/services/network/events/networkUpdatedEventListener.ts +++ b/src/background/services/network/events/networkUpdatedEventListener.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { Network, NetworkEvents } from '../models'; export function networkUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === NetworkEvents.NETWORK_UPDATE_EVENT; } diff --git a/src/background/services/network/events/networksUpdatedEvent.ts b/src/background/services/network/events/networksUpdatedEvent.ts index 984f336d5..f5af31108 100644 --- a/src/background/services/network/events/networksUpdatedEvent.ts +++ b/src/background/services/network/events/networksUpdatedEvent.ts @@ -28,7 +28,7 @@ export class NetworksUpdatedEvents implements ExtensionEventEmitter { value: { activeNetwork: this.networkService.uiActiveNetwork, networks: Object.values(networks).sort((a, b) => - a.chainName.localeCompare(b.chainName) + a.chainName.localeCompare(b.chainName), ), favoriteNetworks, customNetworks: this.networkService.customNetworks, @@ -42,7 +42,7 @@ export class NetworksUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/network/events/networksUpdatedEventListener.ts b/src/background/services/network/events/networksUpdatedEventListener.ts index 017e7d119..df14a8907 100644 --- a/src/background/services/network/events/networksUpdatedEventListener.ts +++ b/src/background/services/network/events/networksUpdatedEventListener.ts @@ -7,7 +7,7 @@ export function networksUpdatedEventListener( activeNetwork?: NetworkWithCaipId; favoriteNetworks: number[]; customNetworks: Record; - }> + }>, ) { return evt.name === NetworkEvents.NETWORKS_UPDATED_EVENT; } diff --git a/src/background/services/network/handlers/addFavoriteNetwork.ts b/src/background/services/network/handlers/addFavoriteNetwork.ts index 9fc774fb1..e88bf85a4 100644 --- a/src/background/services/network/handlers/addFavoriteNetwork.ts +++ b/src/background/services/network/handlers/addFavoriteNetwork.ts @@ -20,7 +20,7 @@ export class AddFavoriteNetworkHandler implements HandlerType { const [network] = params || []; const [favoriteNetworks, err] = await resolve( - this.networkService.addFavoriteNetwork(network) + this.networkService.addFavoriteNetwork(network), ); if (err) { diff --git a/src/background/services/network/handlers/avalanche_setDeveloperMode.ts b/src/background/services/network/handlers/avalanche_setDeveloperMode.ts index c89e79486..f7eadf4b5 100644 --- a/src/background/services/network/handlers/avalanche_setDeveloperMode.ts +++ b/src/background/services/network/handlers/avalanche_setDeveloperMode.ts @@ -25,7 +25,7 @@ export class AvalancheSetDeveloperModeHandler extends DAppRequestHandler { return { ...request, error: ethErrors.rpc.invalidParams( - 'Invalid param, must be true or false' + 'Invalid param, must be true or false', ), }; } @@ -57,9 +57,9 @@ export class AvalancheSetDeveloperModeHandler extends DAppRequestHandler { onActionApproved = async ( pendingAction: Action<{ isTestmode: boolean }>, - result, + _result, onSuccess, - onError + onError, ) => { try { const { @@ -77,8 +77,8 @@ export class AvalancheSetDeveloperModeHandler extends DAppRequestHandler { chainIdToCaip( isTestmode ? ChainId.AVALANCHE_TESTNET_ID - : ChainId.AVALANCHE_MAINNET_ID - ) + : ChainId.AVALANCHE_MAINNET_ID, + ), ); onSuccess(null); diff --git a/src/background/services/network/handlers/getNetworkState.ts b/src/background/services/network/handlers/getNetworkState.ts index c89eb6caf..d0890e80f 100644 --- a/src/background/services/network/handlers/getNetworkState.ts +++ b/src/background/services/network/handlers/getNetworkState.ts @@ -22,7 +22,7 @@ export class GetNetworksStateHandler implements HandlerType { constructor(private networkService: NetworkService) {} handle: HandlerType['handle'] = async ({ request }) => { const [networks, err] = await resolve>( - this.networkService.activeNetworks.promisify() + this.networkService.activeNetworks.promisify(), ); if (err) { @@ -43,12 +43,12 @@ export class GetNetworksStateHandler implements HandlerType { const filteredFavoriteNetworks = await this.networkService.getFavoriteNetworks(); const customNetworks = Object.values( - this.networkService.customNetworks + this.networkService.customNetworks, ).map((network) => network.chainId); const activeNetwork = Object.assign( {}, - this.networkService.uiActiveNetwork + this.networkService.uiActiveNetwork, ); delete activeNetwork?.tokens; diff --git a/src/background/services/network/handlers/removeCustomNetwork.ts b/src/background/services/network/handlers/removeCustomNetwork.ts index 5139f356b..b5b425542 100644 --- a/src/background/services/network/handlers/removeCustomNetwork.ts +++ b/src/background/services/network/handlers/removeCustomNetwork.ts @@ -25,7 +25,7 @@ export class RemoveCustomNetworkHandler implements HandlerType { }; const [, err] = await resolve( - this.networkService.removeCustomNetwork(chainId) + this.networkService.removeCustomNetwork(chainId), ); if (err) { diff --git a/src/background/services/network/handlers/removeFavoriteNetwork.ts b/src/background/services/network/handlers/removeFavoriteNetwork.ts index 920c5b663..299a3fce9 100644 --- a/src/background/services/network/handlers/removeFavoriteNetwork.ts +++ b/src/background/services/network/handlers/removeFavoriteNetwork.ts @@ -19,7 +19,7 @@ export class RemoveFavoriteNetworkHandler implements HandlerType { const [chainId] = request.params; const [favoriteNetworks, err] = await resolve( - this.networkService.removeFavoriteNetwork(chainId) + this.networkService.removeFavoriteNetwork(chainId), ); if (err) { diff --git a/src/background/services/network/handlers/saveCustomNetwork.ts b/src/background/services/network/handlers/saveCustomNetwork.ts index aeb56499b..0c6b88b03 100644 --- a/src/background/services/network/handlers/saveCustomNetwork.ts +++ b/src/background/services/network/handlers/saveCustomNetwork.ts @@ -29,7 +29,7 @@ export class SaveCustomNetworkHandler implements HandlerType { const isValid = await this.networkService.isValidRPCUrl( network.chainId, - network.rpcUrl + network.rpcUrl, ); if (!isValid) { @@ -40,7 +40,7 @@ export class SaveCustomNetworkHandler implements HandlerType { } const [addedNetwork, err] = await resolve( - this.networkService.saveCustomNetwork(network) + this.networkService.saveCustomNetwork(network), ); if (err || !addedNetwork) { diff --git a/src/background/services/network/handlers/setActiveNetwork.ts b/src/background/services/network/handlers/setActiveNetwork.ts index a351326cc..1a22ebcb8 100644 --- a/src/background/services/network/handlers/setActiveNetwork.ts +++ b/src/background/services/network/handlers/setActiveNetwork.ts @@ -22,7 +22,7 @@ export class SetActiveNetworkHandler implements HandlerType { handle: HandlerType['handle'] = async ({ request }) => { const [scope] = request.params; const [, err] = await resolve( - this.networkService.setNetwork(runtime.id, scope) + this.networkService.setNetwork(runtime.id, scope), ); if (err) { diff --git a/src/background/services/network/handlers/setDeveloperMode.ts b/src/background/services/network/handlers/setDeveloperMode.ts index 2cbe146b8..f14a09f5e 100644 --- a/src/background/services/network/handlers/setDeveloperMode.ts +++ b/src/background/services/network/handlers/setDeveloperMode.ts @@ -29,9 +29,9 @@ export class SetDevelopermodeNetworkHandler implements HandlerType { chainIdToCaip( enableDeveloperMode ? ChainId.AVALANCHE_TESTNET_ID - : ChainId.AVALANCHE_MAINNET_ID - ) - ) + : ChainId.AVALANCHE_MAINNET_ID, + ), + ), ); if (err) { diff --git a/src/background/services/network/handlers/updateDefaultNetwork.test.ts b/src/background/services/network/handlers/updateDefaultNetwork.test.ts index 3fd0d4a66..d0454e0e6 100644 --- a/src/background/services/network/handlers/updateDefaultNetwork.test.ts +++ b/src/background/services/network/handlers/updateDefaultNetwork.test.ts @@ -71,7 +71,7 @@ describe('background/services/network/handlers/updateDefaultNetwork.ts', () => { it('update network rpcUrl with overrides -> Error', async () => { isValidRPCUrlMock.mockResolvedValueOnce(true); updateNetworkOverridesMock.mockRejectedValueOnce( - new Error('error comes from network service') + new Error('error comes from network service'), ); const handler = new UpdateDefaultNetworkHandler(networkServiceMock); const request = { @@ -112,7 +112,7 @@ describe('background/services/network/handlers/updateDefaultNetwork.ts', () => { it('reset network rpcUrl -> Error', async () => { isValidRPCUrlMock.mockResolvedValueOnce(true); updateNetworkOverridesMock.mockRejectedValueOnce( - new Error('error comes from network service') + new Error('error comes from network service'), ); const handler = new UpdateDefaultNetworkHandler(networkServiceMock); const request = { diff --git a/src/background/services/network/handlers/updateDefaultNetwork.ts b/src/background/services/network/handlers/updateDefaultNetwork.ts index 0d4da39d4..649cf5601 100644 --- a/src/background/services/network/handlers/updateDefaultNetwork.ts +++ b/src/background/services/network/handlers/updateDefaultNetwork.ts @@ -31,7 +31,7 @@ export class UpdateDefaultNetworkHandler implements HandlerType { if (network.rpcUrl !== undefined) { const isValid = await this.networkService.isValidRPCUrl( network.chainId, - network.rpcUrl + network.rpcUrl, ); if (!isValid) { @@ -44,7 +44,7 @@ export class UpdateDefaultNetworkHandler implements HandlerType { if (network.customRpcHeaders) { const areHeadersValid = Object.entries(network.customRpcHeaders).every( - ([name, value]) => isValidHttpHeader(name, value) + ([name, value]) => isValidHttpHeader(name, value), ); if (!areHeadersValid) { @@ -56,7 +56,7 @@ export class UpdateDefaultNetworkHandler implements HandlerType { } const [, err] = await resolve( - this.networkService.updateNetworkOverrides(network) + this.networkService.updateNetworkOverrides(network), ); if (err) { diff --git a/src/background/services/network/handlers/wallet_addEthereumChain.test.ts b/src/background/services/network/handlers/wallet_addEthereumChain.test.ts index 789df07e7..55d751e45 100644 --- a/src/background/services/network/handlers/wallet_addEthereumChain.test.ts +++ b/src/background/services/network/handlers/wallet_addEthereumChain.test.ts @@ -111,7 +111,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1234' }), - 'network/switch' + 'network/switch', ); expect(result).toEqual({ @@ -300,7 +300,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(mockNetworkService.isValidRPCUrl).toHaveBeenCalledTimes(1); expect(mockNetworkService.isValidRPCUrl).toHaveBeenCalledWith( 43112, - 'https://api.avax.network/ext/bc/C/rpc' + 'https://api.avax.network/ext/bc/C/rpc', ); expect(openApprovalWindow).not.toHaveBeenCalled(); @@ -335,7 +335,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1234' }), - 'networks/add-popup' + 'networks/add-popup', ); }); @@ -370,7 +370,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1234' }), - 'networks/add-popup' + 'networks/add-popup', ); }); @@ -403,7 +403,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1234' }), - 'networks/add-popup' + 'networks/add-popup', ); }); @@ -438,7 +438,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1234' }), - 'networks/add-popup' + 'networks/add-popup', ); }); @@ -476,7 +476,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(mockNetworkService.setNetwork).toHaveBeenCalledTimes(1); expect(mockNetworkService.setNetwork).toHaveBeenCalledWith( 'core.app', - 'eip155:43113' + 'eip155:43113', ); }); @@ -562,7 +562,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1234' }), - 'networks/add-popup' + 'networks/add-popup', ); }); @@ -631,32 +631,32 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = preppedAction, undefined, () => {}, - () => {} + () => {}, ); expect( - mockNetworkService.updateNetworkOverrides + mockNetworkService.updateNetworkOverrides, ).toHaveBeenCalledWith( expect.objectContaining({ customRpcHeaders: { 'X-Glacier-Api-Key': 'test-1234', }, - }) + }), ); expect( - mockNetworkService.updateNetworkOverrides + mockNetworkService.updateNetworkOverrides, ).toHaveBeenCalledWith( expect.not.objectContaining({ rpcUrl: expect.any(String), // RPC is not supposed to be passed here - }) + }), ); }); }); it('saves custom network on approval', async () => { (mockNetworkService.saveCustomNetwork as jest.Mock).mockResolvedValue( - undefined + undefined, ); const successHandler = jest.fn(); @@ -666,12 +666,12 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = mockPendingAction, undefined, successHandler, - errorHandler + errorHandler, ); expect(mockNetworkService.setNetwork).toHaveBeenCalledWith( mockPendingAction.site?.domain, - mockPendingAction.displayData.network.caipId + mockPendingAction.displayData.network.caipId, ); expect(mockNetworkService.saveCustomNetwork).toHaveBeenCalledTimes(1); expect(mockNetworkService.saveCustomNetwork).toHaveBeenCalledWith({ @@ -685,7 +685,7 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = it('calls error when saving custom network fails', async () => { (mockNetworkService.saveCustomNetwork as jest.Mock).mockRejectedValue( - new Error('some serious error') + new Error('some serious error'), ); const successHandler = jest.fn(); @@ -695,12 +695,12 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = mockPendingAction, undefined, successHandler, - errorHandler + errorHandler, ); expect(errorHandler).toHaveBeenCalledTimes(1); expect(errorHandler).toHaveBeenCalledWith( - new Error('some serious error') + new Error('some serious error'), ); expect(successHandler).not.toHaveBeenCalled(); }); @@ -728,13 +728,13 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = }, undefined, successHandler, - errorHandler + errorHandler, ); expect(mockNetworkService.saveCustomNetwork).not.toHaveBeenCalled(); expect(mockNetworkService.setNetwork).toHaveBeenCalledWith( mockPendingAction.site?.domain, - network.caipId + network.caipId, ); expect(successHandler).toHaveBeenCalledTimes(1); @@ -765,12 +765,12 @@ describe('background/services/network/handlers/wallet_addEthereumChain.ts', () = }, undefined, successHandler, - errorHandler + errorHandler, ); expect(errorHandler).toHaveBeenCalledTimes(1); expect(errorHandler).toHaveBeenCalledWith( - new Error('some serious error') + new Error('some serious error'), ); expect(successHandler).not.toHaveBeenCalled(); }); diff --git a/src/background/services/network/handlers/wallet_addEthereumChain.ts b/src/background/services/network/handlers/wallet_addEthereumChain.ts index d4fa833dd..de255aaef 100644 --- a/src/background/services/network/handlers/wallet_addEthereumChain.ts +++ b/src/background/services/network/handlers/wallet_addEthereumChain.ts @@ -138,7 +138,7 @@ export class WalletAddEthereumChainHandler extends DAppRequestHandler< } const skipApproval = await canSkipApproval( request.site.domain, - request.site.tabId + request.site.tabId, ); if (skipApproval) { @@ -162,7 +162,7 @@ export class WalletAddEthereumChainHandler extends DAppRequestHandler< const isValid = await this.networkService.isValidRPCUrl( customNetwork.chainId, - customNetwork.rpcUrl + customNetwork.rpcUrl, ); if (!isValid) { return { @@ -196,12 +196,11 @@ export class WalletAddEthereumChainHandler extends DAppRequestHandler< async actionHandler( chains: ChainList, network: NetworkWithCaipId, - domain: string + domain: string, ) { const supportedChainIds = Object.keys(chains); if (network.customRpcHeaders) { - // eslint-disable-next-line const { rpcUrl, ...overrides } = network; // we do not want to apply rpcUrl override from here await this.networkService.updateNetworkOverrides(overrides); } @@ -218,7 +217,7 @@ export class WalletAddEthereumChainHandler extends DAppRequestHandler< pendingAction: Action, _result, onSuccess, - onError + onError, ) => { try { const chains = await this.networkService.allNetworks.promisify(); diff --git a/src/background/services/network/handlers/wallet_getEthereumChain.test.ts b/src/background/services/network/handlers/wallet_getEthereumChain.test.ts index e0d4d57b0..84051ba36 100644 --- a/src/background/services/network/handlers/wallet_getEthereumChain.test.ts +++ b/src/background/services/network/handlers/wallet_getEthereumChain.test.ts @@ -30,7 +30,7 @@ describe('background/services/network/handlers/wallet_getEthereumChain.ts', () = it('handleAuthenticated inactive', async () => { const handler = new WalletGetEthereumChainHandler(networkServiceInactive); const result = await handler.handleAuthenticated( - buildRpcCall(getChainRequest) + buildRpcCall(getChainRequest), ); expect(result).toEqual({ ...getChainRequest, @@ -41,10 +41,10 @@ describe('background/services/network/handlers/wallet_getEthereumChain.ts', () = }); it('handleAuthenticated mainnet', async () => { const handler = new WalletGetEthereumChainHandler( - networkServiceMockMainnet + networkServiceMockMainnet, ); const { result } = await handler.handleAuthenticated( - buildRpcCall(getChainRequest) + buildRpcCall(getChainRequest), ); expect(result).toEqual(networkToGetEthChainResponse(BITCOIN_NETWORK)); expect(result.chainName).toEqual(BITCOIN_NETWORK.chainName); @@ -53,25 +53,25 @@ describe('background/services/network/handlers/wallet_getEthereumChain.ts', () = }); it('handleAuthenticated testnet', async () => { const handler = new WalletGetEthereumChainHandler( - networkServiceMockTestnet + networkServiceMockTestnet, ); const { result } = await handler.handleAuthenticated( - buildRpcCall(getChainRequest) + buildRpcCall(getChainRequest), ); expect(result).toEqual(networkToGetEthChainResponse(BITCOIN_TEST_NETWORK)); expect(result.chainName).toEqual(BITCOIN_TEST_NETWORK.chainName); expect(result.chainId).toEqual( - `0x${BITCOIN_TEST_NETWORK.chainId.toString(16)}` + `0x${BITCOIN_TEST_NETWORK.chainId.toString(16)}`, ); expect(result.isTestnet).toEqual(true); }); it('handleUnauthenticated', async () => { const handler = new WalletGetEthereumChainHandler( - networkServiceMockMainnet + networkServiceMockMainnet, ); const result = await handler.handleUnauthenticated( - buildRpcCall(getChainRequest) + buildRpcCall(getChainRequest), ); expect(result).toEqual({ ...getChainRequest, diff --git a/src/background/services/network/handlers/wallet_getEthereumChain.ts b/src/background/services/network/handlers/wallet_getEthereumChain.ts index b4791bf58..929b0210f 100644 --- a/src/background/services/network/handlers/wallet_getEthereumChain.ts +++ b/src/background/services/network/handlers/wallet_getEthereumChain.ts @@ -7,7 +7,7 @@ import { ethErrors } from 'eth-rpc-errors'; import { Network } from '@avalabs/core-chains-sdk'; export const networkToGetEthChainResponse = ( - network: Network + network: Network, ): AddEthereumChainParameter => ({ chainId: `0x${network.chainId.toString(16)}`, chainName: network.chainName, diff --git a/src/background/services/network/handlers/wallet_switchEthereumChain.test.ts b/src/background/services/network/handlers/wallet_switchEthereumChain.test.ts index 21299d605..d94b0b6fd 100644 --- a/src/background/services/network/handlers/wallet_switchEthereumChain.test.ts +++ b/src/background/services/network/handlers/wallet_switchEthereumChain.test.ts @@ -82,7 +82,7 @@ describe('src/background/services/network/handlers/wallet_switchEthereumChain.ts it('handleUnauthenticated', async () => { const result = await handler.handleUnauthenticated( - buildRpcCall(switchChainRequest) + buildRpcCall(switchChainRequest), ); expect(result).toEqual({ ...switchChainRequest, @@ -93,7 +93,7 @@ describe('src/background/services/network/handlers/wallet_switchEthereumChain.ts describe('handleAuthenticated', () => { it('opens approval dialog', async () => { const result = await handler.handleAuthenticated( - buildRpcCall(switchChainRequest, 'eip:43114') + buildRpcCall(switchChainRequest, 'eip:43114'), ); expect(result).toEqual({ @@ -104,7 +104,7 @@ describe('src/background/services/network/handlers/wallet_switchEthereumChain.ts expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1234' }), - 'network/switch' + 'network/switch', ); }); @@ -112,7 +112,7 @@ describe('src/background/services/network/handlers/wallet_switchEthereumChain.ts jest.mocked(canSkipApproval).mockResolvedValue(true); const result = await handler.handleAuthenticated( - buildRpcCall(switchChainRequest) + buildRpcCall(switchChainRequest), ); expect(result).toEqual({ @@ -139,7 +139,7 @@ describe('src/background/services/network/handlers/wallet_switchEthereumChain.ts }; const result = await handler.handleAuthenticated( - buildRpcCall(requestWithBadChainId) + buildRpcCall(requestWithBadChainId), ); expect(result).toEqual({ diff --git a/src/background/services/network/handlers/wallet_switchEthereumChain.ts b/src/background/services/network/handlers/wallet_switchEthereumChain.ts index 7131f4c88..df90c8991 100644 --- a/src/background/services/network/handlers/wallet_switchEthereumChain.ts +++ b/src/background/services/network/handlers/wallet_switchEthereumChain.ts @@ -52,7 +52,7 @@ export class WalletSwitchEthereumChainHandler extends DAppRequestHandler< const params = request.params; const targetChainID = params?.[0]?.chainId; // chain ID is hex with 0x perfix const supportedNetwork = await this.networkService.getNetwork( - Number(targetChainID) + Number(targetChainID), ); const currentActiveNetwork = await this.networkService.getNetwork(scope); @@ -72,13 +72,13 @@ export class WalletSwitchEthereumChainHandler extends DAppRequestHandler< if (supportedNetwork?.chainId) { const skipApproval = await canSkipApproval( request.site.domain, - request.site.tabId + request.site.tabId, ); if (skipApproval) { await this.networkService.setNetwork( request.site.domain, - supportedNetwork.caipId + supportedNetwork.caipId, ); return { ...request, result: null }; } @@ -111,9 +111,9 @@ export class WalletSwitchEthereumChainHandler extends DAppRequestHandler< onActionApproved = async ( pendingAction: Action<{ network: NetworkWithCaipId }>, - result, + _result, onSuccess, - onError + onError, ) => { if (!pendingAction.site?.domain) { return onError(new Error('Unrecognized domain')); @@ -122,7 +122,7 @@ export class WalletSwitchEthereumChainHandler extends DAppRequestHandler< try { await this.networkService.setNetwork( pendingAction.site.domain, - pendingAction.displayData.network.caipId + pendingAction.displayData.network.caipId, ); onSuccess(null); diff --git a/src/background/services/network/utils/getSyncDomain.ts b/src/background/services/network/utils/getSyncDomain.ts index e63b72a23..4305c61c8 100644 --- a/src/background/services/network/utils/getSyncDomain.ts +++ b/src/background/services/network/utils/getSyncDomain.ts @@ -12,7 +12,7 @@ const SYNCED_DOMAINS = [ export const isSyncDomain = ( domain: string, - exposedDomainList: string[] = [] + exposedDomainList: string[] = [], ) => { return [...SYNCED_DOMAINS, ...exposedDomainList].some((syncDomain) => { // Match exact domains, but also allow subdomains (i.e. develop.core-web.pages.dev) diff --git a/src/background/services/networkFee/NetworkFeeService.test.ts b/src/background/services/networkFee/NetworkFeeService.test.ts index 6347f1704..db8d4ecef 100644 --- a/src/background/services/networkFee/NetworkFeeService.test.ts +++ b/src/background/services/networkFee/NetworkFeeService.test.ts @@ -59,7 +59,7 @@ describe('src/background/services/networkFee/NetworkFeeService', () => { medium: { maxFeePerGas: 4n }, high: { maxFeePerGas: 5n }, displayDecimals: 0, - }) + }), ); }); diff --git a/src/background/services/networkFee/NetworkFeeService.ts b/src/background/services/networkFee/NetworkFeeService.ts index 25f901f02..4fab2727d 100644 --- a/src/background/services/networkFee/NetworkFeeService.ts +++ b/src/background/services/networkFee/NetworkFeeService.ts @@ -24,7 +24,7 @@ export class NetworkFeeService { to: string, data: string, network: NetworkWithCaipId, - value?: bigint + value?: bigint, ): Promise { if (network.vmName !== NetworkVMType.EVM) { return null; @@ -32,7 +32,7 @@ export class NetworkFeeService { const provider = await getProviderForNetwork(network); const nonce = await (provider as JsonRpcBatchInternal).getTransactionCount( - from + from, ); return Number( @@ -42,7 +42,7 @@ export class NetworkFeeService { to: to, data: data, value, - }) + }), ); } } diff --git a/src/background/services/networkFee/handlers/getNetworkFee.ts b/src/background/services/networkFee/handlers/getNetworkFee.ts index 120821c14..ea83e1c83 100644 --- a/src/background/services/networkFee/handlers/getNetworkFee.ts +++ b/src/background/services/networkFee/handlers/getNetworkFee.ts @@ -18,7 +18,7 @@ export class GetNetworkFeeHandler implements HandlerType { constructor( private networkFeeService: NetworkFeeService, - private networkService: NetworkService + private networkService: NetworkService, ) {} handle: HandlerType['handle'] = async ({ request, scope }) => { diff --git a/src/background/services/onboarding/OnboardingService.ts b/src/background/services/onboarding/OnboardingService.ts index 34b86e293..294b09208 100644 --- a/src/background/services/onboarding/OnboardingService.ts +++ b/src/background/services/onboarding/OnboardingService.ts @@ -79,7 +79,7 @@ export class OnboardingService { private async loadFromStorage(): Promise { const state = await this.storageService.loadUnencrypted( - ONBOARDING_STORAGE_KEY + ONBOARDING_STORAGE_KEY, ); return state || defaultState; } diff --git a/src/background/services/onboarding/events/listeners.ts b/src/background/services/onboarding/events/listeners.ts index 46cfc057e..1ee1cfe19 100644 --- a/src/background/services/onboarding/events/listeners.ts +++ b/src/background/services/onboarding/events/listeners.ts @@ -3,7 +3,7 @@ import { OnboardingState } from '../models'; import { OnboardingEvents } from '../models'; export function onboardingUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === OnboardingEvents.ONBOARDING_UPDATED_EVENT; } diff --git a/src/background/services/onboarding/events/onboardingUpdatedEvent.ts b/src/background/services/onboarding/events/onboardingUpdatedEvent.ts index 206ead81c..5effc2ed9 100644 --- a/src/background/services/onboarding/events/onboardingUpdatedEvent.ts +++ b/src/background/services/onboarding/events/onboardingUpdatedEvent.ts @@ -17,7 +17,7 @@ export class OnboardingUpdatedEvents implements ExtensionEventEmitter { name: OnboardingEvents.ONBOARDING_UPDATED_EVENT, value: onboardingState, }); - } + }, ); } @@ -26,7 +26,7 @@ export class OnboardingUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/onboarding/finalizeOnboarding.test.ts b/src/background/services/onboarding/finalizeOnboarding.test.ts index 77a75ccad..f4542cd5e 100644 --- a/src/background/services/onboarding/finalizeOnboarding.test.ts +++ b/src/background/services/onboarding/finalizeOnboarding.test.ts @@ -76,14 +76,14 @@ describe('src/background/services/onboarding/finalizeOnboarding.test.ts', () => expect(networkServiceMock.addFavoriteNetwork).toHaveBeenNthCalledWith( 1, - ChainId.BITCOIN + ChainId.BITCOIN, ); expect(networkServiceMock.addFavoriteNetwork).toHaveBeenNthCalledWith( 2, - ChainId.ETHEREUM_HOMESTEAD + ChainId.ETHEREUM_HOMESTEAD, ); expect(accountsServiceMock.activateAccount).toHaveBeenCalledWith( - accountMock.id + accountMock.id, ); expect(onboardingServiceMock.setIsOnboarded).toHaveBeenCalledWith(true); expect(lockServiceMock.unlock).toHaveBeenCalledWith('password'); diff --git a/src/background/services/onboarding/handlers/keystoneOnboardingHandler.test.ts b/src/background/services/onboarding/handlers/keystoneOnboardingHandler.test.ts index 9cdc8ca23..d06068713 100644 --- a/src/background/services/onboarding/handlers/keystoneOnboardingHandler.test.ts +++ b/src/background/services/onboarding/handlers/keystoneOnboardingHandler.test.ts @@ -77,7 +77,7 @@ describe('src/background/services/onboarding/handlers/keystoneOnboardingHandler. walletServiceMock, onboardingServiceMock, lockServiceMock, - networkServiceMock + networkServiceMock, ); const getRequest = (params: unknown[]) => @@ -85,7 +85,7 @@ describe('src/background/services/onboarding/handlers/keystoneOnboardingHandler. id: '123', method: ExtensionRequest.KEYSTONE_ONBOARDING_SUBMIT, params, - } as any); + }) as any; beforeEach(() => { jest.resetAllMocks(); @@ -125,7 +125,7 @@ describe('src/background/services/onboarding/handlers/keystoneOnboardingHandler. expect(getXpubFromMnemonic).not.toHaveBeenCalled(); expect(Avalanche.getXpubFromMnemonic).not.toHaveBeenCalled(); expect(storageServiceMock.createStorageKey).toHaveBeenCalledWith( - 'password' + 'password', ); expect(walletServiceMock.init).toHaveBeenCalledWith({ xpub: 'xpub', @@ -141,7 +141,7 @@ describe('src/background/services/onboarding/handlers/keystoneOnboardingHandler. expect(settingsServiceMock.setAnalyticsConsent).toHaveBeenCalledWith(false); expect( - analyticsServiceMock.saveTemporaryAnalyticsIds + analyticsServiceMock.saveTemporaryAnalyticsIds, ).not.toHaveBeenCalled(); expect(addXPChainToFavoriteIfNeeded).toHaveBeenCalledWith([accountMock]); diff --git a/src/background/services/onboarding/handlers/keystoneOnboardingHandler.ts b/src/background/services/onboarding/handlers/keystoneOnboardingHandler.ts index d473ab810..b94a7160f 100644 --- a/src/background/services/onboarding/handlers/keystoneOnboardingHandler.ts +++ b/src/background/services/onboarding/handlers/keystoneOnboardingHandler.ts @@ -24,7 +24,7 @@ type HandlerType = ExtensionRequestHandler< password: string; analyticsConsent: boolean; walletName?: string; - } + }, ] >; @@ -40,7 +40,7 @@ export class KeystoneOnboardingHandler implements HandlerType { private walletService: WalletService, private onboardingService: OnboardingService, private lockService: LockService, - private networkService: NetworkService + private networkService: NetworkService, ) {} handle: HandlerType['handle'] = async ({ request }) => { diff --git a/src/background/services/onboarding/handlers/ledgerOnboardingHandler.test.ts b/src/background/services/onboarding/handlers/ledgerOnboardingHandler.test.ts index fdef9947a..df1368e11 100644 --- a/src/background/services/onboarding/handlers/ledgerOnboardingHandler.test.ts +++ b/src/background/services/onboarding/handlers/ledgerOnboardingHandler.test.ts @@ -78,7 +78,7 @@ describe('src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts walletServiceMock, onboardingServiceMock, lockServiceMock, - networkServiceMock + networkServiceMock, ); const getRequest = (params: unknown[]) => @@ -86,7 +86,7 @@ describe('src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts id: '123', method: ExtensionRequest.LEDGER_ONBOARDING_SUBMIT, params, - } as any); + }) as any; beforeEach(() => { jest.resetAllMocks(); @@ -125,7 +125,7 @@ describe('src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts expect(getXpubFromMnemonic).not.toHaveBeenCalled(); expect(Avalanche.getXpubFromMnemonic).not.toHaveBeenCalled(); expect(storageServiceMock.createStorageKey).toHaveBeenCalledWith( - 'password' + 'password', ); expect(walletServiceMock.init).toHaveBeenCalledWith({ mnemonic: undefined, @@ -142,7 +142,7 @@ describe('src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts expect(settingsServiceMock.setAnalyticsConsent).toHaveBeenCalledWith(false); expect( - analyticsServiceMock.saveTemporaryAnalyticsIds + analyticsServiceMock.saveTemporaryAnalyticsIds, ).not.toHaveBeenCalled(); }); @@ -167,7 +167,7 @@ describe('src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts expect(getXpubFromMnemonic).not.toHaveBeenCalled(); expect(Avalanche.getXpubFromMnemonic).not.toHaveBeenCalled(); expect(storageServiceMock.createStorageKey).toHaveBeenCalledWith( - 'password' + 'password', ); expect(walletServiceMock.init).toHaveBeenCalledWith({ pubKeys: ['pubkey1', 'pubkey2', 'pubkey3'], @@ -188,7 +188,7 @@ describe('src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts expect(settingsServiceMock.setAnalyticsConsent).toHaveBeenCalledWith(false); expect( - analyticsServiceMock.saveTemporaryAnalyticsIds + analyticsServiceMock.saveTemporaryAnalyticsIds, ).not.toHaveBeenCalled(); expect(addXPChainToFavoriteIfNeeded).toHaveBeenCalledWith([accountMock]); diff --git a/src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts b/src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts index bd37516c5..04dcbfee1 100644 --- a/src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts +++ b/src/background/services/onboarding/handlers/ledgerOnboardingHandler.ts @@ -26,7 +26,7 @@ type HandlerType = ExtensionRequestHandler< password: string; analyticsConsent: boolean; walletName?: string; - } + }, ] >; @@ -42,7 +42,7 @@ export class LedgerOnboardingHandler implements HandlerType { private walletService: WalletService, private onboardingService: OnboardingService, private lockService: LockService, - private networkService: NetworkService + private networkService: NetworkService, ) {} handle: HandlerType['handle'] = async ({ request }) => { diff --git a/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.test.ts b/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.test.ts index 0f9b27cff..ac5066519 100644 --- a/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.test.ts +++ b/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.test.ts @@ -77,7 +77,7 @@ describe('src/background/services/onboarding/handlers/mnemonicOnboardingHandler. walletServiceMock, onboardingServiceMock, lockServiceMock, - networkServiceMock + networkServiceMock, ); const getRequest = (params: unknown[]) => @@ -85,7 +85,7 @@ describe('src/background/services/onboarding/handlers/mnemonicOnboardingHandler. id: '123', method: ExtensionRequest.MNEMONIC_ONBOARDING_SUBMIT, params, - } as any); + }) as any; beforeEach(() => { jest.resetAllMocks(); @@ -124,11 +124,11 @@ describe('src/background/services/onboarding/handlers/mnemonicOnboardingHandler. expect(walletServiceMock.init).toHaveBeenCalledWith( expect.objectContaining({ mnemonic: mnemonic.toLowerCase(), - }) + }), ); expect(getXpubFromMnemonic).toHaveBeenCalledWith(mnemonic.toLowerCase()); expect(Avalanche.getXpubFromMnemonic).toHaveBeenCalledWith( - mnemonic.toLowerCase() + mnemonic.toLowerCase(), ); expect(result).toEqual({ @@ -139,10 +139,10 @@ describe('src/background/services/onboarding/handlers/mnemonicOnboardingHandler. it('sets up an mnemonic wallet correctly', async () => { (getXpubFromMnemonic as jest.Mock).mockResolvedValueOnce( - 'xpubFromMnemonic' + 'xpubFromMnemonic', ); (Avalanche.getXpubFromMnemonic as jest.Mock).mockReturnValueOnce( - 'xpubFromMnemonicXP' + 'xpubFromMnemonicXP', ); const handler = getHandler(); @@ -163,7 +163,7 @@ describe('src/background/services/onboarding/handlers/mnemonicOnboardingHandler. expect(getXpubFromMnemonic).toHaveBeenCalledWith('mnemonic'); expect(storageServiceMock.createStorageKey).toHaveBeenCalledWith( - 'password' + 'password', ); expect(walletServiceMock.init).toHaveBeenCalledWith({ mnemonic: 'mnemonic', @@ -181,7 +181,7 @@ describe('src/background/services/onboarding/handlers/mnemonicOnboardingHandler. expect(settingsServiceMock.setAnalyticsConsent).toHaveBeenCalledWith(false); expect( - analyticsServiceMock.saveTemporaryAnalyticsIds + analyticsServiceMock.saveTemporaryAnalyticsIds, ).not.toHaveBeenCalled(); expect(addXPChainToFavoriteIfNeeded).toHaveBeenCalledWith([accountMock]); diff --git a/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.ts b/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.ts index c69f33302..95d1d4fa5 100644 --- a/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.ts +++ b/src/background/services/onboarding/handlers/mnemonicOnboardingHandler.ts @@ -27,7 +27,7 @@ type HandlerType = ExtensionRequestHandler< password: string; analyticsConsent: boolean; walletName?: string; - } + }, ] >; @@ -43,7 +43,7 @@ export class MnemonicOnboardingHandler implements HandlerType { private walletService: WalletService, private onboardingService: OnboardingService, private lockService: LockService, - private networkService: NetworkService + private networkService: NetworkService, ) {} handle: HandlerType['handle'] = async ({ request }) => { diff --git a/src/background/services/onboarding/handlers/seedlessOnboardingHandler.test.ts b/src/background/services/onboarding/handlers/seedlessOnboardingHandler.test.ts index 9def74837..b7484a2b0 100644 --- a/src/background/services/onboarding/handlers/seedlessOnboardingHandler.test.ts +++ b/src/background/services/onboarding/handlers/seedlessOnboardingHandler.test.ts @@ -29,7 +29,7 @@ const mockrMemorySession = { }; (MemorySessionStorage as jest.Mock).mockImplementation( - () => mockrMemorySession + () => mockrMemorySession, ); jest.mock('../../seedless/SeedlessWallet'); @@ -96,7 +96,7 @@ describe('src/background/services/onboarding/handlers/seedlessOnboardingHandler. onboardingServiceMock, lockServiceMock, networkServiceMock, - secretsServiceMock + secretsServiceMock, ); const getRequest = (params: unknown[]) => @@ -104,7 +104,7 @@ describe('src/background/services/onboarding/handlers/seedlessOnboardingHandler. id: '123', method: ExtensionRequest.SEEDLESS_ONBOARDING_SUBMIT, params, - } as any); + }) as any; beforeEach(() => { jest.resetAllMocks(); @@ -159,7 +159,7 @@ describe('src/background/services/onboarding/handlers/seedlessOnboardingHandler. // Creates the storage key expect(storageServiceMock.createStorageKey).toHaveBeenCalledWith( - 'password' + 'password', ); // Initializes the wallet diff --git a/src/background/services/onboarding/handlers/seedlessOnboardingHandler.ts b/src/background/services/onboarding/handlers/seedlessOnboardingHandler.ts index 4e3c15c4b..31e549b94 100644 --- a/src/background/services/onboarding/handlers/seedlessOnboardingHandler.ts +++ b/src/background/services/onboarding/handlers/seedlessOnboardingHandler.ts @@ -32,7 +32,7 @@ type HandlerType = ExtensionRequestHandler< analyticsConsent: boolean; walletName?: string; authProvider: SeedlessAuthProvider; - } + }, ] >; @@ -49,7 +49,7 @@ export class SeedlessOnboardingHandler implements HandlerType { private onboardingService: OnboardingService, private lockService: LockService, private networkService: NetworkService, - private secretsService: SecretsService + private secretsService: SecretsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -93,9 +93,8 @@ export class SeedlessOnboardingHandler implements HandlerType { }; } - const secrets = await this.secretsService.getWalletAccountsSecretsById( - walletId - ); + const secrets = + await this.secretsService.getWalletAccountsSecretsById(walletId); if (secrets?.secretType === SecretType.Seedless) { // Adding accounts cannot be parallelized, they need to be added one-by-one. // Otherwise race conditions occur and addresses get mixed up. diff --git a/src/background/services/onboarding/startOnboarding.test.ts b/src/background/services/onboarding/startOnboarding.test.ts index 6a6aaefc9..f3a2d4716 100644 --- a/src/background/services/onboarding/startOnboarding.test.ts +++ b/src/background/services/onboarding/startOnboarding.test.ts @@ -34,7 +34,7 @@ describe('src/background/services/onboarding/handlers/onboardingInitalWork.ts', password: 'password', }); expect(storageServiceMock.createStorageKey).toHaveBeenCalledWith( - 'password' + 'password', ); expect(settingsServiceMock.setAnalyticsConsent).toHaveBeenCalledWith(true); expect(analyticsServiceMock.saveTemporaryAnalyticsIds).toHaveBeenCalled(); @@ -49,11 +49,11 @@ describe('src/background/services/onboarding/handlers/onboardingInitalWork.ts', password: 'password', }); expect(storageServiceMock.createStorageKey).toHaveBeenCalledWith( - 'password' + 'password', ); expect(settingsServiceMock.setAnalyticsConsent).toHaveBeenCalledWith(false); expect( - analyticsServiceMock.saveTemporaryAnalyticsIds + analyticsServiceMock.saveTemporaryAnalyticsIds, ).not.toHaveBeenCalled(); }); }); diff --git a/src/background/services/onboarding/utils/addXPChainsToFavoriteIfNeeded.ts b/src/background/services/onboarding/utils/addXPChainsToFavoriteIfNeeded.ts index e550c8d0d..859ed4671 100644 --- a/src/background/services/onboarding/utils/addXPChainsToFavoriteIfNeeded.ts +++ b/src/background/services/onboarding/utils/addXPChainsToFavoriteIfNeeded.ts @@ -14,7 +14,7 @@ import { } from '@avalabs/vm-module-types'; export const addXPChainToFavoriteIfNeeded = async ( - accounts: PrimaryAccount[] + accounts: PrimaryAccount[], ) => { const balanceService = container.resolve(BalanceAggregatorService); const networkService = container.resolve(NetworkService); @@ -22,7 +22,7 @@ export const addXPChainToFavoriteIfNeeded = async ( const balances = await balanceService.getBalancesForNetworks( [ChainId.AVALANCHE_P, ChainId.AVALANCHE_X], accounts, - [TokenType.NATIVE] + [TokenType.NATIVE], ); if (hasBalance(balances.tokens, accounts, ChainId.AVALANCHE_P)) { @@ -34,7 +34,7 @@ export const addXPChainToFavoriteIfNeeded = async ( const hasPActivity = await hasChainActivity( historyService, accounts.map(({ addressPVM }) => addressPVM).filter(isString), - pChain + pChain, ); if (hasPActivity) { @@ -52,7 +52,7 @@ export const addXPChainToFavoriteIfNeeded = async ( const hasXActivity = await hasChainActivity( historyService, accounts.map(({ addressAVM }) => addressAVM).filter(isString), - xChain + xChain, ); if (hasXActivity) { @@ -65,14 +65,14 @@ export const addXPChainToFavoriteIfNeeded = async ( async function hasChainActivity( historyService: HistoryService, addresses: string[], - network: NetworkWithCaipId + network: NetworkWithCaipId, ) { try { const results = await Promise.allSettled( - addresses.map((address) => historyService.getTxHistory(network, address)) + addresses.map((address) => historyService.getTxHistory(network, address)), ); const histories = results.map((result) => - result.status === 'fulfilled' ? result.value : [] + result.status === 'fulfilled' ? result.value : [], ); return histories.some((history) => history.length > 0); @@ -84,7 +84,7 @@ async function hasChainActivity( function hasBalance( balances: Balances, activeAccounts: PrimaryAccount[], - chainId: ChainId + chainId: ChainId, ) { return activeAccounts.some((account) => { const address = diff --git a/src/background/services/permissions/PermissionsService.test.ts b/src/background/services/permissions/PermissionsService.test.ts index d5698b333..1813b8bd1 100644 --- a/src/background/services/permissions/PermissionsService.test.ts +++ b/src/background/services/permissions/PermissionsService.test.ts @@ -65,7 +65,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { const permissionService = new PermissionsService(storageService); (storageService.load as jest.Mock).mockRejectedValue( - new Error('storage error') + new Error('storage error'), ); const result = await permissionService.getPermissions(); @@ -82,7 +82,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { }); permissionService.addListener( PermissionEvents.PERMISSIONS_STATE_UPDATE, - eventListener + eventListener, ); const result = await permissionService.getPermissions(); @@ -105,7 +105,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { }); permissionService.addListener( PermissionEvents.PERMISSIONS_STATE_UPDATE, - eventListener + eventListener, ); await permissionService.getPermissions(); @@ -128,9 +128,8 @@ describe('background/services/permissions/PermissionsService.ts', () => { ...mockPermissionData, }); - const result = await permissionService.getPermissionsForDomain( - 'oneaccount.example' - ); + const result = + await permissionService.getPermissionsForDomain('oneaccount.example'); expect(result).toEqual(mockPermissionData['oneaccount.example']); }); @@ -158,7 +157,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { const result = await permissionService.hasDomainPermissionForAccount( 'oneaccount.example', - '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' + '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', ); expect(result).toEqual(true); @@ -173,7 +172,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { const result = await permissionService.hasDomainPermissionForAccount( 'oneaccount.example', - '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', ); expect(result).toEqual(false); @@ -188,7 +187,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { const result = await permissionService.hasDomainPermissionForAccount( 'oneaccount.example', - '0xnonexistentaccount' + '0xnonexistentaccount', ); expect(result).toEqual(false); @@ -203,7 +202,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { const result = await permissionService.hasDomainPermissionForAccount( 'unkown.domain', - '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' + '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', ); expect(result).toEqual(false); @@ -266,7 +265,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { permissionService.addListener( PermissionEvents.PERMISSIONS_STATE_UPDATE, - eventListener + eventListener, ); const newPermission = { @@ -293,20 +292,20 @@ describe('background/services/permissions/PermissionsService.ts', () => { expect( permissions['oneaccount.example']?.accounts[ '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' - ] + ], ).toBe(true); await permissionService.setAccountPermissionForDomain( 'oneaccount.example', '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', - false + false, ); const newPermissions = await permissionService.getPermissions(); expect( newPermissions['oneaccount.example']?.accounts[ '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' - ] + ], ).toBe(false); }); @@ -321,20 +320,20 @@ describe('background/services/permissions/PermissionsService.ts', () => { expect( permissions['newdomain.example']?.accounts[ '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' - ] + ], ).toBe(undefined); await permissionService.setAccountPermissionForDomain( 'newdomain.example', '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', - true + true, ); const newPermissions = await permissionService.getPermissions(); expect( newPermissions['newdomain.example']?.accounts[ '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' - ] + ], ).toBe(true); }); @@ -345,7 +344,7 @@ describe('background/services/permissions/PermissionsService.ts', () => { await permissionService.setAccountPermissionForDomain( 'newdomain.example', '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', - true + true, ); expect(storageService.save).toHaveBeenCalledTimes(1); @@ -367,13 +366,13 @@ describe('background/services/permissions/PermissionsService.ts', () => { permissionService.addListener( PermissionEvents.PERMISSIONS_STATE_UPDATE, - eventListener + eventListener, ); await permissionService.setAccountPermissionForDomain( 'newdomain.example', '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', - true + true, ); expect(eventListener).toHaveBeenCalledTimes(1); @@ -395,13 +394,13 @@ describe('background/services/permissions/PermissionsService.ts', () => { await permissionService.addWhitelistDomains('0x000000'); expect( - permissionService.setAccountPermissionForDomain + permissionService.setAccountPermissionForDomain, ).toHaveBeenCalledTimes(2); expect( - permissionService.setAccountPermissionForDomain + permissionService.setAccountPermissionForDomain, ).toHaveBeenNthCalledWith(1, 'core.app', '0x000000', true); expect( - permissionService.setAccountPermissionForDomain + permissionService.setAccountPermissionForDomain, ).toHaveBeenNthCalledWith(2, 'test.core.app', '0x000000', true); }); }); diff --git a/src/background/services/permissions/PermissionsService.ts b/src/background/services/permissions/PermissionsService.ts index f8c6d4065..5f9737fcb 100644 --- a/src/background/services/permissions/PermissionsService.ts +++ b/src/background/services/permissions/PermissionsService.ts @@ -28,7 +28,7 @@ export class PermissionsService implements OnLock { this.#permissions = permissions; this.#eventEmitter.emit( PermissionEvents.PERMISSIONS_STATE_UPDATE, - this.permissions ?? {} + this.permissions ?? {}, ); } @@ -47,7 +47,7 @@ export class PermissionsService implements OnLock { this.permissions = (await this.storageService.load(PERMISSION_STORAGE_KEY)) ?? {}; - } catch (e) { + } catch (_err) { /** * If permissions arent pulled then dont set permissions to an empty object * since permissions is requested when the extension opens and the password may not have @@ -67,7 +67,7 @@ export class PermissionsService implements OnLock { async hasDomainPermissionForAccount( domain: string, - address: string + address: string, ): Promise { const domainPermissions = await this.getPermissionsForDomain(domain); return !!domainPermissions?.accounts[address]; @@ -91,14 +91,14 @@ export class PermissionsService implements OnLock { this.storageService.save( PERMISSION_STORAGE_KEY, - this.permissions + this.permissions, ); } async setAccountPermissionForDomain( domain: string, address: string, - hasPermission: boolean + hasPermission: boolean, ) { const currentPermissions = await this.getPermissions(); @@ -122,7 +122,7 @@ export class PermissionsService implements OnLock { this.storageService.save( PERMISSION_STORAGE_KEY, - this.permissions + this.permissions, ); } diff --git a/src/background/services/permissions/events/permissionsStateUpdates.ts b/src/background/services/permissions/events/permissionsStateUpdates.ts index 8ee041112..df1bb4aa5 100644 --- a/src/background/services/permissions/events/permissionsStateUpdates.ts +++ b/src/background/services/permissions/events/permissionsStateUpdates.ts @@ -18,7 +18,7 @@ export class PermissionStateUpdateEvents implements ExtensionEventEmitter { name: PermissionEvents.PERMISSIONS_STATE_UPDATE, value: permissions, }); - } + }, ); } @@ -27,7 +27,7 @@ export class PermissionStateUpdateEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/permissions/events/permissionsStateUpdatesListener.ts b/src/background/services/permissions/events/permissionsStateUpdatesListener.ts index b042be75f..902adedc2 100644 --- a/src/background/services/permissions/events/permissionsStateUpdatesListener.ts +++ b/src/background/services/permissions/events/permissionsStateUpdatesListener.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { PermissionEvents, Permissions } from '../models'; export function permissionsUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === PermissionEvents.PERMISSIONS_STATE_UPDATE; } diff --git a/src/background/services/permissions/handlers/addPermissionsForDomain.ts b/src/background/services/permissions/handlers/addPermissionsForDomain.ts index 8749b3d6b..97595599f 100644 --- a/src/background/services/permissions/handlers/addPermissionsForDomain.ts +++ b/src/background/services/permissions/handlers/addPermissionsForDomain.ts @@ -20,7 +20,7 @@ export class PermissionsAddDomainHandler implements HandlerType { constructor( private permissionsService: PermissionsService, private actionsService: ActionsService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { diff --git a/src/background/services/permissions/handlers/wallet_requestPermissions.test.ts b/src/background/services/permissions/handlers/wallet_requestPermissions.test.ts index bf3fd83cb..98587af97 100644 --- a/src/background/services/permissions/handlers/wallet_requestPermissions.test.ts +++ b/src/background/services/permissions/handlers/wallet_requestPermissions.test.ts @@ -18,11 +18,11 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' it('calls handle authenticated', async () => { const handler = new WalletRequestPermissionsHandler( {} as PermissionsService, - {} as AccountsService + {} as AccountsService, ); const handleUnauthenticatedSpy = jest.spyOn( handler, - 'handleUnauthenticated' + 'handleUnauthenticated', ); const mockRequest = { id: '1234', @@ -37,7 +37,7 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' await handler.handleAuthenticated(buildRpcCall(mockRequest)); expect(handleUnauthenticatedSpy).toBeCalledTimes(1); expect(handleUnauthenticatedSpy).toBeCalledWith( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); }); }); @@ -45,7 +45,7 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' it('opens permissions window', async () => { const handler = new WalletRequestPermissionsHandler( {} as PermissionsService, - {} as AccountsService + {} as AccountsService, ); const mockRequest = { @@ -60,7 +60,7 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' }; const result = await handler.handleUnauthenticated( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); expect(result).toEqual({ ...mockRequest, @@ -69,7 +69,7 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '4321' }), - `permissions` + `permissions`, ); }); }); @@ -114,14 +114,14 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' const handler = new WalletRequestPermissionsHandler( permissionServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); await handler.onActionApproved( { ...mockAction }, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect(permissionServiceMock.addPermission).not.toHaveBeenCalled(); @@ -129,26 +129,26 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' expect(onErrorMock).toHaveBeenCalledTimes(1); expect(onErrorMock).toHaveBeenCalledWith( - ethErrors.rpc.internal('Selected account not found') + ethErrors.rpc.internal('Selected account not found'), ); }); it('returns error when domain not set', async () => { const handler = new WalletRequestPermissionsHandler( permissionServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); await handler.onActionApproved( { ...mockAction }, 'uuid', onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).toHaveBeenCalledTimes(1); expect(onErrorMock).toHaveBeenCalledWith( - ethErrors.rpc.internal('Domain not set') + ethErrors.rpc.internal('Domain not set'), ); expect(permissionServiceMock.addPermission).not.toHaveBeenCalled(); expect(accountsServiceMock.activateAccount).not.toHaveBeenCalled(); @@ -169,14 +169,14 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' { invoker: 'example.com', parentCapabitily: 'accounts' }, ]; (getPermissionsConvertedToMetaMaskStructure as jest.Mock).mockReturnValue( - metamaskStructure + metamaskStructure, ); permissionServiceMock.getPermissions.mockReturnValue(mockPermissions); const handler = new WalletRequestPermissionsHandler( permissionServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); await handler.onActionApproved( @@ -186,7 +186,7 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' }, 'uuid', onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).not.toHaveBeenCalled(); @@ -202,7 +202,7 @@ describe('background/services/permissions/handlers/wallet_requestPermissions.ts' expect(accountsServiceMock.activateAccount).toHaveBeenCalledWith('uuid'); expect(onSuccessMock).toHaveBeenCalledTimes(1); expect(getPermissionsConvertedToMetaMaskStructure).toHaveBeenCalledTimes( - 1 + 1, ); expect(onSuccessMock).toHaveBeenCalledWith(metamaskStructure); }); diff --git a/src/background/services/permissions/handlers/wallet_requestPermissions.ts b/src/background/services/permissions/handlers/wallet_requestPermissions.ts index bddeb4d21..c0fa186fd 100644 --- a/src/background/services/permissions/handlers/wallet_requestPermissions.ts +++ b/src/background/services/permissions/handlers/wallet_requestPermissions.ts @@ -15,7 +15,7 @@ export class WalletRequestPermissionsHandler extends DAppRequestHandler { constructor( private permissionsService: PermissionsService, - private accountsService: AccountsService + private accountsService: AccountsService, ) { super(); } @@ -32,7 +32,7 @@ export class WalletRequestPermissionsHandler extends DAppRequestHandler { domainIcon: request.site?.icon, }, }, - `permissions` + `permissions`, ); return { ...request, result: DEFERRED_RESPONSE }; @@ -46,7 +46,7 @@ export class WalletRequestPermissionsHandler extends DAppRequestHandler { pendingAction: Action, result: any, onSuccess: (result: unknown) => void, - onError: (error: Error) => void + onError: (error: Error) => void, ) => { const selectedAccount = this.accountsService.getAccountByID(result); if (!selectedAccount) { @@ -71,8 +71,8 @@ export class WalletRequestPermissionsHandler extends DAppRequestHandler { getPermissionsConvertedToMetaMaskStructure( selectedAccount.addressC, pendingAction.site.domain, - currentPermissions - ) + currentPermissions, + ), ); }; } diff --git a/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.test.ts b/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.test.ts index c26c64b12..d15d85cbe 100644 --- a/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.test.ts +++ b/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.test.ts @@ -14,20 +14,20 @@ describe('background/services/permissions/utils/getPermissionConvertedToMetaMask it('returns empty array if there is no addressC, domain, or permissions', () => { expect(getPermissionsConvertedToMetaMaskStructure()).toStrictEqual([]); expect( - getPermissionsConvertedToMetaMaskStructure('123', undefined, {}) + getPermissionsConvertedToMetaMaskStructure('123', undefined, {}), ).toStrictEqual([]); expect( - getPermissionsConvertedToMetaMaskStructure(undefined, 'example.com', {}) + getPermissionsConvertedToMetaMaskStructure(undefined, 'example.com', {}), ).toStrictEqual([]); expect( getPermissionsConvertedToMetaMaskStructure( '123', 'example.com', - undefined - ) + undefined, + ), ).toStrictEqual([]); expect( - getPermissionsConvertedToMetaMaskStructure('123', 'example.com') + getPermissionsConvertedToMetaMaskStructure('123', 'example.com'), ).toStrictEqual([]); expect(getPermissionsConvertedToMetaMaskStructure('123')).toStrictEqual([]); }); @@ -37,8 +37,8 @@ describe('background/services/permissions/utils/getPermissionConvertedToMetaMask getPermissionsConvertedToMetaMaskStructure( '123', 'example.com', - mockPermissions - ) + mockPermissions, + ), ).toStrictEqual([]); }); @@ -47,8 +47,8 @@ describe('background/services/permissions/utils/getPermissionConvertedToMetaMask getPermissionsConvertedToMetaMaskStructure( '0x11111eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', 'example.com', - mockPermissions - ) + mockPermissions, + ), ).toEqual([{ invoker: 'example.com', parentCapability: 'accounts' }]); }); }); diff --git a/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.ts b/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.ts index 5afc3724b..3c9145193 100644 --- a/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.ts +++ b/src/background/services/permissions/utils/getPermissionsConvertedToMetaMaskStructure.ts @@ -10,7 +10,7 @@ import { Permissions } from '../models'; export function getPermissionsConvertedToMetaMaskStructure( addressC?: string, domain?: string, - permissions?: Permissions + permissions?: Permissions, ) { if (!domain || !permissions || !addressC) { return []; diff --git a/src/background/services/secrets/SecretsService.test.ts b/src/background/services/secrets/SecretsService.test.ts index 47a03a1c8..a49e979f1 100644 --- a/src/background/services/secrets/SecretsService.test.ts +++ b/src/background/services/secrets/SecretsService.test.ts @@ -58,7 +58,7 @@ const ACTIVE_WALLET_ID = 'active-wallet-id'; describe('src/background/services/secrets/SecretsService.ts', () => { const storageService = jest.mocked(new StorageService({} as CallbackManager)); const networkService = jest.mocked( - new NetworkService(storageService, {} as any) + new NetworkService(storageService, {} as any), ); const activeAccount = { type: AccountType.PRIMARY, @@ -73,7 +73,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { beforeEach(() => { jest.resetAllMocks(); - getAddressMock = jest.fn().mockImplementation((pubkey, chain) => { + getAddressMock = jest.fn().mockImplementation((_pubkey, chain) => { return `${chain}-`; }); @@ -86,7 +86,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { } as any; networkService.getAvalanceProviderXP.mockReturnValue( - getDefaultFujiProviderMock() + getDefaultFujiProviderMock(), ); secretsService = new SecretsService(storageService); @@ -215,7 +215,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }; const mockSeedlessWallet = ( additionalData: any = {}, - account?: Partial + account?: Partial, ) => { const data = { secretType: SecretType.Seedless, @@ -258,7 +258,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { const eventListener = jest.fn(); secretsService.addListener( WalletEvents.WALLET_STATE_UPDATE, - eventListener + eventListener, ); await secretsService.onUnlock(); expect(eventListener).toHaveBeenCalledWith([]); @@ -268,7 +268,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { const eventListener = jest.fn(); secretsService.addListener( WalletEvents.WALLET_STATE_UPDATE, - eventListener + eventListener, ); await secretsService.onUnlock(); expect(eventListener).toHaveBeenCalledWith([ @@ -287,7 +287,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { storageService.load.mockResolvedValue(null); await expect(secretsService.getPrimaryAccountSecrets()).resolves.toBe( - null + null, ); }); @@ -301,7 +301,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }); await expect( - secretsService.getPrimaryAccountSecrets(activeAccount) + secretsService.getPrimaryAccountSecrets(activeAccount), ).resolves.toEqual(walletSecrets); }); }); @@ -316,7 +316,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { name: wallet.name, type: wallet.secretType, derivationPath: wallet.derivationPath, - })) + })), ); }); }); @@ -326,7 +326,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { const eventListener = jest.fn(); secretsService.addListener( WalletEvents.WALLET_STATE_UPDATE, - eventListener + eventListener, ); const uuid = 'uuid'; @@ -445,7 +445,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { const eventListener = jest.fn(); secretsService.addListener( WalletEvents.WALLET_STATE_UPDATE, - eventListener + eventListener, ); const existingSecrets = { xpub: 'xpub', @@ -459,7 +459,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { await secretsService.updateSecrets( { xpubXP: 'xpubXP' }, - ACTIVE_WALLET_ID + ACTIVE_WALLET_ID, ); expect(storageService.save).toHaveBeenCalledWith(WALLET_STORAGE_KEY, { @@ -499,7 +499,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { storageService.load.mockResolvedValue(null); await expect( - secretsService.getAccountSecrets(activeAccountData) + secretsService.getAccountSecrets(activeAccountData), ).rejects.toThrow('Wallet is not initialized'); }); @@ -514,7 +514,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { await secretsService.getAccountSecrets({ ...activeAccountData, walletId: 'invalid-wallet-id', - }) + }), ).rejects.toThrow(); }); }); @@ -530,19 +530,17 @@ describe('src/background/services/secrets/SecretsService.ts', () => { it('attaches the account object to the result', async () => { mockMnemonicWallet(); - const result = await secretsService.getAccountSecrets( - activeAccountData - ); + const result = + await secretsService.getAccountSecrets(activeAccountData); expect(result.account).toEqual({ ...activeAccountData, ...account }); }); it('recognizes mnemonic wallets', async () => { const secrets = mockMnemonicWallet(); - const result = await secretsService.getAccountSecrets( - activeAccountData - ); - // eslint-disable-next-line @typescript-eslint/no-unused-vars + const result = + await secretsService.getAccountSecrets(activeAccountData); + const { ...rest } = secrets.wallets[0]; expect(result).toEqual({ account: { ...account, ...activeAccountData }, @@ -553,11 +551,9 @@ describe('src/background/services/secrets/SecretsService.ts', () => { it('recognizes Ledger + BIP44 wallets', async () => { const secrets = mockLedgerWallet(); - const result = await secretsService.getAccountSecrets( - activeAccountData - ); + const result = + await secretsService.getAccountSecrets(activeAccountData); - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { ...rest } = secrets.wallets[0]; expect(result).toEqual({ account: { ...account, ...activeAccountData }, @@ -570,11 +566,9 @@ describe('src/background/services/secrets/SecretsService.ts', () => { it('recognizes Ledger + LedgerLive wallets', async () => { const secrets = mockLedgerLiveWallet(); - const result = await secretsService.getAccountSecrets( - activeAccountData - ); + const result = + await secretsService.getAccountSecrets(activeAccountData); - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { ...rest } = secrets.wallets[0]; expect(result).toEqual({ account: { ...account, ...activeAccountData }, @@ -586,11 +580,9 @@ describe('src/background/services/secrets/SecretsService.ts', () => { it('recognizes Keystone wallets', async () => { const secrets = mockKeystoneWallet(); - const result = await secretsService.getAccountSecrets( - activeAccountData - ); + const result = + await secretsService.getAccountSecrets(activeAccountData); - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { ...rest } = secrets.wallets[0]; expect(result).toEqual({ account: { ...account, ...activeAccountData }, @@ -662,7 +654,6 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }, }); - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { secretType, ...rest } = wcData; expect(await secretsService.getImportedAccountSecrets('wc1')).toEqual({ ...rest, @@ -685,7 +676,6 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }, }); - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { secretType, ...rest } = fbData; expect(await secretsService.getImportedAccountSecrets('fb1')).toEqual({ ...rest, @@ -721,6 +711,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { await secretsService.saveImportedWallet('pkAcc', pkAcc); + // eslint-disable-next-line @typescript-eslint/no-unused-expressions secrets; expect(storageService.save).toHaveBeenCalledWith(WALLET_STORAGE_KEY, { @@ -770,7 +761,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { it('removes specified wallet data from storage', async () => { const result = await secretsService.deleteImportedWallets( ['pkAcc', 'fbAcc'], - walletConnectService + walletConnectService, ); expect(result).toEqual({ @@ -900,7 +891,6 @@ describe('src/background/services/secrets/SecretsService.ts', () => { ...account, }); - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { secretType, ...rest } = secrets; expect(result).toEqual({ ...rest, @@ -925,7 +915,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { mockMnemonicWallet(); await expect( - secretsService.getBtcWalletPolicyDetails(activeAccountData) + secretsService.getBtcWalletPolicyDetails(activeAccountData), ).resolves.toBeUndefined(); }); @@ -945,7 +935,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { type: AccountType.PRIMARY, index: 1, walletId: ACTIVE_WALLET_ID, - }) + }), ).resolves.toEqual({ accountIndex: 1, details: btcWalletPolicyDetails, @@ -958,7 +948,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }); await expect( - secretsService.getBtcWalletPolicyDetails(activeAccountData) + secretsService.getBtcWalletPolicyDetails(activeAccountData), ).resolves.toEqual({ accountIndex: 0, details: btcWalletPolicyDetails, @@ -971,22 +961,22 @@ describe('src/background/services/secrets/SecretsService.ts', () => { mockMnemonicWallet(); expect( - await secretsService.isKnownSecret(SecretType.Mnemonic, 'mnemonic') + await secretsService.isKnownSecret(SecretType.Mnemonic, 'mnemonic'), ).toBe(true); expect( - await secretsService.isKnownSecret(SecretType.Mnemonic, 'cinomenm') + await secretsService.isKnownSecret(SecretType.Mnemonic, 'cinomenm'), ).toBe(false); }); it('returns true when Ledger is already stored', async () => { mockLedgerWallet(); expect( - await secretsService.isKnownSecret(SecretType.Ledger, 'xpub') + await secretsService.isKnownSecret(SecretType.Ledger, 'xpub'), ).toBe(true); expect( - await secretsService.isKnownSecret(SecretType.Ledger, 'newxpub') + await secretsService.isKnownSecret(SecretType.Ledger, 'newxpub'), ).toBe(false); }); it('returns true when Ledger Live is already stored', async () => { @@ -995,20 +985,20 @@ describe('src/background/services/secrets/SecretsService.ts', () => { expect( await secretsService.isKnownSecret(SecretType.LedgerLive, [ { evm: 'evm', xp: 'xp' }, - ]) + ]), ).toBe(true); expect( await secretsService.isKnownSecret(SecretType.LedgerLive, [ { evm: 'evm', xp: 'xp' }, { evm: 'new evm', xp: 'new xp' }, - ]) + ]), ).toBe(true); expect( await secretsService.isKnownSecret(SecretType.LedgerLive, [ { evm: 'new evm', xp: 'new xp' }, - ]) + ]), ).toBe(false); }); }); @@ -1028,20 +1018,20 @@ describe('src/background/services/secrets/SecretsService.ts', () => { hmacHex, name, ACTIVE_WALLET_ID, - activeAccountData + activeAccountData, ); it('throws if wallet type is not Ledger', async () => { mockMnemonicWallet(); await expect(storeBtcWalletPolicyDetails()).rejects.toThrow( - 'Error while saving wallet policy details: incorrect wallet type.' + 'Error while saving wallet policy details: incorrect wallet type.', ); }); it('throws if storage is empty', async () => { await expect(storeBtcWalletPolicyDetails()).rejects.toThrow( - 'Wallet is not initialized' + 'Wallet is not initialized', ); }); @@ -1052,7 +1042,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }); await expect(storeBtcWalletPolicyDetails()).rejects.toThrow( - 'Error while saving wallet policy details: missing record for the provided index.' + 'Error while saving wallet policy details: missing record for the provided index.', ); }); @@ -1066,7 +1056,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }); await expect(storeBtcWalletPolicyDetails()).rejects.toThrow( - 'Error while saving wallet policy details: policy details already stored.' + 'Error while saving wallet policy details: policy details already stored.', ); }); @@ -1112,7 +1102,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }); await expect(storeBtcWalletPolicyDetails()).rejects.toThrow( - 'Error while saving wallet policy details: policy details already stored.' + 'Error while saving wallet policy details: policy details already stored.', ); }); @@ -1171,7 +1161,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { expect(getAddressesSpy).toHaveBeenCalledWith( 1, ACTIVE_WALLET_ID, - networkService + networkService, ); expect(result).toStrictEqual(addressesMock); }); @@ -1191,7 +1181,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { walletId: ACTIVE_WALLET_ID, ledgerService, networkService, - }) + }), ).rejects.toThrow('Ledger transport not available'); }); @@ -1206,7 +1196,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { .mockReturnValue(transportMock); (getPubKeyFromTransport as jest.Mock).mockReturnValueOnce( - Buffer.from('') + Buffer.from(''), ); await expect( @@ -1215,12 +1205,12 @@ describe('src/background/services/secrets/SecretsService.ts', () => { walletId: ACTIVE_WALLET_ID, ledgerService, networkService, - }) + }), ).rejects.toThrow('Failed to get public key from device.'); expect(getPubKeyFromTransport).toHaveBeenCalledWith( transportMock, 1, - DerivationPath.LedgerLive + DerivationPath.LedgerLive, ); }); @@ -1243,12 +1233,12 @@ describe('src/background/services/secrets/SecretsService.ts', () => { walletId: ACTIVE_WALLET_ID, ledgerService, networkService, - }) + }), ).rejects.toThrow('Failed to get public key from device.'); expect(getPubKeyFromTransport).toHaveBeenCalledWith( transportMock, 1, - DerivationPath.LedgerLive + DerivationPath.LedgerLive, ); }); @@ -1274,7 +1264,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { expect(getAddressesSpy).toHaveBeenCalledWith( 0, ACTIVE_WALLET_ID, - networkService + networkService, ); secretsService.updateSecrets = jest.fn(); expect(getPubKeyFromTransport).not.toHaveBeenCalled(); @@ -1307,7 +1297,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { expect(getAddressesSpy).toHaveBeenCalledWith( 0, ACTIVE_WALLET_ID, - networkService + networkService, ); expect(result).toStrictEqual(addressesMock); @@ -1320,7 +1310,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { }, ], }, - ACTIVE_WALLET_ID + ACTIVE_WALLET_ID, ); }); }); @@ -1367,12 +1357,12 @@ describe('src/background/services/secrets/SecretsService.ts', () => { { pubKeys: newKeys, }, - ACTIVE_WALLET_ID + ACTIVE_WALLET_ID, ); expect(getAddressesSpy).toHaveBeenCalledWith( 1, ACTIVE_WALLET_ID, - networkService + networkService, ); expect(result).toStrictEqual(addressesMock); }); @@ -1410,7 +1400,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { expect(getAddressesSpy).toHaveBeenCalledWith( 1, ACTIVE_WALLET_ID, - networkService + networkService, ); expect(result).toStrictEqual(addressesMock); }); @@ -1429,17 +1419,17 @@ describe('src/background/services/secrets/SecretsService.ts', () => { it('throws error if walletId is not provided', async () => { await expect( - secretsService.getAddresses(0, '', networkService) + secretsService.getAddresses(0, '', networkService), ).rejects.toThrow('Wallet id not provided'); }); it('throws if storage is empty', async () => { mockMnemonicWallet( {}, - { secretType: 'unknown', id: 'seedless-wallet-id' } + { secretType: 'unknown', id: 'seedless-wallet-id' }, ); await expect( - secretsService.getAddresses(0, 'seedless-wallet-id', networkService) + secretsService.getAddresses(0, 'seedless-wallet-id', networkService), ).rejects.toThrow('No public key available'); }); @@ -1448,14 +1438,14 @@ describe('src/background/services/secrets/SecretsService.ts', () => { (getAddressFromXPub as jest.Mock).mockReturnValueOnce('0x1'); (getBech32AddressFromXPub as jest.Mock).mockReturnValueOnce('0x2'); await expect( - secretsService.getAddresses(0, ACTIVE_WALLET_ID, networkService) + secretsService.getAddresses(0, ACTIVE_WALLET_ID, networkService), ).resolves.toStrictEqual(addressesMock('0x1', '0x2')); expect(Avalanche.getAddressPublicKeyFromXpub).toBeCalledWith('xpubXP', 0); expect(getAddressFromXPub).toHaveBeenCalledWith('xpub', 0); expect(getBech32AddressFromXPub).toHaveBeenCalledWith( 'xpub', 0, - networks.testnet + networks.testnet, ); }); @@ -1466,7 +1456,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { (networkService.isMainnet as jest.Mock).mockReturnValueOnce(false); await expect( - secretsService.getAddresses(0, ACTIVE_WALLET_ID, networkService) + secretsService.getAddresses(0, ACTIVE_WALLET_ID, networkService), ).rejects.toThrow('Account not added'); }); @@ -1480,28 +1470,28 @@ describe('src/background/services/secrets/SecretsService.ts', () => { (getBtcAddressFromPubKey as jest.Mock).mockReturnValueOnce('0x2'); await expect( - secretsService.getAddresses(0, ACTIVE_WALLET_ID, networkService) + secretsService.getAddresses(0, ACTIVE_WALLET_ID, networkService), ).resolves.toStrictEqual(addressesMock('0x1', '0x2')); expect(getEvmAddressFromPubKey).toHaveBeenCalledWith(pubKeyBuff); expect(getBtcAddressFromPubKey).toHaveBeenCalledWith( pubKeyBuff, - networks.testnet + networks.testnet, ); expect(getAddressMock).toHaveBeenNthCalledWith( 1, expect.any(Buffer), - 'X' + 'X', ); expect(getAddressMock).toHaveBeenNthCalledWith( 2, expect.any(Buffer), - 'P' + 'P', ); expect(getAddressMock).toHaveBeenNthCalledWith( 3, expect.any(Buffer), - 'C' + 'C', ); }); }); @@ -1530,7 +1520,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { importType: ImportType.PRIVATE_KEY, data: 'privateKey', }, - networkService + networkService, ); expect(result).toStrictEqual({ @@ -1569,8 +1559,8 @@ describe('src/background/services/secrets/SecretsService.ts', () => { importType: ImportType.PRIVATE_KEY, data: 'privateKey', }, - networkService - ) + networkService, + ), ).rejects.toThrow('Error while calculating addresses'); }); @@ -1589,8 +1579,8 @@ describe('src/background/services/secrets/SecretsService.ts', () => { importType: ImportType.PRIVATE_KEY, data: 'privateKey', }, - networkService - ) + networkService, + ), ).rejects.toThrow('Error while calculating addresses'); }); @@ -1609,8 +1599,8 @@ describe('src/background/services/secrets/SecretsService.ts', () => { importType: ImportType.PRIVATE_KEY, data: 'privateKey', }, - networkService - ) + networkService, + ), ).rejects.toThrow('Error while calculating addresses'); }); }); @@ -1628,22 +1618,22 @@ describe('src/background/services/secrets/SecretsService.ts', () => { it('throws if imported account is missing from storage', async () => { secretsService.getImportedAccountSecrets = jest.fn(); (secretsService.getImportedAccountSecrets as jest.Mock).mockRejectedValue( - new Error('No secrets found for imported account') + new Error('No secrets found for imported account'), ); await expect( - secretsService.getImportedAddresses('id', networkService) + secretsService.getImportedAddresses('id', networkService), ).rejects.toThrow('No secrets found for imported account'); }); it('throws if importType is not supported', async () => { secretsService.getImportedAccountSecrets = jest.fn(); (secretsService.getImportedAccountSecrets as jest.Mock).mockResolvedValue( - { secretType: 'unknown' as any, secret: 'secret' } + { secretType: 'unknown' as any, secret: 'secret' }, ); await expect( - secretsService.getImportedAddresses('id', networkService) + secretsService.getImportedAddresses('id', networkService), ).rejects.toThrow('Unsupported import type'); }); @@ -1651,13 +1641,13 @@ describe('src/background/services/secrets/SecretsService.ts', () => { (networkService.isMainnet as jest.Mock).mockReturnValue(false); secretsService.getImportedAccountSecrets = jest.fn(); (secretsService.getImportedAccountSecrets as jest.Mock).mockResolvedValue( - { secretType: SecretType.PrivateKey, secret: 'secret' } + { secretType: SecretType.PrivateKey, secret: 'secret' }, ); (getEvmAddressFromPubKey as jest.Mock).mockReturnValueOnce(''); (getBtcAddressFromPubKey as jest.Mock).mockReturnValueOnce(''); await expect( - secretsService.getImportedAddresses('id', networkService) + secretsService.getImportedAddresses('id', networkService), ).rejects.toThrow('Missing address'); }); @@ -1665,12 +1655,12 @@ describe('src/background/services/secrets/SecretsService.ts', () => { (networkService.isMainnet as jest.Mock).mockReturnValue(false); secretsService.getImportedAccountSecrets = jest.fn(); (secretsService.getImportedAccountSecrets as jest.Mock).mockResolvedValue( - { secretType: SecretType.PrivateKey, secret: 'secret' } + { secretType: SecretType.PrivateKey, secret: 'secret' }, ); const result = await secretsService.getImportedAddresses( 'id', - networkService + networkService, ); expect(result).toStrictEqual({ @@ -1685,22 +1675,22 @@ describe('src/background/services/secrets/SecretsService.ts', () => { expect(getEvmAddressFromPubKey).toHaveBeenCalledWith(pubKeyBuffer); expect(getBtcAddressFromPubKey).toHaveBeenCalledWith( pubKeyBuffer, - networks.testnet + networks.testnet, ); expect(getAddressMock).toHaveBeenNthCalledWith( 1, expect.any(Buffer), - 'X' + 'X', ); expect(getAddressMock).toHaveBeenNthCalledWith( 2, expect.any(Buffer), - 'P' + 'P', ); expect(getAddressMock).toHaveBeenNthCalledWith( 3, expect.any(Buffer), - 'C' + 'C', ); }); }); @@ -1726,7 +1716,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { const result = await secretsService.deleteImportedWallets( ['id2', 'id3'], - walletConnectService + walletConnectService, ); expect(result).toEqual({ @@ -1757,7 +1747,7 @@ describe('src/background/services/secrets/SecretsService.ts', () => { mockMnemonicWallet(); await secretsService.getWalletType(ACTIVE_WALLET_ID); expect(secretsService.getWalletAccountsSecretsById).toHaveBeenCalledWith( - ACTIVE_WALLET_ID + ACTIVE_WALLET_ID, ); }); }); diff --git a/src/background/services/secrets/SecretsService.ts b/src/background/services/secrets/SecretsService.ts index e43fce557..98d49ffb3 100644 --- a/src/background/services/secrets/SecretsService.ts +++ b/src/background/services/secrets/SecretsService.ts @@ -100,7 +100,7 @@ export class SecretsService implements OnUnlock { { ...storedSecrets, wallets, - } + }, ); await this.emitWalletsInfo(); @@ -139,7 +139,7 @@ export class SecretsService implements OnUnlock { async updateSecrets( secrets: Partial, - walletId: string + walletId: string, ): Promise { const storedSecrets = await this.#loadSecrets(false); @@ -159,7 +159,7 @@ export class SecretsService implements OnUnlock { { ...storedSecrets, wallets: [...updatedWalletSecrets] as PrimaryWalletSecrets[], - } + }, ); await this.emitWalletsInfo(); return walletId; @@ -172,7 +172,7 @@ export class SecretsService implements OnUnlock { const storedSecrets = await this.#loadSecrets(false); const updatedWalletSecrets = storedSecrets?.wallets.filter( - (wallet) => wallet.id !== walletId + (wallet) => wallet.id !== walletId, ); const updatedImportedSecrets = storedSecrets?.importedAccounts; @@ -185,7 +185,7 @@ export class SecretsService implements OnUnlock { { ...updatedImportedSecrets, wallets: [...updatedWalletSecrets], - } + }, ); } await this.emitWalletsInfo(); @@ -193,7 +193,7 @@ export class SecretsService implements OnUnlock { getWalletSecretsForAcount( walletKeys: WalletSecretInStorage, - account: Account + account: Account, ) { const activeWalletId = isPrimaryAccount(account) ? account.walletId @@ -213,7 +213,7 @@ export class SecretsService implements OnUnlock { } const activeWalletSecrets = this.getWalletSecretsForAcount( walletKeys, - activeAccount + activeAccount, ); if (!activeWalletSecrets) { @@ -224,7 +224,7 @@ export class SecretsService implements OnUnlock { } async getImportedAccountSecrets( - accountId: string + accountId: string, ): Promise { const walletKeys = await this.#loadSecrets(true); @@ -267,7 +267,7 @@ export class SecretsService implements OnUnlock { if (account.type === AccountType.PRIMARY) { const activeWalletSecrets = this.getWalletSecretsForAcount( walletKeys, - account + account, ); if (!activeWalletSecrets) { @@ -292,7 +292,7 @@ export class SecretsService implements OnUnlock { const walletKeys = await this.#loadSecrets(true); const walletSecrets = walletKeys.wallets.find( - (wallet) => wallet.id === walletId + (wallet) => wallet.id === walletId, ); if (!walletSecrets) { @@ -307,11 +307,10 @@ export class SecretsService implements OnUnlock { async deleteImportedWallets( ids: string[], - walletConnectService: WalletConnectService + walletConnectService: WalletConnectService, ): Promise> { - const { importedAccounts, ...primarySecrets } = await this.#loadSecrets( - true - ); + const { importedAccounts, ...primarySecrets } = + await this.#loadSecrets(true); const deleted = pick(importedAccounts, ids); const newImported = omit(importedAccounts, ids); @@ -365,7 +364,7 @@ export class SecretsService implements OnUnlock { hmacHex: string, name: string, walletId: string, - activeAccount: Account + activeAccount: Account, ) { const secrets = await this.getAccountSecrets(activeAccount); @@ -374,7 +373,7 @@ export class SecretsService implements OnUnlock { secrets.secretType !== SecretType.LedgerLive ) { throw new Error( - 'Error while saving wallet policy details: incorrect wallet type.' + 'Error while saving wallet policy details: incorrect wallet type.', ); } @@ -386,13 +385,13 @@ export class SecretsService implements OnUnlock { if (!pubKeyInfo) { throw new Error( - 'Error while saving wallet policy details: missing record for the provided index.' + 'Error while saving wallet policy details: missing record for the provided index.', ); } if (pubKeyInfo?.btcWalletPolicyDetails) { throw new Error( - 'Error while saving wallet policy details: policy details already stored.' + 'Error while saving wallet policy details: policy details already stored.', ); } @@ -409,14 +408,14 @@ export class SecretsService implements OnUnlock { { pubKeys, }, - walletId + walletId, ); } if (secrets.secretType === SecretType.Ledger) { if (secrets?.btcWalletPolicyDetails) { throw new Error( - 'Error while saving wallet policy details: policy details already stored.' + 'Error while saving wallet policy details: policy details already stored.', ); } @@ -429,17 +428,17 @@ export class SecretsService implements OnUnlock { name, }, }, - walletId + walletId, ); } throw new Error( - 'Error while saving wallet policy details: unknown derivation path.' + 'Error while saving wallet policy details: unknown derivation path.', ); } async getBtcWalletPolicyDetails( - account: Account + account: Account, ): Promise< { accountIndex: number; details?: BtcWalletPolicyDetails } | undefined > { @@ -473,9 +472,8 @@ export class SecretsService implements OnUnlock { async #loadSecrets(strict: true): Promise; async #loadSecrets(strict: false): Promise; async #loadSecrets(strict: boolean): Promise { - const walletKeys = await this.storageService.load( - WALLET_STORAGE_KEY - ); + const walletKeys = + await this.storageService.load(WALLET_STORAGE_KEY); if (!walletKeys && strict) { throw new Error('Wallet is not initialized'); @@ -486,15 +484,15 @@ export class SecretsService implements OnUnlock { async isKnownSecret( type: SecretType.Mnemonic, - mnemonic: string + mnemonic: string, ): Promise; async isKnownSecret( type: SecretType.PrivateKey, - privateKey: string + privateKey: string, ): Promise; async isKnownSecret( type: SecretType.LedgerLive | SecretType.Ledger, - pub: string | PubKeyType[] + pub: string | PubKeyType[], ): Promise; async isKnownSecret( type: @@ -502,7 +500,7 @@ export class SecretsService implements OnUnlock { | SecretType.PrivateKey | SecretType.Ledger | SecretType.LedgerLive, - secret: unknown + secret: unknown, ): Promise { const secrets = await this.#loadSecrets(false); @@ -514,7 +512,7 @@ export class SecretsService implements OnUnlock { return secrets.wallets.some( (wallet) => wallet.secretType === SecretType.Mnemonic && - wallet.mnemonic === secret + wallet.mnemonic === secret, ); } @@ -525,14 +523,14 @@ export class SecretsService implements OnUnlock { return Object.values(secrets.importedAccounts).some( (acc) => - acc.secretType === SecretType.PrivateKey && acc.secret === secret + acc.secretType === SecretType.PrivateKey && acc.secret === secret, ); } if (type === SecretType.Ledger) { return secrets.wallets.some( (wallet) => - wallet.secretType === SecretType.Ledger && wallet.xpub === secret + wallet.secretType === SecretType.Ledger && wallet.xpub === secret, ); } @@ -556,7 +554,7 @@ export class SecretsService implements OnUnlock { async addImportedWallet( importData: ImportData, - networkService: NetworkService + networkService: NetworkService, ) { const id = crypto.randomUUID(); @@ -601,7 +599,7 @@ export class SecretsService implements OnUnlock { if (importData.importType === ImportType.PRIVATE_KEY) { const addresses = await this.#calculateAddressesForPrivateKey( importData.data, - networkService + networkService, ); return { account: { @@ -617,7 +615,7 @@ export class SecretsService implements OnUnlock { async #calculateAddressesForPrivateKey( privateKey: string, - networkService: NetworkService + networkService: NetworkService, ) { const addresses = { addressBTC: '', @@ -634,12 +632,12 @@ export class SecretsService implements OnUnlock { addresses.addressC = getEvmAddressFromPubKey(publicKey); addresses.addressBTC = getBtcAddressFromPubKey( publicKey, - networkService.isMainnet() ? networks.bitcoin : networks.testnet + networkService.isMainnet() ? networks.bitcoin : networks.testnet, ); addresses.addressAVM = provXP.getAddress(publicKey, 'X'); addresses.addressPVM = provXP.getAddress(publicKey, 'P'); addresses.addressCoreEth = provXP.getAddress(publicKey, 'C'); - } catch (err) { + } catch (_err) { throw new Error('Error while calculating addresses'); } @@ -683,7 +681,7 @@ export class SecretsService implements OnUnlock { const addressPublicKeyC = await getPubKeyFromTransport( ledgerService.recentTransport, index, - secrets.derivationPath + secrets.derivationPath, ); // Get X/P public key from transport @@ -691,7 +689,7 @@ export class SecretsService implements OnUnlock { ledgerService.recentTransport, index, secrets.derivationPath, - 'AVM' + 'AVM', ); if ( @@ -713,7 +711,7 @@ export class SecretsService implements OnUnlock { { pubKeys, }, - walletId + walletId, ); } @@ -731,7 +729,7 @@ export class SecretsService implements OnUnlock { { pubKeys: await wallet.getPublicKeys(), }, - walletId + walletId, ); } @@ -741,7 +739,7 @@ export class SecretsService implements OnUnlock { async getAddresses( index: number, walletId: string, - networkService: NetworkService + networkService: NetworkService, ): Promise | never> { if (!walletId) { throw new Error('Wallet id not provided'); @@ -771,7 +769,7 @@ export class SecretsService implements OnUnlock { // X and P addresses different derivation path m/44'/9000'/0'... const xpPub = Avalanche.getAddressPublicKeyFromXpub( secrets.xpubXP, - index + index, ); xAddr = providerXP.getAddress(xpPub, 'X'); pAddr = providerXP.getAddress(xpPub, 'P'); @@ -782,7 +780,7 @@ export class SecretsService implements OnUnlock { [NetworkVMType.BITCOIN]: getBech32AddressFromXPub( secrets.xpub, index, - isMainnet ? networks.bitcoin : networks.testnet + isMainnet ? networks.bitcoin : networks.testnet, ), [NetworkVMType.AVM]: xAddr, [NetworkVMType.PVM]: pAddr, @@ -816,7 +814,7 @@ export class SecretsService implements OnUnlock { [NetworkVMType.EVM]: getEvmAddressFromPubKey(pubKeyBuffer), [NetworkVMType.BITCOIN]: getBtcAddressFromPubKey( pubKeyBuffer, - isMainnet ? networks.bitcoin : networks.testnet + isMainnet ? networks.bitcoin : networks.testnet, ), [NetworkVMType.AVM]: addrX, [NetworkVMType.PVM]: addrP, @@ -840,7 +838,7 @@ export class SecretsService implements OnUnlock { if (secrets.secretType === SecretType.PrivateKey) { return this.#calculateAddressesForPrivateKey( secrets.secret, - networkService + networkService, ); } diff --git a/src/background/services/secrets/events/WalletUpdatedEvent.ts b/src/background/services/secrets/events/WalletUpdatedEvent.ts index 63c5f45ee..55b2a9f23 100644 --- a/src/background/services/secrets/events/WalletUpdatedEvent.ts +++ b/src/background/services/secrets/events/WalletUpdatedEvent.ts @@ -18,7 +18,7 @@ export class WalletUpdatedEvents implements ExtensionEventEmitter { name: WalletEvents.WALLET_STATE_UPDATE, value: wallet, }); - } + }, ); } @@ -27,7 +27,7 @@ export class WalletUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/secrets/events/WalletUpdatedEventListener.ts b/src/background/services/secrets/events/WalletUpdatedEventListener.ts index b0fb71939..dbb91c807 100644 --- a/src/background/services/secrets/events/WalletUpdatedEventListener.ts +++ b/src/background/services/secrets/events/WalletUpdatedEventListener.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { WalletDetails, WalletEvents } from '../../wallet/models'; export function walletStateChangedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === WalletEvents.WALLET_STATE_UPDATE; } diff --git a/src/background/services/secrets/handlers/avalanche_renameWallet.test.ts b/src/background/services/secrets/handlers/avalanche_renameWallet.test.ts index 15e6a8383..7505fb889 100644 --- a/src/background/services/secrets/handlers/avalanche_renameWallet.test.ts +++ b/src/background/services/secrets/handlers/avalanche_renameWallet.test.ts @@ -51,7 +51,7 @@ describe('src/background/services/accounts/handlers/avalanche_renameWallet', () displayData: { newName: 'Change Name', walletId: 'wallet-id' }, method: 'avalanche_renameWallet', }), - 'renameWallet' + 'renameWallet', ); expect(secretsService.updateSecrets).not.toHaveBeenCalled(); }); @@ -134,7 +134,7 @@ describe('src/background/services/accounts/handlers/avalanche_renameWallet', () expect.objectContaining({ name: 'Change Name', }), - 'wallet-id' + 'wallet-id', ); expect(result).toEqual({ ...request, result: null }); }); diff --git a/src/background/services/secrets/handlers/avalanche_renameWallet.ts b/src/background/services/secrets/handlers/avalanche_renameWallet.ts index 31e780bb2..9fbdc61d1 100644 --- a/src/background/services/secrets/handlers/avalanche_renameWallet.ts +++ b/src/background/services/secrets/handlers/avalanche_renameWallet.ts @@ -27,7 +27,7 @@ export class AvalancheRenameWalletHandler extends DAppRequestHandler< } handleAuthenticated = async ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ) => { const { request, scope } = rpcCall; const [walletId, newName] = request.params; @@ -50,9 +50,8 @@ export class AvalancheRenameWalletHandler extends DAppRequestHandler< }; } - const wallet = await this.secretsService.getWalletAccountsSecretsById( - walletId - ); + const wallet = + await this.secretsService.getWalletAccountsSecretsById(walletId); if (!wallet) { return { @@ -65,20 +64,20 @@ export class AvalancheRenameWalletHandler extends DAppRequestHandler< const canSkip = await canSkipApproval( request.site.domain, - request.site.tabId + request.site.tabId, ); if (canSkip) { try { await this.secretsService.updateSecrets( { ...wallet, name: newName }, - walletId + walletId, ); return { ...request, result: null, }; - } catch (err) { + } catch (_err) { return { ...request, error: ethErrors.rpc.internal('Wallet renaming failed'), @@ -119,18 +118,17 @@ export class AvalancheRenameWalletHandler extends DAppRequestHandler< pendingAction: Action<{ walletId: string; newName: string }>, _, onSuccess, - onError + onError, ) => { try { const { walletId, newName } = pendingAction.displayData; - const wallet = await this.secretsService.getWalletAccountsSecretsById( - walletId - ); + const wallet = + await this.secretsService.getWalletAccountsSecretsById(walletId); await this.secretsService.updateSecrets( { ...wallet, name: newName }, - walletId + walletId, ); onSuccess(null); diff --git a/src/background/services/seedless/SeedlessBtcSigner.test.ts b/src/background/services/seedless/SeedlessBtcSigner.test.ts index 418c11e4f..69d2ea2a4 100644 --- a/src/background/services/seedless/SeedlessBtcSigner.test.ts +++ b/src/background/services/seedless/SeedlessBtcSigner.test.ts @@ -17,8 +17,8 @@ describe('src/background/services/seedless/SeedlessWallet', () => { 0, [], networks.bitcoin, - {} as any - ) + {} as any, + ), ).toThrow('Invalid public key'); expect( @@ -29,8 +29,8 @@ describe('src/background/services/seedless/SeedlessWallet', () => { 0, [], networks.bitcoin, - {} as any - ) + {} as any, + ), ).not.toThrow(); }); @@ -43,13 +43,13 @@ describe('src/background/services/seedless/SeedlessWallet', () => { 0, [], networks.bitcoin, - {} as any + {} as any, ); expect(signer.address).toEqual('my-btc-address'); expect(getBtcAddressFromPubKey).toHaveBeenCalledWith( Buffer.from(evmKey.publicKey, 'hex'), - networks.bitcoin + networks.bitcoin, ); }); @@ -62,7 +62,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { 0, [], networks.bitcoin, - {} as any + {} as any, ); const pubKey = Buffer.from(strip0x(evmKey.publicKey), 'hex'); @@ -136,7 +136,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { 0, psbt.txInputs, networks.bitcoin, - session + session, ); }); @@ -169,7 +169,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(session.signBtc).toHaveBeenCalledWith( signer.address, - getExpectedSignPayload(0) + getExpectedSignPayload(0), ); const nextInputSigner = new SeedlessBtcSigner( @@ -178,14 +178,14 @@ describe('src/background/services/seedless/SeedlessWallet', () => { 1, psbt.txInputs, networks.bitcoin, - session + session, ); await nextInputSigner.sign(); expect(session.signBtc).toHaveBeenCalledWith( nextInputSigner.address, - getExpectedSignPayload(1) + getExpectedSignPayload(1), ); }); @@ -197,7 +197,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { }); await expect(signer.sign()).rejects.toThrow( - /Unexpected signature length/ + /Unexpected signature length/, ); }); @@ -210,7 +210,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { }); expect(await signer.sign()).toEqual( - Buffer.from(strip0x(mockedSignature), 'hex').subarray(0, 64) + Buffer.from(strip0x(mockedSignature), 'hex').subarray(0, 64), ); }); }); diff --git a/src/background/services/seedless/SeedlessBtcSigner.ts b/src/background/services/seedless/SeedlessBtcSigner.ts index 5c3986545..7874eb3b7 100644 --- a/src/background/services/seedless/SeedlessBtcSigner.ts +++ b/src/background/services/seedless/SeedlessBtcSigner.ts @@ -29,7 +29,7 @@ export class SeedlessBtcSigner implements SignerAsync { get address() { return getBtcAddressFromPubKey( Buffer.from(this.#fromKey, 'hex'), - this.network + this.network, ); } @@ -48,7 +48,7 @@ export class SeedlessBtcSigner implements SignerAsync { inputIndex: number, utxos: BitcoinInputUTXO[], network: Network, - signerSession: SignerSession + signerSession: SignerSession, ) { this.#fromKey = fromKey; this.#psbt = psbt; diff --git a/src/background/services/seedless/SeedlessMfaService.test.ts b/src/background/services/seedless/SeedlessMfaService.test.ts index 63b9ed32e..fe4b25bf7 100644 --- a/src/background/services/seedless/SeedlessMfaService.test.ts +++ b/src/background/services/seedless/SeedlessMfaService.test.ts @@ -159,7 +159,7 @@ describe('src/background/services/seedless/SeedlessMfaService.ts', () => { mfaId: 'abcd', type: MfaRequestType.Totp, tabId: 123, - }) + }), ); expect(service.emitMfaError).toHaveBeenCalledWith('abcd', 123); @@ -169,7 +169,7 @@ describe('src/background/services/seedless/SeedlessMfaService.ts', () => { mfaId: 'abcd', type: MfaRequestType.Totp, tabId: 123, - }) + }), ); }); }); @@ -221,7 +221,7 @@ describe('src/background/services/seedless/SeedlessMfaService.ts', () => { it('fails', async () => { await expect(service.initAuthenticatorChange()).rejects.toThrow( - 'Invalid session data' + 'Invalid session data', ); }); }); @@ -291,7 +291,7 @@ describe('src/background/services/seedless/SeedlessMfaService.ts', () => { it('fails', async () => { await expect( - service.completeAuthenticatorChange('totpId', '123456') + service.completeAuthenticatorChange('totpId', '123456'), ).rejects.toThrow('Invalid session data'); }); }); @@ -303,7 +303,7 @@ describe('src/background/services/seedless/SeedlessMfaService.ts', () => { expect(session.resetTotpComplete).toHaveBeenCalledWith( 'totpId', - '123456' + '123456', ); }); @@ -530,7 +530,7 @@ describe('src/background/services/seedless/SeedlessMfaService.ts', () => { expect.objectContaining({ mfaId: 'mfa-id', mfaConf: fidoAnswer.receipt.confirmation, - }) + }), ); }); }); diff --git a/src/background/services/seedless/SeedlessMfaService.ts b/src/background/services/seedless/SeedlessMfaService.ts index d3e48a6d2..5f2fa8171 100644 --- a/src/background/services/seedless/SeedlessMfaService.ts +++ b/src/background/services/seedless/SeedlessMfaService.ts @@ -61,7 +61,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { this.#challengeSubscription = this.#challengeRequest$.subscribe( (request) => { this.#eventEmitter.emit(SeedlessEvents.MfaRequest, request); - } + }, ); this.#choiceSubscription = this.#choiceRequest$.subscribe((request) => { @@ -75,7 +75,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { } async askForMfaMethod( - mfaChoiceRequest: PartialBy + mfaChoiceRequest: PartialBy, ): Promise { const methods = mfaChoiceRequest.availableMethods ?? (await this.getRecoveryMethods()); @@ -93,8 +93,8 @@ export class SeedlessMfaService implements OnUnlock, OnLock { return firstValueFrom( this.#choiceResponse$.pipe( filter((response) => response.mfaId === mfaChoiceRequest.mfaId), - map((response: MfaChoiceResponse) => response.chosenMethod) - ) + map((response: MfaChoiceResponse) => response.chosenMethod), + ), ); } @@ -144,7 +144,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { const mfaResponse = await this.approveWithMfa( method?.type === 'totp' ? MfaRequestType.Totp : MfaRequestType.Fido, addFidoRequest, - tabId + tabId, ); addFidoChallenge = mfaResponse.data(); @@ -182,7 +182,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { const result = await this.approveWithMfa( method?.type === 'totp' ? MfaRequestType.Totp : MfaRequestType.Fido, response, - tabId + tabId, ); const data = result.data(); @@ -246,7 +246,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { async #emitMfaMethods() { this.#eventEmitter.emit( SeedlessEvents.MfaMethodsUpdated, - await this.getRecoveryMethods() + await this.getRecoveryMethods(), ); } @@ -270,7 +270,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { async approveWithMfa( type: MfaRequestType, request: CubeSignerResponse, - tabId?: number + tabId?: number, ): Promise> { try { if (type === MfaRequestType.Totp) { @@ -282,7 +282,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { const result = await request.approveTotp( await this.#getSession(), - code + code, ); this.clearMfaChallenge(request.mfaId(), tabId); @@ -334,7 +334,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { async requestMfa(mfaRequest: MfaTotpRequest): Promise; async requestMfa(mfaRequest: MfaFidoRequest): Promise; async requestMfa( - mfaRequest: MfaRequestData + mfaRequest: MfaRequestData, ): Promise { this.#challengeRequest$.next(mfaRequest); @@ -342,8 +342,8 @@ export class SeedlessMfaService implements OnUnlock, OnLock { return firstValueFrom( this.#challengeResponse$.pipe( filter((response) => response.mfaId === mfaRequest.mfaId), - map((response: MfaResponseData) => response.code ?? response.answer) - ) + map((response: MfaResponseData) => response.code ?? response.answer), + ), ); } @@ -366,23 +366,23 @@ export class SeedlessMfaService implements OnUnlock, OnLock { addListener( event: SeedlessEvents.MfaRequest, - callback: (data: MfaRequestData) => void + callback: (data: MfaRequestData) => void, ); addListener( event: SeedlessEvents.MfaFailure, - callback: (data: MfaFailureData) => void + callback: (data: MfaFailureData) => void, ); addListener( event: SeedlessEvents.MfaChoiceRequest, - callback: (data: MfaChoiceRequest) => void + callback: (data: MfaChoiceRequest) => void, ); addListener( event: SeedlessEvents.MfaMethodsUpdated, - callback: (data: RecoveryMethod[]) => void + callback: (data: RecoveryMethod[]) => void, ); addListener( event: SeedlessEvents.MfaClear, - callback: (data: MfaClearData) => void + callback: (data: MfaClearData) => void, ); addListener( event: @@ -391,7 +391,7 @@ export class SeedlessMfaService implements OnUnlock, OnLock { | SeedlessEvents.MfaRequest | SeedlessEvents.MfaChoiceRequest | SeedlessEvents.MfaMethodsUpdated, - callback: (data) => void + callback: (data) => void, ) { this.#eventEmitter.on(event, callback); } diff --git a/src/background/services/seedless/SeedlessSessionManager.test.ts b/src/background/services/seedless/SeedlessSessionManager.test.ts index e4fe73d23..00a8b072e 100644 --- a/src/background/services/seedless/SeedlessSessionManager.test.ts +++ b/src/background/services/seedless/SeedlessSessionManager.test.ts @@ -147,7 +147,7 @@ describe('src/background/services/seedless/SeedlessSessionManager', () => { expect(sentryCaptureException).toHaveBeenCalledWith( error, - SentryExceptionTypes.SEEDLESS + SentryExceptionTypes.SEEDLESS, ); }); }); diff --git a/src/background/services/seedless/SeedlessTokenStorage.ts b/src/background/services/seedless/SeedlessTokenStorage.ts index c061c9c02..730db4443 100644 --- a/src/background/services/seedless/SeedlessTokenStorage.ts +++ b/src/background/services/seedless/SeedlessTokenStorage.ts @@ -12,7 +12,7 @@ export class SeedlessTokenStorage implements SignerSessionStorage { async save(seedlessSignerToken: SignerSessionData): Promise { const secrets = await this.secretsService.loadSecrets(); const seedlessSecrets = secrets.wallets.find( - (wallet) => wallet.secretType === SecretType.Seedless + (wallet) => wallet.secretType === SecretType.Seedless, ); // Prevent writing signer token to a different type of wallet if ( @@ -23,7 +23,7 @@ export class SeedlessTokenStorage implements SignerSessionStorage { } await this.secretsService.updateSecrets( { seedlessSignerToken }, - seedlessSecrets.id + seedlessSecrets.id, ); } @@ -31,7 +31,7 @@ export class SeedlessTokenStorage implements SignerSessionStorage { const secrets = await this.secretsService.loadSecrets(); const seedlessSecrets = secrets.wallets.find( - (wallet) => wallet.secretType === SecretType.Seedless + (wallet) => wallet.secretType === SecretType.Seedless, ); if (!seedlessSecrets || !('seedlessSignerToken' in seedlessSecrets)) { diff --git a/src/background/services/seedless/SeedlessWallet.test.ts b/src/background/services/seedless/SeedlessWallet.test.ts index c1bfcfc4c..4e56ed152 100644 --- a/src/background/services/seedless/SeedlessWallet.test.ts +++ b/src/background/services/seedless/SeedlessWallet.test.ts @@ -52,10 +52,10 @@ jest.mock('@src/utils/network/getProviderForNetwork'); describe('src/background/services/seedless/SeedlessWallet', () => { const sessionStorage = jest.mocked( - new SeedlessTokenStorage({} as any) + new SeedlessTokenStorage({} as any), ); const networkService = jest.mocked( - new NetworkService({} as any, {} as any) + new NetworkService({} as any, {} as any), ); const sessionManager = jest.mocked({ notifyTokenExpired: jest.fn(), @@ -132,7 +132,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.getPublicKeys()).rejects.toThrow( - 'Accounts not created' + 'Accounts not created', ); }); }); @@ -148,7 +148,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.getPublicKeys()).rejects.toThrow( - 'Accounts keys missing' + 'Accounts keys missing', ); }); }); @@ -235,7 +235,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTransaction({} as any)).rejects.toThrow( - 'Public key not available' + 'Public key not available', ); }); }); @@ -253,7 +253,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTransaction({} as any)).rejects.toThrow( - 'Unknown network' + 'Unknown network', ); }); }); @@ -273,7 +273,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTransaction({} as any)).rejects.toThrow( - 'Wrong provider obtained for EVM transaction' + 'Wrong provider obtained for EVM transaction', ); }); }); @@ -320,7 +320,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(signerConstructorSpy).toHaveBeenCalledWith( getEvmAddressFromPubKey(Buffer.from(evmKey.publicKey, 'hex')), expect.anything(), - expect.anything() + expect.anything(), ); }); @@ -345,7 +345,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTransaction({} as any)).rejects.toThrow( - new Error('Some API error') + new Error('Some API error'), ); }); }); @@ -375,7 +375,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signAvalancheTx({} as any)).rejects.toThrow( - 'Public key not available' + 'Public key not available', ); }); }); @@ -420,7 +420,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(session.signBlob).toHaveBeenCalledWith( evmKey.key_id, - expect.anything() + expect.anything(), ); }); @@ -431,7 +431,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect.anything(), expect.objectContaining({ message_base64: 'CLteXW6qwQSe3giT0w7QIrGk2bW0jbQUhx9Rycs1KD0=', - }) + }), ); }); @@ -439,13 +439,13 @@ describe('src/background/services/seedless/SeedlessWallet', () => { await wallet.signAvalancheTx(txRequest as any); expect(txRequest.tx.addSignature).toHaveBeenCalledWith( - utils.hexToBuffer(signature) + utils.hexToBuffer(signature), ); }); it('returns the signed transaction', async () => { expect(await wallet.signAvalancheTx(txRequest as any)).toEqual( - txRequest.tx + txRequest.tx, ); }); }); @@ -494,7 +494,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(session.signBlob).toHaveBeenCalledWith( avaTestKey.key_id, - expect.anything() + expect.anything(), ); }); }); @@ -508,7 +508,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(session.signBlob).toHaveBeenCalledWith( avaKey.key_id, - expect.anything() + expect.anything(), ); }); }); @@ -520,7 +520,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect.anything(), expect.objectContaining({ message_base64: 'CLteXW6qwQSe3giT0w7QIrGk2bW0jbQUhx9Rycs1KD0=', - }) + }), ); }); @@ -528,13 +528,13 @@ describe('src/background/services/seedless/SeedlessWallet', () => { await wallet.signAvalancheTx(txRequest as any); expect(txRequest.tx.addSignature).toHaveBeenCalledWith( - utils.hexToBuffer(signature) + utils.hexToBuffer(signature), ); }); it('returns the signed transaction', async () => { expect(await wallet.signAvalancheTx(txRequest as any)).toEqual( - txRequest.tx + txRequest.tx, ); }); }); @@ -549,7 +549,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { from: '', data: {}, ...payload, - } as any); + }) as any; beforeEach(() => { session = { @@ -570,7 +570,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect( - wallet.signMessage(MessageType.ETH_SIGN, getMessage()) + wallet.signMessage(MessageType.ETH_SIGN, getMessage()), ).rejects.toThrow('Public key not available'); }); }); @@ -586,7 +586,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect( - wallet.signMessage(MessageType.ETH_SIGN, getMessage()) + wallet.signMessage(MessageType.ETH_SIGN, getMessage()), ).rejects.toThrow('Network not available'); }); }); @@ -643,14 +643,14 @@ describe('src/background/services/seedless/SeedlessWallet', () => { type: MessageType.ETH_SIGN, msg: ethSignMsg, payload: base64encode( - hashMessage(Uint8Array.from(Buffer.from('4243', 'hex'))) + hashMessage(Uint8Array.from(Buffer.from('4243', 'hex'))), ), }, { type: MessageType.PERSONAL_SIGN, msg: ethSignMsg, payload: base64encode( - hashMessage(Uint8Array.from(Buffer.from('4243', 'hex'))) + hashMessage(Uint8Array.from(Buffer.from('4243', 'hex'))), ), }, { @@ -670,9 +670,9 @@ describe('src/background/services/seedless/SeedlessWallet', () => { Uint8Array.from( TypedDataUtils.eip712Hash( typedDataV3Msg.data, - SignTypedDataVersion.V3 - ) - ) + SignTypedDataVersion.V3, + ), + ), ), }, { @@ -682,9 +682,9 @@ describe('src/background/services/seedless/SeedlessWallet', () => { Uint8Array.from( TypedDataUtils.eip712Hash( typedDataV3Msg.data, - SignTypedDataVersion.V4 - ) - ) + SignTypedDataVersion.V4, + ), + ), ), }, ])( @@ -695,12 +695,12 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(session.signBlob).toHaveBeenCalledWith(evmKey.key_id, { message_base64: payload, }); - } + }, ); it('raises an error for unknown message types', async () => { await expect( - wallet.signMessage('Some unknown type' as MessageType, {} as any) + wallet.signMessage('Some unknown type' as MessageType, {} as any), ).rejects.toThrow('Unknown message type'); }); }); @@ -733,7 +733,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { }); await expect( - wallet.signMessage(MessageType.AVALANCHE_SIGN, getMessage()) + wallet.signMessage(MessageType.AVALANCHE_SIGN, getMessage()), ).rejects.toThrow('X/P public key not available'); }); @@ -755,7 +755,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect.anything(), expect.objectContaining({ message_base64: encodedData.toString('base64'), - }) + }), ); }); }); @@ -781,8 +781,8 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect( await wallet.signMessage( MessageType.ETH_SIGN, - getMessage({ data: '0x1234' }) - ) + getMessage({ data: '0x1234' }), + ), ).toEqual('dummy-signature'); }); }); @@ -814,7 +814,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error for invalid account index', async () => { await expect(wallet.addAccount(-1)).rejects.toThrow( - /Account index must be greater than or equal to 1/ + /Account index must be greater than or equal to 1/, ); }); @@ -825,7 +825,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.addAccount(1)).rejects.toThrow( - /Core Seedless API is unreachable/ + /Core Seedless API is unreachable/, ); }); }); @@ -844,7 +844,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.addAccount(1)).rejects.toThrow( - /Cannot establish the mnemonic id/ + /Cannot establish the mnemonic id/, ); }); }); @@ -862,7 +862,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect.objectContaining({ method: 'POST', body: JSON.stringify({ accountIndex, identityProof, mnemonicId }), - }) + }), ); }); @@ -876,7 +876,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { session.proveIdentity.mockResolvedValue({} as any); await expect(wallet.addAccount(1)).rejects.toThrow( - /Adding new account failed/ + /Adding new account failed/, ); }); }); @@ -899,7 +899,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { Object.assign(psbt, { txInputs: ins, txOutputs: outs, - }) + }), ); return psbt; @@ -924,7 +924,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTx([], [])).rejects.toThrow( - 'Invalid network: Attempting to sign BTC transaction on non Bitcoin network' + 'Invalid network: Attempting to sign BTC transaction on non Bitcoin network', ); }); }); @@ -942,7 +942,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTx([], [])).rejects.toThrow( - 'Invalid network: Attempting to sign BTC transaction on non Bitcoin network' + 'Invalid network: Attempting to sign BTC transaction on non Bitcoin network', ); }); }); @@ -962,7 +962,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTx([], [])).rejects.toThrow( - 'Wrong provider obtained for BTC transaction' + 'Wrong provider obtained for BTC transaction', ); }); }); @@ -984,7 +984,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('raises an error', async () => { await expect(wallet.signTx([1] as any, [])).rejects.toThrow( - 'Public key not available' + 'Public key not available', ); }); }); @@ -1037,7 +1037,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { i, inputs, networks.bitcoin, - session + session, ); }); }); @@ -1053,7 +1053,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(psbt.signInputAsync).toHaveBeenNthCalledWith( i + 1, i, - expect.any(SeedlessBtcSigner) + expect.any(SeedlessBtcSigner), ); }); }); @@ -1172,10 +1172,10 @@ describe('src/background/services/seedless/SeedlessWallet', () => { it('cancels the initiated export & throws an error', async () => { await expect(wallet.initMnemonicExport()).rejects.toEqual( - new Error('Expected MFA to be required') + new Error('Expected MFA to be required'), ); expect(session.userExportDelete).toHaveBeenCalledWith( - expect.any(String) + expect.any(String), ); }); }); @@ -1209,7 +1209,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(mfaService.approveWithMfa).toHaveBeenCalledWith( MfaRequestType.Fido, originalRequest, - 123 + 123, ); }); }); @@ -1227,7 +1227,7 @@ describe('src/background/services/seedless/SeedlessWallet', () => { expect(mfaService.approveWithMfa).toHaveBeenCalledWith( MfaRequestType.Totp, originalRequest, - 123 + 123, ); }); }); diff --git a/src/background/services/seedless/SeedlessWallet.ts b/src/background/services/seedless/SeedlessWallet.ts index 787e801a7..4c5e6faee 100644 --- a/src/background/services/seedless/SeedlessWallet.ts +++ b/src/background/services/seedless/SeedlessWallet.ts @@ -82,7 +82,7 @@ export class SeedlessWallet { } this.#signerSession = await cs.SignerSession.loadSignerSession( - this.#sessionStorage + this.#sessionStorage, ); } @@ -112,7 +112,7 @@ export class SeedlessWallet { identityProof, mnemonicId, }), - } + }, ); if (!response.ok) { @@ -139,7 +139,7 @@ export class SeedlessWallet { const keys = await session.keys(); const activeAccountKey = keys.find( - (key) => strip0x(key.publicKey) === this.#addressPublicKey?.evm + (key) => strip0x(key.publicKey) === this.#addressPublicKey?.evm, ); const mnemonicId = activeAccountKey?.derivation_info?.mnemonic_id; @@ -202,7 +202,7 @@ export class SeedlessWallet { const result = await this.#mfaService.approveWithMfa( method?.type, initRequest, - tabId + tabId, ); return result.data(); @@ -217,7 +217,7 @@ export class SeedlessWallet { async completeMnemonicExport( publicKey: CryptoKey, - tabId?: number + tabId?: number, ): Promise { if (!this.#mfaService) { throw new Error('MFA Service is not available'); @@ -244,7 +244,7 @@ export class SeedlessWallet { const result = await this.#mfaService.approveWithMfa( method?.type, request, - tabId + tabId, ); return result.data(); @@ -267,32 +267,35 @@ export class SeedlessWallet { (k) => k.enabled && requiredKeyTypes.includes(k.key_type) && - k.derivation_info?.derivation_path + k.derivation_info?.derivation_path, ) - .reduce((acc, key) => { - if (!key.derivation_info) { - return acc; - } + .reduce( + (acc, key) => { + if (!key.derivation_info) { + return acc; + } - const index = Number( - key.derivation_info.derivation_path.split('/').pop() - ); - if (index === undefined) { - return acc; - } + const index = Number( + key.derivation_info.derivation_path.split('/').pop(), + ); + if (index === undefined) { + return acc; + } - acc[key.derivation_info.mnemonic_id] = [ - ...(acc[key.derivation_info.mnemonic_id] ?? []), - ]; - const mnemonicBlock = acc[key.derivation_info.mnemonic_id] || []; + acc[key.derivation_info.mnemonic_id] = [ + ...(acc[key.derivation_info.mnemonic_id] ?? []), + ]; + const mnemonicBlock = acc[key.derivation_info.mnemonic_id] || []; - mnemonicBlock[index] = { - ...acc[key.derivation_info.mnemonic_id]?.[index], - [key.key_type]: key, - }; + mnemonicBlock[index] = { + ...acc[key.derivation_info.mnemonic_id]?.[index], + [key.key_type]: key, + }; - return acc; - }, {} as Record[]>); + return acc; + }, + {} as Record[]>, + ); if (!keys || Object.keys(keys).length === 0) { throw new Error('Accounts not created'); @@ -333,7 +336,7 @@ export class SeedlessWallet { async #getSigningKey( type: cs.Secp256k1, - lookupPublicKey?: string + lookupPublicKey?: string, ): Promise { if (!lookupPublicKey) { throw new Error('Public key not available'); @@ -375,7 +378,7 @@ export class SeedlessWallet { const signer = new Signer( getEvmAddressFromPubKey(Buffer.from(this.#addressPublicKey.evm, 'hex')), await this.#getSession(), - provider + provider, ); // We need to await the signing call here so the errors can be // caught by catch clause. @@ -386,7 +389,7 @@ export class SeedlessWallet { } async signAvalancheTx( - request: Avalanche.SignTxRequest + request: Avalanche.SignTxRequest, ): Promise { if (!this.#addressPublicKey) { throw new Error('Public key not available'); @@ -399,13 +402,13 @@ export class SeedlessWallet { ? await this.#getSigningKey(cs.Secp256k1.Evm, this.#addressPublicKey.evm) : await this.#getSigningKey( isMainnet ? cs.Secp256k1.Ava : cs.Secp256k1.AvaTest, - this.#addressPublicKey.xp + this.#addressPublicKey.xp, ); try { const response = await session.signBlob(key.key_id, { message_base64: Buffer.from(sha256(request.tx.toBytes())).toString( - 'base64' + 'base64', ), }); @@ -419,11 +422,11 @@ export class SeedlessWallet { async signTx( ins: BitcoinInputUTXO[], - outs: BitcoinOutputUTXO[] + outs: BitcoinOutputUTXO[], ): Promise { if (!this.#network || !isBitcoinNetwork(this.#network)) { throw new Error( - 'Invalid network: Attempting to sign BTC transaction on non Bitcoin network' + 'Invalid network: Attempting to sign BTC transaction on non Bitcoin network', ); } @@ -450,10 +453,10 @@ export class SeedlessWallet { i, ins, btcNetwork, - session + session, ); return psbt.signInputAsync(i, signer); - }) + }), ); } catch (err) { this.#handleError(err); @@ -468,7 +471,7 @@ export class SeedlessWallet { async signMessage( messageType: MessageType, - messageParams: MessageParams + messageParams: MessageParams, ): Promise { if (!this.#addressPublicKey) { throw new Error('Public key not available'); @@ -493,15 +496,15 @@ export class SeedlessWallet { strip0x( await this.#signBlob( addressAVM, - `0x${Avalanche.digestMessage(message).toString('hex')}` - ) + `0x${Avalanche.digestMessage(message).toString('hex')}`, + ), ), - 'hex' + 'hex', ); } const addressEVM = getEvmAddressFromPubKey( - Buffer.from(this.#addressPublicKey.evm, 'hex') + Buffer.from(this.#addressPublicKey.evm, 'hex'), ).toLowerCase(); switch (messageType) { @@ -510,14 +513,14 @@ export class SeedlessWallet { return this.#signBlob( addressEVM, hashMessage( - Uint8Array.from(Buffer.from(strip0x(messageParams.data), 'hex')) - ) + Uint8Array.from(Buffer.from(strip0x(messageParams.data), 'hex')), + ), ); case MessageType.SIGN_TYPED_DATA: case MessageType.SIGN_TYPED_DATA_V1: return this.#signBlob( addressEVM, - typedSignatureHash(messageParams.data) + typedSignatureHash(messageParams.data), ); case MessageType.SIGN_TYPED_DATA_V3: case MessageType.SIGN_TYPED_DATA_V4: { @@ -528,7 +531,7 @@ export class SeedlessWallet { messageParams.data, messageType == MessageType.SIGN_TYPED_DATA_V3 ? SignTypedDataVersion.V3 - : SignTypedDataVersion.V4 + : SignTypedDataVersion.V4, ).toString('hex'); return this.#signBlob(addressEVM, `0x${hash}`); } diff --git a/src/background/services/seedless/events/eventFilters.ts b/src/background/services/seedless/events/eventFilters.ts index 7a6d543e4..7950324d1 100644 --- a/src/background/services/seedless/events/eventFilters.ts +++ b/src/background/services/seedless/events/eventFilters.ts @@ -7,7 +7,7 @@ import { } from '../models'; export function isSeedlessTokenEvent( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return ( evt?.name === SeedlessEvents.TokenExpired || @@ -16,7 +16,7 @@ export function isSeedlessTokenEvent( } export function isSeedlessMfaEvent( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return ( evt?.name === SeedlessEvents.MfaRequest || @@ -26,13 +26,13 @@ export function isSeedlessMfaEvent( } export function isSeedlessMfaMethodsUpdatedEvent( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return evt?.name === SeedlessEvents.MfaMethodsUpdated; } export function isSeedlessMfaChoiceRequest( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return evt?.name === SeedlessEvents.MfaChoiceRequest; } diff --git a/src/background/services/seedless/events/seedlessMfaEvents.ts b/src/background/services/seedless/events/seedlessMfaEvents.ts index 633f391ba..df0822892 100644 --- a/src/background/services/seedless/events/seedlessMfaEvents.ts +++ b/src/background/services/seedless/events/seedlessMfaEvents.ts @@ -32,7 +32,7 @@ export class SeedlessMfaEvents implements ExtensionEventEmitter { name: SeedlessEvents.MfaChoiceRequest, value, }); - } + }, ); this.seedlessMfaService.addListener(SeedlessEvents.MfaClear, (value) => { this.eventEmitter.emit('update', { @@ -47,7 +47,7 @@ export class SeedlessMfaEvents implements ExtensionEventEmitter { name: SeedlessEvents.MfaMethodsUpdated, value, }); - } + }, ); } @@ -56,7 +56,7 @@ export class SeedlessMfaEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/seedless/events/seedlessTokenEvents.ts b/src/background/services/seedless/events/seedlessTokenEvents.ts index 3362684ed..65d62f3f9 100644 --- a/src/background/services/seedless/events/seedlessTokenEvents.ts +++ b/src/background/services/seedless/events/seedlessTokenEvents.ts @@ -31,7 +31,7 @@ export class SeedlessTokenEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/seedless/handlers/addFidoDevice.test.ts b/src/background/services/seedless/handlers/addFidoDevice.test.ts index e0bb1f76e..89687a8fe 100644 --- a/src/background/services/seedless/handlers/addFidoDevice.test.ts +++ b/src/background/services/seedless/handlers/addFidoDevice.test.ts @@ -19,7 +19,7 @@ describe('src/background/services/seedless/handlers/addFidoDevice', () => { id: 'abcd-1234', params: [name, type], tabId: 1234, - }) + }), ); }; @@ -29,7 +29,7 @@ describe('src/background/services/seedless/handlers/addFidoDevice', () => { it('returns error if request fails', async () => { seedlessMfaService.addFidoDevice.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle('yubi', KeyType.Yubikey); @@ -62,14 +62,14 @@ describe('src/background/services/seedless/handlers/addFidoDevice', () => { expect(seedlessMfaService.addFidoDevice).toHaveBeenCalledWith( 'yubi', KeyType.Yubikey, - 1234 + 1234, ); await handle('paskij', KeyType.Passkey); expect(seedlessMfaService.addFidoDevice).toHaveBeenCalledWith( 'paskij', KeyType.Passkey, - 1234 + 1234, ); }); }); diff --git a/src/background/services/seedless/handlers/addFidoDevice.ts b/src/background/services/seedless/handlers/addFidoDevice.ts index 61a133c6d..bea921238 100644 --- a/src/background/services/seedless/handlers/addFidoDevice.ts +++ b/src/background/services/seedless/handlers/addFidoDevice.ts @@ -48,7 +48,7 @@ export class AddFidoDeviceHandler implements HandlerType { result: await this.seedlessMfaService.addFidoDevice( name, keyType, - request.tabId + request.tabId, ), }; } catch (error: any) { diff --git a/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.test.ts b/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.test.ts index a7f0de4fa..b925371fe 100644 --- a/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.test.ts +++ b/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.test.ts @@ -23,14 +23,14 @@ describe('src/background/services/seedless/handlers/cancelRecoveryPhraseExport', secretsService, networkService, mfaService, - accountsService + accountsService, ); return handler.handle( buildRpcCall({ method: ExtensionRequest.SEEDLESS_CANCEL_RECOVERY_PHRASE_EXPORT, id: 'abcd-1234', - }) + }), ); }; @@ -66,7 +66,7 @@ describe('src/background/services/seedless/handlers/cancelRecoveryPhraseExport', const result = await handle(); expect(result.error).toEqual( - 'Action only available for seedless wallets' + 'Action only available for seedless wallets', ); }); }); @@ -82,7 +82,7 @@ describe('src/background/services/seedless/handlers/cancelRecoveryPhraseExport', it('returns error if export cancellation fails', async () => { wallet.getMnemonicExportState.mockResolvedValueOnce({} as any); wallet.cancelMnemonicExport.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle(); diff --git a/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.ts b/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.ts index f854c996c..2d026b376 100644 --- a/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.ts +++ b/src/background/services/seedless/handlers/cancelRecoveryPhraseExport.ts @@ -24,12 +24,12 @@ export class CancelRecoveryPhraseExportHandler implements HandlerType { private secretsService: SecretsService, private networkService: NetworkService, private seedlessMfaService: SeedlessMfaService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { const secrets = await this.secretsService.getPrimaryAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets?.secretType !== SecretType.Seedless) { diff --git a/src/background/services/seedless/handlers/chooseMfaMethod.test.ts b/src/background/services/seedless/handlers/chooseMfaMethod.test.ts index c040e06a3..ab015e84b 100644 --- a/src/background/services/seedless/handlers/chooseMfaMethod.test.ts +++ b/src/background/services/seedless/handlers/chooseMfaMethod.test.ts @@ -19,7 +19,7 @@ describe('src/background/services/seedless/handlers/chooseMfaMethod', () => { id: 'abcd-1234', params: [choice], tabId: 1234, - }) + }), ); }; @@ -48,7 +48,7 @@ describe('src/background/services/seedless/handlers/chooseMfaMethod', () => { await handle(choice); expect(seedlessMfaService.submitChosenMethod).toHaveBeenCalledWith( choice, - 1234 + 1234, ); }); }); diff --git a/src/background/services/seedless/handlers/completeAuthenticatorChange.test.ts b/src/background/services/seedless/handlers/completeAuthenticatorChange.test.ts index f52912e09..2e8dad3e1 100644 --- a/src/background/services/seedless/handlers/completeAuthenticatorChange.test.ts +++ b/src/background/services/seedless/handlers/completeAuthenticatorChange.test.ts @@ -18,7 +18,7 @@ describe('src/background/services/seedless/handlers/completeAuthenticatorChange' method: ExtensionRequest.SEEDLESS_COMPLETE_AUTHENTICATOR_CHANGE, id: 'abcd-1234', params: ['totpId', '123456'], - }) + }), ); }; @@ -28,7 +28,7 @@ describe('src/background/services/seedless/handlers/completeAuthenticatorChange' it('returns error if change completion fails', async () => { seedlessMfaService.completeAuthenticatorChange.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle(); diff --git a/src/background/services/seedless/handlers/completeAuthenticatorChange.ts b/src/background/services/seedless/handlers/completeAuthenticatorChange.ts index f88a0b5b5..e223e4ec2 100644 --- a/src/background/services/seedless/handlers/completeAuthenticatorChange.ts +++ b/src/background/services/seedless/handlers/completeAuthenticatorChange.ts @@ -25,7 +25,7 @@ export class CompleteAuthenticatorChangeHandler implements HandlerType { ...request, result: await this.seedlessMfaService.completeAuthenticatorChange( totpId, - code + code, ), }; } catch (error: any) { diff --git a/src/background/services/seedless/handlers/completeRecoveryPhraseExport.test.ts b/src/background/services/seedless/handlers/completeRecoveryPhraseExport.test.ts index 3e108eaed..7b261d9ab 100644 --- a/src/background/services/seedless/handlers/completeRecoveryPhraseExport.test.ts +++ b/src/background/services/seedless/handlers/completeRecoveryPhraseExport.test.ts @@ -34,14 +34,14 @@ describe('src/background/services/seedless/handlers/completeRecoveryPhraseExport secretsService, networkService, mfaService, - accountsService + accountsService, ); return handler.handle( buildRpcCall({ method: ExtensionRequest.SEEDLESS_COMPLETE_RECOVERY_PHRASE_EXPORT, id: 'abcd-1234', - }) + }), ); }; @@ -76,7 +76,7 @@ describe('src/background/services/seedless/handlers/completeRecoveryPhraseExport const result = await handle(); expect(result.error).toEqual( - 'Action only available for seedless wallets' + 'Action only available for seedless wallets', ); }); }); @@ -89,7 +89,7 @@ describe('src/background/services/seedless/handlers/completeRecoveryPhraseExport expect(sentryCaptureException).toHaveBeenCalledWith( err, - SentryExceptionTypes.SEEDLESS + SentryExceptionTypes.SEEDLESS, ); expect(result.error).toEqual('Failed to generate the encryption key pair'); }); @@ -106,10 +106,10 @@ describe('src/background/services/seedless/handlers/completeRecoveryPhraseExport expect(sentryCaptureException).toHaveBeenCalledWith( err, - SentryExceptionTypes.SEEDLESS + SentryExceptionTypes.SEEDLESS, ); expect(result.error).toEqual( - 'Failed to complete the recovery phrase export' + 'Failed to complete the recovery phrase export', ); }); @@ -128,7 +128,7 @@ describe('src/background/services/seedless/handlers/completeRecoveryPhraseExport expect(sentryCaptureException).toHaveBeenCalledWith( err, - SentryExceptionTypes.SEEDLESS + SentryExceptionTypes.SEEDLESS, ); expect(result.error).toEqual('Failed to decrypt the recovery phrase'); }); @@ -146,10 +146,10 @@ describe('src/background/services/seedless/handlers/completeRecoveryPhraseExport expect(sentryCaptureException).toHaveBeenCalledWith( new Error('Export decrypted, but has no mnemonic'), - SentryExceptionTypes.SEEDLESS + SentryExceptionTypes.SEEDLESS, ); expect(result.error).toEqual( - 'Unexpected error occured while decrypting the recovery phrase' + 'Unexpected error occured while decrypting the recovery phrase', ); }); diff --git a/src/background/services/seedless/handlers/completeRecoveryPhraseExport.ts b/src/background/services/seedless/handlers/completeRecoveryPhraseExport.ts index 0feea0c8a..84d109589 100644 --- a/src/background/services/seedless/handlers/completeRecoveryPhraseExport.ts +++ b/src/background/services/seedless/handlers/completeRecoveryPhraseExport.ts @@ -31,12 +31,12 @@ export class CompleteRecoveryPhraseExportHandler implements HandlerType { private secretsService: SecretsService, private networkService: NetworkService, private seedlessMfaService: SeedlessMfaService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { const secrets = await this.secretsService.getPrimaryAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets?.secretType !== SecretType.Seedless) { @@ -73,7 +73,7 @@ export class CompleteRecoveryPhraseExportHandler implements HandlerType { try { exportResponse = await wallet.completeMnemonicExport( keyPair.publicKey, - request.tabId + request.tabId, ); } catch (err) { sentryCaptureException(err as Error, SentryExceptionTypes.SEEDLESS); @@ -87,7 +87,7 @@ export class CompleteRecoveryPhraseExportHandler implements HandlerType { try { const exportDecrypted = await userExportDecrypt( keyPair.privateKey, - exportResponse + exportResponse, ); const hasMnemonic = 'mnemonic' in exportDecrypted; @@ -95,7 +95,7 @@ export class CompleteRecoveryPhraseExportHandler implements HandlerType { if (!hasMnemonic || typeof exportDecrypted.mnemonic !== 'string') { sentryCaptureException( new Error('Export decrypted, but has no mnemonic'), - SentryExceptionTypes.SEEDLESS + SentryExceptionTypes.SEEDLESS, ); return { diff --git a/src/background/services/seedless/handlers/getRecoveryMethods.test.ts b/src/background/services/seedless/handlers/getRecoveryMethods.test.ts index 591f21b97..bb107f9b7 100644 --- a/src/background/services/seedless/handlers/getRecoveryMethods.test.ts +++ b/src/background/services/seedless/handlers/getRecoveryMethods.test.ts @@ -24,14 +24,14 @@ describe('src/background/services/seedless/handlers/getRecoveryMethods', () => { const handler = new GetRecoveryMethodsHandler( secretsService, seedlessMfaService, - accountsService + accountsService, ); return handler.handle( buildRpcCall({ method: ExtensionRequest.SEEDLESS_GET_RECOVERY_METHODS, id: 'abcd-1234', - }) + }), ); }; @@ -59,7 +59,7 @@ describe('src/background/services/seedless/handlers/getRecoveryMethods', () => { } as any); seedlessMfaService.getRecoveryMethods.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle(); diff --git a/src/background/services/seedless/handlers/getRecoveryMethods.ts b/src/background/services/seedless/handlers/getRecoveryMethods.ts index 2216762ff..39313ff38 100644 --- a/src/background/services/seedless/handlers/getRecoveryMethods.ts +++ b/src/background/services/seedless/handlers/getRecoveryMethods.ts @@ -22,12 +22,12 @@ export class GetRecoveryMethodsHandler implements HandlerType { constructor( private secretsService: SecretsService, private seedlessMfaService: SeedlessMfaService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { const secrets = await this.secretsService.getPrimaryAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets?.secretType !== SecretType.Seedless) { @@ -38,7 +38,7 @@ export class GetRecoveryMethodsHandler implements HandlerType { } const [result, error] = await resolve( - this.seedlessMfaService.getRecoveryMethods() + this.seedlessMfaService.getRecoveryMethods(), ); return { diff --git a/src/background/services/seedless/handlers/getRecoveryPhraseExportState.test.ts b/src/background/services/seedless/handlers/getRecoveryPhraseExportState.test.ts index 8f5e4b80a..08fb2635c 100644 --- a/src/background/services/seedless/handlers/getRecoveryPhraseExportState.test.ts +++ b/src/background/services/seedless/handlers/getRecoveryPhraseExportState.test.ts @@ -23,14 +23,14 @@ describe('src/background/services/seedless/handlers/ge', () => { secretsService, networkService, mfaService, - accountsService + accountsService, ); return handler.handle( buildRpcCall({ method: ExtensionRequest.SEEDLESS_GET_RECOVERY_PHRASE_EXPORT_STATE, id: 'abcd-1234', - }) + }), ); }; @@ -71,7 +71,7 @@ describe('src/background/services/seedless/handlers/ge', () => { it('returns error if fetching the information fails', async () => { wallet.getMnemonicExportState.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle(); diff --git a/src/background/services/seedless/handlers/getRecoveryPhraseExportState.ts b/src/background/services/seedless/handlers/getRecoveryPhraseExportState.ts index e31e05f2f..bc24e4443 100644 --- a/src/background/services/seedless/handlers/getRecoveryPhraseExportState.ts +++ b/src/background/services/seedless/handlers/getRecoveryPhraseExportState.ts @@ -26,12 +26,12 @@ export class GetRecoveryPhraseExportStateHandler implements HandlerType { private secretsService: SecretsService, private networkService: NetworkService, private seedlessMfaService: SeedlessMfaService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { const secrets = await this.secretsService.getPrimaryAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets?.secretType !== SecretType.Seedless) { diff --git a/src/background/services/seedless/handlers/hasSignerTokenExpired.test.ts b/src/background/services/seedless/handlers/hasSignerTokenExpired.test.ts index e73f322f5..33af13ac2 100644 --- a/src/background/services/seedless/handlers/hasSignerTokenExpired.test.ts +++ b/src/background/services/seedless/handlers/hasSignerTokenExpired.test.ts @@ -13,12 +13,12 @@ describe('src/background/services/seedless/handlers/hasSignerTokenExpired', () = buildRpcCall({ method: ExtensionRequest.SEEDLESS_HAS_TOKEN_EXPIRED, id: 'abcd-1234', - }) - ) + }), + ), ).toEqual( expect.objectContaining({ result: true, - }) + }), ); }); @@ -32,12 +32,12 @@ describe('src/background/services/seedless/handlers/hasSignerTokenExpired', () = buildRpcCall({ method: ExtensionRequest.SEEDLESS_HAS_TOKEN_EXPIRED, id: 'abcd-1234', - }) - ) + }), + ), ).toEqual( expect.objectContaining({ result: false, - }) + }), ); }); }); diff --git a/src/background/services/seedless/handlers/initAuthenticatorChange.test.ts b/src/background/services/seedless/handlers/initAuthenticatorChange.test.ts index 9060cc21a..70fd33928 100644 --- a/src/background/services/seedless/handlers/initAuthenticatorChange.test.ts +++ b/src/background/services/seedless/handlers/initAuthenticatorChange.test.ts @@ -17,7 +17,7 @@ describe('src/background/services/seedless/handlers/initAuthenticatorChange', () buildRpcCall({ method: ExtensionRequest.SEEDLESS_INIT_AUTHENTICATOR_CHANGE, id: 'abcd-1234', - }) + }), ); }; @@ -27,7 +27,7 @@ describe('src/background/services/seedless/handlers/initAuthenticatorChange', () it('returns error if change initialization fails', async () => { seedlessMfaService.initAuthenticatorChange.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle(); diff --git a/src/background/services/seedless/handlers/initAuthenticatorChange.ts b/src/background/services/seedless/handlers/initAuthenticatorChange.ts index bb5976dbf..7cb24239a 100644 --- a/src/background/services/seedless/handlers/initAuthenticatorChange.ts +++ b/src/background/services/seedless/handlers/initAuthenticatorChange.ts @@ -22,7 +22,7 @@ export class InitAuthenticatorChangeHandler implements HandlerType { return { ...request, result: await this.seedlessMfaService.initAuthenticatorChange( - request.tabId + request.tabId, ), }; } catch (err: any) { diff --git a/src/background/services/seedless/handlers/initRecoveryPhraseExport.test.ts b/src/background/services/seedless/handlers/initRecoveryPhraseExport.test.ts index 38f02e6a0..ce3114776 100644 --- a/src/background/services/seedless/handlers/initRecoveryPhraseExport.test.ts +++ b/src/background/services/seedless/handlers/initRecoveryPhraseExport.test.ts @@ -23,14 +23,14 @@ describe('src/background/services/seedless/handlers/initRecoveryPhraseExport', ( secretsService, networkService, mfaService, - accountsService + accountsService, ); return handler.handle( buildRpcCall({ method: ExtensionRequest.SEEDLESS_INIT_RECOVERY_PHRASE_EXPORT, id: 'abcd-1234', - }) + }), ); }; @@ -67,7 +67,7 @@ describe('src/background/services/seedless/handlers/initRecoveryPhraseExport', ( const result = await handle(); expect(result.error).toEqual( - 'Action only available for seedless wallets' + 'Action only available for seedless wallets', ); }); }); @@ -80,19 +80,19 @@ describe('src/background/services/seedless/handlers/initRecoveryPhraseExport', ( const result = await handle(); expect(result.error).toEqual( - 'Recovery phrase export is already in progress' + 'Recovery phrase export is already in progress', ); }); it('returns error if export initialization fails', async () => { wallet.initMnemonicExport.mockRejectedValueOnce( - new Error('Session does not have required scopes: [ExportUserInit]') + new Error('Session does not have required scopes: [ExportUserInit]'), ); const result = await handle(); expect(result.error).toEqual( - 'Session does not have required scopes: [ExportUserInit]' + 'Session does not have required scopes: [ExportUserInit]', ); }); diff --git a/src/background/services/seedless/handlers/initRecoveryPhraseExport.ts b/src/background/services/seedless/handlers/initRecoveryPhraseExport.ts index 0f6cfb4c3..043bb84a1 100644 --- a/src/background/services/seedless/handlers/initRecoveryPhraseExport.ts +++ b/src/background/services/seedless/handlers/initRecoveryPhraseExport.ts @@ -26,12 +26,12 @@ export class InitRecoveryPhraseExportHandler implements HandlerType { private secretsService: SecretsService, private networkService: NetworkService, private seedlessMfaService: SeedlessMfaService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { const secrets = await this.secretsService.getPrimaryAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets?.secretType !== SecretType.Seedless) { diff --git a/src/background/services/seedless/handlers/removeFidoDevice.test.ts b/src/background/services/seedless/handlers/removeFidoDevice.test.ts index ff493d088..c7552fc92 100644 --- a/src/background/services/seedless/handlers/removeFidoDevice.test.ts +++ b/src/background/services/seedless/handlers/removeFidoDevice.test.ts @@ -18,7 +18,7 @@ describe('src/background/services/seedless/handlers/removeFidoDevice', () => { id: 'abcd-1234', params: [id], tabId: 1234, - }) + }), ); }; @@ -28,7 +28,7 @@ describe('src/background/services/seedless/handlers/removeFidoDevice', () => { it('returns error if request fails', async () => { seedlessMfaService.removeFidoDevice.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle('a1b2c3'); @@ -48,7 +48,7 @@ describe('src/background/services/seedless/handlers/removeFidoDevice', () => { await handle('abcd-1234'); expect(seedlessMfaService.removeFidoDevice).toHaveBeenCalledWith( 'abcd-1234', - 1234 + 1234, ); }); }); diff --git a/src/background/services/seedless/handlers/removeFidoDevice.ts b/src/background/services/seedless/handlers/removeFidoDevice.ts index f7fabfdec..48b94e3b4 100644 --- a/src/background/services/seedless/handlers/removeFidoDevice.ts +++ b/src/background/services/seedless/handlers/removeFidoDevice.ts @@ -32,7 +32,7 @@ export class RemoveFidoDeviceHandler implements HandlerType { ...request, result: await this.seedlessMfaService.removeFidoDevice( id, - request.tabId + request.tabId, ), }; } catch (error: any) { diff --git a/src/background/services/seedless/handlers/removeTotp.test.ts b/src/background/services/seedless/handlers/removeTotp.test.ts index 26501c0dd..86224ee70 100644 --- a/src/background/services/seedless/handlers/removeTotp.test.ts +++ b/src/background/services/seedless/handlers/removeTotp.test.ts @@ -17,7 +17,7 @@ describe('src/background/services/seedless/handlers/removeFidoDevice', () => { method: ExtensionRequest.SEEDLESS_REMOVE_TOTP, id: 'abcd-1234', tabId: 1234, - }) + }), ); }; @@ -27,7 +27,7 @@ describe('src/background/services/seedless/handlers/removeFidoDevice', () => { it('returns error if request fails', async () => { seedlessMfaService.removeTotp.mockRejectedValueOnce( - new Error('Session expired') + new Error('Session expired'), ); const result = await handle(); diff --git a/src/background/services/seedless/handlers/submitMfaResponse.test.ts b/src/background/services/seedless/handlers/submitMfaResponse.test.ts index 5c1d2bb2c..4783b6470 100644 --- a/src/background/services/seedless/handlers/submitMfaResponse.test.ts +++ b/src/background/services/seedless/handlers/submitMfaResponse.test.ts @@ -16,7 +16,7 @@ describe('src/background/services/seedless/handlers/submitMfaResponse', () => { method: ExtensionRequest.SEEDLESS_SUBMIT_MFA_RESPONSE, id: 'abcd-1234', params: [response], - }) + }), ); }; @@ -40,7 +40,7 @@ describe('src/background/services/seedless/handlers/submitMfaResponse', () => { await handle(challengeResponse); expect(mfaService.submitMfaResponse).toHaveBeenCalledWith( - challengeResponse + challengeResponse, ); }); }); diff --git a/src/background/services/seedless/handlers/updateSignerToken.test.ts b/src/background/services/seedless/handlers/updateSignerToken.test.ts index e51726ac1..0fdfb5a7e 100644 --- a/src/background/services/seedless/handlers/updateSignerToken.test.ts +++ b/src/background/services/seedless/handlers/updateSignerToken.test.ts @@ -30,7 +30,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { hasTokenExpired: true, } as any, secretsService, - accountsService + accountsService, ); const result = await handler.handle( @@ -38,7 +38,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [] as any, - }) + }), ); expect(result.error).toEqual('missing token'); @@ -50,7 +50,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { hasTokenExpired: true, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla' } as any; @@ -60,7 +60,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'a@b.c', '123'], - }) + }), ); expect(result.error).toEqual('missing session information'); @@ -72,7 +72,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { hasTokenExpired: true, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla', session_info: { bla: 'bla' } } as any; @@ -82,7 +82,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'a@b.c', ''], - }) + }), ); expect(result.error).toEqual('missing user ID'); @@ -101,7 +101,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { hasTokenExpired: true, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla', session_info: { bla: 'bla' } } as any; @@ -111,7 +111,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'a@b.c', '123'], - }) + }), ); expect(result.error).toEqual('mismatching user ID'); }); @@ -122,7 +122,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { hasTokenExpired: true, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla', session_info: { bla: 'bla' } } as any; @@ -132,7 +132,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'a@b.c', '123'], - }) + }), ); expect(result.error).toEqual('mismatching email address'); @@ -147,7 +147,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { updateSignerToken, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla', session_info: { bla: 'bla' } } as any; @@ -157,7 +157,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'x@y.z', '123'], - }) + }), ); expect(result.error).toEqual(error.message); @@ -170,7 +170,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { updateSignerToken, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla', session_info: { bla: 'bla' } } as any; @@ -180,7 +180,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'x@y.z', '123'], - }) + }), ); expect(updateSignerToken).toHaveBeenCalledWith(token); @@ -203,7 +203,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { updateSignerToken, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla', session_info: { bla: 'bla' } } as any; @@ -213,7 +213,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'x@y.z', '123'], - }) + }), ); expect(updateSignerToken).toHaveBeenCalledWith(token); @@ -237,7 +237,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { updateSignerToken, } as any, secretsService, - accountsService + accountsService, ); const token = { token: 'bla bla bla', session_info: { bla: 'bla' } } as any; @@ -247,7 +247,7 @@ describe('src/background/services/seedless/handlers/updateSignerToken', () => { method: ExtensionRequest.SEEDLESS_UPDATE_SIGNER_TOKEN, id: 'abcd-1234', params: [token, 'x@y.z', '123'], - }) + }), ); expect(updateSignerToken).toHaveBeenCalledWith(token); diff --git a/src/background/services/seedless/handlers/updateSignerToken.ts b/src/background/services/seedless/handlers/updateSignerToken.ts index e8bacdd61..9ef89b073 100644 --- a/src/background/services/seedless/handlers/updateSignerToken.ts +++ b/src/background/services/seedless/handlers/updateSignerToken.ts @@ -23,7 +23,7 @@ export class UpdateSignerTokenHandler implements HandlerType { constructor( private sessionMgr: SeedlessSessionManager, private secretsService: SecretsService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -47,7 +47,7 @@ export class UpdateSignerTokenHandler implements HandlerType { } const secrets = await this.secretsService.getAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets.secretType !== SecretType.Seedless) { @@ -72,12 +72,12 @@ export class UpdateSignerTokenHandler implements HandlerType { if (!secrets.userId && email === secrets.userEmail) { await this.secretsService.updateSecrets( { ...secrets, userId, userEmail: undefined }, - secrets.id + secrets.id, ); } const [result, error] = await resolve( - this.sessionMgr.updateSignerToken(token) + this.sessionMgr.updateSignerToken(token), ); return { diff --git a/src/background/services/seedless/utils.ts b/src/background/services/seedless/utils.ts index 841cad274..5279e74cd 100644 --- a/src/background/services/seedless/utils.ts +++ b/src/background/services/seedless/utils.ts @@ -6,7 +6,7 @@ import { ArrayElement } from '@src/background/models'; import { MfaRequestType, RecoveryMethod } from './models'; export const isTokenExpiredError = ( - err: unknown + err: unknown, ): err is Error & { status: 403 } => { // When CubeSigner's refresh token (or the entire session) expires, // we get a 403 Forbidden error on attempted API calls. @@ -14,7 +14,7 @@ export const isTokenExpiredError = ( }; export const isFailedMfaError = ( - err: unknown + err: unknown, ): err is Error & { status: 403 } => { // When CubeSigner's refresh token (or the entire session) expires, // we get a 403 Forbidden error on attempted API calls. @@ -27,11 +27,11 @@ export const isFailedMfaError = ( }; export const isExportRequestOutdated = ( - exportRequest: UserExportInitResponse + exportRequest: UserExportInitResponse, ) => exportRequest.exp_epoch <= Date.now() / 1000; export const mapMfasToRecoveryMethods = ( - method: ArrayElement>['mfa']> + method: ArrayElement>['mfa']>, ): RecoveryMethod => { if (method.type === 'fido') { return { diff --git a/src/background/services/settings/SettingService.test.ts b/src/background/services/settings/SettingService.test.ts index bf678bfaa..0ccb4feff 100644 --- a/src/background/services/settings/SettingService.test.ts +++ b/src/background/services/settings/SettingService.test.ts @@ -97,7 +97,7 @@ describe('background/services/settings/SettingsService.ts', () => { jest.resetAllMocks(); storageServiceMock.load.mockResolvedValue(storedSettings); storageServiceMock.loadUnencrypted.mockResolvedValue( - storedUnencryptedSettings + storedUnencryptedSettings, ); (isTokenSupported as jest.Mock).mockResolvedValue(false); service = new SettingsService(storageServiceMock, networkServiceMock); @@ -205,7 +205,7 @@ describe('background/services/settings/SettingsService.ts', () => { SETTINGS_UNENCRYPTED_STORAGE_KEY, { language: storedSettings.language, - } + }, ); const newState = { @@ -218,7 +218,7 @@ describe('background/services/settings/SettingsService.ts', () => { }; expect(storageServiceMock.save).toBeCalledWith( SETTINGS_STORAGE_KEY, - newState + newState, ); expect(eventListener).toHaveBeenCalledWith(newState); @@ -390,7 +390,7 @@ describe('background/services/settings/SettingsService.ts', () => { }); expect(storageServiceMock.saveUnencrypted).toHaveBeenCalledWith( SETTINGS_UNENCRYPTED_STORAGE_KEY, - { language: Languages.HI } + { language: Languages.HI }, ); }); }); diff --git a/src/background/services/settings/SettingsService.ts b/src/background/services/settings/SettingsService.ts index 3c373abeb..ea23874b5 100644 --- a/src/background/services/settings/SettingsService.ts +++ b/src/background/services/settings/SettingsService.ts @@ -39,7 +39,7 @@ export class SettingsService implements OnStorageReady, OnLock { constructor( private storageService: StorageService, - private networkService: NetworkService + private networkService: NetworkService, ) { this.networkService.uiActiveNetworkChanged.add(() => { this.applySettings(); @@ -59,7 +59,7 @@ export class SettingsService implements OnStorageReady, OnLock { try { settings = await this.getSettings(); changeLanguage(settings.language); - } catch (e) { + } catch (_err) { return; } @@ -72,12 +72,11 @@ export class SettingsService implements OnStorageReady, OnLock { } try { - const state = await this.storageService.load( - SETTINGS_STORAGE_KEY - ); + const state = + await this.storageService.load(SETTINGS_STORAGE_KEY); const unEncryptedState = await this.storageService.loadUnencrypted( - SETTINGS_UNENCRYPTED_STORAGE_KEY + SETTINGS_UNENCRYPTED_STORAGE_KEY, ); const settings = { @@ -94,7 +93,7 @@ export class SettingsService implements OnStorageReady, OnLock { this.needToRetryFetch = true; const unEncryptedState = await this.storageService.loadUnencrypted( - SETTINGS_UNENCRYPTED_STORAGE_KEY + SETTINGS_UNENCRYPTED_STORAGE_KEY, ); const settings = { @@ -120,7 +119,7 @@ export class SettingsService implements OnStorageReady, OnLock { const tokenAlreadyExists = await isTokenSupported( token.address, network, - settings + settings, ); if (tokenAlreadyExists) { @@ -207,7 +206,7 @@ export class SettingsService implements OnStorageReady, OnLock { SETTINGS_UNENCRYPTED_STORAGE_KEY, { language: state.language, - } + }, ); try { await this.storageService.save(SETTINGS_STORAGE_KEY, state); diff --git a/src/background/services/settings/events/listeners.ts b/src/background/services/settings/events/listeners.ts index 7be273af8..67afa57ee 100644 --- a/src/background/services/settings/events/listeners.ts +++ b/src/background/services/settings/events/listeners.ts @@ -2,7 +2,7 @@ import { ExtensionConnectionEvent } from '@src/background/connections/models'; import { SettingsEvents, SettingsState } from '../models'; export function settingsUpdatedEventListener( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ) { return evt.name === SettingsEvents.SETTINGS_UPDATED; } diff --git a/src/background/services/settings/events/settingsUpdatedEvent.ts b/src/background/services/settings/events/settingsUpdatedEvent.ts index 834175ac0..4aa0da198 100644 --- a/src/background/services/settings/events/settingsUpdatedEvent.ts +++ b/src/background/services/settings/events/settingsUpdatedEvent.ts @@ -18,7 +18,7 @@ export class SettingsUpdatedEvents implements ExtensionEventEmitter { name: SettingsEvents.SETTINGS_UPDATED, value: settings, }); - } + }, ); } @@ -27,7 +27,7 @@ export class SettingsUpdatedEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/settings/events/wallet_watchAsset.ts b/src/background/services/settings/events/wallet_watchAsset.ts index eaf0e3c47..ffc71626e 100644 --- a/src/background/services/settings/events/wallet_watchAsset.ts +++ b/src/background/services/settings/events/wallet_watchAsset.ts @@ -19,7 +19,7 @@ export class WalletWatchAssetHandler extends DAppRequestHandler { constructor( private tokenManagerService: TokenManagerService, private settingsService: SettingsService, - private networkService: NetworkService + private networkService: NetworkService, ) { super(); } @@ -45,7 +45,7 @@ export class WalletWatchAssetHandler extends DAppRequestHandler { const tokenAlreadyExists = await isTokenSupported( tokenAddress, network, - settings + settings, ); if (tokenAlreadyExists) { return { ...request, result: true }; @@ -62,7 +62,7 @@ export class WalletWatchAssetHandler extends DAppRequestHandler { } const [tokenData, err] = await resolve( - this.tokenManagerService.getTokenData(tokenAddress, network) + this.tokenManagerService.getTokenData(tokenAddress, network), ); if (!tokenData || err) { @@ -95,13 +95,13 @@ export class WalletWatchAssetHandler extends DAppRequestHandler { onActionApproved = async ( pendingAction: Action, - result, + _result, onSuccess, - onError + onError, ) => { try { await this.settingsService.addCustomToken( - pendingAction.displayData.token + pendingAction.displayData.token, ); onSuccess(null); diff --git a/src/background/services/settings/handlers/addCustomToken.ts b/src/background/services/settings/handlers/addCustomToken.ts index 677b450b4..adf39f397 100644 --- a/src/background/services/settings/handlers/addCustomToken.ts +++ b/src/background/services/settings/handlers/addCustomToken.ts @@ -19,7 +19,7 @@ export class AddCustomTokenHandler implements HandlerType { constructor( private settingsService: SettingsService, private tokenManagerService: TokenManagerService, - private networkService: NetworkService + private networkService: NetworkService, ) {} handle: HandlerType['handle'] = async ({ request, scope }) => { @@ -34,7 +34,7 @@ export class AddCustomTokenHandler implements HandlerType { const [tokenAddress] = request.params; const [tokenData, err] = await resolve( - this.tokenManagerService.getTokenData(tokenAddress, network) + this.tokenManagerService.getTokenData(tokenAddress, network), ); if (!tokenData || err) { @@ -45,7 +45,7 @@ export class AddCustomTokenHandler implements HandlerType { } const [, saveError] = await resolve( - this.settingsService.addCustomToken(tokenData) + this.settingsService.addCustomToken(tokenData), ); if (saveError) { diff --git a/src/background/services/settings/handlers/getTokenDataByAddress.ts b/src/background/services/settings/handlers/getTokenDataByAddress.ts index dc4d21594..ea0d2abe9 100644 --- a/src/background/services/settings/handlers/getTokenDataByAddress.ts +++ b/src/background/services/settings/handlers/getTokenDataByAddress.ts @@ -20,7 +20,7 @@ export class GetTokenDataHandler implements HandlerType { constructor( private tokenManagerService: TokenManagerService, - private networkService: NetworkService + private networkService: NetworkService, ) {} handle: HandlerType['handle'] = async ({ request, scope }) => { @@ -37,7 +37,7 @@ export class GetTokenDataHandler implements HandlerType { try { const tokenData = await this.tokenManagerService.getTokenData( tokenAddress, - network + network, ); return { ...request, diff --git a/src/background/services/settings/handlers/updateCollectiblesVisibility.ts b/src/background/services/settings/handlers/updateCollectiblesVisibility.ts index 0ffb9021e..9ecac1306 100644 --- a/src/background/services/settings/handlers/updateCollectiblesVisibility.ts +++ b/src/background/services/settings/handlers/updateCollectiblesVisibility.ts @@ -20,7 +20,7 @@ export class UpdateCollectiblesVisibilityHandler implements HandlerType { const [collectiblesVisibility] = request.params; await this.settingsService.setCollectiblesVisibility( - collectiblesVisibility + collectiblesVisibility, ); return { diff --git a/src/background/services/settings/handlers/updateShowTokensNoBalance.ts b/src/background/services/settings/handlers/updateShowTokensNoBalance.ts index 16bd39b51..851170dcc 100644 --- a/src/background/services/settings/handlers/updateShowTokensNoBalance.ts +++ b/src/background/services/settings/handlers/updateShowTokensNoBalance.ts @@ -19,7 +19,7 @@ export class UpdateShowNoBalanceHandler implements HandlerType { const [showTokensWithoutBalances] = request.params || []; await this.settingsService.setShowTokensWithNoBalance( - !!showTokensWithoutBalances + !!showTokensWithoutBalances, ); return { diff --git a/src/background/services/storage/StorageService.test.ts b/src/background/services/storage/StorageService.test.ts index a4d76c5e0..04b27680a 100644 --- a/src/background/services/storage/StorageService.test.ts +++ b/src/background/services/storage/StorageService.test.ts @@ -71,7 +71,7 @@ describe('src/background/services/storage/StorageService.ts', () => { const callbackManager = new CallbackManager(); const service = new StorageService(callbackManager); await expect(service.activate('wrong-password')).rejects.toThrow( - new Error('password incorrect') + new Error('password incorrect'), ); expect(callbackManager.onStorageReady).not.toHaveBeenCalled(); @@ -97,7 +97,7 @@ describe('src/background/services/storage/StorageService.ts', () => { // should throw an error when trying to save after lock since key is cleared await expect(service.save('STORAGE_KEY', { data: 1 })).rejects.toThrow( - new Error('No encryption key defined') + new Error('No encryption key defined'), ); }); }); @@ -122,7 +122,7 @@ describe('src/background/services/storage/StorageService.ts', () => { const service = new StorageService(new CallbackManager()); await expect( - service.changePassword('old-password', 'new-password') + service.changePassword('old-password', 'new-password'), ).rejects.toThrow(new Error('password incorrect')); expect(decryptWithPassword).toHaveBeenCalledTimes(1); @@ -232,7 +232,7 @@ describe('src/background/services/storage/StorageService.ts', () => { expect(encryptWithKey).toHaveBeenCalledWith({ secret: '"some-data"', encryptionKey: Buffer.from( - '0101010101010101010101010101010101010101010101010101010101010101' + '0101010101010101010101010101010101010101010101010101010101010101', ), }); }); @@ -243,7 +243,7 @@ describe('src/background/services/storage/StorageService.ts', () => { const service = new StorageService(new CallbackManager()); await expect(service.save('STORAGE_KEY', { data: 1 })).rejects.toThrow( - new Error('No encryption key defined') + new Error('No encryption key defined'), ); }); @@ -356,7 +356,7 @@ describe('src/background/services/storage/StorageService.ts', () => { const service = new StorageService(new CallbackManager()); await expect(service.load('some-key')).rejects.toThrow( - new Error('encryption key missing') + new Error('encryption key missing'), ); }); @@ -373,7 +373,7 @@ describe('src/background/services/storage/StorageService.ts', () => { const service = new StorageService(new CallbackManager()); await expect(service.load('some-key', 'some-password')).resolves.toEqual( - 'some-data' + 'some-data', ); expect(decryptWithPassword).toHaveBeenCalledTimes(1); @@ -391,7 +391,7 @@ describe('src/background/services/storage/StorageService.ts', () => { expect(migrationSpy).toHaveBeenCalledWith( 'some-key', 'some-data', - expect.anything() + expect.anything(), ); }); @@ -415,7 +415,7 @@ describe('src/background/services/storage/StorageService.ts', () => { const fillSpy = jest.fn(); jest .spyOn(Buffer, 'from') - .mockImplementation((value) => ({ value, fill: fillSpy } as any)); + .mockImplementation((value) => ({ value, fill: fillSpy }) as any); const service = new StorageService(new CallbackManager()); await service.activate('some-password'); @@ -487,7 +487,7 @@ describe('src/background/services/storage/StorageService.ts', () => { it('throws error when value is not defined', async () => { const service = new StorageService(new CallbackManager()); await expect( - service.saveToSessionStorage('some-key', null) + service.saveToSessionStorage('some-key', null), ).rejects.toThrow(new Error('trying to store an empty value')); expect(browser.storage.session.set).not.toHaveBeenCalled(); diff --git a/src/background/services/storage/StorageService.ts b/src/background/services/storage/StorageService.ts index 6e6dd649c..58f76c9c3 100644 --- a/src/background/services/storage/StorageService.ts +++ b/src/background/services/storage/StorageService.ts @@ -34,12 +34,12 @@ export class StorageService implements OnLock { try { const keyData = await this.load( WALLET_STORAGE_ENCRYPTION_KEY, - password + password, ); this._storageKey = keyData?.storageKey; this.callbackManager.onStorageReady(); - } catch (err) { + } catch (_err) { return Promise.reject(new Error('password incorrect')); } } @@ -54,7 +54,7 @@ export class StorageService implements OnLock { // double check that the old password is correct const key = await this.load( WALLET_STORAGE_ENCRYPTION_KEY, - oldPassword + oldPassword, ); if (!key) { @@ -64,9 +64,9 @@ export class StorageService implements OnLock { await this.save( WALLET_STORAGE_ENCRYPTION_KEY, key, - newPassword + newPassword, ); - } catch (err) { + } catch (_err) { return Promise.reject(new Error('password incorrect')); } } @@ -75,7 +75,7 @@ export class StorageService implements OnLock { const storageKey = Buffer.from( // generate cryptographically strong random values // https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues - crypto.getRandomValues(new Uint8Array(32)) + crypto.getRandomValues(new Uint8Array(32)), ).toString('hex'); await this.save( @@ -83,7 +83,7 @@ export class StorageService implements OnLock { { storageKey, }, - password + password, ); this._storageKey = storageKey; this.callbackManager.onStorageReady(); @@ -125,7 +125,7 @@ export class StorageService implements OnLock { async load( key: string, - customEncryptionKey?: string + customEncryptionKey?: string, ): Promise { const result = await browser.storage.local.get(key); @@ -171,7 +171,7 @@ export class StorageService implements OnLock { if (deserializedData) { return migrateToLatest(key, deserializedData, (migratedData) => - this.save(key, migratedData, customEncryptionKey) + this.save(key, migratedData, customEncryptionKey), ); } diff --git a/src/background/services/storage/handlers/resetExtensionState.ts b/src/background/services/storage/handlers/resetExtensionState.ts index 00eae4e33..81f8f1fc6 100644 --- a/src/background/services/storage/handlers/resetExtensionState.ts +++ b/src/background/services/storage/handlers/resetExtensionState.ts @@ -19,7 +19,7 @@ export class ResetExtensionStateHandler implements HandlerType { constructor( private storageService: StorageService, private onboardingService: OnboardingService, - private analyticsService: AnalyticsService + private analyticsService: AnalyticsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { diff --git a/src/background/services/storage/schemaMigrations/migrations/accounts_v2.test.ts b/src/background/services/storage/schemaMigrations/migrations/accounts_v2.test.ts index 2480eaab1..8d4526136 100644 --- a/src/background/services/storage/schemaMigrations/migrations/accounts_v2.test.ts +++ b/src/background/services/storage/schemaMigrations/migrations/accounts_v2.test.ts @@ -45,7 +45,6 @@ describe('background/services/storage/schemaMigrations/migrations/accounts_v2', }); it('rejects incorrect inputs', () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { index, ...invalidInput } = validInput[0] ?? {}; const result = accounts_v2.previousSchema.validate(invalidInput); diff --git a/src/background/services/storage/schemaMigrations/migrations/accounts_v2.ts b/src/background/services/storage/schemaMigrations/migrations/accounts_v2.ts index 1931bde95..d563b2d4d 100644 --- a/src/background/services/storage/schemaMigrations/migrations/accounts_v2.ts +++ b/src/background/services/storage/schemaMigrations/migrations/accounts_v2.ts @@ -42,7 +42,7 @@ const previousSchema = Joi.array().items( active: Joi.boolean().required(), addressBTC: Joi.string(), addressC: Joi.string(), - }) + }), ); const up = async (accounts: PreviousSchema) => { @@ -68,7 +68,7 @@ const up = async (accounts: PreviousSchema) => { active: undefined, primary: [], imported: {}, - } + }, ); return { ...newData, version: VERSION }; diff --git a/src/background/services/storage/schemaMigrations/migrations/accounts_v3.test.ts b/src/background/services/storage/schemaMigrations/migrations/accounts_v3.test.ts index 184629cf3..cd8e8ae09 100644 --- a/src/background/services/storage/schemaMigrations/migrations/accounts_v3.test.ts +++ b/src/background/services/storage/schemaMigrations/migrations/accounts_v3.test.ts @@ -49,7 +49,6 @@ describe('background/services/storage/schemaMigrations/migrations/accounts_v3', }); it('should reject the wrong previous account schema input', () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { index, id, addressBTC, addressC, name, type, ...invalidInput } = validInput.primary[0] ?? {}; const result = accounts_v3.previousSchema.validate(invalidInput); diff --git a/src/background/services/storage/schemaMigrations/migrations/accounts_v3.ts b/src/background/services/storage/schemaMigrations/migrations/accounts_v3.ts index 3cc80a45f..25c4c6cb6 100644 --- a/src/background/services/storage/schemaMigrations/migrations/accounts_v3.ts +++ b/src/background/services/storage/schemaMigrations/migrations/accounts_v3.ts @@ -64,7 +64,7 @@ const previousSchema = Joi.object({ addressCoreEth: Joi.string(), }) .required() - .unknown() + .unknown(), ) .required(), imported: Joi.object().unknown(), diff --git a/src/background/services/storage/schemaMigrations/migrations/balances_v2.ts b/src/background/services/storage/schemaMigrations/migrations/balances_v2.ts index ba6373838..0d068d0c7 100644 --- a/src/background/services/storage/schemaMigrations/migrations/balances_v2.ts +++ b/src/background/services/storage/schemaMigrations/migrations/balances_v2.ts @@ -28,7 +28,7 @@ export type NewSchema = { const previousSchema = Joi.object(); export function transformTotalBalance( - totalBalance: PreviousSchema['totalBalance'] + totalBalance: PreviousSchema['totalBalance'], ): NewSchema['totalBalance'] { const newBalance: NewSchema['totalBalance'] = {}; diff --git a/src/background/services/storage/schemaMigrations/migrations/balances_v3.ts b/src/background/services/storage/schemaMigrations/migrations/balances_v3.ts index 654df7ec4..b97dcc829 100644 --- a/src/background/services/storage/schemaMigrations/migrations/balances_v3.ts +++ b/src/background/services/storage/schemaMigrations/migrations/balances_v3.ts @@ -28,10 +28,10 @@ const up = async (cache: PreviousSchema) => { const newPolygonBalances = Object.fromEntries( Object.entries(oldPolygonBalances).map(([address, addressBalances]) => { - const { MATIC, ...addressBalancesWithoutMatic } = addressBalances; // eslint-disable-line + const { MATIC, ...addressBalancesWithoutMatic } = addressBalances; return [address, addressBalancesWithoutMatic]; - }) + }), ); return { diff --git a/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.test.ts b/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.test.ts index 657a18d0c..d854240fd 100644 --- a/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.test.ts +++ b/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.test.ts @@ -65,7 +65,7 @@ describe('background/services/storage/schemaMigrations/migrations/unified_bridge it('accepts correct inputs', () => { expect( - unified_bridge_v2.previousSchema.validate(stateWithPendingTransfers) + unified_bridge_v2.previousSchema.validate(stateWithPendingTransfers), ).toEqual({ error: undefined, value: stateWithPendingTransfers, @@ -76,7 +76,7 @@ describe('background/services/storage/schemaMigrations/migrations/unified_bridge addresses: [], pendingTransfers: {}, version: 1, - }) + }), ).toEqual({ error: undefined, value: { @@ -87,7 +87,7 @@ describe('background/services/storage/schemaMigrations/migrations/unified_bridge }); expect( - unified_bridge_v2.previousSchema.validate({ pendingTransfers: {} }) + unified_bridge_v2.previousSchema.validate({ pendingTransfers: {} }), ).toEqual({ error: undefined, value: { pendingTransfers: {} }, @@ -182,11 +182,11 @@ describe('background/services/storage/schemaMigrations/migrations/unified_bridge }, }, version: 2, - } + }, ); expect( - await unified_bridge_v2.up({ addresses: ['0xTargetAddress'] }) + await unified_bridge_v2.up({ addresses: ['0xTargetAddress'] }), ).toStrictEqual({ pendingTransfers: {}, version: 2, diff --git a/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.ts b/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.ts index 19f4e5c4a..36442f637 100644 --- a/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.ts +++ b/src/background/services/storage/schemaMigrations/migrations/unified_bridge_v2.ts @@ -55,14 +55,14 @@ const previousSchema = Joi.object({ typeof value !== 'undefined' ) { return new Error( - `Expected bigint or number, received ${typeof value}` + `Expected bigint or number, received ${typeof value}`, ); } return value; }, 'bigint'), sourceChain: Joi.object({ chainId: Joi.string() }).unknown(true), - }).unknown(true) + }).unknown(true), ), }).unknown(true); @@ -83,7 +83,7 @@ const getUsdcAddressByChainId = (caipId: string) => { }; const up = async ( - unifiedBridgeState: PreviousSchema + unifiedBridgeState: PreviousSchema, ): Promise => { const { pendingTransfers: oldTransfers } = unifiedBridgeState; diff --git a/src/background/services/storage/schemaMigrations/migrations/wallet_storage_encryption_key_v2.test.ts b/src/background/services/storage/schemaMigrations/migrations/wallet_storage_encryption_key_v2.test.ts index 59129840c..9ab56a220 100644 --- a/src/background/services/storage/schemaMigrations/migrations/wallet_storage_encryption_key_v2.test.ts +++ b/src/background/services/storage/schemaMigrations/migrations/wallet_storage_encryption_key_v2.test.ts @@ -7,7 +7,7 @@ describe('background/services/storage/schemaMigrations/migrations/wallet_storage it('accepts correct inputs', () => { const result = wallet_storage_encryption_key_v2.previousSchema.validate( - validInputEncryptionKey + validInputEncryptionKey, ); expect(result).toEqual({ @@ -31,7 +31,7 @@ describe('background/services/storage/schemaMigrations/migrations/wallet_storage it('migrates to v2 successfully', async () => { const result = await wallet_storage_encryption_key_v2.up( - validInputEncryptionKey + validInputEncryptionKey, ); expect(result).toStrictEqual({ storageKey: validInputEncryptionKey, diff --git a/src/background/services/storage/schemaMigrations/migrations/wallet_v4/utils/getSecretsType.test.ts b/src/background/services/storage/schemaMigrations/migrations/wallet_v4/utils/getSecretsType.test.ts index cb23b4033..b869ca566 100644 --- a/src/background/services/storage/schemaMigrations/migrations/wallet_v4/utils/getSecretsType.test.ts +++ b/src/background/services/storage/schemaMigrations/migrations/wallet_v4/utils/getSecretsType.test.ts @@ -7,7 +7,7 @@ describe('getSecretsType()', () => { it('should throw an error', () => { const walletType = () => getSecretsType({}); expect(walletType).toThrow( - 'Cannot get the secret type for a primary account' + 'Cannot get the secret type for a primary account', ); }); diff --git a/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.test.ts b/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.test.ts index 59cdd1b88..3d987bd43 100644 --- a/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.test.ts +++ b/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.test.ts @@ -44,10 +44,9 @@ describe('background/services/storage/schemaMigrations/migrations/wallet_v4', () }); it('should throw an `invalid wallet type` error', async () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { xpub, ...rest } = validInput; expect(() => wallet_v4.up(rest)).rejects.toThrow( - 'Cannot get the secret type for a primary account' + 'Cannot get the secret type for a primary account', ); }); @@ -82,7 +81,7 @@ describe('background/services/storage/schemaMigrations/migrations/wallet_v4', () it('migrates to v4 successfully', async () => { const result = await wallet_v4.up(validInput); - // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { imported, ...restInput } = validInput; expect(result).toStrictEqual({ wallets: [ diff --git a/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.ts b/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.ts index 81ecec799..31d5950f6 100644 --- a/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.ts +++ b/src/background/services/storage/schemaMigrations/migrations/wallet_v4/wallet_v4.ts @@ -31,7 +31,7 @@ const previousSchema = Joi.object({ pubKeys: Joi.array().items( Joi.object({ evm: Joi.string().required(), - }).unknown() + }).unknown(), ), masterFingerprint: Joi.string().allow('').optional(), derivationPath: Joi.string() @@ -44,7 +44,6 @@ const previousSchema = Joi.object({ let walletId = ''; const up = async (walletStorage: PreviousSchema) => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { imported, version, ...rest } = walletStorage; walletId = WALLET_ID; const secretType = getSecretsType(walletStorage); @@ -52,15 +51,14 @@ const up = async (walletStorage: PreviousSchema) => { secretType === SecretType.Mnemonic ? 'Recovery Phrase' : secretType === SecretType.Seedless - ? 'Seedless' - : secretType === SecretType.Keystone - ? 'Keystone' - : 'Ledger'; + ? 'Seedless' + : secretType === SecretType.Keystone + ? 'Keystone' + : 'Ledger'; const newImported = {}; if (imported) { for (const [key, value] of Object.entries(imported)) { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { type, ...restData } = value; let newSecretType: SecretType | undefined; switch (type) { diff --git a/src/background/services/storage/schemaMigrations/schemaMigrations.test.ts b/src/background/services/storage/schemaMigrations/schemaMigrations.test.ts index b5e4d94bc..9563cfda8 100644 --- a/src/background/services/storage/schemaMigrations/schemaMigrations.test.ts +++ b/src/background/services/storage/schemaMigrations/schemaMigrations.test.ts @@ -146,7 +146,7 @@ describe('background/services/storage/migrations/migrations', () => { }; await expect( - migrateToLatest('missingSchemaKey', data) + migrateToLatest('missingSchemaKey', data), ).resolves.toStrictEqual(data); }); @@ -158,7 +158,7 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(upToDateKey, data); expect( - MOCK_SCHEMA_MAP[upToDateKey].migrations[0]?.migration.up + MOCK_SCHEMA_MAP[upToDateKey].migrations[0]?.migration.up, ).not.toHaveBeenCalled(); expect(result).toStrictEqual(data); }); @@ -170,13 +170,13 @@ describe('background/services/storage/migrations/migrations', () => { }; await expect( - migrateToLatest(outDatedKeyWithInvalidSchema, data) + migrateToLatest(outDatedKeyWithInvalidSchema, data), ).rejects.toThrow( - `Error while upgrading ${outDatedKeyWithInvalidSchema} to version 2` + `Error while upgrading ${outDatedKeyWithInvalidSchema} to version 2`, ); expect( MOCK_SCHEMA_MAP[outDatedKeyWithInvalidSchema].migrations[0]?.migration - .up + .up, ).not.toHaveBeenCalled(); }); @@ -185,7 +185,7 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithArrayInput, data); expect( - MOCK_SCHEMA_MAP[outDatedKeyWithArrayInput].migrations[0]?.migration.up + MOCK_SCHEMA_MAP[outDatedKeyWithArrayInput].migrations[0]?.migration.up, ).toHaveBeenCalledWith(data); expect(result).toStrictEqual({ ...data[0], version: 2 }); }); @@ -196,7 +196,7 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithPrimitiveInput, data); expect( MOCK_SCHEMA_MAP[outDatedKeyWithPrimitiveInput].migrations[0]?.migration - .up + .up, ).toHaveBeenCalledWith(data); expect(result).toStrictEqual({ data: 'some-data-string', version: 2 }); }); @@ -207,7 +207,7 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithPrimitiveInput, data); expect( MOCK_SCHEMA_MAP[outDatedKeyWithPrimitiveInput].migrations[0]?.migration - .up + .up, ).toHaveBeenCalledWith(data); expect(result).toStrictEqual({ data: 12341234, version: 2 }); }); @@ -217,7 +217,7 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithPrimitiveInput, data); expect( MOCK_SCHEMA_MAP[outDatedKeyWithPrimitiveInput].migrations[0]?.migration - .up + .up, ).toHaveBeenCalledWith(data); expect(result).toStrictEqual({ data: false, version: 2 }); }); @@ -230,10 +230,12 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithCorrectOrder, data); expect( - MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[0]?.migration.up + MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[0]?.migration + .up, ).toHaveBeenCalledWith({ ...data, version: 1 }); expect( - MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[1]?.migration.up + MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[1]?.migration + .up, ).toHaveBeenCalledWith({ ...data, version: 2 }); expect(result).toStrictEqual({ ...data, version: 3 }); }); @@ -246,10 +248,12 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithCorrectOrder, data); expect( - MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[0]?.migration.up + MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[0]?.migration + .up, ).not.toHaveBeenCalled(); expect( - MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[1]?.migration.up + MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].migrations[1]?.migration + .up, ).toHaveBeenCalledWith({ ...data, version: 2 }); expect(result).toStrictEqual({ ...data, version: 3 }); }); @@ -263,11 +267,11 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithIncorrectOrder, data); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectOrder].migrations[0]?.migration - .up + .up, ).toHaveBeenCalledWith({ ...data, version: 2 }); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectOrder].migrations[1]?.migration - .up + .up, ).toHaveBeenCalledWith({ ...data, version: 1 }); expect(result).toStrictEqual({ ...data, version: 3 }); }); @@ -281,11 +285,11 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest(outDatedKeyWithIncorrectOrder, data); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectOrder].migrations[0]?.migration - .up + .up, ).toHaveBeenCalledWith({ ...data, version: 2 }); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectOrder].migrations[1]?.migration - .up + .up, ).not.toHaveBeenCalled(); expect(result).toStrictEqual({ ...data, version: 3 }); }); @@ -298,19 +302,19 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest( outDatedKeyWithIncorrectVersion, - data + data, ); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectVersion].migrations[0] - ?.migration.up + ?.migration.up, ).toHaveBeenCalledWith({ ...data, version: 1 }); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectVersion].migrations[1] - ?.migration.up + ?.migration.up, ).toHaveBeenCalledWith({ ...data, version: 2 }); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectVersion].migrations[2] - ?.migration.up + ?.migration.up, ).not.toHaveBeenCalled(); expect(result).toStrictEqual({ ...data, version: 3 }); }); @@ -323,19 +327,19 @@ describe('background/services/storage/migrations/migrations', () => { const result = await migrateToLatest( outDatedKeyWithIncorrectVersion, - data + data, ); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectVersion].migrations[0] - ?.migration.up + ?.migration.up, ).not.toHaveBeenCalled(); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectVersion].migrations[1] - ?.migration.up + ?.migration.up, ).toHaveBeenCalledWith({ ...data, version: 2 }); expect( MOCK_SCHEMA_MAP[outDatedKeyWithIncorrectVersion].migrations[2] - ?.migration.up + ?.migration.up, ).not.toHaveBeenCalled(); expect(result).toStrictEqual({ ...data, version: 3 }); }); @@ -357,7 +361,7 @@ describe('background/services/storage/migrations/migrations', () => { const data = [1, 2, 3]; expect( - getDataWithSchemaVersion(outDatedKeyWithCorrectOrder, data) + getDataWithSchemaVersion(outDatedKeyWithCorrectOrder, data), ).toStrictEqual(data); }); @@ -367,7 +371,7 @@ describe('background/services/storage/migrations/migrations', () => { }; expect(getDataWithSchemaVersion('missingSchemaKey', data)).toStrictEqual( - data + data, ); }); @@ -378,7 +382,7 @@ describe('background/services/storage/migrations/migrations', () => { }; expect( - getDataWithSchemaVersion(outDatedKeyWithCorrectOrder, data) + getDataWithSchemaVersion(outDatedKeyWithCorrectOrder, data), ).toStrictEqual(data); }); @@ -388,7 +392,7 @@ describe('background/services/storage/migrations/migrations', () => { }; expect( - getDataWithSchemaVersion(outDatedKeyWithCorrectOrder, data) + getDataWithSchemaVersion(outDatedKeyWithCorrectOrder, data), ).toStrictEqual({ ...data, version: MOCK_SCHEMA_MAP[outDatedKeyWithCorrectOrder].latestVersion, diff --git a/src/background/services/storage/schemaMigrations/schemaMigrations.ts b/src/background/services/storage/schemaMigrations/schemaMigrations.ts index d391b1007..903df68dc 100644 --- a/src/background/services/storage/schemaMigrations/schemaMigrations.ts +++ b/src/background/services/storage/schemaMigrations/schemaMigrations.ts @@ -11,9 +11,9 @@ export const getDataWithSchemaVersion = (key: string, data: T) => { export const migrateToLatest = async ( key: keyof SchemaMap, data: T & { version?: number }, - onMigrationApplied?: (data: T) => Promise + onMigrationApplied?: (data: T) => Promise, ): Promise => { - const currentVersion = Array.isArray(data) ? 1 : data.version ?? 1; + const currentVersion = Array.isArray(data) ? 1 : (data.version ?? 1); const schema = SCHEMA_MAP[key] as SchemaMap[keyof SchemaMap] | undefined; if (!schema || schema.latestVersion <= currentVersion) { @@ -39,7 +39,7 @@ export const migrateToLatest = async ( if (validationError) { throw new Error( - `Error while upgrading ${key} to version ${currentMigration.version}` + `Error while upgrading ${key} to version ${currentMigration.version}`, ); } @@ -48,8 +48,8 @@ export const migrateToLatest = async ( Promise.resolve( typeof data === 'object' && !Array.isArray(data) && data !== null ? { ...data, version: currentVersion } - : data - ) + : data, + ), ); if (onMigrationApplied) { diff --git a/src/background/services/storage/utils/crypto.e2e.test.ts b/src/background/services/storage/utils/crypto.e2e.test.ts index 7b56d47fc..0c9f25be6 100644 --- a/src/background/services/storage/utils/crypto.e2e.test.ts +++ b/src/background/services/storage/utils/crypto.e2e.test.ts @@ -21,7 +21,7 @@ describe('background/services/storage/utils/crypto.e2e', () => { salt: Uint8Array.from(cypher.salt), nonce: Uint8Array.from(cypher.nonce), keyDerivationVersion: cypher.keyDerivationVersion, - }) + }), ).toEqual(data); }); @@ -43,7 +43,7 @@ describe('background/services/storage/utils/crypto.e2e', () => { salt: Uint8Array.from(cypher.salt), nonce: Uint8Array.from(cypher.nonce), keyDerivationVersion: cypher.keyDerivationVersion, - }) + }), ).rejects.toEqual(new Error('decryption failed')); }); }); @@ -62,7 +62,7 @@ describe('background/services/storage/utils/crypto.e2e', () => { cypher: Uint8Array.from(cypher.cypher), encryptionKey, nonce: Uint8Array.from(cypher.nonce), - }) + }), ).toEqual(data); }); @@ -83,7 +83,7 @@ describe('background/services/storage/utils/crypto.e2e', () => { cypher: Uint8Array.from(cypher.cypher), encryptionKey, nonce: Uint8Array.from(cypher.nonce), - }) + }), ).rejects.toEqual(new Error('decryption failed')); }); }); diff --git a/src/background/services/storage/utils/crypto.test.ts b/src/background/services/storage/utils/crypto.test.ts index 1a044eaa3..97c59dc78 100644 --- a/src/background/services/storage/utils/crypto.test.ts +++ b/src/background/services/storage/utils/crypto.test.ts @@ -111,7 +111,7 @@ describe('background/services/storage/utils/crypto.ts', () => { pass: encryptionPassword, time: 3, type: argon2Browser.ArgonType.Argon2id, - }) + }), ); }); }); @@ -137,16 +137,16 @@ describe('background/services/storage/utils/crypto.ts', () => { it('only accepts 32 and 64 byte long keys', async () => { await expect( - encryptWithKey({ secret, encryptionKey: new Uint8Array(4) }) + encryptWithKey({ secret, encryptionKey: new Uint8Array(4) }), ).rejects.toThrow(new Error('invalid encryption key')); await expect( - encryptWithKey({ secret, encryptionKey: new Uint8Array(33) }) + encryptWithKey({ secret, encryptionKey: new Uint8Array(33) }), ).rejects.toThrow(new Error('invalid encryption key')); await expect( encryptWithKey({ secret, encryptionKey: crypto.getRandomValues(new Uint8Array(65)), - }) + }), ).rejects.toThrow(new Error('invalid encryption key')); }); @@ -204,17 +204,17 @@ describe('background/services/storage/utils/crypto.ts', () => { it('only accepts 32 and 64 byte long keys', async () => { await expect( - decryptWithKey({ cypher, encryptionKey: new Uint8Array(4), nonce }) + decryptWithKey({ cypher, encryptionKey: new Uint8Array(4), nonce }), ).rejects.toThrow(new Error('invalid decryption key')); await expect( - decryptWithKey({ cypher, encryptionKey: new Uint8Array(33), nonce }) + decryptWithKey({ cypher, encryptionKey: new Uint8Array(33), nonce }), ).rejects.toThrow(new Error('invalid decryption key')); await expect( decryptWithKey({ cypher, encryptionKey: crypto.getRandomValues(new Uint8Array(65)), nonce, - }) + }), ).rejects.toThrow(new Error('invalid decryption key')); }); @@ -258,17 +258,17 @@ describe('background/services/storage/utils/crypto.ts', () => { it('only accepts 32 and 64 byte long keys', async () => { await expect( - decryptWithKey({ cypher, encryptionKey: new Uint8Array(4), nonce }) + decryptWithKey({ cypher, encryptionKey: new Uint8Array(4), nonce }), ).rejects.toThrow(new Error('invalid decryption key')); await expect( - decryptWithKey({ cypher, encryptionKey: new Uint8Array(33), nonce }) + decryptWithKey({ cypher, encryptionKey: new Uint8Array(33), nonce }), ).rejects.toThrow(new Error('invalid decryption key')); await expect( decryptWithKey({ cypher, encryptionKey: crypto.getRandomValues(new Uint8Array(65)), nonce, - }) + }), ).rejects.toThrow(new Error('invalid decryption key')); }); @@ -329,7 +329,7 @@ describe('background/services/storage/utils/crypto.ts', () => { keyDerivationVersion: KeyDerivationVersion.V2, }); fail('Should have thrown an exception'); - } catch (error) { + } catch (_err) { expect(Buffer.from).toHaveBeenCalledTimes(0); expect(Uint8Array.prototype.fill).toHaveBeenCalledTimes(1); expect(Uint8Array.prototype.fill).toHaveBeenCalledWith(0); diff --git a/src/background/services/storage/utils/crypto.ts b/src/background/services/storage/utils/crypto.ts index 5a90741dd..4f8bae994 100644 --- a/src/background/services/storage/utils/crypto.ts +++ b/src/background/services/storage/utils/crypto.ts @@ -10,7 +10,7 @@ import argon2Browser from 'argon2-browser'; async function deriveKey( password: string | Uint8Array, salt: Uint8Array, - keyDerivationVersion: KeyDerivationVersion + keyDerivationVersion: KeyDerivationVersion, ): Promise { // takes about 150ms on an i9 mbp, bumping it up to 2 ** 16 would be better but it slows down UX way to much @@ -51,7 +51,7 @@ export async function encryptWithPassword({ const encryptionKey = await deriveKey( password, salt, - KeyDerivationVersion.V2 + KeyDerivationVersion.V2, ); const { cypher, nonce } = await encryptWithKey({ secret, encryptionKey }); diff --git a/src/background/services/tokens/TokenManagerService.ts b/src/background/services/tokens/TokenManagerService.ts index 5606187f3..e71a3c021 100644 --- a/src/background/services/tokens/TokenManagerService.ts +++ b/src/background/services/tokens/TokenManagerService.ts @@ -17,11 +17,11 @@ import { EnsureDefined } from '@src/background/models'; export class TokenManagerService { constructor( private settingsService: SettingsService, - private networkService: NetworkService + private networkService: NetworkService, ) {} async getCustomTokensForNetwork( - network: Network + network: Network, ): Promise { const settings = await this.settingsService.getSettings(); return Object.values(settings.customTokens[network.chainId] || {}) || []; @@ -34,7 +34,7 @@ export class TokenManagerService { async getTokenData( tokenAddress: string, - network: Network + network: Network, ): Promise | null> { if (!network || network.vmName !== NetworkVMType.EVM) { throw new Error('No network'); diff --git a/src/background/services/tokens/handlers/getTokenList.ts b/src/background/services/tokens/handlers/getTokenList.ts index f4501a253..0ca06806b 100644 --- a/src/background/services/tokens/handlers/getTokenList.ts +++ b/src/background/services/tokens/handlers/getTokenList.ts @@ -21,7 +21,7 @@ export class GetTokensListHandler implements HandlerType { const [chainId, disallowedAssets] = request.params; const [tokens, err] = await resolve( - this.tokenManagerService.getTokensByChainId(chainId) + this.tokenManagerService.getTokensByChainId(chainId), ); if (err) { diff --git a/src/background/services/tokens/utils/isTokenSupported.ts b/src/background/services/tokens/utils/isTokenSupported.ts index 347c441ea..8d361ff82 100644 --- a/src/background/services/tokens/utils/isTokenSupported.ts +++ b/src/background/services/tokens/utils/isTokenSupported.ts @@ -4,10 +4,10 @@ import { SettingsState } from '../../settings/models'; export async function isTokenSupported( tokenAddress: string, network: Network, - settings: SettingsState + settings: SettingsState, ) { const tokenExistInNetwork = network.tokens?.find( - (token) => token.address.toLowerCase() === tokenAddress.toLowerCase() + (token) => token.address.toLowerCase() === tokenAddress.toLowerCase(), ); return ( tokenExistInNetwork || diff --git a/src/background/services/unifiedBridge/UnifiedBridgeService.test.ts b/src/background/services/unifiedBridge/UnifiedBridgeService.test.ts index 6510ad03c..4c7256f12 100644 --- a/src/background/services/unifiedBridge/UnifiedBridgeService.test.ts +++ b/src/background/services/unifiedBridge/UnifiedBridgeService.test.ts @@ -82,7 +82,7 @@ describe('src/background/services/unifiedBridge/UnifiedBridgeService', () => { expect(createUnifiedBridgeService).toHaveBeenCalledWith( expect.objectContaining({ environment: Environment.PROD, - }) + }), ); networkService.isMainnet.mockReturnValue(false); @@ -93,7 +93,7 @@ describe('src/background/services/unifiedBridge/UnifiedBridgeService', () => { expect(createUnifiedBridgeService).toHaveBeenCalledWith( expect.objectContaining({ environment: Environment.TEST, - }) + }), ); }); @@ -159,14 +159,14 @@ describe('src/background/services/unifiedBridge/UnifiedBridgeService', () => { const bridgeService = new UnifiedBridgeService( networkService, storageService, - flagsService + flagsService, ); await bridgeService.onStorageReady(); expect(trackTransfer).toHaveBeenCalledTimes(1); expect(trackTransfer).toHaveBeenCalledWith( - expect.objectContaining({ bridgeTransfer: { sourceTxHash: '0x2345' } }) + expect.objectContaining({ bridgeTransfer: { sourceTxHash: '0x2345' } }), ); }); diff --git a/src/background/services/unifiedBridge/UnifiedBridgeService.ts b/src/background/services/unifiedBridge/UnifiedBridgeService.ts index 85cfc205d..94a491f2c 100644 --- a/src/background/services/unifiedBridge/UnifiedBridgeService.ts +++ b/src/background/services/unifiedBridge/UnifiedBridgeService.ts @@ -53,10 +53,10 @@ export class UnifiedBridgeService implements OnStorageReady { constructor( private networkService: NetworkService, private storageService: StorageService, - private featureFlagService: FeatureFlagService + private featureFlagService: FeatureFlagService, ) { this.#flagStates = this.#getTrackedFlags( - this.featureFlagService.featureFlags + this.featureFlagService.featureFlags, ); this.#recreateService(); @@ -76,22 +76,22 @@ export class UnifiedBridgeService implements OnStorageReady { this.#flagStates = newFlags; this.#recreateService(); } - } + }, ); } #getTrackedFlags(flags: FeatureFlags): Partial { return Object.fromEntries( Object.entries(flags).filter(([flag]) => - UNIFIED_BRIDGE_TRACKED_FLAGS.includes(flag as FeatureGates) - ) + UNIFIED_BRIDGE_TRACKED_FLAGS.includes(flag as FeatureGates), + ), ); } async onStorageReady() { const state = (await this.storageService.load( - UNIFIED_BRIDGE_STATE_STORAGE_KEY + UNIFIED_BRIDGE_STATE_STORAGE_KEY, )) ?? UNIFIED_BRIDGE_DEFAULT_STATE; this.#saveState(state); @@ -114,16 +114,16 @@ export class UnifiedBridgeService implements OnStorageReady { } #getBridgeInitializers( - bitcoinProvider: BitcoinProvider + bitcoinProvider: BitcoinProvider, ): BridgeInitializer[] { return getEnabledBridgeTypes(this.#flagStates).map((type) => - this.#getInitializerForBridgeType(type, bitcoinProvider) + this.#getInitializerForBridgeType(type, bitcoinProvider), ); } #getInitializerForBridgeType( type: BridgeType, - bitcoinProvider: BitcoinProvider + bitcoinProvider: BitcoinProvider, ): BridgeInitializer { // This backend service is only used for transaction tracking purposes, // therefore we don't need to provide true signing capabilities. @@ -170,7 +170,7 @@ export class UnifiedBridgeService implements OnStorageReady { environment, enabledBridgeServices: await getEnabledBridgeServices( environment, - this.#getBridgeInitializers(bitcoinProvider) + this.#getBridgeInitializers(bitcoinProvider), ), }); this.#failedInitAttempts = 0; @@ -189,7 +189,7 @@ export class UnifiedBridgeService implements OnStorageReady { console.log( `Initialization of UnifiedBridgeService failed, attempt #${ this.#failedInitAttempts - }. Retry in ${delay / 1000}s` + }. Retry in ${delay / 1000}s`, ); await wait(delay); @@ -217,9 +217,9 @@ export class UnifiedBridgeService implements OnStorageReady { // Just log that this happened. This is edge-casey, but technically possible. sentryCaptureException( new Error( - `UnifiedBridge - tracking attempted with no service insantiated.` + `UnifiedBridge - tracking attempted with no service insantiated.`, ), - SentryExceptionTypes.UNIFIED_BRIDGE + SentryExceptionTypes.UNIFIED_BRIDGE, ); return; } @@ -232,7 +232,7 @@ export class UnifiedBridgeService implements OnStorageReady { }); result.then((completedTransfer) => - this.updatePendingTransfer(completedTransfer) + this.updatePendingTransfer(completedTransfer), ); } @@ -246,7 +246,7 @@ export class UnifiedBridgeService implements OnStorageReady { if (transfer.errorCode) { sentryCaptureException( new Error(`Bridge unsucessful. Error code: ${transfer.errorCode}`), - SentryExceptionTypes.UNIFIED_BRIDGE + SentryExceptionTypes.UNIFIED_BRIDGE, ); } @@ -266,7 +266,7 @@ export class UnifiedBridgeService implements OnStorageReady { try { await this.storageService.save( UNIFIED_BRIDGE_STATE_STORAGE_KEY, - newState + newState, ); } catch { // May be called before extension is unlocked. Ignore. diff --git a/src/background/services/unifiedBridge/events/eventFilters.ts b/src/background/services/unifiedBridge/events/eventFilters.ts index e2e5e69c3..51bbbcffd 100644 --- a/src/background/services/unifiedBridge/events/eventFilters.ts +++ b/src/background/services/unifiedBridge/events/eventFilters.ts @@ -6,11 +6,11 @@ import { } from '../models'; export const isUnifiedBridgeStateUpdate = ( - ev: ExtensionConnectionEvent + ev: ExtensionConnectionEvent, ): ev is UnifiedBridgeStateUpdateEvent => ev.name === UnifiedBridgeEvent.StateUpdated; export const isUnifiedBridgeTransferStepChanged = ( - ev: ExtensionConnectionEvent + ev: ExtensionConnectionEvent, ): ev is UnifiedBridgeTransferStepChangeEvent => ev.name === UnifiedBridgeEvent.TransferStepChange; diff --git a/src/background/services/unifiedBridge/events/unifiedBridgeEvents.ts b/src/background/services/unifiedBridge/events/unifiedBridgeEvents.ts index eb9429418..6d9b54e5d 100644 --- a/src/background/services/unifiedBridge/events/unifiedBridgeEvents.ts +++ b/src/background/services/unifiedBridge/events/unifiedBridgeEvents.ts @@ -20,7 +20,7 @@ export class UnifiedBridgeEvents implements ExtensionEventEmitter { name: UnifiedBridgeEvent.StateUpdated, value: state, }); - } + }, ); this.unifiedBridgeService.addListener( @@ -30,7 +30,7 @@ export class UnifiedBridgeEvents implements ExtensionEventEmitter { name: UnifiedBridgeEvent.TransferStepChange, value: state, }); - } + }, ); this.unifiedBridgeService.addListener( @@ -40,7 +40,7 @@ export class UnifiedBridgeEvents implements ExtensionEventEmitter { name: UnifiedBridgeEvent.AssetsUpdated, value: assets, }); - } + }, ); } @@ -49,7 +49,7 @@ export class UnifiedBridgeEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/wallet/WalletService.test.ts b/src/background/services/wallet/WalletService.test.ts index 6786db4b0..8f994a2d5 100644 --- a/src/background/services/wallet/WalletService.test.ts +++ b/src/background/services/wallet/WalletService.test.ts @@ -91,7 +91,7 @@ describe('background/services/wallet/WalletService.ts', () => { const ledgerSignerMock = Object.create(Avalanche.LedgerSigner.prototype); const evmLedgerSignerMock = Object.create(LedgerSigner.prototype); const ledgerSimpleSignerMock = Object.create( - Avalanche.SimpleLedgerSigner.prototype + Avalanche.SimpleLedgerSigner.prototype, ); const keystoneWalletMock = Object.create(KeystoneWallet.prototype); const walletConnectSignerMock = Object.create(WalletConnectSigner.prototype); @@ -105,7 +105,7 @@ describe('background/services/wallet/WalletService.ts', () => { const mockMnemonicWallet = ( additionalData = {}, - account?: Partial + account?: Partial, ) => { const data = { secretType: SecretType.Mnemonic, @@ -138,7 +138,7 @@ describe('background/services/wallet/WalletService.ts', () => { const mockLedgerWallet = ( additionalData = {}, - account?: Partial + account?: Partial, ) => { const data = { secretType: SecretType.Ledger, @@ -170,7 +170,7 @@ describe('background/services/wallet/WalletService.ts', () => { const mockLedgerLiveWallet = ( additionalData = {}, - account?: Partial + account?: Partial, ) => { const data = { secretType: SecretType.LedgerLive, @@ -201,7 +201,7 @@ describe('background/services/wallet/WalletService.ts', () => { const mockSeedlessWallet = ( additionalData: any = {}, - account?: Partial + account?: Partial, ) => { const data = { secretType: SecretType.Seedless, @@ -242,7 +242,7 @@ describe('background/services/wallet/WalletService.ts', () => { keystoneService = new KeystoneService(); walletConnectService = new WalletConnectService( - new WalletConnectStorage({} as any) + new WalletConnectStorage({} as any), ); fireblocksService = new FireblocksService({} as any); @@ -250,7 +250,7 @@ describe('background/services/wallet/WalletService.ts', () => { secretsService.getPrimaryWalletsDetails = jest.fn().mockResolvedValue([]); - getAddressMock = jest.fn().mockImplementation((pubkey, chain) => { + getAddressMock = jest.fn().mockImplementation((_pubkey, chain) => { return `${chain}-`; }); @@ -269,11 +269,11 @@ describe('background/services/wallet/WalletService.ts', () => { walletConnectService, fireblocksService, secretsService, - accountsService + accountsService, ); (networkService.getAvalanceProviderXP as jest.Mock).mockReturnValue( - Avalanche.JsonRpcProvider.getDefaultFujiProvider() + Avalanche.JsonRpcProvider.getDefaultFujiProvider(), ); }); @@ -355,7 +355,7 @@ describe('background/services/wallet/WalletService.ts', () => { ] as any); await expect(walletService.onUnlock()).rejects.toThrow( - 'Wallet initialization failed, no key found' + 'Wallet initialization failed, no key found', ); }); }); @@ -364,7 +364,7 @@ describe('background/services/wallet/WalletService.ts', () => { it('stores the data and invokes onUnlock', async () => { const onUnlockSpy = jest.spyOn(walletService as any, 'onUnlock'); (getDerivationPath as jest.Mock).mockReturnValueOnce( - DerivationPath.BIP44 + DerivationPath.BIP44, ); await walletService.init({ @@ -382,7 +382,7 @@ describe('background/services/wallet/WalletService.ts', () => { xpub: 'xpub', xpubXP: 'xpubXP', derivationPath: DerivationPath.BIP44, - }) + }), ); expect(onUnlockSpy).toHaveBeenCalled(); }); @@ -396,14 +396,14 @@ describe('background/services/wallet/WalletService.ts', () => { } as AddPrimaryWalletSecrets; (getDerivationPath as jest.Mock).mockReturnValueOnce( - DerivationPath.BIP44 + DerivationPath.BIP44, ); expect( walletService.addPrimaryWallet({ ...params, - }) + }), ).rejects.toThrow( - 'Mnemonic or xpub or pubKey is required to create a new wallet!' + 'Mnemonic or xpub or pubKey is required to create a new wallet!', ); }); it('should throw `ledger live` error', () => { @@ -412,12 +412,12 @@ describe('background/services/wallet/WalletService.ts', () => { } as AddPrimaryWalletSecrets; (getDerivationPath as jest.Mock).mockReturnValueOnce( - DerivationPath.BIP44 + DerivationPath.BIP44, ); expect( walletService.addPrimaryWallet({ ...params, - }) + }), ).rejects.toThrow('PubKey is required to create a new wallet!'); }); it('should throw generic error', () => { @@ -426,14 +426,14 @@ describe('background/services/wallet/WalletService.ts', () => { } as AddPrimaryWalletSecrets; (getDerivationPath as jest.Mock).mockReturnValueOnce( - DerivationPath.BIP44 + DerivationPath.BIP44, ); expect( walletService.addPrimaryWallet({ ...params, - }) + }), ).rejects.toThrow( - 'Mnemonic or xpub or pubKey is required to create a new wallet!' + 'Mnemonic or xpub or pubKey is required to create a new wallet!', ); }); }); @@ -446,13 +446,13 @@ describe('background/services/wallet/WalletService.ts', () => { secretType: SecretType.Mnemonic, } as AddPrimaryWalletSecrets; (getDerivationPath as jest.Mock).mockReturnValueOnce( - DerivationPath.BIP44 + DerivationPath.BIP44, ); await walletService.addPrimaryWallet({ ...params, }); expect(secretsService.addSecrets).toHaveBeenCalledWith( - expect.objectContaining(params) + expect.objectContaining(params), ); }); }); @@ -483,7 +483,7 @@ describe('background/services/wallet/WalletService.ts', () => { getWalletSpy.mockResolvedValueOnce(undefined); await expect( - walletService.sign(txMock, networkMock, tabId) + walletService.sign(txMock, networkMock, tabId), ).rejects.toThrow('Wallet not found'); }); @@ -491,7 +491,7 @@ describe('background/services/wallet/WalletService.ts', () => { getWalletSpy.mockResolvedValueOnce(walletMock); await expect( - walletService.sign(btcTxMock, networkMock, tabId) + walletService.sign(btcTxMock, networkMock, tabId), ).rejects.toThrow('Signing error, wrong network'); }); @@ -499,7 +499,7 @@ describe('background/services/wallet/WalletService.ts', () => { getWalletSpy.mockResolvedValueOnce(btcWalletMock); await expect( - walletService.sign(txMock, networkMock, tabId) + walletService.sign(txMock, networkMock, tabId), ).rejects.toThrow('Signing error, wrong network'); }); @@ -513,11 +513,11 @@ describe('background/services/wallet/WalletService.ts', () => { const { signedTx } = await walletService.sign( btcTxMock, networkMock, - tabId + tabId, ); expect(btcWalletMock.signTx).toHaveBeenCalledWith( btcTxMock.inputs, - btcTxMock.outputs + btcTxMock.outputs, ); expect(signedTx).toBe(buffer.toString('hex')); }); @@ -530,16 +530,16 @@ describe('background/services/wallet/WalletService.ts', () => { btcKeystoneWalletMock.signTx = jest.fn().mockResolvedValueOnce(tx); getWalletSpy.mockResolvedValueOnce(btcKeystoneWalletMock); (networkService.getBitcoinProvider as jest.Mock).mockResolvedValueOnce( - bitcoinProviderMock + bitcoinProviderMock, ); const { signedTx } = await walletService.sign( btcTxMock, networkMock, - tabId + tabId, ); expect(btcKeystoneWalletMock.signTx).toHaveBeenCalledWith( btcTxMock.inputs, - btcTxMock.outputs + btcTxMock.outputs, ); expect(signedTx).toBe(buffer.toString('hex')); }); @@ -552,22 +552,22 @@ describe('background/services/wallet/WalletService.ts', () => { btcLedgerWalletMock.signTx = jest.fn().mockResolvedValueOnce(tx); getWalletSpy.mockResolvedValueOnce(btcLedgerWalletMock); (networkService.getBitcoinProvider as jest.Mock).mockResolvedValueOnce( - bitcoinProviderMock + bitcoinProviderMock, ); (prepareBtcTxForLedger as jest.Mock).mockReturnValueOnce(btcTxMock); const { signedTx } = await walletService.sign( btcTxMock, networkMock, - tabId + tabId, ); expect(prepareBtcTxForLedger).toHaveBeenCalledWith( btcTxMock, - bitcoinProviderMock + bitcoinProviderMock, ); expect(btcLedgerWalletMock.signTx).toHaveBeenCalledWith( btcTxMock.inputs, - btcTxMock.outputs + btcTxMock.outputs, ); expect(signedTx).toBe(buffer.toString('hex')); }); @@ -631,7 +631,7 @@ describe('background/services/wallet/WalletService.ts', () => { getWalletSpy.mockResolvedValueOnce(btcWalletMock); await expect( - walletService.sign(avalancheTxMock, networkMock, tabId) + walletService.sign(avalancheTxMock, networkMock, tabId), ).rejects.toThrow('Signing error, wrong network'); }); @@ -642,7 +642,7 @@ describe('background/services/wallet/WalletService.ts', () => { const { signedTx } = await walletService.sign( avalancheTxMock, networkMock, - tabId + tabId, ); expect(signedTx).toEqual(JSON.stringify(unsignedTxJSON)); @@ -650,7 +650,7 @@ describe('background/services/wallet/WalletService.ts', () => { { tx: unsignedTxMock, }, - undefined + undefined, ); }); @@ -663,7 +663,7 @@ describe('background/services/wallet/WalletService.ts', () => { const { signedTx } = await walletService.sign( avalancheTxMock, networkMock, - tabId + tabId, ); expect(signedTx).toEqual(JSON.stringify(unsignedTxJSON)); @@ -673,7 +673,7 @@ describe('background/services/wallet/WalletService.ts', () => { externalIndices: avalancheTxMock.externalIndices, internalIndices: avalancheTxMock.internalIndices, }, - undefined + undefined, ); }); @@ -688,7 +688,7 @@ describe('background/services/wallet/WalletService.ts', () => { const { signedTx } = await walletService.sign( avalancheTxMock, networkMock, - tabId + tabId, ); expect(signedTx).toEqual(JSON.stringify(unsignedTxJSON)); @@ -697,7 +697,7 @@ describe('background/services/wallet/WalletService.ts', () => { tx: unsignedTxMock, transport: transportMock, }, - undefined + undefined, ); }); @@ -710,7 +710,7 @@ describe('background/services/wallet/WalletService.ts', () => { const { signedTx } = await walletService.sign( avalancheTxMock, networkMock, - tabId + tabId, ); expect(signedTx).toEqual(JSON.stringify(unsignedTxJSON)); @@ -719,7 +719,7 @@ describe('background/services/wallet/WalletService.ts', () => { tx: unsignedTxMock, transport: transportMock, }, - undefined + undefined, ); }); @@ -732,7 +732,7 @@ describe('background/services/wallet/WalletService.ts', () => { const { signedTx } = await walletService.sign( avalancheTxMock, networkMock, - tabId + tabId, ); expect(signedTx).toEqual(JSON.stringify(unsignedTxJSON)); @@ -832,13 +832,13 @@ describe('background/services/wallet/WalletService.ts', () => { walletService.signMessage(MessageType.ETH_SIGN, { ...action, displayData: { messageParams: { data: 'data' } } as any, - }) + }), ).resolves.toBe('0x00001'); expect(evmLedgerSignerMock.signMessage).toHaveBeenCalledTimes(1); expect(evmLedgerSignerMock.signMessage).toHaveBeenCalledWith('data'); await expect( - walletService.signMessage(MessageType.PERSONAL_SIGN, action) + walletService.signMessage(MessageType.PERSONAL_SIGN, action), ).resolves.toBe('0x00002'); expect(evmLedgerSignerMock.signMessage).toHaveBeenCalledTimes(2); expect(evmLedgerSignerMock.signMessage).toHaveBeenNthCalledWith(2, {}); @@ -865,13 +865,13 @@ describe('background/services/wallet/WalletService.ts', () => { }, }, } as any, - }) + }), ).resolves.toBe('0x00001'); expect(evmLedgerSignerMock.signTypedData).toHaveBeenCalledTimes(1); expect(evmLedgerSignerMock.signTypedData).toHaveBeenCalledWith( { name: 'domain' }, { types: 'types' }, - { message: 'message' } + { message: 'message' }, ); }); @@ -890,7 +890,7 @@ describe('background/services/wallet/WalletService.ts', () => { try { await walletService.signMessage('test' as MessageType, action); - } catch (error) { + } catch (_err) { expect(Buffer.from).toHaveBeenCalledTimes(1); expect(Buffer.from).toHaveBeenCalledWith(privateKeyMock, 'hex'); expect(bufferInstance.fill).toHaveBeenCalledTimes(1); @@ -904,12 +904,12 @@ describe('background/services/wallet/WalletService.ts', () => { (personalSign as jest.Mock).mockReturnValue(mockedHash); const result = await walletService.signMessage( MessageType.ETH_SIGN, - action + action, ); expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( MessageType.ETH_SIGN, {}, - activeNetworkMock.chainId + activeNetworkMock.chainId, ); expect(personalSign).toHaveBeenCalledTimes(1); expect(personalSign).toHaveBeenCalledWith({ @@ -927,12 +927,12 @@ describe('background/services/wallet/WalletService.ts', () => { (personalSign as jest.Mock).mockReturnValue(mockedHash); const result = await walletService.signMessage( MessageType.PERSONAL_SIGN, - action + action, ); expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( MessageType.PERSONAL_SIGN, {}, - activeNetworkMock.chainId + activeNetworkMock.chainId, ); expect(personalSign).toHaveBeenCalledTimes(1); expect(personalSign).toHaveBeenCalledWith({ @@ -950,12 +950,12 @@ describe('background/services/wallet/WalletService.ts', () => { (signTypedData as jest.Mock).mockReturnValue(mockedHash); const result = await walletService.signMessage( MessageType.SIGN_TYPED_DATA, - action + action, ); expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( MessageType.SIGN_TYPED_DATA, {}, - activeNetworkMock.chainId + activeNetworkMock.chainId, ); expect(signTypedData).toHaveBeenCalledTimes(1); expect(signTypedData).toHaveBeenCalledWith({ @@ -974,12 +974,12 @@ describe('background/services/wallet/WalletService.ts', () => { (signTypedData as jest.Mock).mockReturnValue(mockedHash); const result = await walletService.signMessage( MessageType.SIGN_TYPED_DATA_V1, - action + action, ); expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( MessageType.SIGN_TYPED_DATA_V1, {}, - activeNetworkMock.chainId + activeNetworkMock.chainId, ); expect(signTypedData).toHaveBeenCalledTimes(1); expect(signTypedData).toHaveBeenCalledWith({ @@ -998,12 +998,12 @@ describe('background/services/wallet/WalletService.ts', () => { (signTypedData as jest.Mock).mockReturnValue(mockedHash); const result = await walletService.signMessage( MessageType.SIGN_TYPED_DATA_V3, - action + action, ); expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( MessageType.SIGN_TYPED_DATA_V3, {}, - activeNetworkMock.chainId + activeNetworkMock.chainId, ); expect(signTypedData).toHaveBeenCalledTimes(1); expect(signTypedData).toHaveBeenCalledWith({ @@ -1022,12 +1022,12 @@ describe('background/services/wallet/WalletService.ts', () => { (signTypedData as jest.Mock).mockReturnValue(mockedHash); const result = await walletService.signMessage( MessageType.SIGN_TYPED_DATA_V4, - action + action, ); expect(ensureMessageFormatIsValid).toHaveBeenCalledWith( MessageType.SIGN_TYPED_DATA_V4, {}, - activeNetworkMock.chainId + activeNetworkMock.chainId, ); expect(signTypedData).toHaveBeenCalledTimes(1); expect(signTypedData).toHaveBeenCalledWith({ @@ -1047,7 +1047,7 @@ describe('background/services/wallet/WalletService.ts', () => { throw new Error(errorMessage); }); await expect( - walletService.signMessage(MessageType.ETH_SIGN, action) + walletService.signMessage(MessageType.ETH_SIGN, action), ).rejects.toThrow(errorMessage); expect(Buffer.from).not.toHaveBeenCalled(); }); @@ -1056,7 +1056,7 @@ describe('background/services/wallet/WalletService.ts', () => { jest.spyOn(networkService, 'getNetwork').mockResolvedValue(undefined); jest.spyOn(walletService as any, 'getWallet').mockReturnValue(walletMock); await expect( - walletService.signMessage(MessageType.ETH_SIGN, action) + walletService.signMessage(MessageType.ETH_SIGN, action), ).rejects.toThrow('no active network found'); expect(Buffer.from).not.toHaveBeenCalled(); }); @@ -1082,7 +1082,7 @@ describe('background/services/wallet/WalletService.ts', () => { try { await walletService.signMessage( MessageType.ETH_SIGN, - undefinedDataAction + undefinedDataAction, ); fail('should have thrown an exception'); } catch (error) { @@ -1099,7 +1099,7 @@ describe('background/services/wallet/WalletService.ts', () => { try { await walletService.signMessage( MessageType.ETH_SIGN, - undefinedDataAction + undefinedDataAction, ); fail('should have thrown an exception'); } catch (error) { @@ -1117,12 +1117,12 @@ describe('background/services/wallet/WalletService.ts', () => { try { await walletService.signMessage( MessageType.ETH_SIGN, - undefinedDataAction + undefinedDataAction, ); fail('should have thrown an exception'); } catch (error) { expect(error).toEqual( - new Error(`this function is not supported on your wallet`) + new Error(`this function is not supported on your wallet`), ); expect(Buffer.from).not.toHaveBeenCalled(); } @@ -1146,7 +1146,7 @@ describe('background/services/wallet/WalletService.ts', () => { jest .mocked(networkService) .getAvalancheNetworkXP.mockReturnValue( - decorateWithCaipId(AVALANCHE_XP_TEST_NETWORK) + decorateWithCaipId(AVALANCHE_XP_TEST_NETWORK), ); const mockedHash = 'mockedHash'; @@ -1156,7 +1156,7 @@ describe('background/services/wallet/WalletService.ts', () => { const result = await walletService.signMessage( MessageType.AVALANCHE_SIGN, - actionWithAccountIndex + actionWithAccountIndex, ); expect(getWalletSpy).toHaveBeenCalledTimes(2); @@ -1179,10 +1179,10 @@ describe('background/services/wallet/WalletService.ts', () => { describe('primary accounts', () => { it('throws if secrets are missing', async () => { secretsService.getAccountSecrets.mockRejectedValue( - new Error('Wallet is not initialized') + new Error('Wallet is not initialized'), ); await expect(walletService.getActiveAccountPublicKey()).rejects.toThrow( - 'Wallet is not initialized' + 'Wallet is not initialized', ); }); @@ -1190,7 +1190,7 @@ describe('background/services/wallet/WalletService.ts', () => { mockLedgerLiveWallet({}, { index: 1 }); await expect(walletService.getActiveAccountPublicKey()).rejects.toThrow( - 'Can not find public key for the given index' + 'Can not find public key for the given index', ); }); @@ -1214,7 +1214,7 @@ describe('background/services/wallet/WalletService.ts', () => { expect(getAddressPublicKeyFromXPub).toHaveBeenCalledWith(xpub, 0); expect(Avalanche.getAddressPublicKeyFromXpub).toHaveBeenCalledWith( xpubXP, - 0 + 0, ); }); @@ -1236,7 +1236,7 @@ describe('background/services/wallet/WalletService.ts', () => { expect(getAddressPublicKeyFromXPub).toHaveBeenCalledWith(xpub, 0); expect(Avalanche.getAddressPublicKeyFromXpub).toHaveBeenCalledWith( xpubXP, - 0 + 0, ); }); @@ -1250,7 +1250,7 @@ describe('background/services/wallet/WalletService.ts', () => { }, ], }, - { index: 0 } + { index: 0 }, ); const result = await walletService.getActiveAccountPublicKey(); @@ -1271,7 +1271,7 @@ describe('background/services/wallet/WalletService.ts', () => { }, ], }, - { index: 0 } + { index: 0 }, ); const result = await walletService.getActiveAccountPublicKey(); @@ -1290,11 +1290,11 @@ describe('background/services/wallet/WalletService.ts', () => { { type: AccountType.IMPORTED, id: 'unknown', - } + }, ); await expect(walletService.getActiveAccountPublicKey()).rejects.toThrow( - 'Cannot find public key for the given imported account' + 'Cannot find public key for the given imported account', ); }); @@ -1307,11 +1307,11 @@ describe('background/services/wallet/WalletService.ts', () => { { type: AccountType.IMPORTED, id: 'id1', - } + }, ); await expect(walletService.getActiveAccountPublicKey()).rejects.toThrow( - 'Unable to get public key' + 'Unable to get public key', ); }); @@ -1324,7 +1324,7 @@ describe('background/services/wallet/WalletService.ts', () => { { type: AccountType.IMPORTED, id: 'id1', - } + }, ); (getPublicKeyFromPrivateKey as jest.Mock).mockReturnValueOnce(evmPub); @@ -1351,7 +1351,7 @@ describe('background/services/wallet/WalletService.ts', () => { { type: AccountType.WALLET_CONNECT, id: accountId, - } + }, ); const result = await walletService.getActiveAccountPublicKey(); @@ -1375,7 +1375,7 @@ describe('background/services/wallet/WalletService.ts', () => { secretsService.getBtcWalletPolicyDetails.mockResolvedValueOnce(undefined); await expect( - walletService['parseWalletPolicyDetails']({} as Account) + walletService['parseWalletPolicyDetails']({} as Account), ).rejects.toThrow('Error while parsing wallet policy: missing data.'); }); @@ -1393,7 +1393,7 @@ describe('background/services/wallet/WalletService.ts', () => { (createWalletPolicy as jest.Mock).mockReturnValueOnce(walletPolicy); await expect( - walletService['parseWalletPolicyDetails']({} as Account) + walletService['parseWalletPolicyDetails']({} as Account), ).resolves.toStrictEqual({ hmac: Buffer.from(hmacHex, 'hex'), policy: walletPolicy, @@ -1403,7 +1403,7 @@ describe('background/services/wallet/WalletService.ts', () => { masterFingerprint, 1, xpub, - name + name, ); }); @@ -1421,7 +1421,7 @@ describe('background/services/wallet/WalletService.ts', () => { (createWalletPolicy as jest.Mock).mockReturnValueOnce(walletPolicy); await expect( - walletService['parseWalletPolicyDetails']({} as Account) + walletService['parseWalletPolicyDetails']({} as Account), ).resolves.toStrictEqual({ hmac: Buffer.from(hmacHex, 'hex'), policy: walletPolicy, @@ -1431,7 +1431,7 @@ describe('background/services/wallet/WalletService.ts', () => { masterFingerprint, 0, xpub, - name + name, ); }); }); @@ -1448,7 +1448,7 @@ describe('background/services/wallet/WalletService.ts', () => { const result = await walletService.getAddressesByIndices( [1, 2], 'X', - false + false, ); expect(result).toStrictEqual([]); @@ -1462,7 +1462,7 @@ describe('background/services/wallet/WalletService.ts', () => { const result = await walletService.getAddressesByIndices( [1, 2], 'P', - true + true, ); expect(result).toStrictEqual([]); @@ -1480,7 +1480,7 @@ describe('background/services/wallet/WalletService.ts', () => { const result = await walletService.getAddressesByIndices( [1, 4], 'X', - false + false, ); expect(result).toStrictEqual(['0x1', '0x4']); @@ -1491,7 +1491,7 @@ describe('background/services/wallet/WalletService.ts', () => { 1, getDefaultFujiProviderMock(), 'X', - false + false, ); expect(Avalanche.getAddressFromXpub).toHaveBeenNthCalledWith( 2, @@ -1499,7 +1499,7 @@ describe('background/services/wallet/WalletService.ts', () => { 4, getDefaultFujiProviderMock(), 'X', - false + false, ); }); }); diff --git a/src/background/services/wallet/WalletService.ts b/src/background/services/wallet/WalletService.ts index 86a7d5bf1..ec4facd6d 100644 --- a/src/background/services/wallet/WalletService.ts +++ b/src/background/services/wallet/WalletService.ts @@ -74,7 +74,7 @@ export class WalletService implements OnUnlock { private walletConnectService: WalletConnectService, private fireblocksService: FireblocksService, private secretService: SecretsService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} async emitsWalletsInfo(wallets: WalletDetails[]) { @@ -89,7 +89,7 @@ export class WalletService implements OnUnlock { } const hasUnsupportedSecret = wallets.some( - ({ type }) => !SUPPORTED_PRIMARY_SECRET_TYPES.includes(type) + ({ type }) => !SUPPORTED_PRIMARY_SECRET_TYPES.includes(type), ); if (hasUnsupportedSecret) { @@ -97,7 +97,7 @@ export class WalletService implements OnUnlock { } const hasSeedlessWallet = wallets.some( - ({ type }) => type === SecretType.Seedless + ({ type }) => type === SecretType.Seedless, ); if (hasSeedlessWallet) { @@ -128,7 +128,7 @@ export class WalletService implements OnUnlock { #validateSecretsType(secrets: AddPrimaryWalletSecrets) { if (secrets.secretType === SecretType.Mnemonic && !secrets.mnemonic) { throw new Error( - 'Mnemonic or xpub or pubKey is required to create a new wallet!' + 'Mnemonic or xpub or pubKey is required to create a new wallet!', ); } if (secrets.secretType === SecretType.LedgerLive && !secrets.pubKeys) { @@ -140,7 +140,7 @@ export class WalletService implements OnUnlock { !secrets.xpub ) { throw new Error( - 'Mnemonic or xpub or pubKey is required to create a new wallet!' + 'Mnemonic or xpub or pubKey is required to create a new wallet!', ); } return true; @@ -159,7 +159,7 @@ export class WalletService implements OnUnlock { return; } const secrets = await this.secretService.getAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (!secrets.account) { // wallet is not initialized @@ -198,7 +198,7 @@ export class WalletService implements OnUnlock { const signer = getWalletFromMnemonic( secrets.mnemonic, accountIndexToUse, - secrets.derivationPath + secrets.derivationPath, ); return signer.connect(provider as JsonRpcBatchInternal); } @@ -217,7 +217,7 @@ export class WalletService implements OnUnlock { accountIndexToUse, this.ledgerService.recentTransport, secrets.derivationPath, - provider as JsonRpcBatchInternal + provider as JsonRpcBatchInternal, ); } @@ -229,7 +229,7 @@ export class WalletService implements OnUnlock { accountIndexToUse, this.keystoneService, network.chainId, - tabId + tabId, ); } @@ -246,7 +246,7 @@ export class WalletService implements OnUnlock { // more time than WalletConnect's default of 5 minutes. secretType === SecretType.Fireblocks ? FIREBLOCKS_REQUEST_EXPIRY - : undefined + : undefined, ); } @@ -255,7 +255,7 @@ export class WalletService implements OnUnlock { } throw new Error( - `No proper signer could be constructed for EVM and ${secretType} account` + `No proper signer could be constructed for EVM and ${secretType} account`, ); } @@ -267,7 +267,7 @@ export class WalletService implements OnUnlock { return await BitcoinWallet.fromMnemonic( secrets.mnemonic, accountIndexToUse, - provider as BitcoinProviderAbstract + provider as BitcoinProviderAbstract, ); } if (secretType === SecretType.Fireblocks) { @@ -278,14 +278,14 @@ export class WalletService implements OnUnlock { return new FireblocksBTCSigner( this.fireblocksService, secrets.api.vaultAccountId, - network.isTestnet + network.isTestnet, ); } if (secretType === SecretType.PrivateKey) { return new BitcoinWallet( Buffer.from(secrets.secret, 'hex'), - provider as BitcoinProviderAbstract + provider as BitcoinProviderAbstract, ); } @@ -298,11 +298,11 @@ export class WalletService implements OnUnlock { getAddressDerivationPath( accountIndexToUse, secrets.derivationPath, - 'EVM' + 'EVM', ), this.keystoneService, provider as BitcoinProviderAbstract, - tabId + tabId, ); } @@ -312,7 +312,7 @@ export class WalletService implements OnUnlock { } const walletPolicy = await this.parseWalletPolicyDetails( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); const accountIndexToUse = accountIndex === undefined ? secrets.account.index : accountIndex; @@ -322,11 +322,11 @@ export class WalletService implements OnUnlock { getAddressDerivationPath( accountIndexToUse, secrets.derivationPath, - 'EVM' + 'EVM', ), provider as BitcoinProviderAbstract, this.ledgerService.recentTransport, - walletPolicy + walletPolicy, ); } @@ -345,7 +345,7 @@ export class WalletService implements OnUnlock { } const walletPolicy = await this.parseWalletPolicyDetails( - secrets.account + secrets.account, ); return new BitcoinLedgerWallet( @@ -353,16 +353,16 @@ export class WalletService implements OnUnlock { getAddressDerivationPath( accountIndexToUse, secrets.derivationPath, - 'EVM' + 'EVM', ), provider as BitcoinProviderAbstract, this.ledgerService.recentTransport, - walletPolicy + walletPolicy, ); } throw new Error( - `No proper signer could be constructed for Bitcoin and ${secretType} account` + `No proper signer could be constructed for Bitcoin and ${secretType} account`, ); } @@ -387,7 +387,7 @@ export class WalletService implements OnUnlock { return new Avalanche.SimpleLedgerSigner( accountIndexToUse, provider as Avalanche.JsonRpcProvider, - secrets.xpubXP + secrets.xpubXP, ); } @@ -415,15 +415,15 @@ export class WalletService implements OnUnlock { getAddressDerivationPath( accountIndexToUse, DerivationPath.LedgerLive, - 'AVM' + 'AVM', ), Buffer.from(pubkey.evm, 'hex'), getAddressDerivationPath( accountIndexToUse, DerivationPath.LedgerLive, - 'EVM' + 'EVM', ), - provider as Avalanche.JsonRpcProvider + provider as Avalanche.JsonRpcProvider, ); } @@ -432,7 +432,7 @@ export class WalletService implements OnUnlock { this.walletConnectService, network.chainId, secrets.account.addressC, - tabId + tabId, ); } @@ -440,12 +440,12 @@ export class WalletService implements OnUnlock { return new Avalanche.StaticSigner( Buffer.from(secrets.secret, 'hex'), Buffer.from(secrets.secret, 'hex'), - provider as Avalanche.JsonRpcProvider + provider as Avalanche.JsonRpcProvider, ); } throw new Error( - `No proper signer could be constructed for Avalanche and ${secretType} account` + `No proper signer could be constructed for Avalanche and ${secretType} account`, ); } } @@ -454,7 +454,7 @@ export class WalletService implements OnUnlock { tx: SignTransactionRequest, network: Network, tabId?: number, - originalRequestMethod?: string + originalRequestMethod?: string, ): Promise { const wallet = await this.getWallet({ network, tabId }); @@ -479,7 +479,7 @@ export class WalletService implements OnUnlock { wallet instanceof BitcoinLedgerWallet ? await prepareBtcTxForLedger( tx, - await this.networkService.getBitcoinProvider() + await this.networkService.getBitcoinProvider(), ) : tx; @@ -536,7 +536,7 @@ export class WalletService implements OnUnlock { * If the wallet returns a string, we treat it as signed TX. */ #normalizeSigningResult( - signingResult: string | UnsignedTx | Transaction | SigningResult + signingResult: string | UnsignedTx | Transaction | SigningResult, ): SigningResult { if (typeof signingResult === 'string') { return { signedTx: signingResult }; @@ -562,7 +562,7 @@ export class WalletService implements OnUnlock { throw new Error('There is no active account'); } const secrets = await this.secretService.getAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets.secretType === SecretType.Fireblocks) { @@ -583,12 +583,12 @@ export class WalletService implements OnUnlock { if (secrets.secretType === SecretType.PrivateKey) { if (!secrets.secret) { throw new Error( - 'Cannot find public key for the given imported account' + 'Cannot find public key for the given imported account', ); } const publicKey = getPublicKeyFromPrivateKey(secrets.secret).toString( - 'hex' + 'hex', ); return { @@ -600,11 +600,11 @@ export class WalletService implements OnUnlock { if (secrets.secretType === SecretType.Mnemonic && secrets.account) { const evmPub = getAddressPublicKeyFromXPub( secrets.xpub, - secrets.account.index + secrets.account.index, ); const xpPub = Avalanche.getAddressPublicKeyFromXpub( secrets.xpubXP, - secrets.account.index + secrets.account.index, ); return { @@ -620,11 +620,11 @@ export class WalletService implements OnUnlock { ) { const evmPub = getAddressPublicKeyFromXPub( secrets.xpub, - secrets.account.index + secrets.account.index, ); const xpPub = Avalanche.getAddressPublicKeyFromXpub( secrets.xpubXP, - secrets.account.index + secrets.account.index, ); return { @@ -744,7 +744,7 @@ export class WalletService implements OnUnlock { throw new Error( wallet ? `this function is not supported on your wallet` - : 'wallet undefined in sign tx' + : 'wallet undefined in sign tx', ); } @@ -797,11 +797,11 @@ export class WalletService implements OnUnlock { async getAddressesByIndices( indices: number[], chainAlias: 'X' | 'P', - isChange: boolean + isChange: boolean, ) { const provXP = await this.networkService.getAvalanceProviderXP(); const secrets = await this.secretService.getPrimaryAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (!secrets || !secrets.xpubXP) { @@ -818,15 +818,14 @@ export class WalletService implements OnUnlock { index, provXP, chainAlias, - isChange - ) + isChange, + ), ); } private async parseWalletPolicyDetails(account: Account) { - const policyInfo = await this.secretService.getBtcWalletPolicyDetails( - account - ); + const policyInfo = + await this.secretService.getBtcWalletPolicyDetails(account); if (!policyInfo || !policyInfo.details) { throw new Error('Error while parsing wallet policy: missing data.'); @@ -838,7 +837,7 @@ export class WalletService implements OnUnlock { details.masterFingerprint, accountIndex, details.xpub, - details.name + details.name, ); return { diff --git a/src/background/services/wallet/handlers/avalanche_sendTransaction.test.ts b/src/background/services/wallet/handlers/avalanche_sendTransaction.test.ts index f8a215eb2..051370fe6 100644 --- a/src/background/services/wallet/handlers/avalanche_sendTransaction.test.ts +++ b/src/background/services/wallet/handlers/avalanche_sendTransaction.test.ts @@ -144,7 +144,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', walletServiceMock, networkServiceMock, accountsServiceMock, - analyticsServicePosthogMock + analyticsServicePosthogMock, ); (encryptAnalyticsData as jest.Mock).mockResolvedValue(mockedEncryptResult); networkServiceMock.isMainnet.mockReturnValue(false); @@ -156,7 +156,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {} as any, {} as any, {} as any, - {} as any + {} as any, ); const result = await handler.handleUnauthenticated(buildRpcCall(request)); @@ -169,16 +169,15 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', describe('handleAuthenticated', () => { it('returns error if transactionHex was not provided', async () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { params, ...requestWithoutParam } = request; handler = new AvalancheSendTransactionHandler( {} as any, {} as any, {} as any, - {} as any + {} as any, ); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithoutParam) + buildRpcCall(requestWithoutParam), ); expect(result).toEqual({ @@ -190,7 +189,6 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', }); it('returns error if chainAlias was not provided', async () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { params, ...requestWithoutParam } = request; const requestWithoutChainAlias = { ...requestWithoutParam, @@ -200,10 +198,10 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {} as any, {} as any, {} as any, - {} as any + {} as any, ); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithoutChainAlias) + buildRpcCall(requestWithoutChainAlias), ); expect(result).toEqual({ @@ -219,7 +217,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', walletServiceMock as any, networkServiceMock as any, {} as any, - {} as any + {} as any, ); const result = await handler.handleAuthenticated(buildRpcCall(request)); @@ -243,7 +241,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', new Uint8Array([0, 1, 2]), ]); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValueOnce( - unsignedTxMock + unsignedTxMock, ); const result = await handler.handleAuthenticated(buildRpcCall(request)); @@ -270,7 +268,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', vm: 'AVM', }, }), - 'approve/avalancheSignTx' + 'approve/avalancheSignTx', ); expect(result).toEqual({ @@ -303,7 +301,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', ).mockReturnValueOnce(unsignedTxMock); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithUtxos) + buildRpcCall(requestWithUtxos), ); expect(Avalanche.getUtxosByTxFromGlacier).not.toHaveBeenCalled(); @@ -333,14 +331,14 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', ...request.params, feeTolerance: 25, }, - }) + }), ); expect(Avalanche.parseAvalancheTx).toHaveBeenCalledWith( unsignedTxMock, providerMock, expect.anything(), - { feeTolerance: 25 } + { feeTolerance: 25 }, ); }); @@ -362,7 +360,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', (getProvidedUtxos as jest.Mock).mockReturnValue([]); const result = await handler.handleAuthenticated( - buildRpcCall(request) + buildRpcCall(request), ); expect(Avalanche.getUtxosByTxFromGlacier).toHaveBeenCalledWith({ @@ -390,7 +388,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', vm: 'EVM', }, }), - 'approve/avalancheSignTx' + 'approve/avalancheSignTx', ); expect(result).toEqual({ @@ -409,7 +407,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', it('works with provided UTXOs', async () => { (Avalanche.getVmByChainAlias as jest.Mock).mockReturnValue(EVM); (utils.hexToBuffer as jest.Mock).mockReturnValueOnce( - new Uint8Array([0, 1, 2]) + new Uint8Array([0, 1, 2]), ); getAddressesByIndicesMock.mockResolvedValue([]); (Avalanche.parseAvalancheTx as jest.Mock).mockReturnValueOnce({ @@ -420,7 +418,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', ).mockReturnValueOnce(unsignedTxMock); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithUtxos) + buildRpcCall(requestWithUtxos), ); checkExpected(requestWithUtxos, result); @@ -430,7 +428,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', it('works without provided UTXOs', async () => { (Avalanche.getVmByChainAlias as jest.Mock).mockReturnValue(EVM); (utils.hexToBuffer as jest.Mock).mockReturnValueOnce( - new Uint8Array([0, 1, 2]) + new Uint8Array([0, 1, 2]), ); getAddressesByIndicesMock.mockResolvedValue([]); (Avalanche.parseAvalancheTx as jest.Mock).mockReturnValueOnce({ @@ -442,7 +440,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', (getProvidedUtxos as jest.Mock).mockReturnValue([]); const result = await handler.handleAuthenticated( - buildRpcCall(request) + buildRpcCall(request), ); checkExpected(request, result); @@ -479,7 +477,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(onErrorMock).toHaveBeenCalledWith(expect.any(Error)); @@ -487,11 +485,11 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', expect.objectContaining({ message: 'Transaction contains multiple addresses, but indices were not provided', - }) + }), ); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -500,7 +498,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', address: activeAccountMock.addressAVM, chainId: ChainId.AVALANCHE_TEST_X, }, - }) + }), ); }); @@ -524,13 +522,13 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(onErrorMock).toHaveBeenCalledWith(error); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -539,7 +537,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', address: activeAccountMock.addressPVM, chainId: ChainId.AVALANCHE_P, }, - }) + }), ); }); @@ -551,14 +549,14 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(onErrorMock).toHaveBeenCalledWith(expect.any(Error)); expect(onErrorMock).toHaveBeenCalledWith( expect.objectContaining({ message: 'Signing error, missing signatures.', - }) + }), ); }); @@ -575,7 +573,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(signMock).toHaveBeenCalledWith( @@ -586,17 +584,17 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', }, { rpcUrl: 'RPCURL' }, frontendTabId, - 'avalanche_sendTransaction' + 'avalanche_sendTransaction', ); expect(EVMUnsignedTx.fromJSON).toBeCalledWith( - pendingActionMock.displayData.unsignedTxJson + pendingActionMock.displayData.unsignedTxJson, ); expect(Avalanche.signedTxToHex).toHaveBeenCalledWith('signedTx'); expect(issueTxHexMock).toHaveBeenCalledWith(signedTxHex, 'EVM'); expect(onSuccessMock).toHaveBeenCalledWith(1); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -606,7 +604,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', txHash: 1, chainId: ChainId.AVALANCHE_TESTNET_ID, }, - }) + }), ); }); @@ -620,7 +618,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(signMock).toHaveBeenCalledWith( @@ -631,17 +629,17 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', }, { rpcUrl: 'RPCURL' }, frontendTabId, - 'avalanche_sendTransaction' + 'avalanche_sendTransaction', ); expect(UnsignedTx.fromJSON).toBeCalledWith( - pendingActionMock.displayData.unsignedTxJson + pendingActionMock.displayData.unsignedTxJson, ); expect(Avalanche.signedTxToHex).toHaveBeenCalledWith('signedTx'); expect(issueTxHexMock).toHaveBeenCalledWith(signedTxHex, 'AVM'); expect(onSuccessMock).toHaveBeenCalledWith(1); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -651,7 +649,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', txHash: 1, chainId: ChainId.AVALANCHE_TEST_X, }, - }) + }), ); }); @@ -670,7 +668,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(signMock).toHaveBeenCalledWith( @@ -681,17 +679,17 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', }, { rpcUrl: 'RPCURL' }, frontendTabId, - 'avalanche_sendTransaction' + 'avalanche_sendTransaction', ); expect(UnsignedTx.fromJSON).toBeCalledWith( - pendingActionMock.displayData.unsignedTxJson + pendingActionMock.displayData.unsignedTxJson, ); expect(Avalanche.signedTxToHex).toHaveBeenCalledWith('signedTx'); expect(issueTxHexMock).toHaveBeenCalledWith(signedTxHex, 'AVM'); expect(onSuccessMock).toHaveBeenCalledWith(1); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith( 1, expect.objectContaining({ @@ -701,7 +699,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', txHash: 1, chainId: ChainId.AVALANCHE_TEST_X, }, - }) + }), ); }); @@ -712,7 +710,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', providerMock.waitForTransaction.mockReturnValue( new Promise((resolve) => { resolveWaitforTransaction = resolve; - }) + }), ); const measurement = measureDuration(); jest.mocked(measurement.end).mockReturnValue(1000); @@ -724,7 +722,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(measurement.start).toHaveBeenCalled(); @@ -732,10 +730,10 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', expect(providerMock.waitForTransaction).toHaveBeenCalledWith( 1, 'AVM', - 60000 + 60000, ); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenCalledTimes(1); resolveWaitforTransaction(undefined); @@ -745,10 +743,10 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', expect(measurement.end).toHaveBeenCalled(); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenCalledTimes(2); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenNthCalledWith(2, { name: 'TransactionTimeToConfirmation', properties: { @@ -769,7 +767,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', providerMock.waitForTransaction.mockReturnValue( new Promise((_, reject) => { rejectWaitforTransaction = reject; - }) + }), ); const measurement = measureDuration(); jest.mocked(measurement.end).mockReturnValue(1000); @@ -781,7 +779,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(measurement.start).toHaveBeenCalled(); @@ -789,10 +787,10 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', expect(providerMock.waitForTransaction).toHaveBeenCalledWith( 1, 'AVM', - 60000 + 60000, ); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenCalledTimes(1); rejectWaitforTransaction(new Error('some error')); @@ -802,7 +800,7 @@ describe('src/background/services/wallet/handlers/avalanche_sendTransaction.ts', expect(measurement.end).toHaveBeenCalled(); expect( - analyticsServicePosthogMock.captureEncryptedEvent + analyticsServicePosthogMock.captureEncryptedEvent, ).toHaveBeenCalledTimes(1); }); }); diff --git a/src/background/services/wallet/handlers/avalanche_sendTransaction.ts b/src/background/services/wallet/handlers/avalanche_sendTransaction.ts index e01fcd69b..1a9a8880b 100644 --- a/src/background/services/wallet/handlers/avalanche_sendTransaction.ts +++ b/src/background/services/wallet/handlers/avalanche_sendTransaction.ts @@ -49,13 +49,13 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< private walletService: WalletService, private networkService: NetworkService, private accountsService: AccountsService, - private analyticsServicePosthog: AnalyticsServicePosthog + private analyticsServicePosthog: AnalyticsServicePosthog, ) { super(); } handleAuthenticated = async ( - rpcCall: JsonRpcRequestParams + rpcCall: JsonRpcRequestParams, ) => { let unsignedTx: UnsignedTx | EVMUnsignedTx; @@ -83,7 +83,7 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< const provider = await this.networkService.getAvalanceProviderXP(); const currentAddress = getAddressByVM( vm, - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (!currentAddress) { @@ -107,8 +107,8 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< network: isDevnet(network) ? Network.DEVNET : network.isTestnet - ? Network.FUJI - : Network.MAINNET, + ? Network.FUJI + : Network.MAINNET, url: process.env.GLACIER_URL as string, token: process.env.GLACIER_API_KEY, headers: HEADERS, @@ -127,13 +127,13 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< const externalAddresses = await this.walletService.getAddressesByIndices( externalIndices ?? [], chainAlias as 'X' | 'P', - false + false, ); const internalAddresses = await this.walletService.getAddressesByIndices( internalIndices ?? [], chainAlias as 'X' | 'P', - true + true, ); const fromAddresses = [ @@ -145,7 +145,7 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< ]; const fromAddressBytes = fromAddresses.map( - (address) => utils.parse(address)[2] + (address) => utils.parse(address)[2], ); unsignedTx = await Avalanche.createAvalancheUnsignedTx({ @@ -162,7 +162,7 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< currentAddress, { feeTolerance, - } + }, ); if (txData.type === 'unknown') { @@ -239,10 +239,10 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< txData: Avalanche.Tx; vm: VM; }>, - result, + _result, onSuccess, onError, - frontendTabId?: number + frontendTabId?: number, ) => { const { displayData: { vm, unsignedTxJson }, @@ -269,7 +269,7 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< !(internalIndices ?? []).length ) { throw new Error( - 'Transaction contains multiple addresses, but indices were not provided' + 'Transaction contains multiple addresses, but indices were not provided', ); } @@ -283,7 +283,7 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< }, network, frontendTabId, - DAppProviderRequest.AVALANCHE_SEND_TRANSACTION + DAppProviderRequest.AVALANCHE_SEND_TRANSACTION, ); let transactionHash: string; @@ -314,7 +314,7 @@ export class AvalancheSendTransactionHandler extends DAppRequestHandler< } const signedTransactionHex = Avalanche.signedTxToHex( - signedTransaction.getSignedTx() + signedTransaction.getSignedTx(), ); // Submit the transaction and return the tx id diff --git a/src/background/services/wallet/handlers/avalanche_signTransaction.test.ts b/src/background/services/wallet/handlers/avalanche_signTransaction.test.ts index 59925ebaa..f1447ddaf 100644 --- a/src/background/services/wallet/handlers/avalanche_signTransaction.test.ts +++ b/src/background/services/wallet/handlers/avalanche_signTransaction.test.ts @@ -95,7 +95,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () (utils.hexToBuffer as jest.Mock).mockReturnValue(txBytes); networkServiceMock.getAvalanceProviderXP.mockReturnValue(providerMock); networkServiceMock.getAvalancheNetworkXP.mockReturnValueOnce( - AVALANCHE_XP_TEST_NETWORK + AVALANCHE_XP_TEST_NETWORK, ); (utils.unpackWithManager as jest.Mock).mockReturnValue(txMock); (utils.addressesFromBytes as jest.Mock).mockReturnValue([ @@ -119,7 +119,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( {} as any, {} as any, - {} as any + {} as any, ); const result = await handler.handleUnauthenticated(buildRpcCall(request)); @@ -132,15 +132,14 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () describe('handleAuthenticated', () => { it('returns error if transactionHex was not provided', async () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { params, ...requestWithoutParam } = request; const handler = new AvalancheSignTransactionHandler( {} as any, {} as any, - {} as any + {} as any, ); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithoutParam) + buildRpcCall(requestWithoutParam), ); expect(result).toEqual({ @@ -152,7 +151,6 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); it('returns error if chainAlias was not provided', async () => { - // eslint-disable-next-line @typescript-eslint/no-unused-vars const { params, ...requestWithoutParam } = request; const requestWithoutChainAlias = { ...requestWithoutParam, @@ -161,10 +159,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( {} as any, {} as any, - {} as any + {} as any, ); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithoutChainAlias) + buildRpcCall(requestWithoutChainAlias), ); expect(result).toEqual({ @@ -179,7 +177,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - {} as any + {} as any, ); const result = await handler.handleAuthenticated(buildRpcCall(request)); @@ -192,10 +190,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); expect(Avalanche.getVmByChainAlias).toHaveBeenCalledWith( - request.params.chainAlias + request.params.chainAlias, ); expect(utils.hexToBuffer).toHaveBeenCalledWith( - request.params.transactionHex + request.params.transactionHex, ); }); @@ -205,7 +203,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); (utils.addressesFromBytes as jest.Mock).mockReturnValue([]); @@ -220,10 +218,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); expect(Avalanche.getVmByChainAlias).toHaveBeenCalledWith( - request.params.chainAlias + request.params.chainAlias, ); expect(utils.hexToBuffer).toHaveBeenCalledWith( - request.params.transactionHex + request.params.transactionHex, ); expect(Avalanche.getUtxosByTxFromGlacier).toHaveBeenCalledWith({ transactionHex: request.params.transactionHex, @@ -250,12 +248,12 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); unsignedTxMock.getSigIndicesForAddress.mockReturnValue(undefined); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValue( - unsignedTxMock + unsignedTxMock, ); const result = await handler.handleAuthenticated(buildRpcCall(request)); @@ -268,10 +266,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); expect(Avalanche.getVmByChainAlias).toHaveBeenCalledWith( - request.params.chainAlias + request.params.chainAlias, ); expect(utils.hexToBuffer).toHaveBeenCalledWith( - request.params.transactionHex + request.params.transactionHex, ); expect(Avalanche.getUtxosByTxFromGlacier).toHaveBeenCalledWith({ transactionHex: request.params.transactionHex, @@ -291,10 +289,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () signerAddressBytesMock, ]); expect(utils.parse).toHaveBeenCalledWith( - accountsServiceMock.activeAccount.addressAVM + accountsServiceMock.activeAccount.addressAVM, ); expect(unsignedTxMock.getSigIndicesForAddress).toHaveBeenCalledWith( - signerAddressMock + signerAddressMock, ); }); @@ -304,13 +302,13 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); unsignedTxMock.getSigIndicesForAddress.mockReturnValueOnce([]); unsignedTxMock.getSigIndices.mockReturnValueOnce([]); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValue( - unsignedTxMock + unsignedTxMock, ); const result = await handler.handleAuthenticated(buildRpcCall(request)); @@ -323,10 +321,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); expect(Avalanche.getVmByChainAlias).toHaveBeenCalledWith( - request.params.chainAlias + request.params.chainAlias, ); expect(utils.hexToBuffer).toHaveBeenCalledWith( - request.params.transactionHex + request.params.transactionHex, ); expect(Avalanche.getUtxosByTxFromGlacier).toHaveBeenCalledWith({ transactionHex: request.params.transactionHex, @@ -347,7 +345,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () ]); expect(utils.parse).toHaveBeenCalledWith(activeAccountMock.addressAVM); expect(unsignedTxMock.getSigIndicesForAddress).toHaveBeenCalledWith( - signerAddressMock + signerAddressMock, ); expect(unsignedTxMock.getSigIndices).toHaveBeenCalled(); }); @@ -358,13 +356,13 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); unsignedTxMock.getSigIndicesForAddress.mockReturnValueOnce([[0, 1]]); unsignedTxMock.getSigIndices.mockReturnValueOnce([[1, 2]]); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValue( - unsignedTxMock + unsignedTxMock, ); (Avalanche.parseAvalancheTx as jest.Mock).mockReturnValueOnce({ type: 'unknown', @@ -380,10 +378,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); expect(Avalanche.getVmByChainAlias).toHaveBeenCalledWith( - request.params.chainAlias + request.params.chainAlias, ); expect(utils.hexToBuffer).toHaveBeenCalledWith( - request.params.transactionHex + request.params.transactionHex, ); expect(Avalanche.getUtxosByTxFromGlacier).toHaveBeenCalledWith({ transactionHex: request.params.transactionHex, @@ -404,13 +402,13 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () ]); expect(utils.parse).toHaveBeenCalledWith(activeAccountMock.addressAVM); expect(unsignedTxMock.getSigIndicesForAddress).toHaveBeenCalledWith( - signerAddressMock + signerAddressMock, ); expect(unsignedTxMock.getSigIndices).toHaveBeenCalled(); expect(Avalanche.parseAvalancheTx).toHaveBeenCalledWith( unsignedTxMock, providerMock, - activeAccountMock.addressAVM + activeAccountMock.addressAVM, ); }); @@ -423,10 +421,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); expect(Avalanche.getVmByChainAlias).toHaveBeenCalledWith( - req.params.chainAlias + req.params.chainAlias, ); expect(utils.hexToBuffer).toHaveBeenCalledWith( - req.params.transactionHex + req.params.transactionHex, ); expect(Avalanche.createAvalancheUnsignedTx).toHaveBeenCalledTimes(1); expect(Avalanche.createAvalancheUnsignedTx).toHaveBeenCalledWith({ @@ -442,16 +440,16 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () signerAddressBytesMock, ]); expect(utils.parse).toHaveBeenCalledWith( - activeAccountMock.addressAVM + activeAccountMock.addressAVM, ); expect(unsignedTxMock.getSigIndicesForAddress).toHaveBeenCalledWith( - signerAddressMock + signerAddressMock, ); expect(unsignedTxMock.getSigIndices).toHaveBeenCalled(); expect(Avalanche.parseAvalancheTx).toHaveBeenCalledWith( unsignedTxMock, providerMock, - activeAccountMock.addressAVM + activeAccountMock.addressAVM, ); expect(openApprovalWindow).toHaveBeenCalledWith( @@ -466,7 +464,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () vm: 'AVM', }, }), - 'approve/avalancheSignTx' + 'approve/avalancheSignTx', ); }; @@ -474,7 +472,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); txMock.getSigIndices.mockReturnValueOnce([ @@ -485,14 +483,14 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () unsignedTxMock.getSigIndicesForAddress.mockReturnValueOnce([[0, 1]]); unsignedTxMock.getSigIndices.mockReturnValueOnce([[1, 2]]); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValue( - unsignedTxMock + unsignedTxMock, ); (Avalanche.parseAvalancheTx as jest.Mock).mockReturnValueOnce({ type: 'import', }); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithUtxos) + buildRpcCall(requestWithUtxos), ); checkExpected(requestWithUtxos, result); @@ -505,7 +503,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); txMock.getSigIndices.mockReturnValueOnce([ @@ -516,14 +514,14 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () unsignedTxMock.getSigIndicesForAddress.mockReturnValueOnce([[0, 1]]); unsignedTxMock.getSigIndices.mockReturnValueOnce([[1, 2]]); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValue( - unsignedTxMock + unsignedTxMock, ); (Avalanche.parseAvalancheTx as jest.Mock).mockReturnValueOnce({ type: 'import', }); const result = await handler.handleAuthenticated( - buildRpcCall(request) + buildRpcCall(request), ); checkExpected(request, result); @@ -546,10 +544,10 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () }); expect(Avalanche.getVmByChainAlias).toHaveBeenCalledWith( - req.params.chainAlias + req.params.chainAlias, ); expect(utils.hexToBuffer).toHaveBeenCalledWith( - req.params.transactionHex + req.params.transactionHex, ); expect(Credential).toHaveBeenCalledTimes(2); @@ -563,7 +561,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () { unsignedTx: unsignedTxMock, credentialIndex: 0, - } + }, ); expect(Avalanche.populateCredential).toHaveBeenNthCalledWith( 2, @@ -571,7 +569,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () { unsignedTx: unsignedTxMock, credentialIndex: 1, - } + }, ); expect(Avalanche.createAvalancheUnsignedTx).toHaveBeenCalledTimes(2); expect(Avalanche.createAvalancheUnsignedTx).toHaveBeenNthCalledWith( @@ -581,7 +579,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () provider: providerMock, credentials: [{ biz: 'baz' }, { baz: 'biz' }], utxos: utxosMock, - } + }, ); expect(Avalanche.createAvalancheUnsignedTx).toHaveBeenNthCalledWith( 2, @@ -593,22 +591,22 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () (Credential as unknown as jest.Mock).mock.instances[1], ], utxos: utxosMock, - } + }, ); expect(utils.addressesFromBytes).toHaveBeenCalledWith([ signerAddressBytesMock, ]); expect(utils.parse).toHaveBeenCalledWith( - activeAccountMock.addressAVM + activeAccountMock.addressAVM, ); expect(unsignedTxMock.getSigIndicesForAddress).toHaveBeenCalledWith( - signerAddressMock + signerAddressMock, ); expect(unsignedTxMock.getSigIndices).toHaveBeenCalled(); expect(Avalanche.parseAvalancheTx).toHaveBeenCalledWith( unsignedTxMock, providerMock, - activeAccountMock.addressAVM + activeAccountMock.addressAVM, ); expect(openApprovalWindow).toHaveBeenCalledWith( @@ -623,7 +621,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () vm: 'AVM', }, }), - 'approve/avalancheSignTx' + 'approve/avalancheSignTx', ); }; @@ -641,7 +639,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); txMock.getSigIndices.mockReturnValueOnce([ @@ -655,7 +653,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () [1, 0], ]); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValue( - unsignedTxMock + unsignedTxMock, ); (Avalanche.parseAvalancheTx as jest.Mock).mockReturnValueOnce({ type: 'import', @@ -665,7 +663,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () .mockReturnValueOnce(signaturesMock[1]); const result = await handler.handleAuthenticated( - buildRpcCall(requestWithUtxos) + buildRpcCall(requestWithUtxos), ); checkExpected(requestWithUtxos, result, signaturesMock); @@ -688,7 +686,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); txMock.getSigIndices.mockReturnValueOnce([ @@ -702,7 +700,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () [1, 0], ]); (Avalanche.createAvalancheUnsignedTx as jest.Mock).mockReturnValue( - unsignedTxMock + unsignedTxMock, ); (Avalanche.parseAvalancheTx as jest.Mock).mockReturnValueOnce({ type: 'import', @@ -712,7 +710,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () .mockReturnValueOnce(signaturesMock[1]); const result = await handler.handleAuthenticated( - buildRpcCall(request) + buildRpcCall(request), ); checkExpected(request, result, signaturesMock); @@ -782,13 +780,13 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () .mockReturnValueOnce(signedTxMock); (avaxSerial.SignedTx as unknown as jest.Mock) = signedTxInstanceMock; (Avalanche.signedTxToHex as jest.Mock).mockReturnValueOnce( - signedTransactionHex + signedTransactionHex, ); const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); await handler.onActionApproved( @@ -796,14 +794,14 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(onErrorMock).toHaveBeenCalledWith(expect.any(Error)); expect(onErrorMock).toHaveBeenCalledWith( expect.objectContaining({ message: 'Failed to sign [0, 3]', - }) + }), ); }); @@ -836,12 +834,12 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () .mockReturnValueOnce(signedTxMock); (avaxSerial.SignedTx as unknown as jest.Mock) = signedTxInstanceMock; (Avalanche.signedTxToHex as jest.Mock).mockReturnValueOnce( - signedTransactionHex + signedTransactionHex, ); const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); await handler.onActionApproved( @@ -849,14 +847,14 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(onErrorMock).toHaveBeenCalledWith(expect.any(Error)); expect(onErrorMock).toHaveBeenCalledWith( expect.objectContaining({ message: 'Failed to sign [0, 2]', - }) + }), ); }); @@ -869,13 +867,13 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () .mockReturnValueOnce(signedTxMock); (avaxSerial.SignedTx as unknown as jest.Mock) = signedTxInstanceMock; (Avalanche.signedTxToHex as jest.Mock).mockReturnValueOnce( - signedTransactionHex + signedTransactionHex, ); const handler = new AvalancheSignTransactionHandler( walletServiceMock as any, networkServiceMock as any, - accountsServiceMock as any + accountsServiceMock as any, ); await handler.onActionApproved( @@ -883,7 +881,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () {}, onSuccessMock, onErrorMock, - frontendTabId + frontendTabId, ); expect(onSuccessMock).toHaveBeenCalledWith({ @@ -900,7 +898,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () expect(UnsignedTx.fromJSON).toHaveBeenNthCalledWith(1, unsignedTxJson); expect(UnsignedTx.fromJSON).toHaveBeenNthCalledWith( 2, - signedTransactionJsonMock + signedTransactionJsonMock, ); expect(walletServiceMock.sign).toHaveBeenCalledWith( @@ -908,7 +906,7 @@ describe('src/background/services/wallet/handlers/avalanche_signTransaction', () tx: mockedTx, }, AVALANCHE_XP_TEST_NETWORK, - frontendTabId + frontendTabId, ); expect(signedTxMock.getCredentials).toHaveBeenCalled(); expect(mockedTx.getSigIndices).toHaveBeenCalled(); diff --git a/src/background/services/wallet/handlers/avalanche_signTransaction.ts b/src/background/services/wallet/handlers/avalanche_signTransaction.ts index f1c4d6335..fa743304b 100644 --- a/src/background/services/wallet/handlers/avalanche_signTransaction.ts +++ b/src/background/services/wallet/handlers/avalanche_signTransaction.ts @@ -37,13 +37,13 @@ export class AvalancheSignTransactionHandler extends DAppRequestHandler + rpcCall: JsonRpcRequestParams, ) => { let credentials: Credential[] | undefined = undefined; @@ -68,7 +68,7 @@ export class AvalancheSignTransactionHandler extends DAppRequestHandler new Credential(Avalanche.populateCredential(indicies)) + (indicies) => new Credential(Avalanche.populateCredential(indicies)), ); } @@ -168,7 +168,7 @@ export class AvalancheSignTransactionHandler extends DAppRequestHandler - sigIndices[inputIndex]?.includes(sigIndex) + sigIndices[inputIndex]?.includes(sigIndex), ); if (!needsToSign) { @@ -184,7 +184,7 @@ export class AvalancheSignTransactionHandler extends DAppRequestHandler { try { const { @@ -241,12 +241,12 @@ export class AvalancheSignTransactionHandler extends DAppRequestHandler JSON.stringify(ownIndices) === - JSON.stringify([inputIndex, sigIndex]) + JSON.stringify([inputIndex, sigIndex]), ); if ( @@ -302,13 +302,13 @@ export class AvalancheSignTransactionHandler extends DAppRequestHandler + params: Partial, ): params is EthSendTransactionParams { return !!params.from; } diff --git a/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.test.ts b/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.test.ts index aafb67fa8..831d7dbfa 100644 --- a/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.test.ts +++ b/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.test.ts @@ -60,7 +60,7 @@ describe('background/services/transactions/utils/getTargetNetworkForTx.ts', () = mockNetworkService = new NetworkService( {} as unknown as StorageService, - {} as unknown as FeatureFlagService + {} as unknown as FeatureFlagService, ); // eslint-disable-next-line @@ -115,7 +115,7 @@ describe('background/services/transactions/utils/getTargetNetworkForTx.ts', () = const network = await getTargetNetworkForTx( { chainId: 2 } as any, mockNetworkService, - eth.caipId + eth.caipId, ); expect(network).toBe(otherNetwork); @@ -126,8 +126,8 @@ describe('background/services/transactions/utils/getTargetNetworkForTx.ts', () = getTargetNetworkForTx( { chainId: 12321 } as any, mockNetworkService, - 'eip155:1' - ) + 'eip155:1', + ), ).rejects.toThrow(getRpcError('Provided ChainID is not supported', 1)); }); @@ -136,8 +136,8 @@ describe('background/services/transactions/utils/getTargetNetworkForTx.ts', () = getTargetNetworkForTx( { chainId: ChainId.BITCOIN_TESTNET } as any, mockNetworkService, - eth.caipId - ) + eth.caipId, + ), ).rejects.toThrow(getRpcError('Provided ChainID is not supported', 1)); }); @@ -146,10 +146,10 @@ describe('background/services/transactions/utils/getTargetNetworkForTx.ts', () = getTargetNetworkForTx( { chainId: 43113 } as any, mockNetworkService, - eth.caipId - ) + eth.caipId, + ), ).rejects.toThrow( - getRpcError('Provided ChainID is in a different environment', 1) + getRpcError('Provided ChainID is in a different environment', 1), ); }); @@ -168,8 +168,8 @@ describe('background/services/transactions/utils/getTargetNetworkForTx.ts', () = await getTargetNetworkForTx( { chainId: otherNetwork.chainId } as any, mockNetworkService, - otherNetwork.caipId - ) + otherNetwork.caipId, + ), ).toEqual(otherNetwork); }); @@ -188,10 +188,10 @@ describe('background/services/transactions/utils/getTargetNetworkForTx.ts', () = getTargetNetworkForTx( { chainId: otherNetwork.chainId } as any, mockNetworkService, - 'eip155:1234' - ) + 'eip155:1234', + ), ).rejects.toThrow( - getRpcError('ChainID is not supported for custom networks', 1) + getRpcError('ChainID is not supported for custom networks', 1), ); }); }); diff --git a/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.ts b/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.ts index d8c60b7d8..0efddeb8a 100644 --- a/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.ts +++ b/src/background/services/wallet/handlers/eth_sendTransaction/utils/getTargetNetworkForTx.ts @@ -16,7 +16,7 @@ const assertSameEnvironment = (networkA: Network, activeNetwork?: Network) => { const getTargetNetworkForTx = async ( tx: EthSendTransactionParams, networkService: NetworkService, - activeScope: string + activeScope: string, ) => { if (typeof tx.chainId === 'undefined') { return networkService.getNetwork(activeScope); diff --git a/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.test.ts b/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.test.ts index 488170084..8eb51252d 100644 --- a/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.test.ts +++ b/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.test.ts @@ -16,7 +16,7 @@ describe('src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts', const getAccountServiceMock = (activeAccount?: { type: AccountType }) => ({ activeAccount, - } as any); + }) as any; beforeEach(() => { jest.resetAllMocks(); @@ -25,7 +25,7 @@ describe('src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts', it('returns undefined if there is no active account', async () => { const handler = new GetBtcWalletPolicyDetails( secretsServiceMock, - getAccountServiceMock() + getAccountServiceMock(), ); const result = await handler.handle(buildRpcCall(request)); @@ -39,7 +39,7 @@ describe('src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts', it('returns undefined if the active account is not primary', async () => { const handler = new GetBtcWalletPolicyDetails( secretsServiceMock, - getAccountServiceMock({ type: AccountType.IMPORTED }) + getAccountServiceMock({ type: AccountType.IMPORTED }), ); const result = await handler.handle(buildRpcCall(request)); @@ -62,7 +62,7 @@ describe('src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts', const handler = new GetBtcWalletPolicyDetails( secretsServiceMock, - getAccountServiceMock({ type: AccountType.PRIMARY }) + getAccountServiceMock({ type: AccountType.PRIMARY }), ); const result = await handler.handle(buildRpcCall(request)); diff --git a/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts b/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts index 2b33a9a7f..fc959ccaf 100644 --- a/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts +++ b/src/background/services/wallet/handlers/getBtcWalletPolicyDetails.ts @@ -16,7 +16,7 @@ export class GetBtcWalletPolicyDetails implements HandlerType { constructor( private secretsService: SecretsService, - private accountService: AccountsService + private accountService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -31,9 +31,8 @@ export class GetBtcWalletPolicyDetails implements HandlerType { throw new Error('incorrect account type'); } - const policyInfo = await this.secretsService.getBtcWalletPolicyDetails( - activeAccount - ); + const policyInfo = + await this.secretsService.getBtcWalletPolicyDetails(activeAccount); return { ...request, @@ -41,7 +40,7 @@ export class GetBtcWalletPolicyDetails implements HandlerType { masterFingerprint: policyInfo?.details?.masterFingerprint, }, }; - } catch (err) { + } catch (_err) { return { ...request, result: undefined, diff --git a/src/background/services/wallet/handlers/getUnencryptedMnemonic.test.ts b/src/background/services/wallet/handlers/getUnencryptedMnemonic.test.ts index 22fa556cb..e1840846b 100644 --- a/src/background/services/wallet/handlers/getUnencryptedMnemonic.test.ts +++ b/src/background/services/wallet/handlers/getUnencryptedMnemonic.test.ts @@ -22,7 +22,7 @@ describe('src/background/services/wallet/handlers/getUnencryptedMnemonic.ts', () new GetUnencryptedMnemonicHandler( secretsService, lockService, - accountsService + accountsService, ); it('returns error if password is invalid', async () => { @@ -31,11 +31,11 @@ describe('src/background/services/wallet/handlers/getUnencryptedMnemonic.ts', () const handler = buildHandler(); expect( - await handler.handle(buildRpcCall({ params: ['abcd'] } as any)) + await handler.handle(buildRpcCall({ params: ['abcd'] } as any)), ).toEqual( expect.objectContaining({ error: 'Password invalid', - }) + }), ); }); @@ -48,11 +48,11 @@ describe('src/background/services/wallet/handlers/getUnencryptedMnemonic.ts', () const handler = buildHandler(); expect( - await handler.handle(buildRpcCall({ params: ['abcd'] } as any)) + await handler.handle(buildRpcCall({ params: ['abcd'] } as any)), ).toEqual( expect.objectContaining({ error: 'Not a MnemonicWallet', - }) + }), ); }); @@ -66,11 +66,11 @@ describe('src/background/services/wallet/handlers/getUnencryptedMnemonic.ts', () const handler = buildHandler(); expect( - await handler.handle(buildRpcCall({ params: ['abcd'] } as any)) + await handler.handle(buildRpcCall({ params: ['abcd'] } as any)), ).toEqual( expect.objectContaining({ result: mnemonic, - }) + }), ); }); }); diff --git a/src/background/services/wallet/handlers/getUnencryptedMnemonic.ts b/src/background/services/wallet/handlers/getUnencryptedMnemonic.ts index 0525fd4f5..3c4bd01d7 100644 --- a/src/background/services/wallet/handlers/getUnencryptedMnemonic.ts +++ b/src/background/services/wallet/handlers/getUnencryptedMnemonic.ts @@ -19,7 +19,7 @@ export class GetUnencryptedMnemonicHandler implements HandlerType { constructor( private secretsService: SecretsService, private lockService: LockService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { const [password] = request.params; @@ -47,7 +47,7 @@ export class GetUnencryptedMnemonicHandler implements HandlerType { }; } const secrets = await this.secretsService.getAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if (secrets.secretType !== SecretType.Mnemonic) { diff --git a/src/background/services/wallet/handlers/importLedger.test.ts b/src/background/services/wallet/handlers/importLedger.test.ts index 61961d205..2ad3cd83b 100644 --- a/src/background/services/wallet/handlers/importLedger.test.ts +++ b/src/background/services/wallet/handlers/importLedger.test.ts @@ -29,7 +29,7 @@ describe('src/background/services/wallet/handlers/importLedger', () => { const handler = new ImportLedgerHandler( walletService, accountsService, - secretsService + secretsService, ); return handler.handle( @@ -37,7 +37,7 @@ describe('src/background/services/wallet/handlers/importLedger', () => { id: '123', method: ExtensionRequest.WALLET_IMPORT_LEDGER, params: [params], - }) + }), ); }; diff --git a/src/background/services/wallet/handlers/importLedger.ts b/src/background/services/wallet/handlers/importLedger.ts index 1836d7cad..3aebaee45 100644 --- a/src/background/services/wallet/handlers/importLedger.ts +++ b/src/background/services/wallet/handlers/importLedger.ts @@ -24,7 +24,7 @@ export class ImportLedgerHandler implements HandlerType { constructor( private walletService: WalletService, private accountsService: AccountsService, - private secretsService: SecretsService + private secretsService: SecretsService, ) {} async #addAccounts(walletId: string, numberOfAccounts: number = 3) { @@ -109,9 +109,8 @@ export class ImportLedgerHandler implements HandlerType { secretType === SecretType.LedgerLive ? pubKeys?.length : undefined; await this.#addAccounts(id, numberOfAccountsToCreate); - const addedWallet = await this.secretsService.getWalletAccountsSecretsById( - id - ); + const addedWallet = + await this.secretsService.getWalletAccountsSecretsById(id); return { ...request, result: { diff --git a/src/background/services/wallet/handlers/importSeedPhrase.test.ts b/src/background/services/wallet/handlers/importSeedPhrase.test.ts index 4ae5d31bc..783fc031c 100644 --- a/src/background/services/wallet/handlers/importSeedPhrase.test.ts +++ b/src/background/services/wallet/handlers/importSeedPhrase.test.ts @@ -32,7 +32,7 @@ describe('src/background/services/wallet/handlers/importSeedPhrase', () => { const handler = new ImportSeedPhraseHandler( walletService, accountsService, - secretsService + secretsService, ); return handler.handle( @@ -40,7 +40,7 @@ describe('src/background/services/wallet/handlers/importSeedPhrase', () => { id: '123', method: ExtensionRequest.WALLET_IMPORT_SEED_PHRASE, params: [params], - }) + }), ); }; @@ -52,7 +52,7 @@ describe('src/background/services/wallet/handlers/importSeedPhrase', () => { expect(error).toEqual( expect.objectContaining({ data: { reason: SeedphraseImportError.ExistingSeedphrase }, - }) + }), ); }); @@ -90,11 +90,11 @@ describe('src/background/services/wallet/handlers/importSeedPhrase', () => { // Expect both calls to be the same despite different casing in the seed phrase expect(walletService.addPrimaryWallet).toHaveBeenNthCalledWith( 1, - expectedCall + expectedCall, ); expect(walletService.addPrimaryWallet).toHaveBeenNthCalledWith( 2, - expectedCall + expectedCall, ); }); diff --git a/src/background/services/wallet/handlers/importSeedPhrase.ts b/src/background/services/wallet/handlers/importSeedPhrase.ts index c1d7f7e1e..9f687df73 100644 --- a/src/background/services/wallet/handlers/importSeedPhrase.ts +++ b/src/background/services/wallet/handlers/importSeedPhrase.ts @@ -33,7 +33,7 @@ export class ImportSeedPhraseHandler implements HandlerType { constructor( private walletService: WalletService, private accountsService: AccountsService, - private secretsService: SecretsService + private secretsService: SecretsService, ) {} async #addAccounts(walletId: string) { @@ -57,7 +57,7 @@ export class ImportSeedPhraseHandler implements HandlerType { const isKnown = await this.secretsService.isKnownSecret( SecretType.Mnemonic, - mnemonic + mnemonic, ); if (isKnown) { @@ -85,9 +85,8 @@ export class ImportSeedPhraseHandler implements HandlerType { await this.#addAccounts(id); - const addedWallet = await this.secretsService.getWalletAccountsSecretsById( - id - ); + const addedWallet = + await this.secretsService.getWalletAccountsSecretsById(id); return { ...request, diff --git a/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.test.ts b/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.test.ts index da4aae745..4b7e5c4c7 100644 --- a/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.test.ts +++ b/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.test.ts @@ -45,11 +45,11 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts const handler = new StoreBtcWalletPolicyDetails( secretsServiceMock, networkServiceMock, - accountsServiceMock + accountsServiceMock, ); await expect(handler.handle(buildRpcCall(request))).rejects.toThrow( - 'no account selected' + 'no account selected', ); }); @@ -63,11 +63,11 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts const handler = new StoreBtcWalletPolicyDetails( secretsServiceMock, networkServiceMock, - accountsServiceMock + accountsServiceMock, ); await expect(handler.handle(buildRpcCall(request))).rejects.toThrow( - 'incorrect account type' + 'incorrect account type', ); }); @@ -84,11 +84,11 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts const handler = new StoreBtcWalletPolicyDetails( secretsServiceMock, networkServiceMock, - accountsServiceMock + accountsServiceMock, ); await expect(handler.handle(buildRpcCall(request))).rejects.toThrow( - 'unknown derivation path' + 'unknown derivation path', ); }); @@ -108,13 +108,13 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts const handler = new StoreBtcWalletPolicyDetails( secretsServiceMock, networkServiceMock, - accountsServiceMock + accountsServiceMock, ); const result = await handler.handle(buildRpcCall(request)); expect( - secretsServiceMock.storeBtcWalletPolicyDetails + secretsServiceMock.storeBtcWalletPolicyDetails, ).not.toHaveBeenCalled(); expect(result).toStrictEqual({ @@ -141,7 +141,7 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts const handler = new StoreBtcWalletPolicyDetails( secretsServiceMock, networkServiceMock, - accountsServiceMock + accountsServiceMock, ); const result = await handler.handle(buildRpcCall(request)); @@ -149,7 +149,7 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts expect(getBech32AddressFromXPub).toHaveBeenCalledWith( 'xpub', 1, - networks.testnet + networks.testnet, ); expect(secretsServiceMock.storeBtcWalletPolicyDetails).toHaveBeenCalledWith( @@ -158,7 +158,7 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts 'hmacHex', 'name', 'wallet-id', - {} + {}, ); expect(result).toStrictEqual({ @@ -186,7 +186,7 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts const handler = new StoreBtcWalletPolicyDetails( secretsServiceMock, networkServiceMock, - accountsServiceMock + accountsServiceMock, ); const result = await handler.handle(buildRpcCall(request)); @@ -194,7 +194,7 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts expect(getBech32AddressFromXPub).toHaveBeenCalledWith( 'xpub', 1, - networks.testnet + networks.testnet, ); expect(secretsServiceMock.storeBtcWalletPolicyDetails).toHaveBeenCalledWith( @@ -203,7 +203,7 @@ describe('src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts 'hmacHex', 'name', 'wallet-id', - {} + {}, ); expect(result).toStrictEqual({ diff --git a/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts b/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts index dae80a4ea..8df23fe42 100644 --- a/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts +++ b/src/background/services/wallet/handlers/storeBtcWalletPolicyDetails.ts @@ -25,7 +25,7 @@ export class StoreBtcWalletPolicyDetails implements HandlerType { constructor( private secretsService: SecretsService, private networkService: NetworkService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request }) => { @@ -33,7 +33,7 @@ export class StoreBtcWalletPolicyDetails implements HandlerType { throw new Error('there is no active account'); } const secrets = await this.secretsService.getAccountSecrets( - this.accountsService.activeAccount + this.accountsService.activeAccount, ); if ( @@ -65,7 +65,7 @@ export class StoreBtcWalletPolicyDetails implements HandlerType { const derivedAddressBtc = getBech32AddressFromXPub( xpub, accountIndex, - isMainnet ? networks.bitcoin : networks.testnet + isMainnet ? networks.bitcoin : networks.testnet, ); const isCorrectDevice = activeAccount.addressBTC === derivedAddressBtc; @@ -76,7 +76,7 @@ export class StoreBtcWalletPolicyDetails implements HandlerType { hmacHex, name, secrets.id, - this.accountsService.activeAccount + this.accountsService.activeAccount, ); } diff --git a/src/background/services/wallet/utils/ensureMessageFormatIsValid.test.ts b/src/background/services/wallet/utils/ensureMessageFormatIsValid.test.ts index 026232e23..cc9718d41 100644 --- a/src/background/services/wallet/utils/ensureMessageFormatIsValid.test.ts +++ b/src/background/services/wallet/utils/ensureMessageFormatIsValid.test.ts @@ -36,7 +36,7 @@ describe('src/background/services/wallet/utils/ensureMessageFormatIsValid.test.t const payload = getPayload('types'); expect(() => ensureMessageFormatIsValid(messageType, payload, 1)).toThrow( - '"types" is required' + '"types" is required', ); }); @@ -44,7 +44,7 @@ describe('src/background/services/wallet/utils/ensureMessageFormatIsValid.test.t const payload = getPayload('types'); expect(() => - ensureMessageFormatIsValid(messageType, { ...payload, types: {} }, 1) + ensureMessageFormatIsValid(messageType, { ...payload, types: {} }, 1), ).toThrow('"types.EIP712Domain" is required'); }); @@ -52,7 +52,7 @@ describe('src/background/services/wallet/utils/ensureMessageFormatIsValid.test.t const payload = getPayload('primaryType'); expect(() => ensureMessageFormatIsValid(messageType, payload, 1)).toThrow( - '"primaryType" is required' + '"primaryType" is required', ); }); @@ -60,7 +60,7 @@ describe('src/background/services/wallet/utils/ensureMessageFormatIsValid.test.t const payload = getPayload('domain'); expect(() => ensureMessageFormatIsValid(messageType, payload, 1)).toThrow( - '"domain" is required' + '"domain" is required', ); }); @@ -68,7 +68,7 @@ describe('src/background/services/wallet/utils/ensureMessageFormatIsValid.test.t const payload = getPayload('message'); expect(() => ensureMessageFormatIsValid(messageType, payload, 1)).toThrow( - '"message" is required' + '"message" is required', ); }); @@ -77,10 +77,10 @@ describe('src/background/services/wallet/utils/ensureMessageFormatIsValid.test.t const payloadWithHexChainId = getPayload(undefined, true); expect(() => ensureMessageFormatIsValid(messageType, payload, 1)).toThrow( - 'target chainId does not match the currently active one' + 'target chainId does not match the currently active one', ); expect(() => - ensureMessageFormatIsValid(messageType, payloadWithHexChainId, 1) + ensureMessageFormatIsValid(messageType, payloadWithHexChainId, 1), ).toThrow('target chainId does not match the currently active one'); }); @@ -89,10 +89,10 @@ describe('src/background/services/wallet/utils/ensureMessageFormatIsValid.test.t const payloadWithHexChainId = getPayload(undefined, true); expect( - ensureMessageFormatIsValid(messageType, payload, 2) + ensureMessageFormatIsValid(messageType, payload, 2), ).toBeUndefined(); expect( - ensureMessageFormatIsValid(messageType, payloadWithHexChainId, 2) + ensureMessageFormatIsValid(messageType, payloadWithHexChainId, 2), ).toBeUndefined(); }); }); diff --git a/src/background/services/wallet/utils/ensureMessageFormatIsValid.ts b/src/background/services/wallet/utils/ensureMessageFormatIsValid.ts index 54c9ed3be..a6d6d40d8 100644 --- a/src/background/services/wallet/utils/ensureMessageFormatIsValid.ts +++ b/src/background/services/wallet/utils/ensureMessageFormatIsValid.ts @@ -31,7 +31,7 @@ const TYPED_MESSAGE_SCHEMA = Joi.object({ const ensureMessageFormatIsValid = ( messageType: MessageType, data: Record, - activeChainId: number + activeChainId: number, ) => { if ( messageType === MessageType.SIGN_TYPED_DATA_V3 || diff --git a/src/background/services/wallet/utils/getAddressByVM.test.ts b/src/background/services/wallet/utils/getAddressByVM.test.ts index 2a0251719..ccb6a059c 100644 --- a/src/background/services/wallet/utils/getAddressByVM.test.ts +++ b/src/background/services/wallet/utils/getAddressByVM.test.ts @@ -35,6 +35,6 @@ describe('src/background/services/wallet/utils/getAddressByVM', () => { 'returns the correct address for $VM', ({ vm, account, expectedAddress }) => { expect(getAddressByVM(vm, account)).toBe(expectedAddress); - } + }, ); }); diff --git a/src/background/services/wallet/utils/getDerivationPath.test.ts b/src/background/services/wallet/utils/getDerivationPath.test.ts index 6ba66698c..b126098c1 100644 --- a/src/background/services/wallet/utils/getDerivationPath.test.ts +++ b/src/background/services/wallet/utils/getDerivationPath.test.ts @@ -6,7 +6,7 @@ import getDerivationPath from './getDerivationPath'; describe('src/background/services/wallet/utils/getDerivationPath.ts', () => { it('throws if none of the secrets were provided', () => { expect(() => getDerivationPath({})).toThrow( - 'Unable to get derivation type for wallet' + 'Unable to get derivation type for wallet', ); }); diff --git a/src/background/services/wallet/utils/getProvidedUtxos.ts b/src/background/services/wallet/utils/getProvidedUtxos.ts index 034d71c83..98412fc04 100644 --- a/src/background/services/wallet/utils/getProvidedUtxos.ts +++ b/src/background/services/wallet/utils/getProvidedUtxos.ts @@ -12,7 +12,7 @@ const getProvidedUtxos = ({ utxoHexes = [], vm }: Param) => { const utxoBytes = utils.hexToBuffer(utxoHex); return Utxo.fromBytes(utxoBytes, codec)[0]; }); - } catch (err) { + } catch (_err) { return []; } }; diff --git a/src/background/services/wallet/utils/prepareBtcTxForLedger.ts b/src/background/services/wallet/utils/prepareBtcTxForLedger.ts index 218c1b0c8..0f024a402 100644 --- a/src/background/services/wallet/utils/prepareBtcTxForLedger.ts +++ b/src/background/services/wallet/utils/prepareBtcTxForLedger.ts @@ -3,7 +3,7 @@ import { BtcTransactionRequest } from '../models'; export async function prepareBtcTxForLedger( tx: BtcTransactionRequest, - provider: BitcoinProviderAbstract + provider: BitcoinProviderAbstract, ): Promise { //get unique hashes const txHashSet = new Set(tx.inputs.map((i) => i.txHash)); diff --git a/src/background/services/walletConnect/WalletConnectService.test.ts b/src/background/services/walletConnect/WalletConnectService.test.ts index d757431e7..72e407330 100644 --- a/src/background/services/walletConnect/WalletConnectService.test.ts +++ b/src/background/services/walletConnect/WalletConnectService.test.ts @@ -234,7 +234,7 @@ describe('src/background/services/walletConnect/WalletConnectService.ts', () => .finally(() => { expect(client.session.delete).toHaveBeenCalledWith( mockedSession.topic, - expect.anything() + expect.anything(), ); done(); }); @@ -276,7 +276,7 @@ describe('src/background/services/walletConnect/WalletConnectService.ts', () => }) .catch((err) => { expect(err.code).toEqual( - WalletConnectErrorCode.NoAccountsConnected + WalletConnectErrorCode.NoAccountsConnected, ); }) .finally(done); @@ -349,11 +349,11 @@ describe('src/background/services/walletConnect/WalletConnectService.ts', () => chainId: 1, fromAddress: mockedAddress, expiry: 1234, - } + }, ); expect(client.request).toHaveBeenCalledWith( - expect.objectContaining({ expiry: 1234 }) + expect.objectContaining({ expiry: 1234 }), ); }); }); diff --git a/src/background/services/walletConnect/WalletConnectService.ts b/src/background/services/walletConnect/WalletConnectService.ts index 30aad3ebc..5ca45b123 100644 --- a/src/background/services/walletConnect/WalletConnectService.ts +++ b/src/background/services/walletConnect/WalletConnectService.ts @@ -64,10 +64,10 @@ export class WalletConnectService implements WalletConnectTransport { }); this.#setupSessionListeners(this.#client); this.#initialized = true; - } catch (err) { + } catch (_err) { throw new WalletConnectError( 'Unable to initialize the WalletConnect client', - WalletConnectErrorCode.ClientInitFailed + WalletConnectErrorCode.ClientInitFailed, ); } } @@ -84,7 +84,7 @@ export class WalletConnectService implements WalletConnectTransport { // Also: TypeScript requirements. throw new WalletConnectError( 'The WalletConnect client was not initialized properly', - WalletConnectErrorCode.NoClient + WalletConnectErrorCode.NoClient, ); } @@ -144,7 +144,7 @@ export class WalletConnectService implements WalletConnectTransport { chainId: accountSession.chains[0] as number, tabId, fromAddress: accountSession.addresses[0], - } + }, ); } catch { // If this request throws an error for whatever reason, @@ -162,7 +162,7 @@ export class WalletConnectService implements WalletConnectTransport { const hopefullySufficientSession = await this.getSessionInfo( fromAddress, - chainId + chainId, ); // At this point we either find a sufficient session or we don't. @@ -177,7 +177,7 @@ export class WalletConnectService implements WalletConnectTransport { async request( { method, params }: RequestPayload, - { chainId, fromAddress, expiry }: RequestOptions + { chainId, fromAddress, expiry }: RequestOptions, ): Promise { const client = await this.#getClient(); @@ -234,7 +234,7 @@ export class WalletConnectService implements WalletConnectTransport { if (!obtainedAddress) { throw new WalletConnectError( 'Cannot retrieve the imported account', - WalletConnectErrorCode.NoAccountsConnected + WalletConnectErrorCode.NoAccountsConnected, ); } @@ -242,12 +242,12 @@ export class WalletConnectService implements WalletConnectTransport { // Remove the session if the user imported the wrong account. client.session.delete( session.topic, - getSdkError('UNSUPPORTED_ACCOUNTS') + getSdkError('UNSUPPORTED_ACCOUNTS'), ); throw new WalletConnectError( 'Imported account has a different address', - WalletConnectErrorCode.IncorrectAddress + WalletConnectErrorCode.IncorrectAddress, ); } @@ -274,11 +274,11 @@ export class WalletConnectService implements WalletConnectTransport { const addressesOverlap = areArraysOverlapping( activeSession.addresses, - oldSession.addresses + oldSession.addresses, ); const chainsOverlap = areArraysOverlapping( activeSession.chains, - oldSession.chains + oldSession.chains, ); return addressesOverlap && chainsOverlap; @@ -290,7 +290,7 @@ export class WalletConnectService implements WalletConnectTransport { if (pairingTopic) { await client.pairing.delete( pairingTopic, - getSdkError('USER_DISCONNECTED') + getSdkError('USER_DISCONNECTED'), ); } }); @@ -305,14 +305,14 @@ export class WalletConnectService implements WalletConnectTransport { if (isUserRejectionError(err)) { throw new WalletConnectError( 'User rejected the request', - WalletConnectErrorCode.UserRejected + WalletConnectErrorCode.UserRejected, ); } if (isProposalExpiredError(err)) { throw new WalletConnectError( 'Session proposal expired', - WalletConnectErrorCode.ProposalExpired + WalletConnectErrorCode.ProposalExpired, ); } @@ -321,7 +321,7 @@ export class WalletConnectService implements WalletConnectTransport { throw new WalletConnectError( 'Unable to connect via WalletConnect', WalletConnectErrorCode.UnknownError, - err + err, ); } @@ -350,7 +350,7 @@ export class WalletConnectService implements WalletConnectTransport { async getSessionInfo( lookupAddress: string, - chainId?: number + chainId?: number, ): Promise { const session = await this.#findSession(lookupAddress, chainId); @@ -379,7 +379,7 @@ export class WalletConnectService implements WalletConnectTransport { async #findSession( lookupAddress: string, - chainId?: number + chainId?: number, ): Promise { const client = await this.#getClient(); const sessions = client.session.getAll() ?? []; @@ -403,7 +403,7 @@ export class WalletConnectService implements WalletConnectTransport { try { await client.session.delete( event.topic, - getSdkError('USER_DISCONNECTED') + getSdkError('USER_DISCONNECTED'), ); } catch (ex: any) { // Ignore "no matching key" error, as it may be caused by the wallet app notifying @@ -423,7 +423,7 @@ export class WalletConnectService implements WalletConnectTransport { try { await core.pairing.pairings.delete( event.topic, - getSdkError('USER_DISCONNECTED') + getSdkError('USER_DISCONNECTED'), ); } catch (ex) { // Ignore "no matching key" error, as it may be caused by the wallet app notifying @@ -438,14 +438,14 @@ export class WalletConnectService implements WalletConnectTransport { } async avalancheGetAccounts( - options: RequestOptions + options: RequestOptions, ): Promise { return this.request( { method: 'avalanche_getAccounts', params: [], }, - options + options, ); } @@ -461,13 +461,13 @@ export class WalletConnectService implements WalletConnectTransport { try { await client.session.delete( session.topic, - getSdkError('USER_DISCONNECTED') + getSdkError('USER_DISCONNECTED'), ); if (session.pairingTopic) { await client.pairing.delete( session.pairingTopic, - getSdkError('USER_DISCONNECTED') + getSdkError('USER_DISCONNECTED'), ); } } catch (ex) { diff --git a/src/background/services/walletConnect/WalletConnectSigner.test.ts b/src/background/services/walletConnect/WalletConnectSigner.test.ts index 42c6f3099..70e8508ce 100644 --- a/src/background/services/walletConnect/WalletConnectSigner.test.ts +++ b/src/background/services/walletConnect/WalletConnectSigner.test.ts @@ -62,7 +62,7 @@ describe('src/background/services/walletConnect/WalletConnectSigner.ts', () => { testChainId, testAddress, testTabId, - requestExpiry + requestExpiry, ); jest.mocked(makeBNLike).mockImplementation((input) => input as BNLike); @@ -114,14 +114,14 @@ describe('src/background/services/walletConnect/WalletConnectSigner.ts', () => { }, ], }, - transportTestOptions + transportTestOptions, ); expect(makeBNLike).toBeCalledTimes(5); expect(makeBNLike).toHaveBeenNthCalledWith(1, txParams.nonce); expect(makeBNLike).toHaveBeenNthCalledWith(2, txParams.maxFeePerGas); expect(makeBNLike).toHaveBeenNthCalledWith( 3, - txParams.maxPriorityFeePerGas + txParams.maxPriorityFeePerGas, ); expect(makeBNLike).toHaveBeenNthCalledWith(4, txParams.gasLimit); expect(makeBNLike).toHaveBeenNthCalledWith(5, txParams.value); @@ -163,7 +163,7 @@ describe('src/background/services/walletConnect/WalletConnectSigner.ts', () => { ...transportTestOptions, chainId: testSession.chains[0], expiry: requestExpiry, - } + }, ); }); @@ -191,7 +191,7 @@ describe('src/background/services/walletConnect/WalletConnectSigner.ts', () => { internalIndices: [2], }, }, - { ...transportTestOptions, chainId: testSession.chains[0] } + { ...transportTestOptions, chainId: testSession.chains[0] }, ); }); @@ -222,7 +222,7 @@ describe('src/background/services/walletConnect/WalletConnectSigner.ts', () => { internalIndices: [2], }, }, - transportTestOptions + transportTestOptions, ); }); }); diff --git a/src/background/services/walletConnect/WalletConnectSigner.ts b/src/background/services/walletConnect/WalletConnectSigner.ts index edc82c92d..207ea1296 100644 --- a/src/background/services/walletConnect/WalletConnectSigner.ts +++ b/src/background/services/walletConnect/WalletConnectSigner.ts @@ -15,7 +15,7 @@ export class WalletConnectSigner { private chainId: number, private address: string, private tabId?: number, - private requestExpiry?: number + private requestExpiry?: number, ) {} /** @@ -55,7 +55,7 @@ export class WalletConnectSigner { tabId: this.tabId, fromAddress: this.address, expiry: this.requestExpiry, - } + }, ); return { @@ -68,7 +68,7 @@ export class WalletConnectSigner { */ async signTx( request: Avalanche.SignTxRequest, - method?: string + method?: string, ): Promise { const { externalIndices, internalIndices, tx } = request; @@ -107,7 +107,7 @@ export class WalletConnectSigner { tabId: this.tabId, fromAddress: this.address, expiry: this.requestExpiry, - } + }, ); const isDispatched = method === 'avalanche_sendTransaction'; @@ -130,7 +130,7 @@ export class WalletConnectSigner { tabId: this.tabId, fromAddress: this.address, expiry: this.requestExpiry, - } + }, ); } } diff --git a/src/background/services/walletConnect/WalletConnectStorage.test.ts b/src/background/services/walletConnect/WalletConnectStorage.test.ts index ef9d4a6ba..e5ba5553b 100644 --- a/src/background/services/walletConnect/WalletConnectStorage.test.ts +++ b/src/background/services/walletConnect/WalletConnectStorage.test.ts @@ -52,7 +52,7 @@ describe('src/background/services/walletConnect/WalletConnectStorage.ts', () => WALLET_CONNECT_STORAGE_KEY, { 'dummy-key': 123, - } + }, ); }); @@ -122,7 +122,7 @@ describe('src/background/services/walletConnect/WalletConnectStorage.ts', () => const service = new WalletConnectStorage(storageEngine); expect(() => service.getItem('dummy-key')).rejects.toThrow( - 'Missing encryption key' + 'Missing encryption key', ); }); @@ -167,35 +167,35 @@ describe('src/background/services/walletConnect/WalletConnectStorage.ts', () => expect(storageEngine.save).toHaveBeenNthCalledWith( 1, WALLET_CONNECT_STORAGE_KEY, - { 'key-1': 1 } + { 'key-1': 1 }, ); // Call: setItem('key-2', 2) expect(storageEngine.save).toHaveBeenNthCalledWith( 2, WALLET_CONNECT_STORAGE_KEY, - { 'key-1': 1, 'key-2': 2 } + { 'key-1': 1, 'key-2': 2 }, ); // Call: setItem('key-3', 3) expect(storageEngine.save).toHaveBeenNthCalledWith( 3, WALLET_CONNECT_STORAGE_KEY, - { 'key-1': 1, 'key-2': 2, 'key-3': 3 } + { 'key-1': 1, 'key-2': 2, 'key-3': 3 }, ); // Call: removeItem('key-2') expect(storageEngine.save).toHaveBeenNthCalledWith( 4, WALLET_CONNECT_STORAGE_KEY, - { 'key-1': 1, 'key-3': 3 } // key-2 was removed + { 'key-1': 1, 'key-3': 3 }, // key-2 was removed ); // Call: setItem('key-4', 4) expect(storageEngine.save).toHaveBeenNthCalledWith( 5, WALLET_CONNECT_STORAGE_KEY, - { 'key-1': 1, 'key-3': 3, 'key-4': 4 } + { 'key-1': 1, 'key-3': 3, 'key-4': 4 }, ); }); }); diff --git a/src/background/services/walletConnect/WalletConnectStorage.ts b/src/background/services/walletConnect/WalletConnectStorage.ts index 3bcbee901..2f4fa3335 100644 --- a/src/background/services/walletConnect/WalletConnectStorage.ts +++ b/src/background/services/walletConnect/WalletConnectStorage.ts @@ -28,13 +28,13 @@ export class WalletConnectStorage { async setItem( key: keyof WalletConnectStore, - value: T + value: T, ): Promise { return this.#addToQueue(() => this.#write(key, value)); } async getItem( - key: keyof WalletConnectStore + key: keyof WalletConnectStore, ): Promise { const store = await this.#getStore(); @@ -73,7 +73,7 @@ export class WalletConnectStorage { async #getStore(): Promise> { const store = await this.storage.load>( - WALLET_CONNECT_STORAGE_KEY + WALLET_CONNECT_STORAGE_KEY, ); return store ?? {}; @@ -124,7 +124,7 @@ export class WalletConnectStorage { async #write( key: keyof WalletConnectStore, - value: T + value: T, ): Promise { const store = await this.#getStore(); diff --git a/src/background/services/walletConnect/events/eventFilters.ts b/src/background/services/walletConnect/events/eventFilters.ts index d2a36b476..e07716468 100644 --- a/src/background/services/walletConnect/events/eventFilters.ts +++ b/src/background/services/walletConnect/events/eventFilters.ts @@ -7,19 +7,19 @@ import { } from '../models'; export function isUriGeneratedEvent( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return evt?.name === WalletConnectEvent.UriGenerated; } export function isSessionPermissionsMismatchEvent( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { return evt?.name === WalletConnectEvent.SessionPermissionsMismatch; } export function isWalletConnectEvent( - evt: ExtensionConnectionEvent + evt: ExtensionConnectionEvent, ): evt is ExtensionConnectionEvent { const wcEvents = Object.values(WalletConnectEvent) as string[]; diff --git a/src/background/services/walletConnect/events/walletConnectEvents.ts b/src/background/services/walletConnect/events/walletConnectEvents.ts index f7ca885d0..953ae6eb9 100644 --- a/src/background/services/walletConnect/events/walletConnectEvents.ts +++ b/src/background/services/walletConnect/events/walletConnectEvents.ts @@ -27,7 +27,7 @@ export class WalletConnectEvents implements ExtensionEventEmitter { name: WalletConnectEvent.SessionPermissionsMismatch, value: data, }); - } + }, ); } @@ -36,7 +36,7 @@ export class WalletConnectEvents implements ExtensionEventEmitter { } removeListener( - handler: (event: ExtensionConnectionEvent) => void + handler: (event: ExtensionConnectionEvent) => void, ): void { this.eventEmitter.off('update', handler); } diff --git a/src/background/services/walletConnect/handlers/walletConnectImportAccount.test.ts b/src/background/services/walletConnect/handlers/walletConnectImportAccount.test.ts index dc40c177c..e51f65390 100644 --- a/src/background/services/walletConnect/handlers/walletConnectImportAccount.test.ts +++ b/src/background/services/walletConnect/handlers/walletConnectImportAccount.test.ts @@ -36,7 +36,7 @@ describe('background/services/walletConnect/handlers/walletConnectImportAccount. const handler = new WalletConnectImportAccount( wcServiceMock, networkServiceMock, - accountServiceMock + accountServiceMock, ); const request = { method: ExtensionRequest.WALLET_CONNECT_IMPORT_ACCOUNT, @@ -84,7 +84,7 @@ describe('background/services/walletConnect/handlers/walletConnectImportAccount. const handler = new WalletConnectImportAccount( wcService, networkServiceMock, - accountsServiceWithAccountsMock + accountsServiceWithAccountsMock, ); const request = { method: ExtensionRequest.WALLET_CONNECT_IMPORT_ACCOUNT, @@ -97,7 +97,7 @@ describe('background/services/walletConnect/handlers/walletConnectImportAccount. connectedApp: mockedSessionInfo.walletApp, }); expect( - accountsServiceWithAccountsMock.addImportedAccount + accountsServiceWithAccountsMock.addImportedAccount, ).toHaveBeenCalledWith({ name: 'WalletConnect #1', options: { @@ -140,7 +140,7 @@ describe('background/services/walletConnect/handlers/walletConnectImportAccount. const handler = new WalletConnectImportAccount( wcServiceWithReturnMock, networkServiceMock, - accountsServiceWithAccountsMock + accountsServiceWithAccountsMock, ); const request = { method: ExtensionRequest.WALLET_CONNECT_IMPORT_ACCOUNT, @@ -154,13 +154,13 @@ describe('background/services/walletConnect/handlers/walletConnectImportAccount. tabId: undefined, }); expect(accountsServiceWithAccountsMock.getAccounts).toHaveBeenCalledTimes( - 1 + 1, ); expect( - accountsServiceWithAccountsMock.addImportedAccount + accountsServiceWithAccountsMock.addImportedAccount, ).toHaveBeenCalledTimes(1); expect( - accountsServiceWithAccountsMock.addImportedAccount + accountsServiceWithAccountsMock.addImportedAccount, ).toHaveBeenCalledWith({ name: 'WalletConnect #1', options: { @@ -193,7 +193,7 @@ describe('background/services/walletConnect/handlers/walletConnectImportAccount. const handler = new WalletConnectImportAccount( wcServiceWithReturnMock, networkServiceMock, - accountServiceMock + accountServiceMock, ); const request = { method: ExtensionRequest.WALLET_CONNECT_IMPORT_ACCOUNT, diff --git a/src/background/services/walletConnect/handlers/walletConnectImportAccount.ts b/src/background/services/walletConnect/handlers/walletConnectImportAccount.ts index c085f8215..2d7ecaa7e 100644 --- a/src/background/services/walletConnect/handlers/walletConnectImportAccount.ts +++ b/src/background/services/walletConnect/handlers/walletConnectImportAccount.ts @@ -32,7 +32,7 @@ export class WalletConnectImportAccount implements HandlerType { constructor( private wcService: WalletConnectService, private networkService: NetworkService, - private accountsService: AccountsService + private accountsService: AccountsService, ) {} handle: HandlerType['handle'] = async ({ request, scope }) => { @@ -57,9 +57,8 @@ export class WalletConnectImportAccount implements HandlerType { // If account was already connected, we only need to activate it after obtaining the sesssion. if (reconnectionAddress) { - const activatedAccountId = await this.#handleSuccessfulReconnection( - request - ); + const activatedAccountId = + await this.#handleSuccessfulReconnection(request); return { ...request, @@ -101,7 +100,7 @@ export class WalletConnectImportAccount implements HandlerType { async #getAccountData( request: RequestPayload, - session: WalletConnectSessionInfo + session: WalletConnectSessionInfo, ) { const addressC = session.addresses[0]; @@ -122,7 +121,7 @@ export class WalletConnectImportAccount implements HandlerType { const pubKey = await this.#getPublicKey(chainId, addressC, tabId); const account = accounts.find( - ({ addressC: mobileAddressC }) => mobileAddressC === addressC + ({ addressC: mobileAddressC }) => mobileAddressC === addressC, ); if (account) { @@ -153,7 +152,7 @@ export class WalletConnectImportAccount implements HandlerType { } #getImportType( - session: WalletConnectSessionInfo + session: WalletConnectSessionInfo, ): Exclude { return session.walletApp.name === FIREBLOCKS_APP_NAME ? ImportType.FIREBLOCKS @@ -164,12 +163,12 @@ export class WalletConnectImportAccount implements HandlerType { const { imported } = await this.accountsService.getAccounts(); const [reconnectionAddress] = request.params; const account = Object.values(imported).find( - (acc) => acc.addressC === reconnectionAddress + (acc) => acc.addressC === reconnectionAddress, ); if (!account) { throw new Error( - 'Attempted to reconnect via WalletConnect, but the account was never imported in the first place' + 'Attempted to reconnect via WalletConnect, but the account was never imported in the first place', ); } @@ -184,7 +183,7 @@ export class WalletConnectImportAccount implements HandlerType { const accountType = IMPORT_TYPE_TO_ACCOUNT_TYPE_MAP[importType]; const accountsByType = Object.values(importedAccounts).filter( - ({ type }) => type === accountType + ({ type }) => type === accountType, ); const prefix = importType === ImportType.FIREBLOCKS ? 'Fireblocks' : 'WalletConnect'; @@ -195,7 +194,7 @@ export class WalletConnectImportAccount implements HandlerType { async #getPublicKey( chainId: number, address: string, - tabId?: number + tabId?: number, ): Promise { return this.wcService.request( { @@ -206,7 +205,7 @@ export class WalletConnectImportAccount implements HandlerType { chainId, tabId, fromAddress: address, - } + }, ); } } diff --git a/src/background/services/walletConnect/models.ts b/src/background/services/walletConnect/models.ts index 796c634ec..278c47a8c 100644 --- a/src/background/services/walletConnect/models.ts +++ b/src/background/services/walletConnect/models.ts @@ -74,7 +74,7 @@ export class WalletConnectError extends Error { constructor( message: string, code: WalletConnectErrorCode, - originalError?: Error + originalError?: Error, ) { super(message); this.code = code; @@ -103,10 +103,10 @@ export interface WalletConnectTransport { connect(options: ConnectOptions): Promise; request( payload: RequestPayload, - options: RequestOptions + options: RequestOptions, ): Promise; getSessionInfo( lookupAddress: string, - chainId?: number + chainId?: number, ): Promise; } diff --git a/src/background/services/web3/handlers/avalanche_getProviderState.test.ts b/src/background/services/web3/handlers/avalanche_getProviderState.test.ts index 9e588f1c2..165f82b9d 100644 --- a/src/background/services/web3/handlers/avalanche_getProviderState.test.ts +++ b/src/background/services/web3/handlers/avalanche_getProviderState.test.ts @@ -24,7 +24,7 @@ describe('background/services/web3/handlers/avalanche_getProviderState.ts', () = } as AccountsService); expect( - await handler.handleUnauthenticated(buildRpcCall(mockRequest)) + await handler.handleUnauthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: { @@ -41,11 +41,11 @@ describe('background/services/web3/handlers/avalanche_getProviderState.ts', () = { getInitialNetworkForDapp: () => ({ chainId: 1 }), } as unknown as NetworkService, - { activeAccount: { addressC: '0x000000' } } as AccountsService + { activeAccount: { addressC: '0x000000' } } as AccountsService, ); expect( - await handler.handleUnauthenticated(buildRpcCall(mockRequest)) + await handler.handleUnauthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: { @@ -69,7 +69,7 @@ describe('background/services/web3/handlers/avalanche_getProviderState.ts', () = } as AccountsService); expect( - await handler.handleAuthenticated(buildRpcCall(mockRequest)) + await handler.handleAuthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: { @@ -86,11 +86,11 @@ describe('background/services/web3/handlers/avalanche_getProviderState.ts', () = { getInitialNetworkForDapp: () => ({ chainId: 1 }), } as unknown as NetworkService, - { activeAccount: { addressC: '0x000000' } } as AccountsService + { activeAccount: { addressC: '0x000000' } } as AccountsService, ); expect( - await handler.handleAuthenticated(buildRpcCall(mockRequest)) + await handler.handleAuthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: { @@ -107,11 +107,11 @@ describe('background/services/web3/handlers/avalanche_getProviderState.ts', () = { getInitialNetworkForDapp: () => ({ chainId: 43114 }), } as unknown as NetworkService, - { activeAccount: undefined } as AccountsService + { activeAccount: undefined } as AccountsService, ); expect( - await handler.handleAuthenticated(buildRpcCall(mockRequest)) + await handler.handleAuthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: { diff --git a/src/background/services/web3/handlers/avalanche_getProviderState.ts b/src/background/services/web3/handlers/avalanche_getProviderState.ts index 00f9d8c7b..bd6db23c1 100644 --- a/src/background/services/web3/handlers/avalanche_getProviderState.ts +++ b/src/background/services/web3/handlers/avalanche_getProviderState.ts @@ -10,7 +10,7 @@ export class AvalancheGetProviderState extends DAppRequestHandler { constructor( private networkService: NetworkService, - private accountsService: AccountsService + private accountsService: AccountsService, ) { super(); } diff --git a/src/background/services/web3/handlers/avalanche_selectWallet.ts b/src/background/services/web3/handlers/avalanche_selectWallet.ts index 249857bd2..0edc59c5f 100644 --- a/src/background/services/web3/handlers/avalanche_selectWallet.ts +++ b/src/background/services/web3/handlers/avalanche_selectWallet.ts @@ -29,7 +29,7 @@ export class AvalancheSelectWalletHandler extends DAppRequestHandler { info: availableExtensions.map((extension) => extension.info), }, }, - `approve/select-wallet` + `approve/select-wallet`, ); return { ...request, result: DEFERRED_RESPONSE }; @@ -40,10 +40,10 @@ export class AvalancheSelectWalletHandler extends DAppRequestHandler { }; onActionApproved = async ( - pendingAction: Action, + _pendingAction: Action, result, onSuccess, - onError + onError, ) => { if (result >= 0) { onSuccess(result); diff --git a/src/background/services/web3/handlers/avalanche_sendDomainMetadata.test.ts b/src/background/services/web3/handlers/avalanche_sendDomainMetadata.test.ts index 1d00004c4..fafd42006 100644 --- a/src/background/services/web3/handlers/avalanche_sendDomainMetadata.test.ts +++ b/src/background/services/web3/handlers/avalanche_sendDomainMetadata.test.ts @@ -13,14 +13,14 @@ describe('background/services/web3/handlers/avalanche_sendDomainMetadata.ts', () }; expect( - await handler.handleAuthenticated(buildRpcCall(mockRequest)) + await handler.handleAuthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: [{ domain: 'site.example' }], }); expect( - await handler.handleUnauthenticated(buildRpcCall(mockRequest)) + await handler.handleUnauthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: [{ domain: 'site.example' }], diff --git a/src/background/services/web3/handlers/connect.test.ts b/src/background/services/web3/handlers/connect.test.ts index 9b174c99d..2612dcae4 100644 --- a/src/background/services/web3/handlers/connect.test.ts +++ b/src/background/services/web3/handlers/connect.test.ts @@ -16,7 +16,7 @@ describe('background/services/web3/handlers/connect.ts', () => { it('returns error when no active account available', async () => { const handler = new ConnectRequestHandler( { activeAccount: undefined } as AccountsService, - {} as PermissionsService + {} as PermissionsService, ); const mockRequest = { @@ -25,7 +25,7 @@ describe('background/services/web3/handlers/connect.ts', () => { }; expect( - await handler.handleAuthenticated(buildRpcCall(mockRequest)) + await handler.handleAuthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, error: ethErrors.rpc.internal('wallet locked, undefined or malformed'), @@ -40,7 +40,7 @@ describe('background/services/web3/handlers/connect.ts', () => { addressBTC: '', }, } as AccountsService, - {} as PermissionsService + {} as PermissionsService, ); const mockRequest = { @@ -49,7 +49,7 @@ describe('background/services/web3/handlers/connect.ts', () => { }; expect( - await handler.handleAuthenticated(buildRpcCall(mockRequest)) + await handler.handleAuthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, result: ['0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'], @@ -61,7 +61,7 @@ describe('background/services/web3/handlers/connect.ts', () => { it('returns error when domain not set', async () => { const handler = new ConnectRequestHandler( {} as AccountsService, - {} as PermissionsService + {} as PermissionsService, ); const mockRequest = { @@ -70,7 +70,7 @@ describe('background/services/web3/handlers/connect.ts', () => { }; expect( - await handler.handleUnauthenticated(buildRpcCall(mockRequest)) + await handler.handleUnauthenticated(buildRpcCall(mockRequest)), ).toEqual({ ...mockRequest, error: ethErrors.rpc.invalidRequest('domain unknown'), @@ -80,7 +80,7 @@ describe('background/services/web3/handlers/connect.ts', () => { it('opens approval window', async () => { const handler = new ConnectRequestHandler( {} as AccountsService, - {} as PermissionsService + {} as PermissionsService, ); const mockRequest = { @@ -95,7 +95,7 @@ describe('background/services/web3/handlers/connect.ts', () => { }; const result = await handler.handleUnauthenticated( - buildRpcCall(mockRequest) + buildRpcCall(mockRequest), ); expect(result).toEqual({ ...mockRequest, @@ -105,7 +105,7 @@ describe('background/services/web3/handlers/connect.ts', () => { expect(openApprovalWindow).toHaveBeenCalledTimes(1); expect(openApprovalWindow).toHaveBeenCalledWith( expect.objectContaining({ id: '1235' }), - 'permissions' + 'permissions', ); }); }); @@ -150,46 +150,46 @@ describe('background/services/web3/handlers/connect.ts', () => { const handler = new ConnectRequestHandler( accountsServiceMock as any, - permissionServiceMock as any + permissionServiceMock as any, ); await handler.onActionApproved( { ...mockAction }, undefined, onSuccessMock, - onErrorMock + onErrorMock, ); expect( - permissionServiceMock.setAccountPermissionForDomain + permissionServiceMock.setAccountPermissionForDomain, ).not.toHaveBeenCalled(); expect(onSuccessMock).not.toHaveBeenCalled(); expect(onErrorMock).toHaveBeenCalledTimes(1); expect(onErrorMock).toHaveBeenCalledWith( - ethErrors.rpc.internal('Selected account not found') + ethErrors.rpc.internal('Selected account not found'), ); }); it('returns error when domain not set', async () => { const handler = new ConnectRequestHandler( accountsServiceMock as any, - permissionServiceMock as any + permissionServiceMock as any, ); await handler.onActionApproved( { ...mockAction }, 'uuid', onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).toHaveBeenCalledTimes(1); expect(onErrorMock).toHaveBeenCalledWith( - ethErrors.rpc.internal('Domain not set') + ethErrors.rpc.internal('Domain not set'), ); expect( - permissionServiceMock.setAccountPermissionForDomain + permissionServiceMock.setAccountPermissionForDomain, ).not.toHaveBeenCalled(); expect(accountsServiceMock.activateAccount).not.toHaveBeenCalled(); expect(onSuccessMock).not.toHaveBeenCalled(); @@ -208,7 +208,7 @@ describe('background/services/web3/handlers/connect.ts', () => { type: AccountType.PRIMARY, }, } as any, - permissionServiceMock as any + permissionServiceMock as any, ); await handler.onActionApproved( @@ -218,21 +218,21 @@ describe('background/services/web3/handlers/connect.ts', () => { }, 'uuid', onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).not.toHaveBeenCalled(); expect( - permissionServiceMock.hasDomainPermissionForAccount + permissionServiceMock.hasDomainPermissionForAccount, ).toHaveBeenCalledTimes(1); expect( - permissionServiceMock.hasDomainPermissionForAccount + permissionServiceMock.hasDomainPermissionForAccount, ).toHaveBeenCalledWith( 'example.com', - '0x11111eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' + '0x11111eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', ); expect( - permissionServiceMock.setAccountPermissionForDomain + permissionServiceMock.setAccountPermissionForDomain, ).not.toHaveBeenCalled(); expect(accountsServiceMock.activateAccount).not.toHaveBeenCalled(); expect(onSuccessMock).toHaveBeenCalledTimes(1); @@ -244,7 +244,7 @@ describe('background/services/web3/handlers/connect.ts', () => { it('updates permissons for primary account', async () => { const handler = new ConnectRequestHandler( accountsServiceMock as any, - permissionServiceMock as any + permissionServiceMock as any, ); await handler.onActionApproved( @@ -254,19 +254,19 @@ describe('background/services/web3/handlers/connect.ts', () => { }, 'uuid', onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).not.toHaveBeenCalled(); expect( - permissionServiceMock.setAccountPermissionForDomain + permissionServiceMock.setAccountPermissionForDomain, ).toHaveBeenCalledTimes(1); expect( - permissionServiceMock.setAccountPermissionForDomain + permissionServiceMock.setAccountPermissionForDomain, ).toHaveBeenCalledWith( 'example.com', '0x11111eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', - true + true, ); expect(accountsServiceMock.activateAccount).toHaveBeenCalledTimes(1); expect(accountsServiceMock.activateAccount).toHaveBeenCalledWith('uuid'); @@ -285,7 +285,7 @@ describe('background/services/web3/handlers/connect.ts', () => { const handler = new ConnectRequestHandler( accountsServiceMock as any, - permissionServiceMock as any + permissionServiceMock as any, ); await handler.onActionApproved( @@ -295,19 +295,19 @@ describe('background/services/web3/handlers/connect.ts', () => { }, '0x2', onSuccessMock, - onErrorMock + onErrorMock, ); expect(onErrorMock).not.toHaveBeenCalled(); expect( - permissionServiceMock.setAccountPermissionForDomain + permissionServiceMock.setAccountPermissionForDomain, ).toHaveBeenCalledTimes(1); expect( - permissionServiceMock.setAccountPermissionForDomain + permissionServiceMock.setAccountPermissionForDomain, ).toHaveBeenCalledWith( 'example.com', '0x11111eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', - true + true, ); expect(accountsServiceMock.activateAccount).toHaveBeenCalledTimes(1); expect(accountsServiceMock.activateAccount).toHaveBeenCalledWith('0x2'); diff --git a/src/background/services/web3/handlers/connect.ts b/src/background/services/web3/handlers/connect.ts index af2ab0b30..d282413ca 100644 --- a/src/background/services/web3/handlers/connect.ts +++ b/src/background/services/web3/handlers/connect.ts @@ -23,7 +23,7 @@ export class ConnectRequestHandler implements DAppRequestHandler { constructor( private accountsService: AccountsService, - private permissionsService: PermissionsService + private permissionsService: PermissionsService, ) {} async handleAuthenticated(rpcCall) { @@ -61,7 +61,7 @@ export class ConnectRequestHandler implements DAppRequestHandler { domainIcon: request.site?.icon, }, }, - `permissions` + `permissions`, ); return { ...request, result: DEFERRED_RESPONSE }; @@ -71,7 +71,7 @@ export class ConnectRequestHandler implements DAppRequestHandler { pendingAction: Action, result, onSuccess, - onError + onError, ) => { const selectedAccount = this.accountsService.getAccountByID(result); @@ -91,7 +91,7 @@ export class ConnectRequestHandler implements DAppRequestHandler { this.accountsService.activeAccount?.id === result && (await this.permissionsService.hasDomainPermissionForAccount( pendingAction.site.domain, - selectedAccount.addressC + selectedAccount.addressC, )) ) { onSuccess([selectedAccount.addressC]); @@ -101,7 +101,7 @@ export class ConnectRequestHandler implements DAppRequestHandler { await this.permissionsService.setAccountPermissionForDomain( pendingAction.site.domain, selectedAccount.addressC, - true + true, ); await this.accountsService.activateAccount(result); diff --git a/src/background/utils/findToken.ts b/src/background/utils/findToken.ts index a78cdc826..41e2becb0 100644 --- a/src/background/utils/findToken.ts +++ b/src/background/utils/findToken.ts @@ -28,7 +28,7 @@ const UNKNOWN_TOKEN = (address: string): TokenWithBalanceERC20 => ({ export async function findToken( addressOrSymbol: string, - network: Network + network: Network, ): Promise { const balancesService = container.resolve(BalanceAggregatorService); const accountsService = container.resolve(AccountsService); @@ -45,7 +45,7 @@ export async function findToken( await balancesService.getBalancesForNetworks( [network.chainId], [accountsService.activeAccount], - [TokenType.NATIVE, TokenType.ERC20] + [TokenType.NATIVE, TokenType.ERC20], ) ).tokens; } @@ -66,7 +66,7 @@ export async function findToken( if (addressOrSymbol === network.networkToken.symbol) { const balance = await provider.getBalance( - accountsService.activeAccount.addressC + accountsService.activeAccount.addressC, ); return { ...network.networkToken, @@ -74,7 +74,7 @@ export async function findToken( balance, balanceDisplayValue: bigIntToString( balance, - network.networkToken.decimals + network.networkToken.decimals, ), type: TokenType.NATIVE, }; @@ -85,9 +85,9 @@ export async function findToken( try { tokenData = await tokenManagerService.getTokenData( addressOrSymbol, - network + network, ); - } catch (e) { + } catch (_err) { return UNKNOWN_TOKEN(addressOrSymbol); } @@ -98,7 +98,7 @@ export async function findToken( } const balance = await contract.balanceOf( - accountsService.activeAccount.addressC + accountsService.activeAccount.addressC, ); return { diff --git a/src/background/utils/messaging/AbstractConnection.test.ts b/src/background/utils/messaging/AbstractConnection.test.ts index 740542d49..c6c162469 100644 --- a/src/background/utils/messaging/AbstractConnection.test.ts +++ b/src/background/utils/messaging/AbstractConnection.test.ts @@ -11,7 +11,7 @@ class TestConnection extends AbstractConnection { disconnect: jest.Mock; send: jest.Mock; }, - concurrentReuestLimit = 1000 + concurrentReuestLimit = 1000, ) { super(concurrentReuestLimit); } diff --git a/src/background/utils/messaging/AbstractConnection.ts b/src/background/utils/messaging/AbstractConnection.ts index c0726b8ca..40a73143d 100644 --- a/src/background/utils/messaging/AbstractConnection.ts +++ b/src/background/utils/messaging/AbstractConnection.ts @@ -90,7 +90,11 @@ export default abstract class AbstractConnection extends EventEmitter { const { resolve, reject } = request; this.#waitingMap.delete(id); - err ? reject(err) : resolve(res); + if (err) { + reject(err); + return; + } + resolve(res); }; protected onMessage = (message: Message) => { @@ -116,9 +120,15 @@ export default abstract class AbstractConnection extends EventEmitter { err = { message: e.message, }; - isDevelopment() && (err.stack = e.stack); - e.code !== undefined && (err.code = e.code); - e.data !== undefined && (err.data = e.data); + if (isDevelopment()) { + err.stack = e.stack; + } + if (e.code !== undefined) { + err.code = e.code; + } + if (e.data !== undefined) { + err.data = e.data; + } } if (res === DEFERRED_RESPONSE) { diff --git a/src/background/utils/messaging/AutoPairingPostMessageConnection.test.ts b/src/background/utils/messaging/AutoPairingPostMessageConnection.test.ts index ab555477f..d91288ea3 100644 --- a/src/background/utils/messaging/AutoPairingPostMessageConnection.test.ts +++ b/src/background/utils/messaging/AutoPairingPostMessageConnection.test.ts @@ -30,7 +30,7 @@ describe('background/providers/utils/AutoPairingPostMessageConnection', () => { type: 'initialize-post-message-connection', }, }, - 'core.app' + 'core.app', ); }); @@ -98,7 +98,7 @@ describe('background/providers/utils/AutoPairingPostMessageConnection', () => { type: 'initialize-post-message-connection', }, }, - 'core.app' + 'core.app', ); }); @@ -112,7 +112,7 @@ describe('background/providers/utils/AutoPairingPostMessageConnection', () => { type: 'initialize-post-message-connection-request', }, }, - 'core.app' + 'core.app', ); }); @@ -356,7 +356,7 @@ describe('background/providers/utils/AutoPairingPostMessageConnection', () => { expect(addEventListenerSpy).toHaveBeenCalledTimes(2); expect(addEventListenerSpy).toHaveBeenCalledWith( 'message', - expect.any(Function) + expect.any(Function), ); // clean up pending promise @@ -406,7 +406,7 @@ describe('background/providers/utils/AutoPairingPostMessageConnection', () => { expect(removeEventListenerSpy).toHaveBeenCalledTimes(1); // check if same listener is removed expect(removeEventListenerSpy).toHaveBeenCalledWith( - ...(addEventListenerSpy.mock.calls[1] as any) + ...(addEventListenerSpy.mock.calls[1] as any), ); await new Promise(process.nextTick); diff --git a/src/background/utils/messaging/AutoPairingPostMessageConnection.ts b/src/background/utils/messaging/AutoPairingPostMessageConnection.ts index c554754e7..391238dde 100644 --- a/src/background/utils/messaging/AutoPairingPostMessageConnection.ts +++ b/src/background/utils/messaging/AutoPairingPostMessageConnection.ts @@ -13,7 +13,7 @@ export default class AutoPairingPostMessageConnection extends AbstractConnection constructor( private isConnectionLeader: boolean, - concurrentRequestLimit = 1000 + concurrentRequestLimit = 1000, ) { super(concurrentRequestLimit); @@ -37,7 +37,7 @@ export default class AutoPairingPostMessageConnection extends AbstractConnection connectionId: this.#connectionId, }, }, - window.location.origin + window.location.origin, ); }; @@ -83,7 +83,7 @@ export default class AutoPairingPostMessageConnection extends AbstractConnection type: CHANNEL_BROADCAST_REQUEST_EVENT, }, }, - window.location.origin + window.location.origin, ); }; diff --git a/src/background/utils/messaging/PortConnection.test.ts b/src/background/utils/messaging/PortConnection.test.ts index e23b87842..764fc18bd 100644 --- a/src/background/utils/messaging/PortConnection.test.ts +++ b/src/background/utils/messaging/PortConnection.test.ts @@ -54,7 +54,7 @@ describe('background/providers/utils/PortConnection', () => { serializeToJSON({ type: 'message', data: 'mock-message', - }) + }), ); expect(callback).toHaveBeenCalledTimes(1); @@ -73,7 +73,7 @@ describe('background/providers/utils/PortConnection', () => { serializeToJSON({ type: 'message', data: 'message-data', - }) + }), ); }); @@ -94,7 +94,7 @@ describe('background/providers/utils/PortConnection', () => { value: '1000', }, }, - }) + }), ); }); }); diff --git a/src/background/vmModules/ApprovalController.test.ts b/src/background/vmModules/ApprovalController.test.ts index bf3eaa439..eaeab9e76 100644 --- a/src/background/vmModules/ApprovalController.test.ts +++ b/src/background/vmModules/ApprovalController.test.ts @@ -173,7 +173,7 @@ describe('src/background/vmModules/ApprovalController', () => { request: { chainId: 'abcd-1234', }, - } as any) + } as any), ).toEqual({ error: expect.objectContaining({ message: 'Unsupported network' }), }); @@ -187,7 +187,7 @@ describe('src/background/vmModules/ApprovalController', () => { expect(openApprovalWindow).toHaveBeenCalledWith( getExpectedAction(approvalParams), - 'approve/generic' + 'approve/generic', ); }); @@ -232,7 +232,7 @@ describe('src/background/vmModules/ApprovalController', () => { outputs: btcTx.outputs, }), btcNetwork, - action.tabId + action.tabId, ); expect(await promise).toEqual({ @@ -272,7 +272,7 @@ describe('src/background/vmModules/ApprovalController', () => { outputs: btcTx.outputs, }), btcNetwork, - action.tabId + action.tabId, ); expect(await promise).toEqual({ signedData: signedTx }); diff --git a/src/background/vmModules/ApprovalController.ts b/src/background/vmModules/ApprovalController.ts index 7e4bbd654..ac3a8f6f0 100644 --- a/src/background/vmModules/ApprovalController.ts +++ b/src/background/vmModules/ApprovalController.ts @@ -83,7 +83,7 @@ export class ApprovalController implements IApprovalController { const { signedTx: signedData, txHash } = await this.#handleApproval( params, action, - network + network, ); if (signedData) { @@ -115,10 +115,10 @@ export class ApprovalController implements IApprovalController { * This method should never throw. Instead, return an { error } object. */ requestApproval = async ( - params: ApprovalParamsWithContext + params: ApprovalParamsWithContext, ): Promise => { const network = await this.#networkService.getNetwork( - params.request.chainId + params.request.chainId, ); if (!network) { return { @@ -131,7 +131,7 @@ export class ApprovalController implements IApprovalController { const action = await openApprovalWindow( this.#buildAction(params), - 'approve/generic' + 'approve/generic', ); return new Promise((resolve) => { @@ -145,7 +145,7 @@ export class ApprovalController implements IApprovalController { updateTx = ( id: string, - newData: Parameters[0] | Parameters[0] + newData: Parameters[0] | Parameters[0], ): { signingData: SigningData; displayData: DisplayData } => { const request = this.#requests.get(id); @@ -163,7 +163,7 @@ export class ApprovalController implements IApprovalController { #handleApproval = async ( params: ApprovalParams, action: Action, - network: NetworkWithCaipId + network: NetworkWithCaipId, ) => { const { signingData } = action; @@ -178,7 +178,7 @@ export class ApprovalController implements IApprovalController { return await this.#walletService.sign( signingData.data, network, - action.tabId + action.tabId, ); default: diff --git a/src/background/vmModules/ModuleManager.test.ts b/src/background/vmModules/ModuleManager.test.ts index 740b34d83..551319dd6 100644 --- a/src/background/vmModules/ModuleManager.test.ts +++ b/src/background/vmModules/ModuleManager.test.ts @@ -117,9 +117,9 @@ describe('ModuleManager', () => { params.map(async (param) => { const module = await manager.loadModule(param.chainId, param.method); expect(module?.getManifest()?.name.toLowerCase()).toContain( - param.name.toLowerCase() + param.name.toLowerCase(), ); - }) + }), ); }); diff --git a/src/background/vmModules/ModuleManager.ts b/src/background/vmModules/ModuleManager.ts index aa9dcb951..402c9a22f 100644 --- a/src/background/vmModules/ModuleManager.ts +++ b/src/background/vmModules/ModuleManager.ts @@ -99,7 +99,7 @@ export class ModuleManager { async loadModuleByNetwork( network: NetworkWithCaipId, - method?: string + method?: string, ): Promise { return this.loadModule(network.caipId, method); } @@ -123,13 +123,13 @@ export class ModuleManager { async #getModuleByChainId(chainId: string): Promise { return this.#modules.find((module) => - module.getManifest()?.network.chainIds.includes(chainId) + module.getManifest()?.network.chainIds.includes(chainId), ); } async #getModuleByNamespace(namespace: string): Promise { return this.#modules.find((module) => - module.getManifest()?.network.namespaces.includes(namespace) + module.getManifest()?.network.namespaces.includes(namespace), ); } diff --git a/src/components/common/CameraAccessDeniedDialog.tsx b/src/components/common/CameraAccessDeniedDialog.tsx index 7fc96b501..cec20f90e 100644 --- a/src/components/common/CameraAccessDeniedDialog.tsx +++ b/src/components/common/CameraAccessDeniedDialog.tsx @@ -30,13 +30,13 @@ export const CameraAccessDeniedDialog = ({ refreshPermissions }) => { {t( - `You've blocked access to your camera. Please allow access to continue.` + `You've blocked access to your camera. Please allow access to continue.`, )} {t( - 'If you block access, look in the top right corner of your browser to enable camera access' + 'If you block access, look in the top right corner of your browser to enable camera access', )} diff --git a/src/components/common/CameraAccessPromptDialog.tsx b/src/components/common/CameraAccessPromptDialog.tsx index d047a68a2..c8998a006 100644 --- a/src/components/common/CameraAccessPromptDialog.tsx +++ b/src/components/common/CameraAccessPromptDialog.tsx @@ -41,7 +41,7 @@ export const CameraAccessPromptDialog = ({ QRScanner }) => { {t( - 'If you block access, look in the top right corner of your browser to enable camera access' + 'If you block access, look in the top right corner of your browser to enable camera access', )} diff --git a/src/components/common/ConfirmationTracker.tsx b/src/components/common/ConfirmationTracker.tsx index 18ee8d96e..5adcf9b82 100644 --- a/src/components/common/ConfirmationTracker.tsx +++ b/src/components/common/ConfirmationTracker.tsx @@ -56,7 +56,7 @@ const Line: any = styled(Box, { background: active || complete ? theme.palette.text.primary : theme.palette.divider, transition: 'background-color 500ms', - }) + }), ); const Dot: any = styled('div')(({ theme, delay }: any) => ({ @@ -154,8 +154,10 @@ export const ConfirmationTracker = memo(function ConfirmationTracker({ currentCount, ...props }: ConfirmationTrackerProps) { + // eslint-disable-next-line react-hooks/rules-of-hooks const { t } = useTranslation(); const numberOfDots = requiredCount - 1; + // eslint-disable-next-line react-hooks/rules-of-hooks const containerRef = useRef(null); const dots: JSX.Element[] = []; let left = 0; @@ -210,7 +212,7 @@ export const ConfirmationTracker = memo(function ConfirmationTracker({ {i}/{requiredCount} - + , ); } @@ -277,7 +279,7 @@ export const ConfirmationTracker = memo(function ConfirmationTracker({ {renderLine( currentCount >= requiredCount, lastStepActive, - requiredCount === 1 + requiredCount === 1, )} diff --git a/src/components/common/ContainedDropdown.tsx b/src/components/common/ContainedDropdown.tsx index 62817ebda..97479dc25 100644 --- a/src/components/common/ContainedDropdown.tsx +++ b/src/components/common/ContainedDropdown.tsx @@ -12,7 +12,7 @@ const BOTTOM_PADDING = 16; // Dropdown is absolutely positioned, and fills the viewport beneath the select element const getDropdownHeight = ( anchorEl: MutableRefObject, - containerRef?: MutableRefObject + containerRef?: MutableRefObject, ): number => { if (!anchorEl.current || !window.visualViewport) return 0; // Default height @@ -47,7 +47,7 @@ const Dropdown = forwardRef( }} {...props} /> - ) + ), ); Dropdown.displayName = 'Dropdown'; diff --git a/src/components/common/CustomFees.tsx b/src/components/common/CustomFees.tsx index b16b051cd..cac9ea314 100644 --- a/src/components/common/CustomFees.tsx +++ b/src/components/common/CustomFees.tsx @@ -185,7 +185,7 @@ export function CustomFees({ const [customGasLimit, setCustomGasLimit] = useState(); const gasLimit = customGasLimit || limit; const [customFee, setCustomFee] = useState( - networkFee?.low + networkFee?.low, ); const [newFees, setNewFees] = useState< ReturnType @@ -195,7 +195,7 @@ export function CustomFees({ tokenPrice, tokenDecimals: network?.networkToken.decimals, gasLimit, - }) + }), ); const [isCollapsed, setIsCollapsed] = useState(isCollapsible); const customInputRef = useRef(null); @@ -203,7 +203,7 @@ export function CustomFees({ const [selectedFee, setSelectedFee] = useState( networkFee?.isFixedFee ? GasFeeModifier.NORMAL - : selectedGasFeeModifier || GasFeeModifier.NORMAL + : selectedGasFeeModifier || GasFeeModifier.NORMAL, ); useLiveBalance(POLLED_BALANCES); // Make sure we always use the latest native balance. @@ -248,7 +248,7 @@ export function CustomFees({ customGasLimit, maxGasPrice, onChange, - ] + ], ); const getFeeRateForCustomGasPrice = useCallback( @@ -267,7 +267,7 @@ export function CustomFees({ maxPriorityFeePerGas: maxTip, }; }, - [] + [], ); const updateGasFee = useCallback( @@ -294,7 +294,7 @@ export function CustomFees({ handleGasChange(networkFee.low, GasFeeModifier.NORMAL); } }, - [handleGasChange, networkFee, customFee] + [handleGasChange, networkFee, customFee], ); const handleModifierClick = useCallback( @@ -305,7 +305,7 @@ export function CustomFees({ onModifierChangeCallback(modifier); } }, - [updateGasFee, onModifierChangeCallback] + [updateGasFee, onModifierChangeCallback], ); useEffect(() => { @@ -331,7 +331,7 @@ export function CustomFees({ return new TokenUnit( estimatedFee, network?.networkToken.decimals, - network?.networkToken.symbol + network?.networkToken.symbol, ).toString(); } @@ -354,7 +354,7 @@ export function CustomFees({ tooltip={ isMaxFeeUsed ? t( - 'Core estimates the maximum gas (maxFeePerGas) a transaction could consume based on network conditions. This transaction will likely consume less gas than estimated.' + 'Core estimates the maximum gas (maxFeePerGas) a transaction could consume based on network conditions. This transaction will likely consume less gas than estimated.', ) : undefined } @@ -406,7 +406,7 @@ export function CustomFees({ {formatGasPrice( networkFee.low.maxFeePerGas, - networkFee.displayDecimals + networkFee.displayDecimals, )} @@ -430,7 +430,7 @@ export function CustomFees({ {formatGasPrice( networkFee.medium.maxFeePerGas, - networkFee.displayDecimals + networkFee.displayDecimals, )} @@ -452,7 +452,7 @@ export function CustomFees({ {formatGasPrice( networkFee.high.maxFeePerGas, - networkFee.displayDecimals + networkFee.displayDecimals, )} @@ -478,7 +478,7 @@ export function CustomFees({ type="number" value={formatGasPrice( customFee?.maxFeePerGas ?? 0n, - networkFee.displayDecimals + networkFee.displayDecimals, )} min={1} step={1} @@ -486,9 +486,9 @@ export function CustomFees({ handleGasChange( getFeeRateForCustomGasPrice( e.target.value || '0', - networkFee + networkFee, ), - GasFeeModifier.CUSTOM + GasFeeModifier.CUSTOM, ); }} onBlur={(e) => { @@ -548,7 +548,7 @@ export function CustomFees({ open={Boolean( network?.vmName === NetworkVMType.EVM && showEditGasLimit && - customFee?.maxFeePerGas + customFee?.maxFeePerGas, )} > ({ ...existingErrors, maxPriorityFee: t( - 'Maximum priority fee cannot be greater than maximum fee' + 'Maximum priority fee cannot be greater than maximum fee', ), })); hasErrors = true; @@ -205,7 +205,7 @@ export function CustomGasSettings({ { setCustomMaxFeePerGas( - parseUnits(evt.currentTarget.value || '0', feeDisplayDecimals) + parseUnits(evt.currentTarget.value || '0', feeDisplayDecimals), ); }} error={!!errors.maxFee} @@ -232,7 +232,7 @@ export function CustomGasSettings({ { setCustomMaxPriorityFeePerGas( - parseUnits(evt.currentTarget.value || '0', feeDisplayDecimals) + parseUnits(evt.currentTarget.value || '0', feeDisplayDecimals), ); }} error={!!errors.maxPriorityFee} @@ -264,10 +264,10 @@ export function CustomGasSettings({ tooltip={ isLimitReadonly ? t( - 'Estimated gas units needed to complete the transaction. Includes a small buffer. Not editable for this transaction.' + 'Estimated gas units needed to complete the transaction. Includes a small buffer. Not editable for this transaction.', ) : t( - 'Total units of gas needed to complete the transaction. Do not edit unless necessary.' + 'Total units of gas needed to complete the transaction. Do not edit unless necessary.', ) } /> @@ -311,13 +311,13 @@ export function CustomGasSettings({ <>
{t( - 'Total Network Fee = (Current Base Fee + Max Priority Fee) * Gas Limit.' + 'Total Network Fee = (Current Base Fee + Max Priority Fee) * Gas Limit.', )}

{t( - 'It will never be higher than Max Base Fee * Gas Limit.' + 'It will never be higher than Max Base Fee * Gas Limit.', )}
diff --git a/src/components/common/EmptyContent.test.tsx b/src/components/common/EmptyContent.test.tsx index b7e6f6794..cbae0170b 100644 --- a/src/components/common/EmptyContent.test.tsx +++ b/src/components/common/EmptyContent.test.tsx @@ -6,7 +6,7 @@ describe('components/common/EmptyContent', () => { render(); expect(screen.getByTestId('empty-list-text').textContent).toEqual( - 'Some test text' + 'Some test text', ); }); }); diff --git a/src/components/common/ImageWithFallback.tsx b/src/components/common/ImageWithFallback.tsx index 8364e64f8..17fb597cc 100644 --- a/src/components/common/ImageWithFallback.tsx +++ b/src/components/common/ImageWithFallback.tsx @@ -19,7 +19,7 @@ export function ImageWithFallback({ const [fallbackImage, setFallbackImage] = useState(''); const imageOnErrorHandler = ( - event: React.SyntheticEvent + event: React.SyntheticEvent, ) => { setFallbackImage('images/no_image.svg'); onError?.(event); diff --git a/src/components/common/InvalidQRCodeDialog.tsx b/src/components/common/InvalidQRCodeDialog.tsx index e203e223b..211a82fd8 100644 --- a/src/components/common/InvalidQRCodeDialog.tsx +++ b/src/components/common/InvalidQRCodeDialog.tsx @@ -30,7 +30,7 @@ export const InvalidQRCodeDialog = ({ onRetry }) => { {t( - `Please ensure you have selected a valid QR code from your Keystone device` + `Please ensure you have selected a valid QR code from your Keystone device`, )} diff --git a/src/components/common/PageTitle.tsx b/src/components/common/PageTitle.tsx index 7cc85aa2f..9f186fe5e 100644 --- a/src/components/common/PageTitle.tsx +++ b/src/components/common/PageTitle.tsx @@ -1,5 +1,4 @@ import { PropsWithChildren } from 'react'; -import { useHistory } from 'react-router-dom'; import { ImageWithFallback } from '@src/components/common/ImageWithFallback'; import { ChevronLeftIcon, @@ -9,6 +8,7 @@ import { styled, keyframes, } from '@avalabs/core-k2-components'; +import { useGoBack } from '@src/hooks/useGoBack'; const ShowThumbnailImageAnimation = keyframes` 0% { @@ -50,13 +50,7 @@ export const PageTitle = ({ thumbnailImage, margin = '8px 0', }: PropsWithChildren) => { - const history = useHistory(); - - const goBack = () => { - // history can be empty when the extension is opened and the last - // location is loaded back from localstorage - history.length <= 2 ? history.replace('/home') : history.goBack(); - }; + const goBack = useGoBack(); return ( { const PASSWORD_STRENGTH_ERROR = translate('The new password is too weak'); const PASSWORDS_MATCH_ERROR = translate('Passwords do not match'); diff --git a/src/components/common/TokenIcon.tsx b/src/components/common/TokenIcon.tsx index 9b4d60934..49c43d30b 100644 --- a/src/components/common/TokenIcon.tsx +++ b/src/components/common/TokenIcon.tsx @@ -7,7 +7,7 @@ import { ipfsResolverWithFallback } from '@src/utils/ipsfResolverWithFallback'; import { useEffect, useState } from 'react'; const TOKEN_IMAGE_BORDER_RADIUS = '50%'; -const TOKEN_IMAGE_DFEAULT_SIZE = '32px'; +const TOKEN_IMAGE_DEFAULT_SIZE = '32px'; const getTokenIconInitials = (name: string | undefined) => { const names = (name || '').split(' '); @@ -17,8 +17,8 @@ const getTokenIconInitials = (name: string | undefined) => { firstName && lastName ? firstName.substring(0, 1) + lastName.substring(0, 1) : firstName - ? firstName.substring(0, 1) - : ''; + ? firstName.substring(0, 1) + : ''; return initials; }; @@ -58,10 +58,13 @@ export function TokenIcon({ img.src = ipfsResolverWithFallback(src); }) .then(() => { - !isCancelled && setState({ success: true }); + setState({ success: true }); }) .catch(() => { - !isCancelled && setState({ error: true }); + if (isCancelled) { + return; + } + setState({ error: true }); }); return () => { @@ -78,8 +81,8 @@ export function TokenIcon({ sx={{ borderRadius: TOKEN_IMAGE_BORDER_RADIUS, backgroundColor: 'grey.600', - width: width || TOKEN_IMAGE_DFEAULT_SIZE, - height: height || TOKEN_IMAGE_DFEAULT_SIZE, + width: width || TOKEN_IMAGE_DEFAULT_SIZE, + height: height || TOKEN_IMAGE_DEFAULT_SIZE, flexShrink: 0, }} {...rest} @@ -95,8 +98,8 @@ export function TokenIcon({ direction="row" sx={{ borderRadius: TOKEN_IMAGE_BORDER_RADIUS, - width: width || TOKEN_IMAGE_DFEAULT_SIZE, - height: height || TOKEN_IMAGE_DFEAULT_SIZE, + width: width || TOKEN_IMAGE_DEFAULT_SIZE, + height: height || TOKEN_IMAGE_DEFAULT_SIZE, flexShrink: 0, }} {...rest} @@ -118,8 +121,8 @@ export function TokenIcon({ sx={{ borderRadius: TOKEN_IMAGE_BORDER_RADIUS, backgroundColor: 'grey.600', - width: width || TOKEN_IMAGE_DFEAULT_SIZE, - height: height || TOKEN_IMAGE_DFEAULT_SIZE, + width: width || TOKEN_IMAGE_DEFAULT_SIZE, + height: height || TOKEN_IMAGE_DEFAULT_SIZE, flexShrink: 0, }} {...rest} diff --git a/src/components/common/TokenSelect.tsx b/src/components/common/TokenSelect.tsx index 8b0812322..b050c8dc3 100644 --- a/src/components/common/TokenSelect.tsx +++ b/src/components/common/TokenSelect.tsx @@ -127,14 +127,13 @@ export function TokenSelect({ const handleAmountChange = useCallback( ({ amount, bigint }: { amount: string; bigint: bigint }) => { + onInputAmountChange?.({ amount, bigint }); if (!maxAmountString) { - onInputAmountChange && onInputAmountChange({ amount, bigint }); return; } setIsMaxAmount(maxAmountString === amount); - onInputAmountChange && onInputAmountChange({ amount, bigint }); }, - [onInputAmountChange, maxAmountString] + [onInputAmountChange, maxAmountString], ); const hideTokenDropdown = tokensList && tokensList.length < 2; @@ -151,9 +150,9 @@ export function TokenSelect({ parseFloat( bigToLocaleString(bigintToBig(inputAmount, decimals)).replace( /,/g, - '' - ) - ) * price + '', + ), + ) * price, ) : undefined; return amount; @@ -216,7 +215,7 @@ export function TokenSelect({ key={key} onClick={() => { onTokenChange(token.token); - onSelectToggle && onSelectToggle(); + onSelectToggle?.(); }} > ); }, - [displayTokenList, onSelectToggle, onTokenChange] + [displayTokenList, onSelectToggle, onTokenChange], ); const renderTokenLabel = useCallback(() => { diff --git a/src/components/common/WalletChip.tsx b/src/components/common/WalletChip.tsx index 5db2a3ce4..e851c0bf2 100644 --- a/src/components/common/WalletChip.tsx +++ b/src/components/common/WalletChip.tsx @@ -23,7 +23,7 @@ export const WalletChip = ({ const onLabelChange = useCallback((label: HTMLSpanElement) => { if (label?.parentElement) { setIsOverflowing( - label.parentElement.scrollWidth > label.parentElement.offsetWidth + label.parentElement.scrollWidth > label.parentElement.offsetWidth, ); } }, []); diff --git a/src/components/common/approval/TransactionDetailItem.tsx b/src/components/common/approval/TransactionDetailItem.tsx index ff0790933..c14377f0d 100644 --- a/src/components/common/approval/TransactionDetailItem.tsx +++ b/src/components/common/approval/TransactionDetailItem.tsx @@ -146,7 +146,7 @@ const FundsRecipientInfo = ({ item }: { item: FundsRecipientItem }) => { }} > {currencyFormatter( - tokenPrice * token.toDisplay({ asNumber: true }) + tokenPrice * token.toDisplay({ asNumber: true }), )} ) : null} @@ -182,7 +182,7 @@ const CurrencyInfo = ({ item }: { item: CurrencyItem }) => { }} > {currencyFormatter( - tokenPrice * token.toDisplay({ asNumber: true }) + tokenPrice * token.toDisplay({ asNumber: true }), )} ) : null} diff --git a/src/components/common/fab/FAB.tsx b/src/components/common/fab/FAB.tsx index 29d2fa3fc..bcda27860 100644 --- a/src/components/common/fab/FAB.tsx +++ b/src/components/common/fab/FAB.tsx @@ -238,8 +238,11 @@ export function FAB({ isContentScrolling }: { isContentScrolling: boolean }) { icon={icon} onClick={() => { capture(`FABItemSelected_${name}`); - onclick && onclick(); - route && history.push(route); + onclick?.(); + if (!route) { + return; + } + history.push(route); }} /> ); diff --git a/src/components/common/header/Header.tsx b/src/components/common/header/Header.tsx index 33940a363..11ad7d531 100644 --- a/src/components/common/header/Header.tsx +++ b/src/components/common/header/Header.tsx @@ -51,7 +51,7 @@ export function Header() { const showWalletInfo = Boolean( walletDetails?.name && activeAccount?.type === AccountType.PRIMARY && - wallets.length > 1 + wallets.length > 1, ); return ( @@ -85,7 +85,7 @@ export function Header() { {!isConnected && ( {t( - 'To connect, locate the connect button on their site.' + 'To connect, locate the connect button on their site.', )} )} diff --git a/src/components/common/header/NetworkSwitcher/NetworkSwitcher.tsx b/src/components/common/header/NetworkSwitcher/NetworkSwitcher.tsx index d5873ac62..800656ab8 100644 --- a/src/components/common/header/NetworkSwitcher/NetworkSwitcher.tsx +++ b/src/components/common/header/NetworkSwitcher/NetworkSwitcher.tsx @@ -47,17 +47,17 @@ export function NetworkSwitcher() { ...networks.filter( (networkItem) => defaultNetworks.includes(networkItem.chainId) && - networkItem.chainId !== network?.chainId + networkItem.chainId !== network?.chainId, ), ...favoriteNetworks.filter( (networkItem) => !defaultNetworks.includes(networkItem.chainId) && - networkItem.chainId !== network?.chainId + networkItem.chainId !== network?.chainId, ), ]; const isActiveInList = networkList.find( - (networkItem) => networkItem?.chainId === network?.chainId + (networkItem) => networkItem?.chainId === network?.chainId, ); const [isOpen, setIsOpen] = useState(false); diff --git a/src/components/common/infiniteScroll/InfiniteScroll.tsx b/src/components/common/infiniteScroll/InfiniteScroll.tsx index 18e4299fb..9194fe67d 100644 --- a/src/components/common/infiniteScroll/InfiniteScroll.tsx +++ b/src/components/common/infiniteScroll/InfiniteScroll.tsx @@ -32,7 +32,7 @@ export function InfiniteScroll({ loadMore(); } }, - [loading, hasMore, loadMore] + [loading, hasMore, loadMore], ); useEffect(() => { diff --git a/src/components/common/scrollbars/Scrollbars.tsx b/src/components/common/scrollbars/Scrollbars.tsx index 973acef39..da83c5b2b 100644 --- a/src/components/common/scrollbars/Scrollbars.tsx +++ b/src/components/common/scrollbars/Scrollbars.tsx @@ -8,7 +8,7 @@ export type ScrollbarsRef = CustomScrollbars.Scrollbars; // for available props export const Scrollbars = forwardRef(function Scrollbars( props: CustomScrollbars.ScrollbarProps, - ref: LegacyRef | undefined + ref: LegacyRef | undefined, ) { const theme = useTheme(); const renderThumb = ({ style, ...rest }) => { diff --git a/src/components/common/seedless/SeedlessAuthPrompt.tsx b/src/components/common/seedless/SeedlessAuthPrompt.tsx index b74c474c1..90f208f1f 100644 --- a/src/components/common/seedless/SeedlessAuthPrompt.tsx +++ b/src/components/common/seedless/SeedlessAuthPrompt.tsx @@ -53,7 +53,7 @@ export const SeedlessAuthPrompt = () => { {t( - 'For security reasons your session has timed out. Please log in again.' + 'For security reasons your session has timed out. Please log in again.', )} diff --git a/src/components/common/seedless/components/AuthenticationError.tsx b/src/components/common/seedless/components/AuthenticationError.tsx index c9d93fcce..d0bb10ebd 100644 --- a/src/components/common/seedless/components/AuthenticationError.tsx +++ b/src/components/common/seedless/components/AuthenticationError.tsx @@ -30,7 +30,7 @@ export const AuthenticationError = ({ error }: Props) => { {t('Wrong email address.')} {t( - 'Please log in with the email address you used when you created your wallet.' + 'Please log in with the email address you used when you created your wallet.', )} diff --git a/src/components/common/seedless/components/ExportPending.tsx b/src/components/common/seedless/components/ExportPending.tsx index 85566fe0b..5b4bd79d4 100644 --- a/src/components/common/seedless/components/ExportPending.tsx +++ b/src/components/common/seedless/components/ExportPending.tsx @@ -65,7 +65,7 @@ export const ExportPending = ({ {t( - 'Your recovery phrase is loading. You will receive a notification when it is done. Please check back in a little while.' + 'Your recovery phrase is loading. You will receive a notification when it is done. Please check back in a little while.', )} diff --git a/src/components/common/seedless/components/MfaChoicePrompt.tsx b/src/components/common/seedless/components/MfaChoicePrompt.tsx index 52d5ca3aa..136e6f92e 100644 --- a/src/components/common/seedless/components/MfaChoicePrompt.tsx +++ b/src/components/common/seedless/components/MfaChoicePrompt.tsx @@ -28,7 +28,7 @@ export const MfaChoicePrompt = ({ mfaChoice, onChosen }: Props) => { {t( - 'Select one of the available verification methods below to proceed.' + 'Select one of the available verification methods below to proceed.', )} diff --git a/src/components/common/seedless/components/PhraseReadyToExport.tsx b/src/components/common/seedless/components/PhraseReadyToExport.tsx index d519a6bf4..48f3d4d99 100644 --- a/src/components/common/seedless/components/PhraseReadyToExport.tsx +++ b/src/components/common/seedless/components/PhraseReadyToExport.tsx @@ -70,7 +70,7 @@ export const PhraseReadyToExport = ({ {t( - 'Do not share this phrase with anyone! These words can be used to steal all your accounts.' + 'Do not share this phrase with anyone! These words can be used to steal all your accounts.', )} @@ -131,7 +131,7 @@ export const PhraseReadyToExport = ({ {t( - 'Closing the settings menu will require you to restart the 2 day waiting period.' + 'Closing the settings menu will require you to restart the 2 day waiting period.', )} diff --git a/src/components/common/seedless/components/WaitingForAuthentication.tsx b/src/components/common/seedless/components/WaitingForAuthentication.tsx index 9628eb4c4..9166218df 100644 --- a/src/components/common/seedless/components/WaitingForAuthentication.tsx +++ b/src/components/common/seedless/components/WaitingForAuthentication.tsx @@ -37,7 +37,7 @@ export const WaitingForAuthentication = ({ provider }: Props) => { {t( - 'Do not close this window until the process is complete or you may need to restart.' + 'Do not close this window until the process is complete or you may need to restart.', )} diff --git a/src/components/common/walletConnect/useRequiredSession.ts b/src/components/common/walletConnect/useRequiredSession.ts index 732eb15cf..fe9d6280a 100644 --- a/src/components/common/walletConnect/useRequiredSession.ts +++ b/src/components/common/walletConnect/useRequiredSession.ts @@ -71,7 +71,7 @@ export const useRequiredSession = () => { sessionSubscription.unsubscribe(); }); }, - [events, tabId, request] + [events, tabId, request], ); return { diff --git a/src/components/dialogs/AnalyticsOptInDialog.tsx b/src/components/dialogs/AnalyticsOptInDialog.tsx index 29fe55444..0252ad452 100644 --- a/src/components/dialogs/AnalyticsOptInDialog.tsx +++ b/src/components/dialogs/AnalyticsOptInDialog.tsx @@ -37,7 +37,7 @@ export const AnalyticsOptInDialog = () => { {t( - 'Core would like to gather data using local storage and similar technologies to help us understand how our users interact with Core.' + 'Core would like to gather data using local storage and similar technologies to help us understand how our users interact with Core.', )} diff --git a/src/components/ledger/LedgerConnector.tsx b/src/components/ledger/LedgerConnector.tsx index c7dfd1baf..4dc24ab3f 100644 --- a/src/components/ledger/LedgerConnector.tsx +++ b/src/components/ledger/LedgerConnector.tsx @@ -71,12 +71,12 @@ export function LedgerConnector({ const { getAvaxBalance } = useGetAvaxBalance(); const [publicKeyState, setPublicKeyState] = useState( - LedgerStatus.LEDGER_UNINITIATED + LedgerStatus.LEDGER_UNINITIATED, ); const [isLedgerExistsError, setIsLedgerExistsError] = useState(false); const [pathSpec, setPathSpec] = useState( - DerivationPath.BIP44 + DerivationPath.BIP44, ); const [addresses, setAddresses] = useState([]); const [hasPublicKeys, setHasPublicKeys] = useState(false); @@ -95,7 +95,7 @@ export function LedgerConnector({ async ( xpubValue: string, accountIndex: number, - addressList: AddressType[] = [] + addressList: AddressType[] = [], ) => { const address = getAddressFromXPub(xpubValue, accountIndex); const { balance } = await getAvaxBalance(address); @@ -113,7 +113,7 @@ export function LedgerConnector({ setHasPublicKeys(true); } }, - [capture, getAvaxBalance] + [capture, getAvaxBalance], ); const isLedgerWalletExist = useCallback( @@ -137,14 +137,14 @@ export function LedgerConnector({ throw new Error(String(e)); } }, - [importLedger] + [importLedger], ); const getXPublicKey = useCallback(async () => { try { const xpubValue = await getExtendedPublicKey(); const xpubXPValue = await getExtendedPublicKey( - Avalanche.LedgerWallet.getAccountPath('X') + Avalanche.LedgerWallet.getAccountPath('X'), ); if (checkIfWalletExists) { await isLedgerWalletExist({ @@ -186,7 +186,7 @@ export function LedgerConnector({ } await initLedgerTransport(); }, - [initLedgerTransport] + [initLedgerTransport], ); useEffect(() => { @@ -198,14 +198,14 @@ export function LedgerConnector({ derivationPathSpec: DerivationPath, accountIndex = 0, addressList: AddressType[] = [], - pubKeys: PubKeyType[] = [] + pubKeys: PubKeyType[] = [], ) => { try { const pubKey = await getPublicKey(accountIndex, derivationPathSpec); const pubKeyXP = await getPublicKey( accountIndex, derivationPathSpec, - 'AVM' + 'AVM', ); const address = getEvmAddressFromPubKey(pubKey); const { balance } = await getAvaxBalance(address); @@ -258,7 +258,7 @@ export function LedgerConnector({ getPublicKey, onSuccess, popDeviceSelection, - ] + ], ); const tryPublicKey = useCallback(async () => { diff --git a/src/components/settings/components/ContactForm.tsx b/src/components/settings/components/ContactForm.tsx index 7df2e8031..d5ec93c69 100644 --- a/src/components/settings/components/ContactForm.tsx +++ b/src/components/settings/components/ContactForm.tsx @@ -31,7 +31,7 @@ export const ContactForm = ({ const FormErrors = { NAME_ERROR: t('Name is required'), ADDRESS_ERROR: t( - 'Not a valid Avalanche (C-Chain) address. C-Chain addresses being with 0x' + 'Not a valid Avalanche (C-Chain) address. C-Chain addresses being with 0x', ), ADDRESS_BTC_ERROR: t('Not a valid Bitcoin address'), ADDRESS_XP_ERROR: t('Not a valid X/P-Chain address'), @@ -95,7 +95,7 @@ export const ContactForm = ({ updatedContact.address && contacts.find( ({ id, address }) => - id !== updatedContact.id && address === updatedContact.address + id !== updatedContact.id && address === updatedContact.address, ) ) { setAddressError(FormErrors.ADDRESS_EXISTS); @@ -106,7 +106,8 @@ export const ContactForm = ({ updatedContact.addressBTC && contacts.find( ({ id, addressBTC }) => - id !== updatedContact.id && addressBTC === updatedContact.addressBTC + id !== updatedContact.id && + addressBTC === updatedContact.addressBTC, ) ) { setAddressBtcError(FormErrors.ADDRESS_EXISTS); @@ -125,7 +126,7 @@ export const ContactForm = ({ FormErrors.ADDRESS_XP_PREFIX_ERROR, FormErrors.ADDRESS_XP_ERROR, FormErrors.ADDRESS_EXISTS, - ] + ], ); // Used when "Save" is clicked on New Contact when no iputs filled out. diff --git a/src/components/settings/components/ContactListItem.tsx b/src/components/settings/components/ContactListItem.tsx index 1f7d622b3..654b4e8c2 100644 --- a/src/components/settings/components/ContactListItem.tsx +++ b/src/components/settings/components/ContactListItem.tsx @@ -31,7 +31,10 @@ export const ContactListItem = ({ contactId: contact.id, }).toString()}`, }); - navigateTo && navigateTo(SettingsPages.CONTACT_PROFILE); + if (!navigateTo) { + return; + } + navigateTo(SettingsPages.CONTACT_PROFILE); }} sx={{ p: 0 }} > diff --git a/src/components/settings/components/ContactProfile.tsx b/src/components/settings/components/ContactProfile.tsx index ee374be68..b21418380 100644 --- a/src/components/settings/components/ContactProfile.tsx +++ b/src/components/settings/components/ContactProfile.tsx @@ -33,7 +33,7 @@ export const ContactProfile = ({ goBack, width }: ContactProfileProps) => { const [showDeleteDialog, setShowDeleteDialog] = useState(false); const [contact, setContact] = useState( - getContactById(contactId) || { id: '', name: '', address: '' } + getContactById(contactId) || { id: '', name: '', address: '' }, ); const [isEdit, setIsEdit] = useState(false); const [isFormValid, setIsFormValid] = useState(true); @@ -83,7 +83,7 @@ export const ContactProfile = ({ goBack, width }: ContactProfileProps) => { success: { duration: 2000, }, - } + }, ); setShowDeleteDialog(false); }} @@ -132,7 +132,7 @@ export const ContactProfile = ({ goBack, width }: ContactProfileProps) => { success: { duration: 2000, }, - } + }, ); setIsEdit(false); }} diff --git a/src/components/settings/pages/AddContact.tsx b/src/components/settings/pages/AddContact.tsx index 4b8672603..b5799ebe6 100644 --- a/src/components/settings/pages/AddContact.tsx +++ b/src/components/settings/pages/AddContact.tsx @@ -90,7 +90,7 @@ export function AddContact({ goBack, navigateTo, width }: SettingsPageProps) { success: { duration: 2000, }, - } + }, ); goBack(); }} diff --git a/src/components/settings/pages/Advanced.tsx b/src/components/settings/pages/Advanced.tsx index f857de99a..ee495e278 100644 --- a/src/components/settings/pages/Advanced.tsx +++ b/src/components/settings/pages/Advanced.tsx @@ -71,7 +71,7 @@ export function Advanced({ goBack, navigateTo, width }: SettingsPageProps) { }, }} title={t( - 'Testnet mode changes the interface to allow you to interact with supported testnets.' + 'Testnet mode changes the interface to allow you to interact with supported testnets.', )} > @@ -85,7 +85,7 @@ export function Advanced({ goBack, navigateTo, width }: SettingsPageProps) { const isEnabled = !isDeveloperMode; setDeveloperMode(isEnabled); capture( - isEnabled ? 'DeveloperModeEnabled' : 'DeveloperModeDisabled' + isEnabled ? 'DeveloperModeEnabled' : 'DeveloperModeDisabled', ); history.push('/home'); }} diff --git a/src/components/settings/pages/ChangePassword.tsx b/src/components/settings/pages/ChangePassword.tsx index 07ce03c09..889458cd1 100644 --- a/src/components/settings/pages/ChangePassword.tsx +++ b/src/components/settings/pages/ChangePassword.tsx @@ -45,7 +45,7 @@ export function ChangePassword({ isFieldsFilled, newPassword, confirmPassword, - newPasswordStrength + newPasswordStrength, ); const canSubmit = !error && isFieldsFilled; @@ -95,7 +95,7 @@ export function ChangePassword({ {t( - 'Avoid using a password that you use with other websites or that might be easy for someone to guess.' + 'Avoid using a password that you use with other websites or that might be easy for someone to guess.', )} diff --git a/src/components/settings/pages/ConnectedSites.tsx b/src/components/settings/pages/ConnectedSites.tsx index 12761a5bd..664355255 100644 --- a/src/components/settings/pages/ConnectedSites.tsx +++ b/src/components/settings/pages/ConnectedSites.tsx @@ -37,7 +37,7 @@ const getAccountConnectedSites = ({ return []; } return Object.values(list).filter( - (listItem: any) => listItem?.accounts[account.addressC] + (listItem: any) => listItem?.accounts[account.addressC], ); }; diff --git a/src/components/settings/pages/ContactList.tsx b/src/components/settings/pages/ContactList.tsx index fd90300ff..f6a368f2c 100644 --- a/src/components/settings/pages/ContactList.tsx +++ b/src/components/settings/pages/ContactList.tsx @@ -28,7 +28,7 @@ export function ContactList({ goBack, navigateTo, width }: SettingsPageProps) { (c) => !searchTerm || c.address.toLowerCase().includes(searchTerm) || - c.name.toLowerCase().includes(searchTerm) + c.name.toLowerCase().includes(searchTerm), ); return ( diff --git a/src/components/settings/pages/Currencies.tsx b/src/components/settings/pages/Currencies.tsx index 9cee5c45d..60119693c 100644 --- a/src/components/settings/pages/Currencies.tsx +++ b/src/components/settings/pages/Currencies.tsx @@ -46,7 +46,7 @@ export function Currencies({ goBack, navigateTo, width }: SettingsPageProps) { (c) => !searchTerm || c.symbol.toLowerCase().includes(searchTerm.toLowerCase()) || - c.name.toLowerCase().includes(searchTerm.toLowerCase()) + c.name.toLowerCase().includes(searchTerm.toLowerCase()), ); return ( diff --git a/src/components/settings/pages/ExportRecoveryPhrase.tsx b/src/components/settings/pages/ExportRecoveryPhrase.tsx index a133e32c8..1cf5e8b43 100644 --- a/src/components/settings/pages/ExportRecoveryPhrase.tsx +++ b/src/components/settings/pages/ExportRecoveryPhrase.tsx @@ -166,7 +166,7 @@ export function ExportRecoveryPhrase({ {t('2 Day Waiting Period')} {t( - 'For your safety there is a 2 day waiting period to retrieve a phrase.' + 'For your safety there is a 2 day waiting period to retrieve a phrase.', )} diff --git a/src/components/settings/pages/Feedback.tsx b/src/components/settings/pages/Feedback.tsx index 435971b73..6347af0e8 100644 --- a/src/components/settings/pages/Feedback.tsx +++ b/src/components/settings/pages/Feedback.tsx @@ -59,7 +59,7 @@ export function Feedback({ goBack, navigateTo, width }) { window.open( `https://docs.google.com/forms/d/e/1FAIpQLSdUQiVnJoqQ1g_6XTREpkSB5vxKKK8ba5DRjhzQf1XVeET8Rw/viewform?usp=pp_url&entry.2070152111=Core%20browser%20extension&entry.903657115=${extensionVersion}&entry.1148340936=${os}`, '_blank', - 'noreferrer' + 'noreferrer', ); }} data-testid="report-bug-link" @@ -86,7 +86,7 @@ export function Feedback({ goBack, navigateTo, width }) { window.open( 'https://docs.google.com/forms/d/e/1FAIpQLSdQ9nOPPGjVPmrLXh3B9NR1NuXXUiW2fKW1ylrXpiW_vZB_hw/viewform?entry.2070152111=Core%20browser%20extension', '_blank', - 'noreferrer' + 'noreferrer', ); }} data-testid="product-feedback-request-link" diff --git a/src/components/settings/pages/Ledger.tsx b/src/components/settings/pages/Ledger.tsx index 7093c8064..b6f8ca42e 100644 --- a/src/components/settings/pages/Ledger.tsx +++ b/src/components/settings/pages/Ledger.tsx @@ -138,7 +138,7 @@ export function Ledger({ goBack, navigateTo, width }: SettingsPageProps) { }} > {t( - 'If you do not have the Avalanche app on your Ledger, please add it through the Ledger Live app manager.' + 'If you do not have the Avalanche app on your Ledger, please add it through the Ledger Live app manager.', )} diff --git a/src/components/settings/pages/Legal.tsx b/src/components/settings/pages/Legal.tsx index 5a74de381..093c73ab2 100644 --- a/src/components/settings/pages/Legal.tsx +++ b/src/components/settings/pages/Legal.tsx @@ -46,7 +46,7 @@ export function Legal({ goBack, navigateTo, width }) { window.open( `https://core.app/terms/core`, '_blank', - 'noreferrer' + 'noreferrer', ); }} data-testid="terms-of-use-link" @@ -73,7 +73,7 @@ export function Legal({ goBack, navigateTo, width }) { window.open( `https://www.avalabs.org/privacy-policy`, '_blank', - 'noreferrer' + 'noreferrer', ); }} data-testid="privacy-policy-link" diff --git a/src/components/settings/pages/MainPage.tsx b/src/components/settings/pages/MainPage.tsx index 8460256dc..f4bdb78cf 100644 --- a/src/components/settings/pages/MainPage.tsx +++ b/src/components/settings/pages/MainPage.tsx @@ -142,7 +142,7 @@ export function MainPage({ window.open( getCoreWebUrl(activeAccount?.addressC), '_blank', - 'noreferrer' + 'noreferrer', ); }} > @@ -324,7 +324,7 @@ export function MainPage({ variant="dot" invisible={ !showNotificationDotOn.includes( - SettingsPages.SECURITY_AND_PRIVACY + SettingsPages.SECURITY_AND_PRIVACY, ) } > @@ -403,7 +403,7 @@ export function MainPage({ currentLanguage ? currentLanguage.linkCode : 'en' }/collections/3391518-core`, '_blank', - 'noreferrer' + 'noreferrer', ); }} data-testid="help-center-option" diff --git a/src/components/settings/pages/RecoveryMethods/AuthenticatorDetails.tsx b/src/components/settings/pages/RecoveryMethods/AuthenticatorDetails.tsx index 2673475a7..67680bdde 100644 --- a/src/components/settings/pages/RecoveryMethods/AuthenticatorDetails.tsx +++ b/src/components/settings/pages/RecoveryMethods/AuthenticatorDetails.tsx @@ -114,7 +114,7 @@ export function AuthenticatorDetails({ setState(State.Failure); } }, - [completeAuthenticatorChange, onUpdated, t] + [completeAuthenticatorChange, onUpdated, t], ); useEffect(() => { @@ -237,7 +237,7 @@ export function AuthenticatorDetails({ hasFidoConfigured ? '' : t( - 'To remove the authenticator app, you first need to configure a different recovery method.' + 'To remove the authenticator app, you first need to configure a different recovery method.', ) } > @@ -280,10 +280,10 @@ export function AuthenticatorDetails({ {state === State.ConfirmChange ? t( - 'You will no longer be able to use this authenticator once you switch. You can always re-add an authenticator app.' + 'You will no longer be able to use this authenticator once you switch. You can always re-add an authenticator app.', ) : t( - 'You will no longer be able to use this authenticator once you remove it. You can always re-add it later.' + 'You will no longer be able to use this authenticator once you remove it. You can always re-add it later.', )} diff --git a/src/components/settings/pages/RecoveryMethods/AuthenticatorVerifyScreen.tsx b/src/components/settings/pages/RecoveryMethods/AuthenticatorVerifyScreen.tsx index 6fb7cf665..b51537565 100644 --- a/src/components/settings/pages/RecoveryMethods/AuthenticatorVerifyScreen.tsx +++ b/src/components/settings/pages/RecoveryMethods/AuthenticatorVerifyScreen.tsx @@ -54,8 +54,8 @@ export const AuthenticatorVerifyScreen = ({ {screen === Screen.Scan ? t('Scan QR Code') : screen === Screen.Manual - ? t('Authenticator Setup') - : t('Learn more')} + ? t('Authenticator Setup') + : t('Learn more')} @@ -177,7 +177,7 @@ export function FIDODetails({ onBackClick, details }: Props) { {t('Remove This Method?')} {t( - 'You will no longer be able to use this method to verify any operations. You can always re-add it later.' + 'You will no longer be able to use this method to verify any operations. You can always re-add it later.', )} diff --git a/src/components/settings/pages/RecoveryMethods/RecoveryMethods.tsx b/src/components/settings/pages/RecoveryMethods/RecoveryMethods.tsx index 515494fa3..a3517a887 100644 --- a/src/components/settings/pages/RecoveryMethods/RecoveryMethods.tsx +++ b/src/components/settings/pages/RecoveryMethods/RecoveryMethods.tsx @@ -75,7 +75,7 @@ export function RecoveryMethods({ } } }, - [startRecoveryMethodSetup, hasFidoConfigured] + [startRecoveryMethodSetup, hasFidoConfigured], ); return ( diff --git a/src/components/settings/pages/RecoveryMethods/RecoveryMethodsList.tsx b/src/components/settings/pages/RecoveryMethods/RecoveryMethodsList.tsx index fd7f4ce0f..9343cff1f 100644 --- a/src/components/settings/pages/RecoveryMethods/RecoveryMethodsList.tsx +++ b/src/components/settings/pages/RecoveryMethods/RecoveryMethodsList.tsx @@ -35,7 +35,7 @@ export const RecoveryMethodsList = ({ methodIcon={} methodName={t('Authenticator')} methodDescription={t( - 'Use an authenticator app as a recovery method.' + 'Use an authenticator app as a recovery method.', )} /> )} diff --git a/src/components/settings/pages/RecoveryPhrase.tsx b/src/components/settings/pages/RecoveryPhrase.tsx index 58d19de8b..fcb6460b0 100644 --- a/src/components/settings/pages/RecoveryPhrase.tsx +++ b/src/components/settings/pages/RecoveryPhrase.tsx @@ -62,7 +62,7 @@ export function RecoveryPhrase({ {t( - 'Do not share this phrase with anyone! These words can be used to steal all your accounts.' + 'Do not share this phrase with anyone! These words can be used to steal all your accounts.', )} @@ -113,7 +113,7 @@ export function RecoveryPhrase({ sx={{ color: 'text.secondary', textAlign: 'center', mb: 2, px: 0.25 }} > {t( - 'If you ever change browsers or move computers, you will need this Secret Recovery Phrase to access your accounts. Save them somewhere safe and secret.' + 'If you ever change browsers or move computers, you will need this Secret Recovery Phrase to access your accounts. Save them somewhere safe and secret.', )}