diff --git a/package.json b/package.json index c1f6f121e5..813e323423 100644 --- a/package.json +++ b/package.json @@ -21,18 +21,18 @@ "dist/" ], "scripts": { - "setup": "yarn install && yarn allow-scripts", - "prepublishOnly": "yarn build", - "lint:eslint": "eslint . --cache --ext js,ts", - "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' --ignore-path .gitignore", + "build": "rimraf dist && tsc --project tsconfig.build.json", + "build:link": "yarn build && cd dist && yarn link && rm -rf node_modules && cd ..", + "build:watch": "yarn build --watch", + "doc": "typedoc && touch docs/.nojekyll", "lint": "yarn lint:eslint && yarn lint:misc --check", + "lint:eslint": "eslint . --cache --ext js,ts", "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write", + "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' --ignore-path .gitignore", + "prepublishOnly": "yarn build", + "setup": "yarn install && yarn allow-scripts", "test": "jest", - "test:watch": "jest --watch", - "build": "rimraf dist && tsc --project tsconfig.build.json", - "build:watch": "yarn build --watch", - "build:link": "yarn build && cd dist && yarn link && rm -rf node_modules && cd ..", - "doc": "typedoc && touch docs/.nojekyll" + "test:watch": "jest --watch" }, "dependencies": { "@ethereumjs/common": "^2.3.1", @@ -89,20 +89,20 @@ "@typescript-eslint/eslint-plugin": "^4.22.0", "@typescript-eslint/parser": "^4.22.0", "eslint": "^7.24.0", - "eslint-config-prettier": "^8.1.0", + "eslint-config-prettier": "^8.5.0", "eslint-import-resolver-typescript": "^2.4.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jest": "^24.1.5", "eslint-plugin-jsdoc": "^36.1.0", "eslint-plugin-node": "^11.1.0", - "eslint-plugin-prettier": "^3.3.1", + "eslint-plugin-prettier": "^3.4.1", "ethjs-provider-http": "^0.1.6", "jest": "^26.4.2", "jest-environment-jsdom": "^25.0.0", "jest-when": "^3.4.2", "nock": "^13.0.7", - "prettier": "^2.2.1", - "prettier-plugin-packagejson": "^2.2.11", + "prettier": "^2.6.2", + "prettier-plugin-packagejson": "^2.2.17", "rimraf": "^3.0.2", "sinon": "^9.2.4", "ts-jest": "^26.5.2", diff --git a/src/BaseControllerV2.test.ts b/src/BaseControllerV2.test.ts index 2c2eea7175..14edbe29db 100644 --- a/src/BaseControllerV2.test.ts +++ b/src/BaseControllerV2.test.ts @@ -779,13 +779,12 @@ describe('getPersistentState', () => { const visitorController = new VisitorController( visitorControllerMessenger, ); - const visitorOverflowControllerMessenger = controllerMessenger.getRestricted( - { + const visitorOverflowControllerMessenger = + controllerMessenger.getRestricted({ name: visitorOverflowName, allowedActions: ['VisitorController:clear'], allowedEvents: ['VisitorController:stateChange'], - }, - ); + }); const visitorOverflowController = new VisitorOverflowController( visitorOverflowControllerMessenger, ); diff --git a/src/BaseControllerV2.ts b/src/BaseControllerV2.ts index 26fe4b0a20..d144e5c888 100644 --- a/src/BaseControllerV2.ts +++ b/src/BaseControllerV2.ts @@ -75,7 +75,7 @@ export type Json = export class BaseController< N extends string, S extends Record, - messenger extends RestrictedControllerMessenger + messenger extends RestrictedControllerMessenger, > { private internalState: S; @@ -158,10 +158,12 @@ export class BaseController< // We run into ts2589, "infinite type depth", if we don't cast // produceWithPatches here. // The final, omitted member of the returned tuple are the inverse patches. - const [nextState, patches] = ((produceWithPatches as unknown) as ( - state: S, - cb: typeof callback, - ) => [S, Patch[], Patch[]])(this.internalState, callback); + const [nextState, patches] = ( + produceWithPatches as unknown as ( + state: S, + cb: typeof callback, + ) => [S, Patch[], Patch[]] + )(this.internalState, callback); this.internalState = nextState; this.messagingSystem.publish( diff --git a/src/ControllerMessenger.test.ts b/src/ControllerMessenger.test.ts index 8bfc0e4ebd..55759315d3 100644 --- a/src/ControllerMessenger.test.ts +++ b/src/ControllerMessenger.test.ts @@ -956,11 +956,10 @@ describe('RestrictedControllerMessenger', () => { handler: (increment: number) => void; }; const controllerMessenger = new ControllerMessenger(); - const externalRestrictedControllerMessenger = controllerMessenger.getRestricted( - { + const externalRestrictedControllerMessenger = + controllerMessenger.getRestricted({ name: 'CountController', - }, - ); + }); const restrictedControllerMessenger = controllerMessenger.getRestricted({ name: 'OtherController', allowedActions: ['CountController:count'], @@ -984,11 +983,10 @@ describe('RestrictedControllerMessenger', () => { payload: [string]; }; const controllerMessenger = new ControllerMessenger(); - const externalRestrictedControllerMessenger = controllerMessenger.getRestricted( - { + const externalRestrictedControllerMessenger = + controllerMessenger.getRestricted({ name: 'MessageController', - }, - ); + }); const restrictedControllerMessenger = controllerMessenger.getRestricted({ name: 'OtherController', allowedEvents: ['MessageController:message'], diff --git a/src/ControllerMessenger.ts b/src/ControllerMessenger.ts index 9b403689d0..1c080b9a7a 100644 --- a/src/ControllerMessenger.ts +++ b/src/ControllerMessenger.ts @@ -87,7 +87,7 @@ export class RestrictedControllerMessenger< Action extends ActionConstraint, Event extends EventConstraint, AllowedAction extends string, - AllowedEvent extends string + AllowedEvent extends string, > { private controllerMessenger: ControllerMessenger< ActionConstraint, @@ -352,7 +352,7 @@ export class RestrictedControllerMessenger< */ export class ControllerMessenger< Action extends ActionConstraint, - Event extends EventConstraint + Event extends EventConstraint, > { private actions = new Map(); @@ -595,7 +595,7 @@ export class ControllerMessenger< getRestricted< N extends string, AllowedAction extends string, - AllowedEvent extends string + AllowedEvent extends string, >({ name, allowedActions, diff --git a/src/approval/ApprovalController.test.ts b/src/approval/ApprovalController.test.ts index fddc6905da..048afc5995 100644 --- a/src/approval/ApprovalController.test.ts +++ b/src/approval/ApprovalController.test.ts @@ -97,9 +97,9 @@ describe('approval controller', () => { expect(approvalController.has({ id: 'foo' })).toStrictEqual(true); expect(approvalController.has({ origin: 'bar.baz' })).toStrictEqual(true); expect(approvalController.has({ type: 'myType' })).toStrictEqual(true); - expect( - approvalController.state[STORE_KEY].foo.requestData, - ).toStrictEqual({ foo: 'bar' }); + expect(approvalController.state[STORE_KEY].foo.requestData).toStrictEqual( + { foo: 'bar' }, + ); }); it('adds multiple entries for same origin with different types and ids', () => { diff --git a/src/assets/AccountTrackerController.ts b/src/assets/AccountTrackerController.ts index e026ce9e97..f64ed85d2b 100644 --- a/src/assets/AccountTrackerController.ts +++ b/src/assets/AccountTrackerController.ts @@ -166,14 +166,12 @@ export class AccountTrackerController extends BaseController< addresses: string[], ): Promise> { return await Promise.all( - addresses.map( - (address): Promise<[string, string] | undefined> => { - return safelyExecuteWithTimeout(async () => { - const balance = await query(this.ethQuery, 'getBalance', [address]); - return [address, balance]; - }); - }, - ), + addresses.map((address): Promise<[string, string] | undefined> => { + return safelyExecuteWithTimeout(async () => { + const balance = await query(this.ethQuery, 'getBalance', [address]); + return [address, balance]; + }); + }), ).then((value) => { return value.reduce((obj, item) => { if (!item) { diff --git a/src/assets/CollectibleDetectionController.test.ts b/src/assets/CollectibleDetectionController.test.ts index 3398f62824..09da9adf1d 100644 --- a/src/assets/CollectibleDetectionController.test.ts +++ b/src/assets/CollectibleDetectionController.test.ts @@ -30,20 +30,16 @@ describe('CollectibleDetectionController', () => { collectiblesController = new CollectiblesController({ onPreferencesStateChange: (listener) => preferences.subscribe(listener), onNetworkStateChange: (listener) => network.subscribe(listener), - getERC721AssetName: assetsContract.getERC721AssetName.bind( - assetsContract, - ), - getERC721AssetSymbol: assetsContract.getERC721AssetSymbol.bind( - assetsContract, - ), + getERC721AssetName: + assetsContract.getERC721AssetName.bind(assetsContract), + getERC721AssetSymbol: + assetsContract.getERC721AssetSymbol.bind(assetsContract), getERC721TokenURI: assetsContract.getERC721TokenURI.bind(assetsContract), getERC721OwnerOf: assetsContract.getERC721OwnerOf.bind(assetsContract), - getERC1155BalanceOf: assetsContract.getERC1155BalanceOf.bind( - assetsContract, - ), - getERC1155TokenURI: assetsContract.getERC1155TokenURI.bind( - assetsContract, - ), + getERC1155BalanceOf: + assetsContract.getERC1155BalanceOf.bind(assetsContract), + getERC1155TokenURI: + assetsContract.getERC1155TokenURI.bind(assetsContract), }); collectibleDetection = new CollectibleDetectionController({ @@ -222,21 +218,22 @@ describe('CollectibleDetectionController', () => { CollectibleDetectionController.prototype, 'detectCollectibles', ); - const collectiblesDetectionController = new CollectibleDetectionController( - { - onCollectiblesStateChange: (listener) => - collectiblesController.subscribe(listener), - onPreferencesStateChange: (listener) => - preferences.subscribe(listener), - onNetworkStateChange: (listener) => network.subscribe(listener), - getOpenSeaApiKey: () => collectiblesController.openSeaApiKey, - addCollectible: collectiblesController.addCollectible.bind( - collectiblesController, - ), - getCollectiblesState: () => collectiblesController.state, - }, - { interval: 10 }, - ); + const collectiblesDetectionController = + new CollectibleDetectionController( + { + onCollectiblesStateChange: (listener) => + collectiblesController.subscribe(listener), + onPreferencesStateChange: (listener) => + preferences.subscribe(listener), + onNetworkStateChange: (listener) => network.subscribe(listener), + getOpenSeaApiKey: () => collectiblesController.openSeaApiKey, + addCollectible: collectiblesController.addCollectible.bind( + collectiblesController, + ), + getCollectiblesState: () => collectiblesController.state, + }, + { interval: 10 }, + ); collectiblesDetectionController.configure({ disabled: false }); collectiblesDetectionController.start(); expect(mockCollectibles.calledOnce).toBe(true); diff --git a/src/assets/CollectibleDetectionController.ts b/src/assets/CollectibleDetectionController.ts index 3db32a07a9..9f3421d5a7 100644 --- a/src/assets/CollectibleDetectionController.ts +++ b/src/assets/CollectibleDetectionController.ts @@ -222,10 +222,8 @@ export class CollectibleDetectionController extends BaseController< this.initialize(); this.getCollectiblesState = getCollectiblesState; onPreferencesStateChange(({ selectedAddress, useCollectibleDetection }) => { - const { - selectedAddress: previouslySelectedAddress, - disabled, - } = this.config; + const { selectedAddress: previouslySelectedAddress, disabled } = + this.config; if ( selectedAddress !== previouslySelectedAddress || diff --git a/src/assets/CollectiblesController.test.ts b/src/assets/CollectiblesController.test.ts index 3c58d411f4..bccf7c92ab 100644 --- a/src/assets/CollectiblesController.test.ts +++ b/src/assets/CollectiblesController.test.ts @@ -58,20 +58,16 @@ describe('CollectiblesController', () => { collectiblesController = new CollectiblesController({ onPreferencesStateChange: (listener) => preferences.subscribe(listener), onNetworkStateChange: (listener) => network.subscribe(listener), - getERC721AssetName: assetsContract.getERC721AssetName.bind( - assetsContract, - ), - getERC721AssetSymbol: assetsContract.getERC721AssetSymbol.bind( - assetsContract, - ), + getERC721AssetName: + assetsContract.getERC721AssetName.bind(assetsContract), + getERC721AssetSymbol: + assetsContract.getERC721AssetSymbol.bind(assetsContract), getERC721TokenURI: assetsContract.getERC721TokenURI.bind(assetsContract), getERC721OwnerOf: assetsContract.getERC721OwnerOf.bind(assetsContract), - getERC1155BalanceOf: assetsContract.getERC1155BalanceOf.bind( - assetsContract, - ), - getERC1155TokenURI: assetsContract.getERC1155TokenURI.bind( - assetsContract, - ), + getERC1155BalanceOf: + assetsContract.getERC1155BalanceOf.bind(assetsContract), + getERC1155TokenURI: + assetsContract.getERC1155TokenURI.bind(assetsContract), }); preferences.update({ @@ -1294,10 +1290,11 @@ describe('CollectiblesController', () => { .stub(collectiblesController, 'isCollectibleOwner' as any) .returns(false); - const updatedCollectible = await collectiblesController.checkAndUpdateSingleCollectibleOwnershipStatus( - collectible, - true, - ); + const updatedCollectible = + await collectiblesController.checkAndUpdateSingleCollectibleOwnershipStatus( + collectible, + true, + ); expect( collectiblesController.state.allCollectibles[selectedAddress][ diff --git a/src/assets/Standards/CollectibleStandards/ERC1155/ERC1155Standard.test.ts b/src/assets/Standards/CollectibleStandards/ERC1155/ERC1155Standard.test.ts index c7e709f15d..01869b2a03 100644 --- a/src/assets/Standards/CollectibleStandards/ERC1155/ERC1155Standard.test.ts +++ b/src/assets/Standards/CollectibleStandards/ERC1155/ERC1155Standard.test.ts @@ -32,8 +32,7 @@ describe('ERC1155Standard', () => { params: [ { to: '0xfaaFDc07907ff5120a76b34b731b278c38d6043C', - data: - '0x01ffc9a70e89341c00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a70e89341c00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -44,9 +43,10 @@ describe('ERC1155Standard', () => { result: '0x0000000000000000000000000000000000000000000000000000000000000001', }); - const contractSupportsUri = await erc1155Standard.contractSupportsURIMetadataInterface( - ERC1155_ADDRESS, - ); + const contractSupportsUri = + await erc1155Standard.contractSupportsURIMetadataInterface( + ERC1155_ADDRESS, + ); expect(contractSupportsUri).toBe(true); }); }); diff --git a/src/assets/Standards/CollectibleStandards/ERC721/ERC721Standard.test.ts b/src/assets/Standards/CollectibleStandards/ERC721/ERC721Standard.test.ts index 4e7e3940dc..fcdf46578b 100644 --- a/src/assets/Standards/CollectibleStandards/ERC721/ERC721Standard.test.ts +++ b/src/assets/Standards/CollectibleStandards/ERC721/ERC721Standard.test.ts @@ -34,8 +34,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d', - data: - '0x01ffc9a7780e9d6300000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a7780e9d6300000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -53,8 +52,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x6EbeAf8e8E946F0716E6533A6f2cefc83f60e8Ab', - data: - '0x01ffc9a7780e9d6300000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a7780e9d6300000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -66,12 +64,14 @@ describe('ERC721Standard', () => { '0x0000000000000000000000000000000000000000000000000000000000000001', }); - const CKSupportsEnumerable = await erc721Standard.contractSupportsEnumerableInterface( - CRYPTO_KITTIES_ADDRESS, - ); - const GODSSupportsEnumerable = await erc721Standard.contractSupportsEnumerableInterface( - ERC721_GODSADDRESS, - ); + const CKSupportsEnumerable = + await erc721Standard.contractSupportsEnumerableInterface( + CRYPTO_KITTIES_ADDRESS, + ); + const GODSSupportsEnumerable = + await erc721Standard.contractSupportsEnumerableInterface( + ERC721_GODSADDRESS, + ); expect(CKSupportsEnumerable).toBe(false); expect(GODSSupportsEnumerable).toBe(true); }); @@ -85,8 +85,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x6EbeAf8e8E946F0716E6533A6f2cefc83f60e8Ab', - data: - '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -104,8 +103,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x6EbeAf8e8E946F0716E6533A6f2cefc83f60e8Ab', - data: - '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -174,8 +172,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x6EbeAf8e8E946F0716E6533A6f2cefc83f60e8Ab', - data: - '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -193,8 +190,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x6EbeAf8e8E946F0716E6533A6f2cefc83f60e8Ab', - data: - '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -248,8 +244,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x6EbeAf8e8E946F0716E6533A6f2cefc83f60e8Ab', - data: - '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -267,8 +262,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x6EbeAf8e8E946F0716E6533A6f2cefc83f60e8Ab', - data: - '0xc87b56dd0000000000000000000000000000000000000000000000000000000000000004', + data: '0xc87b56dd0000000000000000000000000000000000000000000000000000000000000004', }, 'latest', ], @@ -313,8 +307,7 @@ describe('ERC721Standard', () => { params: [ { to: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', - data: - '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -332,8 +325,7 @@ describe('ERC721Standard', () => { params: [ { to: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', - data: - '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -387,8 +379,7 @@ describe('ERC721Standard', () => { params: [ { to: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', - data: - '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -408,8 +399,7 @@ describe('ERC721Standard', () => { params: [ { to: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', - data: - '0xc87b56dd0000000000000000000000000000000000000000000000000000000000000003', + data: '0xc87b56dd0000000000000000000000000000000000000000000000000000000000000003', }, 'latest', ], @@ -459,8 +449,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x57f1887a8bf19b14fc0df6fd9b2acc9af147ea85', - data: - '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -478,8 +467,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x57f1887a8bf19b14fc0df6fd9b2acc9af147ea85', - data: - '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -514,8 +502,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d', - data: - '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a780ac58cd00000000000000000000000000000000000000000000000000000000', }, 'latest', ], @@ -533,8 +520,7 @@ describe('ERC721Standard', () => { params: [ { to: '0x06012c8cf97BEaD5deAe237070F9587f8E7A266d', - data: - '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', + data: '0x01ffc9a75b5e139f00000000000000000000000000000000000000000000000000000000', }, 'latest', ], diff --git a/src/assets/TokenBalancesController.test.ts b/src/assets/TokenBalancesController.test.ts index f27a052633..12834c3be3 100644 --- a/src/assets/TokenBalancesController.test.ts +++ b/src/assets/TokenBalancesController.test.ts @@ -201,9 +201,8 @@ describe('TokenBalancesController', () => { { onTokensStateChange: (listener) => tokensController.subscribe(listener), getSelectedAddress: () => preferences.state.selectedAddress, - getERC20BalanceOf: assetsContract.getERC20BalanceOf.bind( - assetsContract, - ), + getERC20BalanceOf: + assetsContract.getERC20BalanceOf.bind(assetsContract), }, { interval: 1337 }, ); diff --git a/src/assets/TokenDetectionController.test.ts b/src/assets/TokenDetectionController.test.ts index 8eb484a03f..d93835eaba 100644 --- a/src/assets/TokenDetectionController.test.ts +++ b/src/assets/TokenDetectionController.test.ts @@ -147,7 +147,8 @@ describe('TokenDetectionController', () => { onTokensStateChange: (listener) => tokensController.subscribe(listener), onPreferencesStateChange: (listener) => preferences.subscribe(listener), onNetworkStateChange: (listener) => network.subscribe(listener), - getBalancesInSingleCall: (getBalancesInSingleCall as unknown) as AssetsContractController['getBalancesInSingleCall'], + getBalancesInSingleCall: + getBalancesInSingleCall as unknown as AssetsContractController['getBalancesInSingleCall'], addTokens: tokensController.addTokens.bind(tokensController), getTokensState: () => tokensController.state, getTokenListState: () => tokenList.state, @@ -186,9 +187,8 @@ describe('TokenDetectionController', () => { onPreferencesStateChange: (listener) => preferences.subscribe(listener), onNetworkStateChange: (listener) => network.subscribe(listener), - getBalancesInSingleCall: assetsContract.getBalancesInSingleCall.bind( - assetsContract, - ), + getBalancesInSingleCall: + assetsContract.getBalancesInSingleCall.bind(assetsContract), addTokens: tokensController.addTokens.bind(tokensController), getTokensState: () => tokensController.state, getTokenListState: () => tokenList.state, @@ -226,9 +226,8 @@ describe('TokenDetectionController', () => { onPreferencesStateChange: (listener) => preferences.subscribe(listener), onNetworkStateChange: (listener) => network.subscribe(listener), - getBalancesInSingleCall: assetsContract.getBalancesInSingleCall.bind( - assetsContract, - ), + getBalancesInSingleCall: + assetsContract.getBalancesInSingleCall.bind(assetsContract), addTokens: tokensController.addTokens.bind(tokensController), getTokensState: () => tokensController.state, getTokenListState: () => tokenList.state, diff --git a/src/assets/TokenListController.test.ts b/src/assets/TokenListController.test.ts index d8a51beee6..3be6e58654 100644 --- a/src/assets/TokenListController.test.ts +++ b/src/assets/TokenListController.test.ts @@ -21,9 +21,11 @@ const timestamp = Date.now(); const staticTokenList: TokenListMap = {}; for (const tokenAddress in contractMap) { - const { erc20, logo: filePath, ...token } = (contractMap as ContractMap)[ - tokenAddress - ]; + const { + erc20, + logo: filePath, + ...token + } = (contractMap as ContractMap)[tokenAddress]; if (erc20) { staticTokenList[tokenAddress] = { ...token, diff --git a/src/assets/TokenListController.ts b/src/assets/TokenListController.ts index 4aced204e5..9ec4cae465 100644 --- a/src/assets/TokenListController.ts +++ b/src/assets/TokenListController.ts @@ -241,9 +241,11 @@ export class TokenListController extends BaseController< async fetchFromStaticTokenList(): Promise { const tokenList: TokenListMap = {}; for (const tokenAddress in contractMap) { - const { erc20, logo: filePath, ...token } = (contractMap as ContractMap)[ - tokenAddress - ]; + const { + erc20, + logo: filePath, + ...token + } = (contractMap as ContractMap)[tokenAddress]; if (erc20) { tokenList[tokenAddress] = { ...token, diff --git a/src/gas/GasFeeController.test.ts b/src/gas/GasFeeController.test.ts index 42a363a83c..b0e8633f82 100644 --- a/src/gas/GasFeeController.test.ts +++ b/src/gas/GasFeeController.test.ts @@ -298,9 +298,8 @@ describe('GasFeeController', () => { it('should call determineGasFeeCalculations again', async () => { setupGasFeeController(); - const pollToken = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await gasFeeController.getGasFeeEstimatesAndStartPolling(pollToken); expect(mockedDetermineGasFeeCalculations).toHaveBeenCalledTimes(2); @@ -309,9 +308,8 @@ describe('GasFeeController', () => { it('should not make more than one call to determineGasFeeCalculations per set interval', async () => { setupGasFeeController(); - const pollToken = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await gasFeeController.getGasFeeEstimatesAndStartPolling(pollToken); await clock.nextAsync(); await clock.nextAsync(); @@ -358,9 +356,8 @@ describe('GasFeeController', () => { describe('given the same token as the result of the first call', () => { it('should prevent calls to determineGasFeeCalculations from being made periodically', async () => { setupGasFeeController(); - const pollToken = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await clock.nextAsync(); expect(mockedDetermineGasFeeCalculations).toHaveBeenCalledTimes(2); @@ -372,9 +369,8 @@ describe('GasFeeController', () => { it('should make it so that a second call to getGasFeeEstimatesAndStartPolling with the same token has the same effect as the inaugural call', async () => { setupGasFeeController(); - const pollToken = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await clock.nextAsync(); expect(mockedDetermineGasFeeCalculations).toHaveBeenCalledTimes(2); @@ -404,9 +400,8 @@ describe('GasFeeController', () => { describe('if getGasFeeEstimatesAndStartPolling was called twice with different tokens', () => { it('should not prevent calls to determineGasFeeCalculations from being made periodically', async () => { setupGasFeeController(); - const pollToken1 = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken1 = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await clock.nextAsync(); expect(mockedDetermineGasFeeCalculations).toHaveBeenCalledTimes(2); @@ -444,9 +439,8 @@ describe('GasFeeController', () => { it('should make it so that a second call to getGasFeeEstimatesAndStartPolling with the same token has the same effect as the inaugural call', async () => { setupGasFeeController(); - const pollToken = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await clock.nextAsync(); expect(mockedDetermineGasFeeCalculations).toHaveBeenCalledTimes(2); @@ -475,9 +469,8 @@ describe('GasFeeController', () => { describe('if getGasFeeEstimatesAndStartPolling was called multiple times with the same token (thereby restarting the polling once)', () => { it('should prevent calls to determineGasFeeCalculations from being made periodically', async () => { setupGasFeeController(); - const pollToken = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await gasFeeController.getGasFeeEstimatesAndStartPolling(pollToken); await clock.nextAsync(); expect(mockedDetermineGasFeeCalculations).toHaveBeenCalledTimes(3); @@ -490,9 +483,8 @@ describe('GasFeeController', () => { it('should make it so that another call to getGasFeeEstimatesAndStartPolling with a previously generated token has the same effect as the inaugural call', async () => { setupGasFeeController(); - const pollToken = await gasFeeController.getGasFeeEstimatesAndStartPolling( - undefined, - ); + const pollToken = + await gasFeeController.getGasFeeEstimatesAndStartPolling(undefined); await gasFeeController.getGasFeeEstimatesAndStartPolling(pollToken); await clock.nextAsync(); expect(mockedDetermineGasFeeCalculations).toHaveBeenCalledTimes(3); diff --git a/src/gas/GasFeeController.ts b/src/gas/GasFeeController.ts index 1196997bae..b5749d5361 100644 --- a/src/gas/GasFeeController.ts +++ b/src/gas/GasFeeController.ts @@ -314,9 +314,14 @@ export class GasFeeController extends BaseController< }); this.intervalDelay = interval; this.pollTokens = new Set(); - this.getCurrentNetworkEIP1559Compatibility = getCurrentNetworkEIP1559Compatibility; - this.getCurrentNetworkLegacyGasAPICompatibility = getCurrentNetworkLegacyGasAPICompatibility; - this.getCurrentAccountEIP1559Compatibility = getCurrentAccountEIP1559Compatibility; + this.getCurrentNetworkEIP1559Compatibility = + getCurrentNetworkEIP1559Compatibility; + + this.getCurrentNetworkLegacyGasAPICompatibility = + getCurrentNetworkLegacyGasAPICompatibility; + + this.getCurrentAccountEIP1559Compatibility = + getCurrentAccountEIP1559Compatibility; this.EIP1559APIEndpoint = EIP1559APIEndpoint; this.legacyAPIEndpoint = legacyAPIEndpoint; this.getChainId = getChainId; @@ -378,7 +383,8 @@ export class GasFeeController extends BaseController< ): Promise { const { shouldUpdateState = true } = options; let isEIP1559Compatible; - const isLegacyGasAPICompatible = this.getCurrentNetworkLegacyGasAPICompatibility(); + const isLegacyGasAPICompatible = + this.getCurrentNetworkLegacyGasAPICompatibility(); let chainId = this.getChainId(); if (typeof chainId === 'string' && isHexString(chainId)) { @@ -471,7 +477,8 @@ export class GasFeeController extends BaseController< } private async getEIP1559Compatibility() { - const currentNetworkIsEIP1559Compatible = await this.getCurrentNetworkEIP1559Compatibility(); + const currentNetworkIsEIP1559Compatible = + await this.getCurrentNetworkEIP1559Compatibility(); const currentAccountIsEIP1559Compatible = this.getCurrentAccountEIP1559Compatibility?.() ?? true; diff --git a/src/gas/determineGasFeeCalculations.test.ts b/src/gas/determineGasFeeCalculations.test.ts index fa59690e95..4ca928dbbd 100644 --- a/src/gas/determineGasFeeCalculations.test.ts +++ b/src/gas/determineGasFeeCalculations.test.ts @@ -137,7 +137,8 @@ describe('determineGasFeeCalculations', () => { it('returns a combination of the fetched fee and time estimates', async () => { const gasFeeEstimates = buildMockDataForFetchGasEstimates(); mockedFetchGasEstimates.mockResolvedValue(gasFeeEstimates); - const estimatedGasFeeTimeBounds = buildMockDataForCalculateTimeEstimate(); + const estimatedGasFeeTimeBounds = + buildMockDataForCalculateTimeEstimate(); mockedCalculateTimeEstimate.mockReturnValue(estimatedGasFeeTimeBounds); const gasFeeCalculations = await determineGasFeeCalculations(options); @@ -163,7 +164,8 @@ describe('determineGasFeeCalculations', () => { mockedFetchGasEstimatesViaEthFeeHistory.mockResolvedValue( gasFeeEstimates, ); - const estimatedGasFeeTimeBounds = buildMockDataForCalculateTimeEstimate(); + const estimatedGasFeeTimeBounds = + buildMockDataForCalculateTimeEstimate(); mockedCalculateTimeEstimate.mockReturnValue( estimatedGasFeeTimeBounds, ); diff --git a/src/gas/determineGasFeeCalculations.ts b/src/gas/determineGasFeeCalculations.ts index 0168c6dbca..efb3436903 100644 --- a/src/gas/determineGasFeeCalculations.ts +++ b/src/gas/determineGasFeeCalculations.ts @@ -78,10 +78,8 @@ export default async function determineGasFeeCalculations({ } catch { estimates = await fetchGasEstimatesViaEthFeeHistory(ethQuery); } - const { - suggestedMaxPriorityFeePerGas, - suggestedMaxFeePerGas, - } = estimates.medium; + const { suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas } = + estimates.medium; const estimatedGasFeeTimeBounds = calculateTimeEstimate( suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas, diff --git a/src/gas/fetchGasEstimatesViaEthFeeHistory.ts b/src/gas/fetchGasEstimatesViaEthFeeHistory.ts index 0a82936437..85db2fdac9 100644 --- a/src/gas/fetchGasEstimatesViaEthFeeHistory.ts +++ b/src/gas/fetchGasEstimatesViaEthFeeHistory.ts @@ -36,9 +36,8 @@ export default async function fetchGasEstimatesViaEthFeeHistory( }); const estimatedBaseFee = fromWei(latestBlock.baseFeePerGas, GWEI); - const levelSpecificEstimates = calculateGasFeeEstimatesForPriorityLevels( - blocks, - ); + const levelSpecificEstimates = + calculateGasFeeEstimatesForPriorityLevels(blocks); return { ...levelSpecificEstimates, diff --git a/src/keyring/KeyringController.test.ts b/src/keyring/KeyringController.test.ts index 7aa44a4d52..db4a0cb6b0 100644 --- a/src/keyring/KeyringController.test.ts +++ b/src/keyring/KeyringController.test.ts @@ -76,8 +76,9 @@ describe('KeyringController', () => { }); it('should add new account', async () => { - const initialIdentitiesLength = Object.keys(preferences.state.identities) - .length; + const initialIdentitiesLength = Object.keys( + preferences.state.identities, + ).length; const currentKeyringMemState = await keyringController.addNewAccount(); expect(initialState.keyrings).toHaveLength(1); expect(initialState.keyrings[0].accounts).not.toBe( @@ -89,9 +90,11 @@ describe('KeyringController', () => { }); it('should add new account without updating', async () => { - const initialIdentitiesLength = Object.keys(preferences.state.identities) - .length; - const currentKeyringMemState = await keyringController.addNewAccountWithoutUpdate(); + const initialIdentitiesLength = Object.keys( + preferences.state.identities, + ).length; + const currentKeyringMemState = + await keyringController.addNewAccountWithoutUpdate(); expect(initialState.keyrings).toHaveLength(1); expect(initialState.keyrings[0].accounts).not.toBe( currentKeyringMemState.keyrings, @@ -847,8 +850,7 @@ describe('KeyringController', () => { name: 'Keystone', version: 1, xfp: '5271c071', - xpub: - 'xpub6CNhtuXAHDs84AhZj5ALZB6ii4sP5LnDXaKDSjiy6kcBbiysq89cDrLG29poKvZtX9z4FchZKTjTyiPuDeiFMUd1H4g5zViQxt4tpkronJr', + xpub: 'xpub6CNhtuXAHDs84AhZj5ALZB6ii4sP5LnDXaKDSjiy6kcBbiysq89cDrLG29poKvZtX9z4FchZKTjTyiPuDeiFMUd1H4g5zViQxt4tpkronJr', hdPath: "m/44'/60'/0'", childrenPath: '0/*', indexes: { diff --git a/src/keyring/KeyringController.ts b/src/keyring/KeyringController.ts index b551bc5e57..ea906ad7bf 100644 --- a/src/keyring/KeyringController.ts +++ b/src/keyring/KeyringController.ts @@ -601,19 +601,21 @@ export class KeyringController extends BaseController< */ async fullUpdate(): Promise { const keyrings: Keyring[] = await Promise.all( - privates.get(this).keyring.keyrings.map( - async (keyring: KeyringObject, index: number): Promise => { - const keyringAccounts = await keyring.getAccounts(); - const accounts = Array.isArray(keyringAccounts) - ? keyringAccounts.map((address) => toChecksumHexAddress(address)) - : /* istanbul ignore next */ []; - return { - accounts, - index, - type: keyring.type, - }; - }, - ), + privates + .get(this) + .keyring.keyrings.map( + async (keyring: KeyringObject, index: number): Promise => { + const keyringAccounts = await keyring.getAccounts(); + const accounts = Array.isArray(keyringAccounts) + ? keyringAccounts.map((address) => toChecksumHexAddress(address)) + : /* istanbul ignore next */ []; + return { + accounts, + index, + type: keyring.type, + }; + }, + ), ); this.update({ keyrings: [...keyrings] }); return privates.get(this).keyring.fullUpdate(); diff --git a/src/message-manager/AbstractMessageManager.ts b/src/message-manager/AbstractMessageManager.ts index 6f8631e865..288e005626 100644 --- a/src/message-manager/AbstractMessageManager.ts +++ b/src/message-manager/AbstractMessageManager.ts @@ -72,7 +72,7 @@ export interface MessageManagerState export abstract class AbstractMessageManager< M extends AbstractMessage, P extends AbstractMessageParams, - PM extends AbstractMessageParamsMetamask + PM extends AbstractMessageParamsMetamask, > extends BaseController> { protected messages: M[]; diff --git a/src/network/NetworkController.ts b/src/network/NetworkController.ts index 4a23107e41..aab969b86f 100644 --- a/src/network/NetworkController.ts +++ b/src/network/NetworkController.ts @@ -280,12 +280,8 @@ export class NetworkController extends BaseController< * @param type - Human readable network name. */ setProviderType(type: NetworkType) { - const { - rpcTarget, - chainId, - nickname, - ...providerState - } = this.state.provider; + const { rpcTarget, chainId, nickname, ...providerState } = + this.state.provider; this.update({ provider: { ...providerState, diff --git a/src/permissions/Caveat.ts b/src/permissions/Caveat.ts index 5bf4aa522f..e3d5b96e65 100644 --- a/src/permissions/Caveat.ts +++ b/src/permissions/Caveat.ts @@ -76,16 +76,15 @@ export type CaveatDecorator = ( * @template Decorator - The {@link CaveatDecorator} to extract a caveat value * type from. */ -type ExtractCaveatValueFromDecorator< - Decorator extends CaveatDecorator -> = Decorator extends ( - decorated: any, - caveat: infer ParentCaveat, -) => AsyncRestrictedMethod - ? ParentCaveat extends CaveatConstraint - ? ParentCaveat['value'] - : never - : never; +type ExtractCaveatValueFromDecorator> = + Decorator extends ( + decorated: any, + caveat: infer ParentCaveat, + ) => AsyncRestrictedMethod + ? ParentCaveat extends CaveatConstraint + ? ParentCaveat['value'] + : never + : never; /** * A function for validating caveats of a particular type. @@ -142,7 +141,7 @@ export type CaveatSpecificationConstraint = { */ type CaveatSpecificationBuilderOptions< DecoratorHooks extends Record, - ValidatorHooks extends Record + ValidatorHooks extends Record, > = { type?: string; decoratorHooks?: DecoratorHooks; @@ -157,7 +156,7 @@ type CaveatSpecificationBuilderOptions< */ export type CaveatSpecificationBuilder< Options extends CaveatSpecificationBuilderOptions, - Specification extends CaveatSpecificationConstraint + Specification extends CaveatSpecificationConstraint, > = (options: Options) => Specification; /** @@ -180,7 +179,7 @@ export type CaveatSpecificationBuilderExportConstraint = { * @template Specifications - The union of all {@link CaveatSpecificationConstraint} types. */ export type CaveatSpecificationMap< - CaveatSpecification extends CaveatSpecificationConstraint + CaveatSpecification extends CaveatSpecificationConstraint, > = Record; /** @@ -191,7 +190,7 @@ export type CaveatSpecificationMap< * caveat type union from. */ export type ExtractCaveats< - CaveatSpecification extends CaveatSpecificationConstraint + CaveatSpecification extends CaveatSpecificationConstraint, > = CaveatSpecification extends any ? Caveat< CaveatSpecification['type'], @@ -208,7 +207,7 @@ export type ExtractCaveats< */ export type ExtractCaveat< CaveatSpecifications extends CaveatSpecificationConstraint, - CaveatType extends string + CaveatType extends string, > = Extract, { type: CaveatType }>; /** @@ -220,7 +219,7 @@ export type ExtractCaveat< */ export type ExtractCaveatValue< CaveatSpecifications extends CaveatSpecificationConstraint, - CaveatType extends string + CaveatType extends string, > = ExtractCaveat['value']; /** @@ -235,7 +234,7 @@ export type ExtractCaveatValue< * @returns The decorated method implementation */ export function decorateWithCaveats< - CaveatSpecifications extends CaveatSpecificationConstraint + CaveatSpecifications extends CaveatSpecificationConstraint, >( methodImplementation: RestrictedMethod, permission: Readonly, // bound to the requesting origin diff --git a/src/permissions/Permission.ts b/src/permissions/Permission.ts index df6b87db03..7112af5e93 100644 --- a/src/permissions/Permission.ts +++ b/src/permissions/Permission.ts @@ -82,7 +82,7 @@ export type PermissionConstraint = { */ export type ValidPermission< TargetKey extends TargetName, - AllowedCaveat extends CaveatConstraint + AllowedCaveat extends CaveatConstraint, > = PermissionConstraint & { // TODO:TS4.4 Make optional /** @@ -134,7 +134,7 @@ export type ExtractPermissionTargetNames = ValidTargetName< */ type KeyOfTargetName< Key extends string, - Name extends string + Name extends string, > = Name extends ExtractPermissionTargetNames ? Key : never; /** @@ -148,7 +148,7 @@ type KeyOfTargetName< */ export type ExtractPermissionTargetKey< Key extends string, - Name extends string + Name extends string, > = Key extends Name ? Key : Extract>; /** @@ -172,7 +172,7 @@ type ExtractArrayMembers = ArrayType extends [] * extract valid caveat types from. */ export type ExtractAllowedCaveatTypes< - PermissionSpecification extends PermissionSpecificationConstraint + PermissionSpecification extends PermissionSpecificationConstraint, > = ExtractArrayMembers; /** @@ -204,7 +204,7 @@ export type PermissionOptions = { * @returns The new permission object. */ export function constructPermission< - TargetPermission extends PermissionConstraint + TargetPermission extends PermissionConstraint, >(options: PermissionOptions): TargetPermission { const { caveats = null, invoker, target } = options; @@ -259,13 +259,12 @@ export type RestrictedMethodParameters = Json[] | Record | void; * * @template Params - The JSON-RPC parameters of the restricted method. */ -export type RestrictedMethodOptions< - Params extends RestrictedMethodParameters -> = { - method: TargetName; - params?: Params; - context: RestrictedMethodContext; -}; +export type RestrictedMethodOptions = + { + method: TargetName; + params?: Params; + context: RestrictedMethodContext; + }; /** * A synchronous restricted method implementation. @@ -275,7 +274,7 @@ export type RestrictedMethodOptions< */ export type SyncRestrictedMethod< Params extends RestrictedMethodParameters, - Result extends Json + Result extends Json, > = (args: RestrictedMethodOptions) => Result; /** @@ -286,7 +285,7 @@ export type SyncRestrictedMethod< */ export type AsyncRestrictedMethod< Params extends RestrictedMethodParameters, - Result extends Json + Result extends Json, > = (args: RestrictedMethodOptions) => Promise; /** @@ -297,13 +296,13 @@ export type AsyncRestrictedMethod< */ export type RestrictedMethod< Params extends RestrictedMethodParameters, - Result extends Json + Result extends Json, > = | SyncRestrictedMethod | AsyncRestrictedMethod; export type ValidRestrictedMethod< - MethodImplementation extends RestrictedMethod + MethodImplementation extends RestrictedMethod, > = MethodImplementation extends (args: infer Options) => Json | Promise ? Options extends RestrictedMethodOptions ? MethodImplementation @@ -338,7 +337,7 @@ export type EndowmentGetter = ( export type PermissionFactory< TargetPermission extends PermissionConstraint, - RequestData extends Record + RequestData extends Record, > = ( options: PermissionOptions, requestData?: RequestData, @@ -442,13 +441,14 @@ type PermissionSpecificationBase = { * * See the README for more details. */ -export type RestrictedMethodSpecificationConstraint = PermissionSpecificationBase & { - /** - * The implementation of the restricted method that the permission - * corresponds to. - */ - methodImplementation: RestrictedMethod; -}; +export type RestrictedMethodSpecificationConstraint = + PermissionSpecificationBase & { + /** + * The implementation of the restricted method that the permission + * corresponds to. + */ + methodImplementation: RestrictedMethod; + }; /** * The constraint for endowment permission specification objects. Permissions @@ -457,20 +457,21 @@ export type RestrictedMethodSpecificationConstraint = PermissionSpecificationBas * * See the README for more details. */ -export type EndowmentSpecificationConstraint = PermissionSpecificationBase & { - /** - * Endowment permissions do not support caveats. - */ - allowedCaveats: null; +export type EndowmentSpecificationConstraint = + PermissionSpecificationBase & { + /** + * Endowment permissions do not support caveats. + */ + allowedCaveats: null; - /** - * The {@link EndowmentGetter} function for the permission. This function - * will be called by the {@link PermissionController} whenever the - * permission is invoked, after which the host can apply the endowments to - * the requesting subject in the intended manner. - */ - endowmentGetter: EndowmentGetter; -}; + /** + * The {@link EndowmentGetter} function for the permission. This function + * will be called by the {@link PermissionController} whenever the + * permission is invoked, after which the host can apply the endowments to + * the requesting subject in the intended manner. + */ + endowmentGetter: EndowmentGetter; + }; /** * The constraint for permission specification objects. Every {@link Permission} @@ -492,7 +493,7 @@ export type PermissionSpecificationConstraint = type PermissionSpecificationBuilderOptions< FactoryHooks extends Record, MethodHooks extends Record, - ValidatorHooks extends Record + ValidatorHooks extends Record, > = { targetKey?: string; allowedCaveats?: Readonly> | null; @@ -512,7 +513,7 @@ export type PermissionSpecificationBuilder< Options extends PermissionSpecificationBuilderOptions, Specification extends PermissionSpecificationConstraint & { permissionType: Type; - } + }, > = (options: Options) => Specification; /** @@ -532,7 +533,7 @@ export type PermissionSpecificationBuilderExportConstraint = { }; type ValidRestrictedMethodSpecification< - Specification extends RestrictedMethodSpecificationConstraint + Specification extends RestrictedMethodSpecificationConstraint, > = Specification['methodImplementation'] extends ValidRestrictedMethod< Specification['methodImplementation'] > @@ -546,7 +547,7 @@ type ValidRestrictedMethodSpecification< * @template Specification - The permission specification to validate. */ export type ValidPermissionSpecification< - Specification extends PermissionSpecificationConstraint + Specification extends PermissionSpecificationConstraint, > = Specification['targetKey'] extends ValidTargetKey< Specification['targetKey'] > @@ -570,7 +571,7 @@ export type ValidPermissionSpecification< */ export function hasSpecificationType< Specification extends PermissionSpecificationConstraint, - Type extends PermissionType + Type extends PermissionType, >( specification: Specification, expectedType: Type, @@ -587,7 +588,7 @@ export function hasSpecificationType< * @template Specifications - The union of all {@link PermissionSpecificationConstraint} types. */ export type PermissionSpecificationMap< - Specification extends PermissionSpecificationConstraint + Specification extends PermissionSpecificationConstraint, > = { [TargetKey in Specification['targetKey']]: Specification extends { targetKey: TargetKey; @@ -605,7 +606,7 @@ export type PermissionSpecificationMap< */ export type ExtractPermissionSpecification< Specification extends PermissionSpecificationConstraint, - TargetKey extends Specification['targetKey'] + TargetKey extends Specification['targetKey'], > = Specification extends { targetKey: TargetKey; } diff --git a/src/permissions/PermissionController.test.ts b/src/permissions/PermissionController.test.ts index 3fd9e0833b..fadae6fd81 100644 --- a/src/permissions/PermissionController.test.ts +++ b/src/permissions/PermissionController.test.ts @@ -67,21 +67,21 @@ function getDefaultCaveatSpecifications() { return { [CaveatTypes.filterArrayResponse]: { type: CaveatTypes.filterArrayResponse, - decorator: ( - method: AsyncRestrictedMethod, - caveat: FilterArrayCaveat, - ) => async ( - args: RestrictedMethodOptions, - ) => { - const result: string[] | unknown = await method(args); - if (!Array.isArray(result)) { - throw Error('not an array'); - } + decorator: + ( + method: AsyncRestrictedMethod, + caveat: FilterArrayCaveat, + ) => + async (args: RestrictedMethodOptions) => { + const result: string[] | unknown = await method(args); + if (!Array.isArray(result)) { + throw Error('not an array'); + } - return result.filter((resultValue) => - caveat.value.includes(resultValue), - ); - }, + return result.filter((resultValue) => + caveat.value.includes(resultValue), + ); + }, validator: (caveat: { type: typeof CaveatTypes.filterArrayResponse; value: unknown; @@ -95,51 +95,51 @@ function getDefaultCaveatSpecifications() { }, [CaveatTypes.reverseArrayResponse]: { type: CaveatTypes.reverseArrayResponse, - decorator: ( - method: AsyncRestrictedMethod, - _caveat: ReverseArrayCaveat, - ) => async ( - args: RestrictedMethodOptions, - ) => { - const result: unknown[] | unknown = await method(args); - if (!Array.isArray(result)) { - throw Error('not an array'); - } + decorator: + ( + method: AsyncRestrictedMethod, + _caveat: ReverseArrayCaveat, + ) => + async (args: RestrictedMethodOptions) => { + const result: unknown[] | unknown = await method(args); + if (!Array.isArray(result)) { + throw Error('not an array'); + } - return result.reverse(); - }, + return result.reverse(); + }, }, [CaveatTypes.filterObjectResponse]: { type: CaveatTypes.filterObjectResponse, - decorator: ( - method: AsyncRestrictedMethod, - caveat: FilterObjectCaveat, - ) => async ( - args: RestrictedMethodOptions, - ) => { - const result = await method(args); - if (!isPlainObject(result)) { - throw Error('not a plain object'); - } - - Object.keys(result).forEach((key) => { - if (!caveat.value.includes(key)) { - delete result[key]; + decorator: + ( + method: AsyncRestrictedMethod, + caveat: FilterObjectCaveat, + ) => + async (args: RestrictedMethodOptions) => { + const result = await method(args); + if (!isPlainObject(result)) { + throw Error('not a plain object'); } - }); - return result; - }, + + Object.keys(result).forEach((key) => { + if (!caveat.value.includes(key)) { + delete result[key]; + } + }); + return result; + }, }, [CaveatTypes.noopCaveat]: { type: CaveatTypes.noopCaveat, - decorator: ( - method: AsyncRestrictedMethod, - _caveat: NoopCaveat, - ) => async ( - args: RestrictedMethodOptions, - ) => { - return method(args); - }, + decorator: + ( + method: AsyncRestrictedMethod, + _caveat: NoopCaveat, + ) => + async (args: RestrictedMethodOptions) => { + return method(args); + }, validator: (caveat: { type: typeof CaveatTypes.noopCaveat; value: unknown; @@ -593,9 +593,9 @@ describe('PermissionController', () => { it('throws if a permission specification lists unrecognized caveats', () => { const permissionSpecifications = getDefaultPermissionSpecifications(); - (permissionSpecifications as any).wallet_getSecretArray.allowedCaveats.push( - 'foo', - ); + ( + permissionSpecifications as any + ).wallet_getSecretArray.allowedCaveats.push('foo'); expect( () => @@ -4131,8 +4131,9 @@ describe('PermissionController', () => { it('throws if the restricted method returns undefined', async () => { const permissionSpecifications = getDefaultPermissionSpecifications(); - (permissionSpecifications as any).wallet_doubleNumber.methodImplementation = () => - undefined; + ( + permissionSpecifications as any + ).wallet_doubleNumber.methodImplementation = () => undefined; const controller = new PermissionController< DefaultPermissionSpecifications, @@ -4700,8 +4701,9 @@ describe('PermissionController', () => { it('returns an error if the restricted method returns undefined', async () => { const permissionSpecifications = getDefaultPermissionSpecifications(); - (permissionSpecifications as any).wallet_doubleNumber.methodImplementation = () => - undefined; + ( + permissionSpecifications as any + ).wallet_doubleNumber.methodImplementation = () => undefined; const controller = new PermissionController< DefaultPermissionSpecifications, diff --git a/src/permissions/PermissionController.ts b/src/permissions/PermissionController.ts index de35ff29e2..6a59608c38 100644 --- a/src/permissions/PermissionController.ts +++ b/src/permissions/PermissionController.ts @@ -109,16 +109,15 @@ const controllerName = 'PermissionController'; /** * Permissions associated with a {@link PermissionController} subject. */ -export type SubjectPermissions< - Permission extends PermissionConstraint -> = Record; +export type SubjectPermissions = + Record; /** * Permissions and metadata associated with a {@link PermissionController} * subject. */ export type PermissionSubjectEntry< - SubjectPermission extends PermissionConstraint + SubjectPermission extends PermissionConstraint, > = { origin: SubjectPermission['invoker']; permissions: SubjectPermissions; @@ -130,7 +129,7 @@ export type PermissionSubjectEntry< * @template SubjectPermission - The permissions of the subject. */ export type PermissionControllerSubjects< - SubjectPermission extends PermissionConstraint + SubjectPermission extends PermissionConstraint, > = Record< SubjectPermission['invoker'], PermissionSubjectEntry @@ -142,13 +141,12 @@ export type PermissionControllerSubjects< * * @template Permission - The controller's permission type union. */ -export type PermissionControllerState< - Permission -> = Permission extends PermissionConstraint - ? { - subjects: PermissionControllerSubjects; - } - : never; +export type PermissionControllerState = + Permission extends PermissionConstraint + ? { + subjects: PermissionControllerSubjects; + } + : never; /** * Get the state metadata of the {@link PermissionController}. @@ -380,7 +378,7 @@ type CaveatMutatorResult = */ export type ExtractPermission< ControllerPermissionSpecification extends PermissionSpecificationConstraint, - ControllerCaveatSpecification extends CaveatSpecificationConstraint + ControllerCaveatSpecification extends CaveatSpecificationConstraint, > = ControllerPermissionSpecification extends ValidPermissionSpecification ? ValidPermission< ControllerPermissionSpecification['targetKey'], @@ -400,7 +398,7 @@ export type ExtractPermission< */ export type ExtractRestrictedMethodPermission< ControllerPermissionSpecification extends PermissionSpecificationConstraint, - ControllerCaveatSpecification extends CaveatSpecificationConstraint + ControllerCaveatSpecification extends CaveatSpecificationConstraint, > = ExtractPermission< Extract< ControllerPermissionSpecification, @@ -421,7 +419,7 @@ export type ExtractRestrictedMethodPermission< */ export type ExtractEndowmentPermission< ControllerPermissionSpecification extends PermissionSpecificationConstraint, - ControllerCaveatSpecification extends CaveatSpecificationConstraint + ControllerCaveatSpecification extends CaveatSpecificationConstraint, > = ExtractPermission< Extract, ControllerCaveatSpecification @@ -438,7 +436,7 @@ export type ExtractEndowmentPermission< */ export type PermissionControllerOptions< ControllerPermissionSpecification extends PermissionSpecificationConstraint, - ControllerCaveatSpecification extends CaveatSpecificationConstraint + ControllerCaveatSpecification extends CaveatSpecificationConstraint, > = { messenger: PermissionControllerMessenger; caveatSpecifications: CaveatSpecificationMap; @@ -468,7 +466,7 @@ export type PermissionControllerOptions< */ export class PermissionController< ControllerPermissionSpecification extends PermissionSpecificationConstraint, - ControllerCaveatSpecification extends CaveatSpecificationConstraint + ControllerCaveatSpecification extends CaveatSpecificationConstraint, > extends BaseController< typeof controllerName, PermissionControllerState< @@ -543,12 +541,13 @@ export class PermissionController< super({ name: controllerName, - metadata: getStateMetadata< - ExtractPermission< - ControllerPermissionSpecification, - ControllerCaveatSpecification - > - >(), + metadata: + getStateMetadata< + ExtractPermission< + ControllerPermissionSpecification, + ControllerCaveatSpecification + > + >(), messenger, state: { ...getDefaultState< @@ -590,7 +589,7 @@ export class PermissionController< * @returns The permission specification with the specified target key. */ private getPermissionSpecification< - TargetKey extends ControllerPermissionSpecification['targetKey'] + TargetKey extends ControllerPermissionSpecification['targetKey'], >( targetKey: TargetKey, ): ExtractPermissionSpecification< @@ -607,7 +606,7 @@ export class PermissionController< * @returns The caveat specification with the specified type. */ private getCaveatSpecification< - CaveatType extends ControllerCaveatSpecification['type'] + CaveatType extends ControllerCaveatSpecification['type'], >(caveatType: CaveatType) { return this._caveatSpecifications[caveatType]; } @@ -835,7 +834,7 @@ export class PermissionController< SubjectPermission extends ExtractPermission< ControllerPermissionSpecification, ControllerCaveatSpecification - > + >, >( origin: OriginString, targetName: SubjectPermission['parentCapability'], @@ -1035,7 +1034,7 @@ export class PermissionController< ControllerPermissionSpecification, ControllerCaveatSpecification >['parentCapability'], - CaveatType extends ExtractAllowedCaveatTypes + CaveatType extends ExtractAllowedCaveatTypes, >(origin: OriginString, target: TargetName, caveatType: CaveatType): boolean { return Boolean(this.getCaveat(origin, target, caveatType)); } @@ -1060,7 +1059,7 @@ export class PermissionController< ControllerPermissionSpecification, ControllerCaveatSpecification >['parentCapability'], - CaveatType extends ExtractAllowedCaveatTypes + CaveatType extends ExtractAllowedCaveatTypes, >( origin: OriginString, target: TargetName, @@ -1100,7 +1099,7 @@ export class PermissionController< ControllerPermissionSpecification, ControllerCaveatSpecification >['parentCapability'], - CaveatType extends ExtractAllowedCaveatTypes + CaveatType extends ExtractAllowedCaveatTypes, >( origin: OriginString, target: TargetName, @@ -1141,7 +1140,7 @@ export class PermissionController< CaveatValue extends ExtractCaveatValue< ControllerCaveatSpecification, CaveatType - > + >, >( origin: OriginString, target: TargetName, @@ -1178,7 +1177,7 @@ export class PermissionController< ControllerPermissionSpecification, ControllerCaveatSpecification >['parentCapability'], - CaveatType extends ExtractAllowedCaveatTypes + CaveatType extends ExtractAllowedCaveatTypes, >( origin: OriginString, target: TargetName, @@ -1258,7 +1257,7 @@ export class PermissionController< TargetCaveat extends ExtractCaveat< ControllerCaveatSpecification, CaveatType - > + >, >(targetCaveatType: CaveatType, mutator: CaveatMutator): void { if (Object.keys(this.state.subjects).length === 0) { return; @@ -1349,7 +1348,7 @@ export class PermissionController< ControllerPermissionSpecification, ControllerCaveatSpecification >['parentCapability'], - CaveatType extends ExtractAllowedCaveatTypes + CaveatType extends ExtractAllowedCaveatTypes, >(origin: OriginString, target: TargetName, caveatType: CaveatType): void { this.update((draftState) => { const permission = draftState.subjects[origin]?.permissions[target]; @@ -1383,7 +1382,7 @@ export class PermissionController< ControllerPermissionSpecification, ControllerCaveatSpecification >['parentCapability'], - CaveatType extends ExtractCaveats['type'] + CaveatType extends ExtractCaveats['type'], >( permission: Draft, caveatType: CaveatType, @@ -1534,11 +1533,13 @@ export class PermissionController< throw new InvalidSubjectIdentifierError(origin); } - const permissions = (preserveExistingPermissions - ? { - ...this.getPermissions(origin), - } - : {}) as SubjectPermissions< + const permissions = ( + preserveExistingPermissions + ? { + ...this.getPermissions(origin), + } + : {} + ) as SubjectPermissions< ExtractPermission< ControllerPermissionSpecification, ControllerCaveatSpecification @@ -1840,10 +1841,8 @@ export class PermissionController< permissions: requestedPermissions, }; - const { - permissions: approvedPermissions, - ...requestData - } = await this.requestUserApproval(permissionsRequest); + const { permissions: approvedPermissions, ...requestData } = + await this.requestUserApproval(permissionsRequest); return [ this.grantPermissions({ diff --git a/src/permissions/README.md b/src/permissions/README.md index bb17c517d4..8481df6200 100644 --- a/src/permissions/README.md +++ b/src/permissions/README.md @@ -101,19 +101,23 @@ const caveatSpecifications = { // If a permission has any caveats, its corresponding restricted method // implementation is decorated / wrapped with the implementations of its // caveats, using the caveat's decorator function. - decorator: ( - // Restricted methods and other caveats can be async, so we have to - // assume that the method is async. - method: AsyncRestrictedMethod, - caveat: FilterArrayCaveat, - ) => async (args: RestrictedMethodOptions) => { - const result = await method(args); - if (!Array.isArray(result)) { - throw Error('not an array'); - } - - return result.filter((resultValue) => caveat.value.includes(resultValue)); - }, + decorator: + ( + // Restricted methods and other caveats can be async, so we have to + // assume that the method is async. + method: AsyncRestrictedMethod, + caveat: FilterArrayCaveat, + ) => + async (args: RestrictedMethodOptions) => { + const result = await method(args); + if (!Array.isArray(result)) { + throw Error('not an array'); + } + + return result.filter((resultValue) => + caveat.value.includes(resultValue), + ); + }, }, }; diff --git a/src/permissions/utils.ts b/src/permissions/utils.ts index a613e5d134..8441d2d260 100644 --- a/src/permissions/utils.ts +++ b/src/permissions/utils.ts @@ -23,5 +23,5 @@ export enum MethodNames { export type ExtractSpecifications< SpecificationsMap extends | CaveatSpecificationMap - | PermissionSpecificationMap + | PermissionSpecificationMap, > = SpecificationsMap[keyof SpecificationsMap]; diff --git a/src/ratelimit/RateLimitController.ts b/src/ratelimit/RateLimitController.ts index 8d0340a2aa..c6aa1ee49e 100644 --- a/src/ratelimit/RateLimitController.ts +++ b/src/ratelimit/RateLimitController.ts @@ -10,7 +10,7 @@ import type { RestrictedControllerMessenger } from '../ControllerMessenger'; * @property requests - Object containing number of requests in a given interval for each origin and api type combination */ export type RateLimitState< - RateLimitedApis extends Record any> + RateLimitedApis extends Record any>, > = { requests: Record>; }; @@ -18,32 +18,32 @@ export type RateLimitState< const name = 'RateLimitController'; export type RateLimitStateChange< - RateLimitedApis extends Record any> + RateLimitedApis extends Record any>, > = { type: `${typeof name}:stateChange`; payload: [RateLimitState, Patch[]]; }; export type GetRateLimitState< - RateLimitedApis extends Record any> + RateLimitedApis extends Record any>, > = { type: `${typeof name}:getState`; handler: () => RateLimitState; }; export type CallApi< - RateLimitedApis extends Record any> + RateLimitedApis extends Record any>, > = { type: `${typeof name}:call`; handler: RateLimitController['call']; }; export type ControllerActions< - RateLimitedApis extends Record any> + RateLimitedApis extends Record any>, > = GetRateLimitState | CallApi; export type RateLimitMessenger< - RateLimitedApis extends Record any> + RateLimitedApis extends Record any>, > = RestrictedControllerMessenger< typeof name, ControllerActions, @@ -60,7 +60,7 @@ const metadata = { * Controller with logic for rate-limiting API endpoints per requesting origin. */ export class RateLimitController< - RateLimitedApis extends Record any> + RateLimitedApis extends Record any>, > extends BaseController< typeof name, RateLimitState, diff --git a/src/subject-metadata/SubjectMetadataController.test.ts b/src/subject-metadata/SubjectMetadataController.test.ts index 72fca87950..647db58cbc 100644 --- a/src/subject-metadata/SubjectMetadataController.test.ts +++ b/src/subject-metadata/SubjectMetadataController.test.ts @@ -76,10 +76,8 @@ describe('SubjectMetadataController', () => { }); it('trims subject metadata state on startup', () => { - const [ - messenger, - hasPermissionsSpy, - ] = getSubjectMetadataControllerMessenger(); + const [messenger, hasPermissionsSpy] = + getSubjectMetadataControllerMessenger(); hasPermissionsSpy.mockImplementationOnce(() => false); hasPermissionsSpy.mockImplementationOnce(() => true); @@ -116,10 +114,8 @@ describe('SubjectMetadataController', () => { describe('clearState', () => { it('clears the controller state, and continues to function normally afterwards', () => { - const [ - messenger, - hasPermissionsSpy, - ] = getSubjectMetadataControllerMessenger(); + const [messenger, hasPermissionsSpy] = + getSubjectMetadataControllerMessenger(); const controller = new SubjectMetadataController({ messenger, subjectCacheLimit: 3, @@ -179,10 +175,8 @@ describe('SubjectMetadataController', () => { }); it('does not delete metadata for subjects with permissions if cache size is exceeded', () => { - const [ - messenger, - hasPermissionsSpy, - ] = getSubjectMetadataControllerMessenger(); + const [messenger, hasPermissionsSpy] = + getSubjectMetadataControllerMessenger(); const controller = new SubjectMetadataController({ messenger, subjectCacheLimit: 1, @@ -200,10 +194,8 @@ describe('SubjectMetadataController', () => { }); it('deletes metadata for subjects without permissions if cache size is exceeded', () => { - const [ - messenger, - hasPermissionsSpy, - ] = getSubjectMetadataControllerMessenger(); + const [messenger, hasPermissionsSpy] = + getSubjectMetadataControllerMessenger(); const controller = new SubjectMetadataController({ messenger, subjectCacheLimit: 1, @@ -222,10 +214,8 @@ describe('SubjectMetadataController', () => { describe('trimMetadataState', () => { it('deletes all subjects without permissions from state', () => { - const [ - messenger, - hasPermissionsSpy, - ] = getSubjectMetadataControllerMessenger(); + const [messenger, hasPermissionsSpy] = + getSubjectMetadataControllerMessenger(); const controller = new SubjectMetadataController({ messenger, subjectCacheLimit: 4, diff --git a/src/transaction/TransactionController.test.ts b/src/transaction/TransactionController.test.ts index cf81926069..f3ba9b1779 100644 --- a/src/transaction/TransactionController.test.ts +++ b/src/transaction/TransactionController.test.ts @@ -188,20 +188,23 @@ const TRANSACTIONS_IN_STATE: TransactionMeta[] = txsInStateMock( TOKEN_TRANSACTION_HASH, ); -const TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS: TransactionMeta[] = txsInStateWithOutdatedStatusMock( - ETHER_TRANSACTION_HASH, - TOKEN_TRANSACTION_HASH, -); +const TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS: TransactionMeta[] = + txsInStateWithOutdatedStatusMock( + ETHER_TRANSACTION_HASH, + TOKEN_TRANSACTION_HASH, + ); -const TRANSACTIONS_IN_STATE_WITH_OUTDATED_GAS_DATA: TransactionMeta[] = txsInStateWithOutdatedGasDataMock( - ETHER_TRANSACTION_HASH, - TOKEN_TRANSACTION_HASH, -); +const TRANSACTIONS_IN_STATE_WITH_OUTDATED_GAS_DATA: TransactionMeta[] = + txsInStateWithOutdatedGasDataMock( + ETHER_TRANSACTION_HASH, + TOKEN_TRANSACTION_HASH, + ); -const TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS_AND_GAS_DATA: TransactionMeta[] = txsInStateWithOutdatedStatusAndGasDataMock( - ETHER_TRANSACTION_HASH, - TOKEN_TRANSACTION_HASH, -); +const TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS_AND_GAS_DATA: TransactionMeta[] = + txsInStateWithOutdatedStatusAndGasDataMock( + ETHER_TRANSACTION_HASH, + TOKEN_TRANSACTION_HASH, + ); const ETH_TX_HISTORY_DATA = { message: 'OK', @@ -234,14 +237,22 @@ const ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND = { }; const MOCK_FETCH_TX_HISTORY_DATA_OK = { - 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=tokentx&tag=latest&page=1': ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND, - 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=tokentx&tag=latest&page=1': TOKEN_TX_HISTORY_DATA, - 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&startBlock=999&offset=40&order=desc&action=tokentx&tag=latest&page=1': TOKEN_TX_HISTORY_DATA_FROM_BLOCK, - 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA, - 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA, - 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&startBlock=999&offset=40&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA_FROM_BLOCK, - 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=2&order=desc&action=tokentx&tag=latest&page=1': ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND, - 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=2&order=desc&action=txlist&tag=latest&page=1': ETH_TX_HISTORY_DATA, + 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=tokentx&tag=latest&page=1': + ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND, + 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=tokentx&tag=latest&page=1': + TOKEN_TX_HISTORY_DATA, + 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&startBlock=999&offset=40&order=desc&action=tokentx&tag=latest&page=1': + TOKEN_TX_HISTORY_DATA_FROM_BLOCK, + 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=txlist&tag=latest&page=1': + ETH_TX_HISTORY_DATA, + 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=40&order=desc&action=txlist&tag=latest&page=1': + ETH_TX_HISTORY_DATA, + 'https://api.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&startBlock=999&offset=40&order=desc&action=txlist&tag=latest&page=1': + ETH_TX_HISTORY_DATA_FROM_BLOCK, + 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=2&order=desc&action=tokentx&tag=latest&page=1': + ETH_TX_HISTORY_DATA_ROPSTEN_NO_TRANSACTIONS_FOUND, + 'https://api-ropsten.etherscan.io/api?module=account&address=0x6bf137f335ea1b8f193b8f6ea92561a60d23a207&offset=2&order=desc&action=txlist&tag=latest&page=1': + ETH_TX_HISTORY_DATA, }; const MOCK_FETCH_TX_HISTORY_DATA_ERROR = { @@ -380,9 +391,8 @@ describe('TransactionController', () => { it('should add a valid transaction after a network switch', async () => { const getNetworkState = stub().returns(MOCK_NETWORK.state); - let networkStateChangeListener: - | ((state: NetworkState) => void) - | null = null; + let networkStateChangeListener: ((state: NetworkState) => void) | null = + null; const onNetworkStateChange = (listener: (state: NetworkState) => void) => { networkStateChangeListener = listener; }; @@ -420,9 +430,8 @@ describe('TransactionController', () => { it('should add a valid transaction after a switch to custom network', async () => { const getNetworkState = stub().returns(MOCK_NETWORK.state); - let networkStateChangeListener: - | ((state: NetworkState) => void) - | null = null; + let networkStateChangeListener: ((state: NetworkState) => void) | null = + null; const onNetworkStateChange = (listener: (state: NetworkState) => void) => { networkStateChangeListener = listener; }; @@ -905,7 +914,8 @@ describe('TransactionController', () => { controller.wipeTransactions(); expect(controller.state.transactions).toHaveLength(0); - controller.state.transactions = TRANSACTIONS_IN_STATE_WITH_OUTDATED_GAS_DATA; + controller.state.transactions = + TRANSACTIONS_IN_STATE_WITH_OUTDATED_GAS_DATA; await controller.fetchAll(from); expect(controller.state.transactions).toHaveLength(17); @@ -931,7 +941,8 @@ describe('TransactionController', () => { controller.wipeTransactions(); expect(controller.state.transactions).toHaveLength(0); - controller.state.transactions = TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS_AND_GAS_DATA; + controller.state.transactions = + TRANSACTIONS_IN_STATE_WITH_OUTDATED_STATUS_AND_GAS_DATA; await controller.fetchAll(from); expect(controller.state.transactions).toHaveLength(17); diff --git a/src/transaction/TransactionController.ts b/src/transaction/TransactionController.ts index 24c1153bb2..d974885b8a 100644 --- a/src/transaction/TransactionController.ts +++ b/src/transaction/TransactionController.ts @@ -1028,10 +1028,8 @@ export class TransactionController extends BaseController< (!meta.chainId && meta.networkID === currentNetworkID); if (!meta.verifiedOnBlockchain && txBelongsToCurrentChain) { - const [ - reconciledTx, - updateRequired, - ] = await this.blockchainTransactionStateReconciler(meta); + const [reconciledTx, updateRequired] = + await this.blockchainTransactionStateReconciler(meta); if (updateRequired) { transactions[index] = reconciledTx; gotUpdates = updateRequired; @@ -1117,15 +1115,13 @@ export class TransactionController extends BaseController< return undefined; } - const [ - etherscanTxResponse, - etherscanTokenResponse, - ] = await handleTransactionFetch( - networkType, - address, - this.config.txHistoryLimit, - opt, - ); + const [etherscanTxResponse, etherscanTokenResponse] = + await handleTransactionFetch( + networkType, + address, + this.config.txHistoryLimit, + opt, + ); const normalizedTxs = etherscanTxResponse.result.map( (tx: EtherscanTransactionMeta) => @@ -1283,9 +1279,8 @@ export class TransactionController extends BaseController< ]); if (!txObj) { - const receiptShowsFailedStatus = await this.checkTxReceiptStatusIsFailed( - transactionHash, - ); + const receiptShowsFailedStatus = + await this.checkTxReceiptStatusIsFailed(transactionHash); // Case the txObj is evaluated as false, a second check will // determine if the tx failed or it is pending or confirmed diff --git a/src/util.ts b/src/util.ts index 437ed2cc0c..0ff977cb10 100644 --- a/src/util.ts +++ b/src/util.ts @@ -603,7 +603,7 @@ export function validateTokenToWatch(token: Token) { `Invalid symbol "${symbol}": longer than 11 characters.`, ); } - const numDecimals = parseInt((decimals as unknown) as string, 10); + const numDecimals = parseInt(decimals as unknown as string, 10); if (isNaN(numDecimals) || numDecimals > 36 || numDecimals < 0) { throw ethErrors.rpc.invalidParams( `Invalid decimals "${decimals}": must be 0 <= 36.`, @@ -831,9 +831,10 @@ export function removeIpfsProtocolPrefix(ipfsUrl: string) { * @returns IFPS content identifier (cid) and sub path as string. * @throws Will throw if the url passed is not ipfs. */ -export function getIpfsCIDv1AndPath( - ipfsUrl: string, -): { cid: string; path?: string } { +export function getIpfsCIDv1AndPath(ipfsUrl: string): { + cid: string; + path?: string; +} { const url = removeIpfsProtocolPrefix(ipfsUrl); // check if there is a path diff --git a/yarn.lock b/yarn.lock index 6c976e566d..2fd531cdf0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3053,10 +3053,10 @@ escodegen@^1.11.1, escodegen@^1.14.1: optionalDependencies: source-map "~0.6.1" -eslint-config-prettier@^8.1.0: - version "8.1.0" - resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.1.0.tgz#4ef1eaf97afe5176e6a75ddfb57c335121abc5a6" - integrity sha512-oKMhGv3ihGbCIimCAjqkdzx2Q+jthoqnXSP+d86M9tptwugycmTFdVR4IpLgq2c4SHifbwO90z2fQ8/Aio73yw== +eslint-config-prettier@^8.5.0: + version "8.5.0" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz#5a81680ec934beca02c7b1a61cf8ca34b66feab1" + integrity sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q== eslint-import-resolver-node@^0.3.4: version "0.3.4" @@ -3146,10 +3146,10 @@ eslint-plugin-node@^11.1.0: resolve "^1.10.1" semver "^6.1.0" -eslint-plugin-prettier@^3.3.1: - version "3.3.1" - resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.3.1.tgz#7079cfa2497078905011e6f82e8dd8453d1371b7" - integrity sha512-Rq3jkcFY8RYeQLgk2cCwuc0P7SEFwDravPhsJZOQ5N4YI4DSg50NyqJ/9gdZHzQlHf8MvafSesbNJCcP/FF6pQ== +eslint-plugin-prettier@^3.4.1: + version "3.4.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.4.1.tgz#e9ddb200efb6f3d05ffe83b1665a716af4a387e5" + integrity sha512-htg25EUYUeIhKHXjOinK4BgCcDwtLHjqaxCDsMy5nbnUMkKFvIhMVCp+5GFUXQ4Nr8lBsPqtGAqBenbpFqAA2g== dependencies: prettier-linter-helpers "^1.0.0" @@ -6750,17 +6750,17 @@ prettier-linter-helpers@^1.0.0: dependencies: fast-diff "^1.1.2" -prettier-plugin-packagejson@^2.2.11: - version "2.2.11" - resolved "https://registry.yarnpkg.com/prettier-plugin-packagejson/-/prettier-plugin-packagejson-2.2.11.tgz#640b6301da3a58c489889b3d315255e18153daf0" - integrity sha512-oJCBCEkHIKScEv6qNQC47S39NXlevbzwvoJE3gflmBB8/3BEsC6ZRi+hwFVajw32b4tDI9hFXPIzmVd/T8Rm9w== +prettier-plugin-packagejson@^2.2.17: + version "2.2.17" + resolved "https://registry.yarnpkg.com/prettier-plugin-packagejson/-/prettier-plugin-packagejson-2.2.17.tgz#fc5c93203f9091ad063d9ea5960d2e1a989b94ac" + integrity sha512-Z1l3stIdkEzuv5w2ZyLl7mvl1Q/7vr2wjLAaKCQtafPHB7h09dir0tgXK/W5iEc/jP+C4XtvJl/HhiZBvPh4rQ== dependencies: - sort-package-json "1.50.0" + sort-package-json "1.55.0" -prettier@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.2.1.tgz#795a1a78dd52f073da0cd42b21f9c91381923ff5" - integrity sha512-PqyhM2yCjg/oKkFPtTGUojv7gnZAoG80ttl45O6x2Ug/rMJw4wcc9k6aaf2hibP7BGVCCM33gZoGjyvt9mm16Q== +prettier@^2.6.2: + version "2.6.2" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-2.6.2.tgz#e26d71a18a74c3d0f0597f55f01fb6c06c206032" + integrity sha512-PkUpF+qoXTqhOeWL9fu7As8LXsIUZ1WYaJiY/a7McAQzxjk82OF0tibkFXVCDImZtWxbvojFjerkiLb0/q8mew== pretty-format@^25.2.1, pretty-format@^25.5.0: version "25.5.0" @@ -7547,10 +7547,10 @@ sort-object-keys@^1.1.3: resolved "https://registry.yarnpkg.com/sort-object-keys/-/sort-object-keys-1.1.3.tgz#bff833fe85cab147b34742e45863453c1e190b45" integrity sha512-855pvK+VkU7PaKYPc+Jjnmt4EzejQHyhhF33q31qG8x7maDzkeFhAAThdCYay11CISO+qAMwjOBP+fPZe0IPyg== -sort-package-json@1.50.0: - version "1.50.0" - resolved "https://registry.yarnpkg.com/sort-package-json/-/sort-package-json-1.50.0.tgz#19fc109fe23bd157bd03c8e572fa3251a52467d8" - integrity sha512-qZpqhMU9XTntebgAgc4hv/D6Fzhh7kFnwvV6a7+q8y8J5JoaDqPYQnvXPf7BBqG95tdE8X6JVNo7/jDzcbdfUg== +sort-package-json@1.55.0: + version "1.55.0" + resolved "https://registry.yarnpkg.com/sort-package-json/-/sort-package-json-1.55.0.tgz#150328328a9ac8b417b43d5a1fae74e5f27254e9" + integrity sha512-xhKvRD8WGbALjXQkVuk4/93Z/2NIO+5IzKamdMjN5kn3L+N+M9YWQssmM6GXlQr9v1F7PGWsOJEo1gvXOhM7Mg== dependencies: detect-indent "^6.0.0" detect-newline "3.1.0"