@metamask/assets-controllers 30.0.0 → 32.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +96 -1
- package/dist/AccountTrackerController.js +2 -2
- package/dist/AccountTrackerController.mjs +1 -1
- package/dist/AssetsContractController.js +2 -2
- package/dist/AssetsContractController.mjs +1 -1
- package/dist/NftController.js +2 -2
- package/dist/NftController.mjs +3 -3
- package/dist/NftDetectionController.js +2 -2
- package/dist/NftDetectionController.mjs +1 -1
- package/dist/TokenBalancesController.js +2 -2
- package/dist/TokenBalancesController.mjs +1 -1
- package/dist/TokenListController.js +3 -3
- package/dist/TokenListController.mjs +2 -2
- package/dist/TokenRatesController.js +2 -2
- package/dist/TokenRatesController.mjs +1 -1
- package/dist/TokensController.js +3 -3
- package/dist/TokensController.mjs +2 -2
- package/dist/chunk-4AC3X2U5.js +771 -0
- package/dist/chunk-4AC3X2U5.js.map +1 -0
- package/dist/chunk-543CC74T.mjs +253 -0
- package/dist/chunk-543CC74T.mjs.map +1 -0
- package/dist/{chunk-Z3OQU4XW.mjs → chunk-5W5OO2Q5.mjs} +2 -2
- package/dist/chunk-5W5OO2Q5.mjs.map +1 -0
- package/dist/chunk-62T7RKU3.mjs +1265 -0
- package/dist/chunk-62T7RKU3.mjs.map +1 -0
- package/dist/{chunk-PAJTKWEC.mjs → chunk-65PB33TE.mjs} +1 -1
- package/dist/chunk-65PB33TE.mjs.map +1 -0
- package/dist/{chunk-7MMEHAKG.mjs → chunk-73F3SN5O.mjs} +332 -265
- package/dist/chunk-73F3SN5O.mjs.map +1 -0
- package/dist/{chunk-XHMM35YT.mjs → chunk-A2DDWXMS.mjs} +2 -2
- package/dist/chunk-CGLUTXI7.js +1265 -0
- package/dist/chunk-CGLUTXI7.js.map +1 -0
- package/dist/{chunk-X4FFNQHE.mjs → chunk-E4ECCGJV.mjs} +1 -1
- package/dist/chunk-E4ECCGJV.mjs.map +1 -0
- package/dist/{chunk-V4ZO3F2S.js → chunk-GU53EI7A.js} +1 -1
- package/dist/chunk-GU53EI7A.js.map +1 -0
- package/dist/{chunk-MHN7CJCZ.mjs → chunk-HLCGZGPA.mjs} +1 -1
- package/dist/chunk-HLCGZGPA.mjs.map +1 -0
- package/dist/{chunk-LD4GC7OR.js → chunk-IBK6AXPP.js} +8 -9
- package/dist/chunk-IBK6AXPP.js.map +1 -0
- package/dist/{chunk-5F5EQAX5.js → chunk-JUI3XNEF.js} +3 -3
- package/dist/{chunk-3R43XIIX.js → chunk-PYMUBJQX.js} +2 -2
- package/dist/chunk-PYMUBJQX.js.map +1 -0
- package/dist/chunk-QFDTOEYR.js +253 -0
- package/dist/chunk-QFDTOEYR.js.map +1 -0
- package/dist/{chunk-4ODKGWYQ.js → chunk-QHWKLZUC.js} +1 -1
- package/dist/chunk-QHWKLZUC.js.map +1 -0
- package/dist/{chunk-6W5EQ3JQ.js → chunk-UEDNQBJN.js} +1 -1
- package/dist/chunk-UEDNQBJN.js.map +1 -0
- package/dist/{chunk-4LY47RPI.mjs → chunk-WCCLSUOI.mjs} +8 -9
- package/dist/{chunk-4LY47RPI.mjs.map → chunk-WCCLSUOI.mjs.map} +1 -1
- package/dist/index.js +10 -12
- package/dist/index.mjs +11 -13
- package/dist/token-service.js +2 -2
- package/dist/token-service.mjs +1 -1
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/AccountTrackerController.d.ts +1 -1
- package/dist/types/AccountTrackerController.d.ts.map +1 -1
- package/dist/types/AssetsContractController.d.ts +1 -1
- package/dist/types/AssetsContractController.d.ts.map +1 -1
- package/dist/types/NftController.d.ts +65 -184
- package/dist/types/NftController.d.ts.map +1 -1
- package/dist/types/NftDetectionController.d.ts +34 -75
- package/dist/types/NftDetectionController.d.ts.map +1 -1
- package/dist/types/TokenRatesController.d.ts +6 -6
- package/dist/types/TokenRatesController.d.ts.map +1 -1
- package/dist/types/TokensController.d.ts +27 -131
- package/dist/types/TokensController.d.ts.map +1 -1
- package/dist/types/index.d.ts +5 -3
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +16 -16
- package/dist/chunk-3R43XIIX.js.map +0 -1
- package/dist/chunk-46UZDIXW.mjs +0 -1205
- package/dist/chunk-46UZDIXW.mjs.map +0 -1
- package/dist/chunk-4ODKGWYQ.js.map +0 -1
- package/dist/chunk-6W5EQ3JQ.js.map +0 -1
- package/dist/chunk-7MMEHAKG.mjs.map +0 -1
- package/dist/chunk-FMZML3V5.js +0 -237
- package/dist/chunk-FMZML3V5.js.map +0 -1
- package/dist/chunk-KOKB6U4Z.mjs +0 -237
- package/dist/chunk-KOKB6U4Z.mjs.map +0 -1
- package/dist/chunk-LAU6ZDZR.js +0 -1205
- package/dist/chunk-LAU6ZDZR.js.map +0 -1
- package/dist/chunk-LD4GC7OR.js.map +0 -1
- package/dist/chunk-MBCN3MNX.js +0 -704
- package/dist/chunk-MBCN3MNX.js.map +0 -1
- package/dist/chunk-MHN7CJCZ.mjs.map +0 -1
- package/dist/chunk-PAJTKWEC.mjs.map +0 -1
- package/dist/chunk-V4ZO3F2S.js.map +0 -1
- package/dist/chunk-X4FFNQHE.mjs.map +0 -1
- package/dist/chunk-Z3OQU4XW.mjs.map +0 -1
- /package/dist/{chunk-XHMM35YT.mjs.map → chunk-A2DDWXMS.mjs.map} +0 -0
- /package/dist/{chunk-5F5EQAX5.js.map → chunk-JUI3XNEF.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/NftController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAM1B;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAWP,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AACzB,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,SA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UAAM;AAAA,MACJ,eAAe,EAAE,QAAQ;AAAA,IAC3B,IAAI,KAAK,gBAAgB;AAAA,MACvB;AAAA,MACA;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACA,SAAO,mBAAK;AACd;AA0qBF,IAAO,wBAAQ","sourcesContent":["import { isAddress } from '@ethersproject/address';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n} from '@metamask/base-controller';\nimport {\n safelyExecute,\n handleFetch,\n toChecksumHexAddress,\n BNToHex,\n fetchWithErrorHandling,\n IPFS_DEFAULT_GATEWAY_URL,\n ERC721,\n ERC1155,\n ApprovalType,\n NFT_API_BASE_URL,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerNetworkDidChangeEvent,\n NetworkState,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { remove0x } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport BN from 'bn.js';\nimport { v4 as random } from 'uuid';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport { compareNftMetadata, getFormattedIpfsUrl } from './assetsUtil';\nimport { Source } from './constants';\nimport type {\n ApiNftContract,\n ReservoirResponse,\n Collection,\n Attributes,\n LastSale,\n} from './NftDetectionController';\n\ntype NFTStandardType = 'ERC721' | 'ERC1155';\n\ntype SuggestedNftMeta = {\n asset: { address: string; tokenId: string } & NftMetadata;\n id: string;\n time: number;\n type: NFTStandardType;\n interactingAddress: string;\n origin: string;\n};\n\n/**\n * @type Nft\n *\n * NFT representation\n * @property address - Hex address of a ERC721 contract\n * @property description - The NFT description\n * @property image - URI of custom NFT image associated with this tokenId\n * @property name - Name associated with this tokenId and contract address\n * @property tokenId - The NFT identifier\n * @property numberOfSales - Number of sales\n * @property backgroundColor - The background color to be displayed with the item\n * @property imagePreview - URI of a smaller image associated with this NFT\n * @property imageThumbnail - URI of a thumbnail image associated with this NFT\n * @property imageOriginal - URI of the original image associated with this NFT\n * @property animation - URI of a animation associated with this NFT\n * @property animationOriginal - URI of the original animation associated with this NFT\n * @property externalLink - External link containing additional information\n * @property creator - The NFT owner information object\n * @property isCurrentlyOwned - Boolean indicating whether the address/chainId combination where it's currently stored currently owns this NFT\n * @property transactionId - Transaction Id associated with the NFT\n */\nexport type Nft =\n | {\n tokenId: string;\n address: string;\n isCurrentlyOwned?: boolean;\n } & NftMetadata;\n\ntype NftUpdate = {\n nft: Nft;\n newMetadata: NftMetadata;\n};\n\n/**\n * @type NftContract\n *\n * NFT contract information representation\n * @property name - Contract name\n * @property logo - Contract logo\n * @property address - Contract address\n * @property symbol - Contract symbol\n * @property description - Contract description\n * @property totalSupply - Total supply of NFTs\n * @property assetContractType - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property createdDate - Creation date\n * @property schemaName - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property externalLink - External link containing additional information\n */\nexport type NftContract = {\n name?: string;\n logo?: string;\n address: string;\n symbol?: string;\n description?: string;\n totalSupply?: string;\n assetContractType?: string;\n createdDate?: string;\n schemaName?: string;\n externalLink?: string;\n};\n\n/**\n * @type NftMetadata\n *\n * NFT custom information\n * @property name - NFT custom name\n * @property description - The NFT description\n * @property numberOfSales - Number of sales\n * @property backgroundColor - The background color to be displayed with the item\n * @property image - Image custom image URI\n * @property imagePreview - URI of a smaller image associated with this NFT\n * @property imageThumbnail - URI of a thumbnail image associated with this NFT\n * @property imageOriginal - URI of the original image associated with this NFT\n * @property animation - URI of a animation associated with this NFT\n * @property animationOriginal - URI of the original animation associated with this NFT\n * @property externalLink - External link containing additional information\n * @property creator - The NFT owner information object\n * @property standard - NFT standard name for the NFT, e.g., ERC-721 or ERC-1155\n */\nexport type NftMetadata = {\n name: string | null;\n description: string | null;\n image: string | null;\n standard: string | null;\n favorite?: boolean;\n numberOfSales?: number;\n backgroundColor?: string;\n imagePreview?: string;\n imageThumbnail?: string;\n imageOriginal?: string;\n animation?: string;\n animationOriginal?: string;\n externalLink?: string;\n creator?: string;\n transactionId?: string;\n tokenURI?: string | null;\n collection?: Collection;\n address?: string;\n attributes?: Attributes;\n lastSale?: LastSale;\n rarityRank?: string;\n};\n\n/**\n * @type NftControllerState\n *\n * NFT controller state\n * @property allNftContracts - Object containing NFT contract information\n * @property allNfts - Object containing NFTs per account and network\n * @property ignoredNfts - List of NFTs that should be ignored\n */\nexport type NftControllerState = {\n allNftContracts: {\n [key: string]: {\n [chainId: Hex]: NftContract[];\n };\n };\n allNfts: {\n [key: string]: {\n [chainId: Hex]: Nft[];\n };\n };\n ignoredNfts: Nft[];\n};\n\nconst nftControllerMetadata = {\n allNftContracts: { persist: true, anonymous: false },\n allNfts: { persist: true, anonymous: false },\n ignoredNfts: { persist: true, anonymous: false },\n};\n\nconst ALL_NFTS_STATE_KEY = 'allNfts';\nconst ALL_NFTS_CONTRACTS_STATE_KEY = 'allNftContracts';\n\ntype NftAsset = {\n address: string;\n tokenId: string;\n};\n\n/**\n * The name of the {@link NftController}.\n */\nconst controllerName = 'NftController';\n\nexport type NftControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n NftControllerState\n>;\nexport type NftControllerActions = NftControllerGetStateAction;\n\n/**\n * The external actions available to the {@link NftController}.\n */\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetNetworkClientByIdAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerNetworkDidChangeEvent;\n\nexport type NftControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n NftControllerState\n>;\n\nexport type NftControllerEvents = NftControllerStateChangeEvent;\n\n/**\n * The messenger of the {@link NftController}.\n */\nexport type NftControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n NftControllerActions | AllowedActions,\n NftControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const getDefaultNftControllerState = (): NftControllerState => ({\n allNftContracts: {},\n allNfts: {},\n ignoredNfts: [],\n});\n\n/**\n * Controller that stores assets and exposes convenience methods\n */\nexport class NftController extends BaseController<\n typeof controllerName,\n NftControllerState,\n NftControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n /**\n * Optional API key to use with opensea\n */\n openSeaApiKey?: string;\n\n #selectedAddress: string;\n\n #chainId: Hex;\n\n #ipfsGateway: string;\n\n #openSeaEnabled: boolean;\n\n #useIpfsSubdomains: boolean;\n\n #isIpfsGatewayEnabled: boolean;\n\n readonly #getERC721AssetName: AssetsContractController['getERC721AssetName'];\n\n readonly #getERC721AssetSymbol: AssetsContractController['getERC721AssetSymbol'];\n\n readonly #getERC721TokenURI: AssetsContractController['getERC721TokenURI'];\n\n readonly #getERC721OwnerOf: AssetsContractController['getERC721OwnerOf'];\n\n readonly #getERC1155BalanceOf: AssetsContractController['getERC1155BalanceOf'];\n\n readonly #getERC1155TokenURI: AssetsContractController['getERC1155TokenURI'];\n\n readonly #onNftAdded?: (data: {\n address: string;\n symbol: string | undefined;\n tokenId: string;\n standard: string | null;\n source: Source;\n }) => void;\n\n /**\n * Creates an NftController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.selectedAddress - The currently selected address.\n * @param options.ipfsGateway - The configured IPFS gateway.\n * @param options.openSeaEnabled - Controls whether the OpenSea API is used.\n * @param options.useIpfsSubdomains - Controls whether IPFS subdomains are used.\n * @param options.isIpfsGatewayEnabled - Controls whether IPFS is enabled or not.\n * @param options.getERC721AssetName - Gets the name of the asset at the given address.\n * @param options.getERC721AssetSymbol - Gets the symbol of the asset at the given address.\n * @param options.getERC721TokenURI - Gets the URI of the ERC721 token at the given address, with the given ID.\n * @param options.getERC721OwnerOf - Get the owner of a ERC-721 NFT.\n * @param options.getERC1155BalanceOf - Gets balance of a ERC-1155 NFT.\n * @param options.getERC1155TokenURI - Gets the URI of the ERC1155 token at the given address, with the given ID.\n * @param options.onNftAdded - Callback that is called when an NFT is added. Currently used pass data\n * for tracking the NFT added event.\n * @param options.messenger - The controller messenger.\n * @param options.state - Initial state to set on this controller.\n */\n constructor({\n chainId: initialChainId,\n selectedAddress = '',\n ipfsGateway = IPFS_DEFAULT_GATEWAY_URL,\n openSeaEnabled = false,\n useIpfsSubdomains = true,\n isIpfsGatewayEnabled = true,\n getERC721AssetName,\n getERC721AssetSymbol,\n getERC721TokenURI,\n getERC721OwnerOf,\n getERC1155BalanceOf,\n getERC1155TokenURI,\n onNftAdded,\n messenger,\n state = {},\n }: {\n chainId: Hex;\n selectedAddress?: string;\n ipfsGateway?: string;\n openSeaEnabled?: boolean;\n useIpfsSubdomains?: boolean;\n isIpfsGatewayEnabled?: boolean;\n getERC721AssetName: AssetsContractController['getERC721AssetName'];\n getERC721AssetSymbol: AssetsContractController['getERC721AssetSymbol'];\n getERC721TokenURI: AssetsContractController['getERC721TokenURI'];\n getERC721OwnerOf: AssetsContractController['getERC721OwnerOf'];\n getERC1155BalanceOf: AssetsContractController['getERC1155BalanceOf'];\n getERC1155TokenURI: AssetsContractController['getERC1155TokenURI'];\n onNftAdded?: (data: {\n address: string;\n symbol: string | undefined;\n tokenId: string;\n standard: string | null;\n source: string;\n }) => void;\n messenger: NftControllerMessenger;\n state?: Partial<NftControllerState>;\n }) {\n super({\n name: controllerName,\n metadata: nftControllerMetadata,\n messenger,\n state: {\n ...getDefaultNftControllerState(),\n ...state,\n },\n });\n\n this.#selectedAddress = selectedAddress;\n this.#chainId = initialChainId;\n this.#ipfsGateway = ipfsGateway;\n this.#openSeaEnabled = openSeaEnabled;\n this.#useIpfsSubdomains = useIpfsSubdomains;\n this.#isIpfsGatewayEnabled = isIpfsGatewayEnabled;\n\n this.#getERC721AssetName = getERC721AssetName;\n this.#getERC721AssetSymbol = getERC721AssetSymbol;\n this.#getERC721TokenURI = getERC721TokenURI;\n this.#getERC721OwnerOf = getERC721OwnerOf;\n this.#getERC1155BalanceOf = getERC1155BalanceOf;\n this.#getERC1155TokenURI = getERC1155TokenURI;\n this.#onNftAdded = onNftAdded;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesControllerStateChange.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n this.#onNetworkControllerNetworkDidChange.bind(this),\n );\n }\n\n /**\n * Handles the network change on the network controller.\n * @param networkState - The new state of the preference controller.\n * @param networkState.selectedNetworkClientId - The current selected network client id.\n */\n #onNetworkControllerNetworkDidChange({\n selectedNetworkClientId,\n }: NetworkState) {\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n this.#chainId = chainId;\n }\n\n /**\n * Handles the state change of the preference controller.\n * @param preferencesState - The new state of the preference controller.\n * @param preferencesState.selectedAddress - The current selected address.\n * @param preferencesState.ipfsGateway - The configured IPFS gateway.\n * @param preferencesState.openSeaEnabled - Controls whether the OpenSea API is used.\n * @param preferencesState.isIpfsGatewayEnabled - Controls whether IPFS is enabled or not.\n */\n async #onPreferencesControllerStateChange({\n selectedAddress,\n ipfsGateway,\n openSeaEnabled,\n isIpfsGatewayEnabled,\n }: PreferencesState) {\n this.#selectedAddress = selectedAddress;\n this.#ipfsGateway = ipfsGateway;\n this.#openSeaEnabled = openSeaEnabled;\n this.#isIpfsGatewayEnabled = isIpfsGatewayEnabled;\n\n const needsUpdateNftMetadata =\n (isIpfsGatewayEnabled && ipfsGateway !== '') || openSeaEnabled;\n\n if (needsUpdateNftMetadata) {\n const nfts: Nft[] =\n this.state.allNfts[selectedAddress]?.[this.#chainId] ?? [];\n // filter only nfts\n const nftsToUpdate = nfts.filter(\n (singleNft) =>\n !singleNft.name && !singleNft.description && !singleNft.image,\n );\n if (nftsToUpdate.length !== 0) {\n await this.updateNftMetadata({\n nfts: nftsToUpdate,\n userAddress: selectedAddress,\n });\n }\n }\n }\n\n getNftApi() {\n return `${NFT_API_BASE_URL}/tokens`;\n }\n\n /**\n * Helper method to update nested state for allNfts and allNftContracts.\n *\n * @param newCollection - the modified piece of state to update in the controller's store\n * @param baseStateKey - The root key in the store to update.\n * @param passedConfig - An object containing the selectedAddress and chainId that are passed through the auto-detection flow.\n * @param passedConfig.userAddress - the address passed through the NFT detection flow to ensure assets are stored to the correct account\n * @param passedConfig.chainId - the chainId passed through the NFT detection flow to ensure assets are stored to the correct account\n */\n #updateNestedNftState<\n Key extends typeof ALL_NFTS_STATE_KEY | typeof ALL_NFTS_CONTRACTS_STATE_KEY,\n NftCollection extends Key extends typeof ALL_NFTS_STATE_KEY\n ? Nft[]\n : NftContract[],\n >(\n newCollection: NftCollection,\n baseStateKey: Key,\n { userAddress, chainId }: { userAddress: string; chainId: Hex },\n ) {\n this.update((state) => {\n const oldState = state[baseStateKey];\n const addressState = oldState[userAddress] || {};\n const newAddressState = {\n ...addressState,\n [chainId]: newCollection,\n };\n state[baseStateKey] = {\n ...oldState,\n [userAddress]: newAddressState,\n };\n });\n }\n\n /**\n * Request individual NFT information from NFT API.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformationFromApi(\n contractAddress: string,\n tokenId: string,\n ): Promise<NftMetadata> {\n // TODO Parameterize this by chainId for non-mainnet token detection\n // Attempt to fetch the data with the nft-api\n const urlParams = new URLSearchParams({\n chainIds: '1',\n tokens: `${contractAddress}:${tokenId}`,\n includeTopBid: 'true',\n includeAttributes: 'true',\n includeLastSale: 'true',\n }).toString();\n const nftInformation: ReservoirResponse | undefined =\n await fetchWithErrorHandling({\n url: `${this.getNftApi()}?${urlParams}`,\n options: {\n headers: {\n Version: '1',\n },\n },\n });\n // if we were still unable to fetch the data we return out the default/null of `NftMetadata`\n if (!nftInformation?.tokens?.[0]?.token) {\n return {\n name: null,\n description: null,\n image: null,\n standard: null,\n };\n }\n\n // if we've reached this point, we have successfully fetched some data for nftInformation\n // now we reconfigure the data to conform to the `NftMetadata` type for storage.\n\n const {\n image,\n metadata: { imageOriginal } = {},\n name,\n description,\n collection,\n kind,\n rarityRank,\n rarity,\n attributes,\n lastSale,\n imageSmall,\n } = nftInformation.tokens[0].token;\n\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name: name || null },\n { description: description || null },\n { image: image || null },\n collection?.creator && { creator: collection.creator },\n imageOriginal && { imageOriginal },\n imageSmall && { imageThumbnail: imageSmall },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n nftInformation.tokens[0].market?.topBid && {\n topBid: nftInformation.tokens[0].market?.topBid,\n },\n rarityRank && { rarityRank },\n rarity && { rarity },\n collection && { collection },\n );\n\n return nftMetadata;\n }\n\n /**\n * Request individual NFT information from contracts that follows Metadata Interface.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformationFromTokenURI(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<NftMetadata> {\n const result = await this.#getNftURIAndStandard(\n contractAddress,\n tokenId,\n networkClientId,\n );\n let tokenURI = result[0];\n const standard = result[1];\n\n const hasIpfsTokenURI = tokenURI.startsWith('ipfs://');\n\n if (hasIpfsTokenURI && !this.#isIpfsGatewayEnabled) {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n\n const isDisplayNFTMediaToggleEnabled = this.#openSeaEnabled;\n if (!hasIpfsTokenURI && !isDisplayNFTMediaToggleEnabled) {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n\n if (hasIpfsTokenURI) {\n tokenURI = getFormattedIpfsUrl(\n this.#ipfsGateway,\n tokenURI,\n this.#useIpfsSubdomains,\n );\n }\n\n try {\n const object = await handleFetch(tokenURI);\n // TODO: Check image_url existence. This is not part of EIP721 nor EIP1155\n const image = Object.prototype.hasOwnProperty.call(object, 'image')\n ? 'image'\n : /* istanbul ignore next */ 'image_url';\n\n return {\n image: object[image],\n name: object.name,\n description: object.description,\n standard,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n } catch {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n }\n\n /**\n * Retrieve NFT uri with metadata. TODO Update method to use IPFS.\n *\n * @param contractAddress - NFT contract address.\n * @param tokenId - NFT token id.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving NFT uri and token standard.\n */\n async #getNftURIAndStandard(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<[string, string]> {\n // try ERC721 uri\n try {\n const uri = await this.#getERC721TokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n );\n return [uri, ERC721];\n } catch {\n // Ignore error\n }\n\n // try ERC1155 uri\n try {\n const tokenURI = await this.#getERC1155TokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n );\n\n /**\n * According to EIP1155 the URI value allows for ID substitution\n * in case the string `{id}` exists.\n * https://eips.ethereum.org/EIPS/eip-1155#metadata\n */\n\n if (!tokenURI.includes('{id}')) {\n return [tokenURI, ERC1155];\n }\n\n const hexTokenId = remove0x(BNToHex(new BN(tokenId)))\n .padStart(64, '0')\n .toLowerCase();\n return [tokenURI.replace('{id}', hexTokenId), ERC1155];\n } catch {\n // Ignore error\n }\n\n return ['', ''];\n }\n\n /**\n * Request individual NFT information (name, image url and description).\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformation(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<NftMetadata> {\n const chainId = this.#getCorrectChainId({\n networkClientId,\n });\n const [blockchainMetadata, nftApiMetadata] = await Promise.all([\n safelyExecute(() =>\n this.#getNftInformationFromTokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n ),\n ),\n this.#openSeaEnabled && chainId === '0x1'\n ? safelyExecute(() =>\n this.#getNftInformationFromApi(contractAddress, tokenId),\n )\n : undefined,\n ]);\n return {\n ...nftApiMetadata,\n name: blockchainMetadata?.name ?? nftApiMetadata?.name ?? null,\n description:\n blockchainMetadata?.description ?? nftApiMetadata?.description ?? null,\n image: blockchainMetadata?.image ?? nftApiMetadata?.image ?? null,\n standard:\n blockchainMetadata?.standard ?? nftApiMetadata?.standard ?? null,\n tokenURI: blockchainMetadata?.tokenURI ?? null,\n };\n }\n\n /**\n * Request NFT contract information from the contract itself.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftContractInformationFromContract(\n contractAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<\n Partial<ApiNftContract> &\n Pick<ApiNftContract, 'address'> &\n Pick<ApiNftContract, 'collection'>\n > {\n const [name, symbol] = await Promise.all([\n this.#getERC721AssetName(contractAddress, networkClientId),\n this.#getERC721AssetSymbol(contractAddress, networkClientId),\n ]);\n\n return {\n collection: { name },\n symbol,\n address: contractAddress,\n };\n }\n\n /**\n * Request NFT contract information from Blockchain and aggregate with received data from NFTMetadata.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param nftMetadataFromApi - Received NFT information to be aggregated with blockchain contract information.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the NFT contract name, image and description.\n */\n async #getNftContractInformation(\n contractAddress: string,\n nftMetadataFromApi: NftMetadata,\n networkClientId?: NetworkClientId,\n ): Promise<\n Partial<ApiNftContract> &\n Pick<ApiNftContract, 'address'> &\n Pick<ApiNftContract, 'collection'>\n > {\n const blockchainContractData = await safelyExecute(() =>\n this.#getNftContractInformationFromContract(\n contractAddress,\n networkClientId,\n ),\n );\n\n if (\n blockchainContractData ||\n !Object.values(nftMetadataFromApi).every((value) => value === null)\n ) {\n return {\n address: contractAddress,\n ...blockchainContractData,\n schema_name: nftMetadataFromApi?.standard ?? null,\n collection: {\n name: null,\n image_url:\n nftMetadataFromApi?.collection?.image ??\n nftMetadataFromApi?.collection?.imageUrl ??\n null,\n tokenCount: nftMetadataFromApi?.collection?.tokenCount ?? null,\n ...nftMetadataFromApi?.collection,\n ...blockchainContractData?.collection,\n },\n };\n }\n\n /* istanbul ignore next */\n return {\n address: contractAddress,\n asset_contract_type: null,\n created_date: null,\n schema_name: null,\n symbol: null,\n total_supply: null,\n description: null,\n external_link: null,\n collection: { name: null, image_url: null },\n };\n }\n\n /**\n * Adds an individual NFT to the stored NFT list.\n *\n * @param tokenAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param nftMetadata - NFT optional information (name, image and description).\n * @param nftContract - An object containing contract data of the NFT being added.\n * @param chainId - The chainId of the network where the NFT is being added.\n * @param userAddress - The address of the account where the NFT is being added.\n * @param source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @returns A promise resolving to `undefined`.\n */\n async #addIndividualNft(\n tokenAddress: string,\n tokenId: string,\n nftMetadata: NftMetadata,\n nftContract: NftContract,\n chainId: Hex,\n userAddress: string,\n source: Source,\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n try {\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n const { allNfts } = this.state;\n\n const nfts = [...(allNfts[userAddress]?.[chainId] ?? [])];\n\n const existingEntry = nfts.find(\n (nft) =>\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n nftMetadata,\n existingEntry,\n );\n\n if (!differentMetadata && existingEntry.isCurrentlyOwned) {\n return;\n }\n\n const indexToUpdate = nfts.findIndex(\n (nft) =>\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (indexToUpdate !== -1) {\n nfts[indexToUpdate] = {\n ...existingEntry,\n ...nftMetadata,\n };\n }\n } else {\n const newEntry: Nft = {\n address: checksumHexAddress,\n tokenId,\n favorite: false,\n isCurrentlyOwned: true,\n ...nftMetadata,\n };\n\n nfts.push(newEntry);\n }\n\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n if (this.#onNftAdded) {\n this.#onNftAdded({\n address: checksumHexAddress,\n symbol: nftContract.symbol,\n tokenId: tokenId.toString(),\n standard: nftMetadata.standard,\n source,\n });\n }\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Adds an NFT contract to the stored NFT contracts list.\n *\n * @param options - options.\n * @param options.tokenAddress - Hex address of the NFT contract.\n * @param options.userAddress - The address of the account where the NFT is being added.\n * @param options.nftMetadata - The retrieved NFTMetadata from API.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @returns Promise resolving to the current NFT contracts list.\n */\n async #addNftContract({\n tokenAddress,\n userAddress,\n networkClientId,\n source,\n nftMetadata,\n }: {\n tokenAddress: string;\n userAddress: string;\n nftMetadata: NftMetadata;\n networkClientId?: NetworkClientId;\n source?: Source;\n }): Promise<NftContract[]> {\n const releaseLock = await this.#mutex.acquire();\n try {\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n const { allNftContracts } = this.state;\n const chainId = this.#getCorrectChainId({\n networkClientId,\n });\n\n const nftContracts = allNftContracts[userAddress]?.[chainId] || [];\n\n const existingEntry = nftContracts.find(\n (nftContract) =>\n nftContract.address.toLowerCase() ===\n checksumHexAddress.toLowerCase(),\n );\n if (existingEntry) {\n return nftContracts;\n }\n\n // this doesn't work currently for detection if the user switches networks while the detection is processing\n // will be fixed once detection uses networkClientIds\n // get name and symbol if ERC721 then put together the metadata\n const contractInformation = await this.#getNftContractInformation(\n checksumHexAddress,\n nftMetadata,\n networkClientId,\n );\n const {\n asset_contract_type,\n created_date,\n symbol,\n description,\n external_link,\n schema_name,\n collection: { name, image_url, tokenCount },\n } = contractInformation;\n\n // If the nft is auto-detected we want some valid metadata to be present\n if (\n source === Source.Detected &&\n 'address' in contractInformation &&\n typeof contractInformation.address === 'string' &&\n 'collection' in contractInformation &&\n contractInformation.collection.name === null &&\n 'image_url' in contractInformation.collection &&\n contractInformation.collection.image_url === null &&\n Object.entries(contractInformation).every(([key, value]) => {\n return key === 'address' || key === 'collection' || !value;\n })\n ) {\n return nftContracts;\n }\n\n /* istanbul ignore next */\n const newEntry: NftContract = Object.assign(\n {},\n { address: checksumHexAddress },\n description && { description },\n name && { name },\n image_url && { logo: image_url },\n symbol && { symbol },\n tokenCount !== null &&\n typeof tokenCount !== 'undefined' && { totalSupply: tokenCount },\n asset_contract_type && { assetContractType: asset_contract_type },\n created_date && { createdDate: created_date },\n schema_name && { schemaName: schema_name },\n external_link && { externalLink: external_link },\n );\n const newNftContracts = [...nftContracts, newEntry];\n this.#updateNestedNftState(\n newNftContracts,\n ALL_NFTS_CONTRACTS_STATE_KEY,\n {\n chainId,\n userAddress,\n },\n );\n\n return newNftContracts;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Removes an individual NFT from the stored token list and saves it in ignored NFTs list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n #removeAndIgnoreIndividualNft(\n address: string,\n tokenId: string,\n {\n chainId,\n userAddress,\n }: {\n chainId: Hex;\n userAddress: string;\n },\n ) {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNfts, ignoredNfts } = this.state;\n const newIgnoredNfts = [...ignoredNfts];\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const newNfts = nfts.filter((nft) => {\n if (\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId\n ) {\n const alreadyIgnored = newIgnoredNfts.find(\n (c) => c.address === checksumHexAddress && c.tokenId === tokenId,\n );\n !alreadyIgnored && newIgnoredNfts.push(nft);\n return false;\n }\n return true;\n });\n\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n\n this.update((state) => {\n state.ignoredNfts = newIgnoredNfts;\n });\n }\n\n /**\n * Removes an individual NFT from the stored token list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n #removeIndividualNft(\n address: string,\n tokenId: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ) {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNfts } = this.state;\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const newNfts = nfts.filter(\n (nft) =>\n !(\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId\n ),\n );\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n }\n\n /**\n * Removes an NFT contract to the stored NFT contracts list.\n *\n * @param address - Hex address of the NFT contract.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n * @returns Promise resolving to the current NFT contracts list.\n */\n #removeNftContract(\n address: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ): NftContract[] {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNftContracts } = this.state;\n const nftContracts = allNftContracts[userAddress]?.[chainId] || [];\n\n const newNftContracts = nftContracts.filter(\n (nftContract) =>\n !(\n nftContract.address.toLowerCase() === checksumHexAddress.toLowerCase()\n ),\n );\n this.#updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n return newNftContracts;\n }\n\n async #validateWatchNft(\n asset: NftAsset,\n type: NFTStandardType,\n userAddress: string,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ) {\n const { address: contractAddress, tokenId } = asset;\n\n // Validate parameters\n if (!type) {\n throw rpcErrors.invalidParams('Asset type is required');\n }\n\n if (type !== ERC721 && type !== ERC1155) {\n throw rpcErrors.invalidParams(\n `Non NFT asset type ${type} not supported by watchNft`,\n );\n }\n\n if (!contractAddress || !tokenId) {\n throw rpcErrors.invalidParams('Both address and tokenId are required');\n }\n\n if (!isAddress(contractAddress)) {\n throw rpcErrors.invalidParams('Invalid address');\n }\n\n if (!/^\\d+$/u.test(tokenId)) {\n throw rpcErrors.invalidParams('Invalid tokenId');\n }\n\n // Check if the user owns the suggested NFT\n try {\n const isOwner = await this.isNftOwner(\n userAddress,\n contractAddress,\n tokenId,\n { networkClientId },\n );\n if (!isOwner) {\n throw rpcErrors.invalidInput(\n 'Suggested NFT is not owned by the selected account',\n );\n }\n } catch (error) {\n // error thrown here: \"Unable to verify ownership. Possibly because the standard is not supported or the user's currently selected network does not match the chain of the asset in question.\"\n if (error instanceof Error) {\n throw rpcErrors.resourceUnavailable(error.message);\n }\n throw error;\n }\n }\n\n // temporary method to get the correct chainId until we remove chainId from the config & the chainId arg from the detection logic\n // Just a helper method to prefer the networkClient chainId first then the chainId argument and then finally the config chainId\n #getCorrectChainId({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n }) {\n if (networkClientId) {\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return chainId;\n }\n return this.#chainId;\n }\n\n /**\n * Adds a new suggestedAsset to state. Parameters will be validated according to\n * asset type being watched. A `<suggestedNftMeta.id>:pending` hub event will be emitted once added.\n *\n * @param asset - The asset to be watched. For now ERC721 and ERC1155 tokens are accepted.\n * @param asset.address - The address of the asset contract.\n * @param asset.tokenId - The ID of the asset.\n * @param type - The asset type.\n * @param origin - Domain origin to register the asset from.\n * @param options - Options bag.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being added.\n * @returns Object containing a Promise resolving to the suggestedAsset address if accepted.\n */\n async watchNft(\n asset: NftAsset,\n type: NFTStandardType,\n origin: string,\n {\n networkClientId,\n userAddress = this.#selectedAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {\n userAddress: this.#selectedAddress,\n },\n ) {\n await this.#validateWatchNft(asset, type, userAddress);\n\n const nftMetadata = await this.#getNftInformation(\n asset.address,\n asset.tokenId,\n networkClientId,\n );\n\n if (nftMetadata.standard && nftMetadata.standard !== type) {\n throw rpcErrors.invalidInput(\n `Suggested NFT of type ${nftMetadata.standard} does not match received type ${type}`,\n );\n }\n\n const suggestedNftMeta: SuggestedNftMeta = {\n asset: { ...asset, ...nftMetadata },\n type,\n id: random(),\n time: Date.now(),\n interactingAddress: userAddress,\n origin,\n };\n await this._requestApproval(suggestedNftMeta);\n const { address, tokenId } = asset;\n const { name, standard, description, image } = nftMetadata;\n\n await this.addNft(address, tokenId, {\n nftMetadata: {\n name: name ?? null,\n description: description ?? null,\n image: image ?? null,\n standard: standard ?? null,\n },\n userAddress,\n source: Source.Dapp,\n networkClientId,\n });\n }\n\n /**\n * Sets an OpenSea API key to retrieve NFT information.\n *\n * @param openSeaApiKey - OpenSea API key.\n */\n setApiKey(openSeaApiKey: string) {\n this.openSeaApiKey = openSeaApiKey;\n }\n\n /**\n * Checks the ownership of a ERC-721 or ERC-1155 NFT for a given address.\n *\n * @param ownerAddress - User public address.\n * @param nftAddress - NFT contract address.\n * @param tokenId - NFT token ID.\n * @param options - Options bag.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving the NFT ownership.\n */\n async isNftOwner(\n ownerAddress: string,\n nftAddress: string,\n tokenId: string,\n {\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {},\n ): Promise<boolean> {\n // Checks the ownership for ERC-721.\n try {\n const owner = await this.#getERC721OwnerOf(\n nftAddress,\n tokenId,\n networkClientId,\n );\n return ownerAddress.toLowerCase() === owner.toLowerCase();\n // eslint-disable-next-line no-empty\n } catch {\n // Ignore ERC-721 contract error\n }\n\n // Checks the ownership for ERC-1155.\n try {\n const balance = await this.#getERC1155BalanceOf(\n ownerAddress,\n nftAddress,\n tokenId,\n networkClientId,\n );\n return !balance.isZero();\n // eslint-disable-next-line no-empty\n } catch {\n // Ignore ERC-1155 contract error\n }\n\n throw new Error(\n `Unable to verify ownership. Possibly because the standard is not supported or the user's currently selected network does not match the chain of the asset in question.`,\n );\n }\n\n /**\n * Verifies currently selected address owns entered NFT address/tokenId combo and\n * adds the NFT and respective NFT contract to the stored NFT and NFT contracts lists.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param options - an object of arguments\n * @param options.userAddress - The address of the current user.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.\n */\n async addNftVerifyOwnership(\n address: string,\n tokenId: string,\n {\n userAddress = this.#selectedAddress,\n networkClientId,\n source,\n }: {\n userAddress?: string;\n networkClientId?: NetworkClientId;\n source?: Source;\n } = {\n userAddress: this.#selectedAddress,\n },\n ) {\n if (\n !(await this.isNftOwner(userAddress, address, tokenId, {\n networkClientId,\n }))\n ) {\n throw new Error('This NFT is not owned by the user');\n }\n await this.addNft(address, tokenId, {\n networkClientId,\n userAddress,\n source,\n });\n }\n\n /**\n * Adds an NFT and respective NFT contract to the stored NFT and NFT contracts lists.\n *\n * @param tokenAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param options - an object of arguments\n * @param options.nftMetadata - NFT optional metadata.\n * @param options.userAddress - The address of the current user.\n * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT list.\n */\n async addNft(\n tokenAddress: string,\n tokenId: string,\n {\n nftMetadata,\n userAddress = this.#selectedAddress,\n source = Source.Custom,\n networkClientId,\n }: {\n nftMetadata?: NftMetadata;\n userAddress?: string;\n source?: Source;\n networkClientId?: NetworkClientId;\n } = { userAddress: this.#selectedAddress },\n ) {\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n\n const chainId = this.#getCorrectChainId({ networkClientId });\n\n nftMetadata =\n nftMetadata ||\n (await this.#getNftInformation(\n checksumHexAddress,\n tokenId,\n networkClientId,\n ));\n\n const newNftContracts = await this.#addNftContract({\n tokenAddress: checksumHexAddress,\n userAddress,\n networkClientId,\n source,\n nftMetadata,\n });\n\n // If NFT contract was not added, do not add individual NFT\n const nftContract = newNftContracts.find(\n (contract) =>\n contract.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n\n // If NFT contract information, add individual NFT\n if (nftContract) {\n await this.#addIndividualNft(\n checksumHexAddress,\n tokenId,\n nftMetadata,\n nftContract,\n chainId,\n userAddress,\n source,\n );\n }\n }\n\n /**\n * Refetches NFT metadata and updates the state\n *\n * @param options - Options for refetching NFT metadata\n * @param options.nfts - nfts to update metadata for.\n * @param options.userAddress - The current user address\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n */\n async updateNftMetadata({\n nfts,\n userAddress = this.#selectedAddress,\n networkClientId,\n }: {\n nfts: Nft[];\n userAddress?: string;\n networkClientId?: NetworkClientId;\n }) {\n const chainId = this.#getCorrectChainId({ networkClientId });\n\n const nftsWithChecksumAdr = nfts.map((nft) => {\n return {\n ...nft,\n address: toChecksumHexAddress(nft.address),\n };\n });\n const nftMetadataResults = await Promise.all(\n nftsWithChecksumAdr.map(async (nft) => {\n const resMetadata = await this.#getNftInformation(\n nft.address,\n nft.tokenId,\n networkClientId,\n );\n return {\n nft,\n newMetadata: resMetadata,\n };\n }),\n );\n\n // We want to avoid updating the state if the state and fetched nft info are the same\n const nftsWithDifferentMetadata: NftUpdate[] = [];\n const { allNfts } = this.state;\n const stateNfts = allNfts[userAddress]?.[chainId] || [];\n\n nftMetadataResults.forEach((singleNft) => {\n const existingEntry: Nft | undefined = stateNfts.find(\n (nft) =>\n nft.address.toLowerCase() === singleNft.nft.address.toLowerCase() &&\n nft.tokenId === singleNft.nft.tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n singleNft.newMetadata,\n existingEntry,\n );\n\n if (differentMetadata) {\n nftsWithDifferentMetadata.push(singleNft);\n }\n }\n });\n\n if (nftsWithDifferentMetadata.length !== 0) {\n nftsWithDifferentMetadata.forEach((elm) =>\n this.updateNft(elm.nft, elm.newMetadata, userAddress, chainId),\n );\n }\n }\n\n /**\n * Removes an NFT from the stored token list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n removeNft(\n address: string,\n tokenId: string,\n {\n networkClientId,\n userAddress = this.#selectedAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.#selectedAddress,\n },\n ) {\n const chainId = this.#getCorrectChainId({ networkClientId });\n const checksumHexAddress = toChecksumHexAddress(address);\n this.#removeIndividualNft(checksumHexAddress, tokenId, {\n chainId,\n userAddress,\n });\n const { allNfts } = this.state;\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const remainingNft = nfts.find(\n (nft) => nft.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n\n if (!remainingNft) {\n this.#removeNftContract(checksumHexAddress, { chainId, userAddress });\n }\n }\n\n /**\n * Removes an NFT from the stored token list and saves it in ignored NFTs list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n removeAndIgnoreNft(\n address: string,\n tokenId: string,\n {\n networkClientId,\n userAddress = this.#selectedAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.#selectedAddress,\n },\n ) {\n const chainId = this.#getCorrectChainId({ networkClientId });\n const checksumHexAddress = toChecksumHexAddress(address);\n this.#removeAndIgnoreIndividualNft(checksumHexAddress, tokenId, {\n chainId,\n userAddress,\n });\n const { allNfts } = this.state;\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const remainingNft = nfts.find(\n (nft) => nft.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n if (!remainingNft) {\n this.#removeNftContract(checksumHexAddress, { chainId, userAddress });\n }\n }\n\n /**\n * Removes all NFTs from the ignored list.\n */\n clearIgnoredNfts() {\n this.update((state) => {\n state.ignoredNfts = [];\n });\n }\n\n /**\n * Checks whether input NFT is still owned by the user\n * And updates the isCurrentlyOwned value on the NFT object accordingly.\n *\n * @param nft - The NFT object to check and update.\n * @param batch - A boolean indicating whether this method is being called as part of a batch or single update.\n * @param accountParams - The userAddress and chainId to check ownership against\n * @param accountParams.userAddress - the address passed through the confirmed transaction flow to ensure assets are stored to the correct account\n * @param accountParams.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns the NFT with the updated isCurrentlyOwned value\n */\n async checkAndUpdateSingleNftOwnershipStatus(\n nft: Nft,\n batch: boolean,\n {\n userAddress = this.#selectedAddress,\n networkClientId,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.#selectedAddress,\n },\n ) {\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { address, tokenId } = nft;\n let isOwned = nft.isCurrentlyOwned;\n try {\n isOwned = await this.isNftOwner(userAddress, address, tokenId, {\n networkClientId,\n });\n } catch {\n // ignore error\n // this will only throw an error 'Unable to verify ownership' in which case\n // we want to keep the current value of isCurrentlyOwned for this flow.\n }\n\n const updatedNft = {\n ...nft,\n isCurrentlyOwned: isOwned,\n };\n\n if (batch) {\n return updatedNft;\n }\n\n // if this is not part of a batched update we update this one NFT in state\n const { allNfts } = this.state;\n const nfts = [...(allNfts[userAddress]?.[chainId] || [])];\n const indexToUpdate = nfts.findIndex(\n (item) =>\n item.tokenId === tokenId &&\n item.address.toLowerCase() === address.toLowerCase(),\n );\n\n if (indexToUpdate !== -1) {\n nfts[indexToUpdate] = updatedNft;\n this.update((state) => {\n state.allNfts[userAddress] = Object.assign(\n {},\n state.allNfts[userAddress],\n {\n [chainId]: nfts,\n },\n );\n });\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n }\n\n return updatedNft;\n }\n\n /**\n * Checks whether NFTs associated with current selectedAddress/chainId combination are still owned by the user\n * And updates the isCurrentlyOwned value on each accordingly.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT ownership status is checked/updated.\n */\n async checkAndUpdateAllNftsOwnershipStatus(\n {\n networkClientId,\n userAddress = this.#selectedAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.#selectedAddress,\n },\n ) {\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { allNfts } = this.state;\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const updatedNfts = await Promise.all(\n nfts.map(async (nft) => {\n return (\n (await this.checkAndUpdateSingleNftOwnershipStatus(nft, true, {\n networkClientId,\n userAddress,\n })) ?? nft\n );\n }),\n );\n\n this.#updateNestedNftState(updatedNfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n }\n\n /**\n * Update NFT favorite status.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Hex address of the NFT contract.\n * @param favorite - NFT new favorite status.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n updateNftFavoriteStatus(\n address: string,\n tokenId: string,\n favorite: boolean,\n {\n networkClientId,\n userAddress = this.#selectedAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {\n userAddress: this.#selectedAddress,\n },\n ) {\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { allNfts } = this.state;\n const nfts = [...(allNfts[userAddress]?.[chainId] || [])];\n const index: number = nfts.findIndex(\n (nft) => nft.address === address && nft.tokenId === tokenId,\n );\n\n if (index === -1) {\n return;\n }\n\n const updatedNft: Nft = {\n ...nfts[index],\n favorite,\n };\n\n // Update Nfts array\n nfts[index] = updatedNft;\n\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n }\n\n /**\n * Returns an NFT by the address and token id.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Number that represents the id of the token.\n * @param selectedAddress - Hex address of the user account.\n * @param chainId - Id of the current network.\n * @returns Object containing the NFT and its position in the array\n */\n findNftByAddressAndTokenId(\n address: string,\n tokenId: string,\n selectedAddress: string,\n chainId: Hex,\n ): { nft: Nft; index: number } | null {\n const { allNfts } = this.state;\n const nfts = allNfts[selectedAddress]?.[chainId] || [];\n const index: number = nfts.findIndex(\n (nft) =>\n nft.address.toLowerCase() === address.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (index === -1) {\n return null;\n }\n\n return { nft: nfts[index], index };\n }\n\n /**\n * Update NFT data.\n *\n * @param nft - NFT object to find the right NFT to updates.\n * @param updates - NFT partial object to update properties of the NFT.\n * @param selectedAddress - Hex address of the user account.\n * @param chainId - Id of the current network.\n */\n updateNft(\n nft: Nft,\n updates: Partial<Nft>,\n selectedAddress: string,\n chainId: Hex,\n ) {\n const { allNfts } = this.state;\n const nfts = allNfts[selectedAddress]?.[chainId] || [];\n const nftInfo = this.findNftByAddressAndTokenId(\n nft.address,\n nft.tokenId,\n selectedAddress,\n chainId,\n );\n\n if (!nftInfo) {\n return;\n }\n\n const updatedNft: Nft = {\n ...nft,\n ...updates,\n };\n\n const newNfts = [\n ...nfts.slice(0, nftInfo.index),\n updatedNft,\n ...nfts.slice(nftInfo.index + 1),\n ];\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress: selectedAddress,\n });\n }\n\n /**\n * Resets the transaction status of an NFT.\n *\n * @param transactionId - NFT transaction id.\n * @param selectedAddress - Hex address of the user account.\n * @param chainId - Id of the current network.\n * @returns a boolean indicating if the reset was well succeeded or not\n */\n resetNftTransactionStatusByTransactionId(\n transactionId: string,\n selectedAddress: string,\n chainId: Hex,\n ): boolean {\n const { allNfts } = this.state;\n const nfts = allNfts[selectedAddress]?.[chainId] || [];\n const index: number = nfts.findIndex(\n (nft) => nft.transactionId === transactionId,\n );\n\n if (index === -1) {\n return false;\n }\n const updatedNft: Nft = {\n ...nfts[index],\n transactionId: undefined,\n };\n\n const newNfts = [\n ...nfts.slice(0, index),\n updatedNft,\n ...nfts.slice(index + 1),\n ];\n\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress: selectedAddress,\n });\n\n return true;\n }\n\n async _requestApproval(suggestedNftMeta: SuggestedNftMeta) {\n return this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n id: suggestedNftMeta.id,\n origin: suggestedNftMeta.origin,\n type: ApprovalType.WatchAsset,\n requestData: {\n id: suggestedNftMeta.id,\n interactingAddress: suggestedNftMeta.interactingAddress,\n asset: {\n address: suggestedNftMeta.asset.address,\n tokenId: suggestedNftMeta.asset.tokenId,\n name: suggestedNftMeta.asset.name,\n description: suggestedNftMeta.asset.description,\n image: suggestedNftMeta.asset.image,\n standard: suggestedNftMeta.asset.standard,\n },\n },\n },\n true,\n );\n }\n}\n\nexport default NftController;\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/TokenRatesController.ts"],"sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport {\n safelyExecute,\n toChecksumHexAddress,\n FALL_BACK_VS_CURRENCY,\n toHex,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\nimport { isEqual } from 'lodash';\n\nimport { reduceInBatchesSerially, TOKEN_PRICES_BATCH_SIZE } from './assetsUtil';\nimport { fetchExchangeRate as fetchNativeCurrencyExchangeRate } from './crypto-compare-service';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\nimport { ZERO_ADDRESS } from './token-prices-service/codefi-v2';\nimport type { TokensControllerState } from './TokensController';\n\n/**\n * @type Token\n *\n * Token representation\n * @property address - Hex address of the token contract\n * @property decimals - Number of decimals the token uses\n * @property symbol - Symbol of the token\n * @property image - Image of the token, url or bit32 image\n */\n\nexport type Token = {\n address: string;\n decimals: number;\n symbol: string;\n aggregators?: string[];\n image?: string;\n hasBalanceError?: boolean;\n isERC721?: boolean;\n name?: string;\n};\n\n/**\n * @type TokenRatesConfig\n *\n * Token rates controller configuration\n * @property interval - Polling interval used to fetch new token rates\n * @property nativeCurrency - Current native currency selected to use base of rates\n * @property chainId - Current network chainId\n * @property tokens - List of tokens to track exchange rates for\n * @property threshold - Threshold to invalidate the supportedChains\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface TokenRatesConfig extends BaseConfig {\n interval: number;\n nativeCurrency: string;\n chainId: Hex;\n selectedAddress: string;\n allTokens: { [chainId: Hex]: { [key: string]: Token[] } };\n allDetectedTokens: { [chainId: Hex]: { [key: string]: Token[] } };\n threshold: number;\n}\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface ContractExchangeRates {\n [address: string]: number | undefined;\n}\n\ntype MarketDataDetails = {\n tokenAddress: `0x${string}`;\n value: number;\n currency: string;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\n\nexport type ContractMarketData = Record<Hex, MarketDataDetails>;\n\nenum PollState {\n Active = 'Active',\n Inactive = 'Inactive',\n}\n\n/**\n * @type TokenRatesState\n *\n * Token rates controller state\n * @property marketData - Market data for tokens, keyed by chain ID and then token contract address.\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface TokenRatesState extends BaseState {\n marketData: Record<Hex, Record<Hex, MarketDataDetails>>;\n}\n\n/**\n * Uses the CryptoCompare API to fetch the exchange rate between one currency\n * and another, i.e., the multiplier to apply the amount of one currency in\n * order to convert it to another.\n *\n * @param args - The arguments to this function.\n * @param args.from - The currency to convert from.\n * @param args.to - The currency to convert to.\n * @returns The exchange rate between `fromCurrency` to `toCurrency` if one\n * exists, or null if one does not.\n */\nasync function getCurrencyConversionRate({\n from,\n to,\n}: {\n from: string;\n to: string;\n}) {\n const includeUSDRate = false;\n try {\n const result = await fetchNativeCurrencyExchangeRate(\n to,\n from,\n includeUSDRate,\n );\n return result.conversionRate;\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes('market does not exist for this coin pair')\n ) {\n return null;\n }\n throw error;\n }\n}\n\n/**\n * Controller that passively polls on a set interval for token-to-fiat exchange rates\n * for tokens stored in the TokensController\n */\nexport class TokenRatesController extends StaticIntervalPollingControllerV1<\n TokenRatesConfig,\n TokenRatesState\n> {\n private handle?: ReturnType<typeof setTimeout>;\n\n #pollState = PollState.Inactive;\n\n #tokenPricesService: AbstractTokenPricesService;\n\n #inProcessExchangeRateUpdates: Record<`${Hex}:${string}`, Promise<void>> = {};\n\n /**\n * Name of this controller used during composition\n */\n override name = 'TokenRatesController' as const;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates a TokenRatesController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The polling interval in ms\n * @param options.threshold - The duration in ms before metadata fetched from CoinGecko is considered stale\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param options.chainId - The chain ID of the current network.\n * @param options.ticker - The ticker for the current network.\n * @param options.selectedAddress - The current selected address.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.onTokensStateChange - Allows subscribing to token controller state changes.\n * @param options.onNetworkStateChange - Allows subscribing to network state changes.\n * @param options.tokenPricesService - An object in charge of retrieving token prices.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n interval = 3 * 60 * 1000,\n threshold = 6 * 60 * 60 * 1000,\n getNetworkClientById,\n chainId: initialChainId,\n ticker: initialTicker,\n selectedAddress: initialSelectedAddress,\n onPreferencesStateChange,\n onTokensStateChange,\n onNetworkStateChange,\n tokenPricesService,\n }: {\n interval?: number;\n threshold?: number;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n chainId: Hex;\n ticker: string;\n selectedAddress: string;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onTokensStateChange: (\n listener: (tokensState: TokensControllerState) => void,\n ) => void;\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n tokenPricesService: AbstractTokenPricesService;\n },\n config?: Partial<TokenRatesConfig>,\n state?: Partial<TokenRatesState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval,\n threshold,\n disabled: false,\n nativeCurrency: initialTicker,\n chainId: initialChainId,\n selectedAddress: initialSelectedAddress,\n allTokens: {}, // TODO: initialize these correctly, maybe as part of BaseControllerV2 migration\n allDetectedTokens: {},\n };\n\n this.defaultState = {\n marketData: {},\n };\n this.initialize();\n this.setIntervalLength(interval);\n this.getNetworkClientById = getNetworkClientById;\n this.#tokenPricesService = tokenPricesService;\n\n if (config?.disabled) {\n this.configure({ disabled: true }, false, false);\n }\n\n onPreferencesStateChange(async ({ selectedAddress }) => {\n if (this.config.selectedAddress !== selectedAddress) {\n this.configure({ selectedAddress });\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n });\n\n onTokensStateChange(async ({ allTokens, allDetectedTokens }) => {\n const previousTokenAddresses = this.#getTokenAddresses(\n this.config.chainId,\n );\n this.configure({ allTokens, allDetectedTokens });\n const newTokenAddresses = this.#getTokenAddresses(this.config.chainId);\n if (\n !isEqual(previousTokenAddresses, newTokenAddresses) &&\n this.#pollState === PollState.Active\n ) {\n await this.updateExchangeRates();\n }\n });\n\n onNetworkStateChange(async ({ selectedNetworkClientId }) => {\n const selectedNetworkClient = getNetworkClientById(\n selectedNetworkClientId,\n );\n const { chainId, ticker } = selectedNetworkClient.configuration;\n\n if (\n this.config.chainId !== chainId ||\n this.config.nativeCurrency !== ticker\n ) {\n this.update({ ...this.defaultState });\n this.configure({ chainId, nativeCurrency: ticker });\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n });\n }\n\n /**\n * Get the user's tokens for the given chain.\n *\n * @param chainId - The chain ID.\n * @returns The list of tokens addresses for the current chain\n */\n #getTokenAddresses(chainId: Hex): Hex[] {\n const { allTokens, allDetectedTokens } = this.config;\n const tokens = allTokens[chainId]?.[this.config.selectedAddress] || [];\n const detectedTokens =\n allDetectedTokens[chainId]?.[this.config.selectedAddress] || [];\n\n return [\n ...new Set(\n [...tokens, ...detectedTokens].map((token) =>\n toHex(toChecksumHexAddress(token.address)),\n ),\n ),\n ].sort();\n }\n\n /**\n * Start (or restart) polling.\n */\n async start() {\n this.#stopPoll();\n this.#pollState = PollState.Active;\n await this.#poll();\n }\n\n /**\n * Stop polling.\n */\n stop() {\n this.#stopPoll();\n this.#pollState = PollState.Inactive;\n }\n\n /**\n * Clear the active polling timer, if present.\n */\n #stopPoll() {\n if (this.handle) {\n clearTimeout(this.handle);\n }\n }\n\n /**\n * Poll for exchange rate updates.\n */\n async #poll() {\n await safelyExecute(() => this.updateExchangeRates());\n\n // Poll using recursive `setTimeout` instead of `setInterval` so that\n // requests don't stack if they take longer than the polling interval\n this.handle = setTimeout(() => {\n this.#poll();\n }, this.config.interval);\n }\n\n /**\n * Updates exchange rates for all tokens.\n */\n async updateExchangeRates() {\n const { chainId, nativeCurrency } = this.config;\n await this.updateExchangeRatesByChainId({\n chainId,\n nativeCurrency,\n });\n }\n\n /**\n * Updates exchange rates for all tokens.\n *\n * @param options - The options to fetch exchange rates.\n * @param options.chainId - The chain ID.\n * @param options.nativeCurrency - The ticker for the chain.\n */\n async updateExchangeRatesByChainId({\n chainId,\n nativeCurrency,\n }: {\n chainId: Hex;\n nativeCurrency: string;\n }) {\n if (this.disabled) {\n return;\n }\n\n const tokenAddresses = this.#getTokenAddresses(chainId);\n\n const updateKey: `${Hex}:${string}` = `${chainId}:${nativeCurrency}`;\n if (updateKey in this.#inProcessExchangeRateUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessExchangeRateUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessExchangeRateUpdates[updateKey] = inProgressUpdate;\n\n try {\n const contractInformations = await this.#fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n\n const marketData = {\n [chainId]: {\n ...(contractInformations ?? {}),\n },\n };\n\n this.update({\n marketData,\n });\n updateSucceeded();\n } catch (error: unknown) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessExchangeRateUpdates[updateKey];\n }\n }\n\n /**\n * Uses the token prices service to retrieve exchange rates for tokens in a\n * particular currency.\n *\n * If the price API does not support the given chain ID, returns an empty\n * object.\n *\n * If the price API does not support the given currency, retrieves exchange\n * rates in a known currency instead, then converts those rates using the\n * exchange rate between the known currency and desired currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * exchange rates.\n * @returns A map from token address to its exchange rate in the native\n * currency, or an empty map if no exchange rates can be obtained for the\n * chain ID.\n */\n async #fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n if (!this.#tokenPricesService.validateChainIdSupported(chainId)) {\n return tokenAddresses.reduce((obj, tokenAddress) => {\n obj = {\n ...obj,\n [tokenAddress]: undefined,\n };\n\n return obj;\n }, {});\n }\n\n if (this.#tokenPricesService.validateCurrencySupported(nativeCurrency)) {\n return await this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n }\n return await this.#fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n });\n }\n\n /**\n * Updates token rates for the given networkClientId\n *\n * @param networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.getNetworkClientById(networkClientId);\n await this.updateExchangeRatesByChainId({\n chainId: networkClient.configuration.chainId,\n nativeCurrency: networkClient.configuration.ticker,\n });\n }\n\n /**\n * Retrieves prices in the given currency for the given tokens on the given\n * chain. Ensures that token addresses are checksum addresses.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n let contractNativeInformations;\n const tokenPricesByTokenAddress = await reduceInBatchesSerially<\n Hex,\n Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>\n >({\n values: [...tokenAddresses].sort(),\n batchSize: TOKEN_PRICES_BATCH_SIZE,\n eachBatch: async (allTokenPricesByTokenAddress, batch) => {\n const tokenPricesByTokenAddressForBatch =\n await this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: batch,\n chainId,\n currency: nativeCurrency,\n });\n\n return {\n ...allTokenPricesByTokenAddress,\n ...tokenPricesByTokenAddressForBatch,\n };\n },\n initialResult: {},\n });\n contractNativeInformations = tokenPricesByTokenAddress;\n\n // fetch for native token\n if (tokenAddresses.length === 0) {\n const contractNativeInformationsNative =\n await this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: [],\n chainId,\n currency: nativeCurrency,\n });\n\n contractNativeInformations = {\n [ZERO_ADDRESS]: {\n currency: nativeCurrency,\n ...contractNativeInformationsNative[ZERO_ADDRESS],\n },\n };\n }\n return Object.entries(contractNativeInformations).reduce(\n (obj, [tokenAddress, token]) => {\n obj = {\n ...obj,\n [tokenAddress.toLowerCase()]: { ...token },\n };\n\n return obj;\n },\n {},\n );\n }\n\n /**\n * If the price API does not support a given native currency, then we need to\n * convert it to a fallback currency and feed that currency into the price\n * API, then convert the prices to our desired native currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n const [\n contractExchangeInformations,\n fallbackCurrencyToNativeCurrencyConversionRate,\n ] = await Promise.all([\n this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId: this.config.chainId,\n nativeCurrency: FALL_BACK_VS_CURRENCY,\n }),\n getCurrencyConversionRate({\n from: FALL_BACK_VS_CURRENCY,\n to: nativeCurrency,\n }),\n ]);\n\n if (fallbackCurrencyToNativeCurrencyConversionRate === null) {\n return {};\n }\n\n const updatedContractExchangeRates = Object.entries(\n contractExchangeInformations,\n ).reduce((acc, [tokenAddress, token]) => {\n acc = {\n ...acc,\n [tokenAddress]: {\n ...token,\n value: token.value\n ? token.value * fallbackCurrencyToNativeCurrencyConversionRate\n : undefined,\n },\n };\n return acc;\n }, {});\n\n return updatedContractExchangeRates;\n }\n}\n\nexport default TokenRatesController;\n"],"mappings":";;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,yCAAyC;AAElD,SAAS,6BAAuC;AAChD,SAAS,eAAe;AAkHxB,eAAe,0BAA0B;AAAA,EACvC;AAAA,EACA;AACF,GAGG;AACD,QAAM,iBAAiB;AACvB,MAAI;AACF,UAAM,SAAS,MAAM;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,WAAO,OAAO;AAAA,EAChB,SAAS,OAAO;AACd,QACE,iBAAiB,SACjB,MAAM,QAAQ,SAAS,0CAA0C,GACjE;AACA,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AACF;AAzJA;AA+JO,IAAM,uBAAN,cAAmC,kCAGxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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A,QAAM,+BAA+B,OAAO;AAAA,IAC1C;AAAA,EACF,EAAE,OAAO,CAAC,KAAK,CAAC,cAAc,KAAK,MAAM;AACvC,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,CAAC,YAAY,GAAG;AAAA,QACd,GAAG;AAAA,QACH,OAAO,MAAM,QACT,MAAM,QAAQ,iDACd;AAAA,MACN;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;AAGF,IAAO,+BAAQ;","names":[]}
|
|
@@ -243,4 +243,4 @@ var AccountTrackerController_default = AccountTrackerController;
|
|
|
243
243
|
|
|
244
244
|
|
|
245
245
|
exports.AccountTrackerController = AccountTrackerController; exports.AccountTrackerController_default = AccountTrackerController_default;
|
|
246
|
-
//# sourceMappingURL=chunk-
|
|
246
|
+
//# sourceMappingURL=chunk-GU53EI7A.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/AccountTrackerController.ts"],"names":[],"mappings":";;;;;;AACA,SAAS,OAAO,gCAAgC;AAChD,OAAO,cAAc;AAOrB,SAAS,yCAAyC;AAElD,SAAS,cAAc;AACvB,SAAS,aAAa;AACtB,SAAS,iBAAiB;AAb1B;AA2DO,IAAM,2BAAN,cAAuC,kCAG5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA6EA,YACE;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAUA,QACA,OACA;AACA,UAAM,QAAQ,KAAK;AA6CrB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA5IA,SAAiB,eAAe,IAAI,MAAM;AAiD1C;AAAA;AAAA;AAAA,SAAS,OAAO;AA4IhB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAU,OAAO,oBAAsC;AACrD,YAAM,cAAc,MAAM,KAA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A,UACH,CAAC,OAAO,GAAG;AAAA,YACT;AAAA,UACF;AAAA,QACF;AAAA,MACF,GAAG,CAAC,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AACF;AA9IE;AAAA,6BAAwB,SAAC,iBAGvB;AACA,MAAI,iBAAiB;AACnB,UAAM,gBAAgB,KAAK,qBAAqB,eAAe;AAE/D,WAAO;AAAA,MACL,SAAS,cAAc,cAAc;AAAA,MACrC,UAAU,IAAI,SAAS,cAAc,QAAQ;AAAA,IAC/C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,SAAS,KAAK,kBAAkB;AAAA,IAChC,UAAU,KAAK,YAAY,IAAI,SAAS,KAAK,SAAS,IAAI;AAAA,EAC5D;AACF;AA+HF,IAAO,mCAAQ","sourcesContent":["import type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { query, safelyExecuteWithTimeout } from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type { Provider } from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport { assert } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport { cloneDeep } from 'lodash';\n\n/**\n * @type AccountInformation\n *\n * Account information object\n * @property balance - Hex string of an account balancec in wei\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountInformation {\n balance: string;\n}\n\n/**\n * @type AccountTrackerConfig\n *\n * Account tracker controller configuration\n * @property provider - Provider used to create a new underlying EthQuery instance\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerConfig extends BaseConfig {\n interval: number;\n provider?: Provider;\n}\n\n/**\n * @type AccountTrackerState\n *\n * Account tracker controller state\n * @property accounts - Map of addresses to account information\n */\n// This interface was created before this ESLint rule was added.\n// Remove in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AccountTrackerState extends BaseState {\n accounts: { [address: string]: AccountInformation };\n accountsByChainId: Record<string, { [address: string]: AccountInformation }>;\n}\n\n/**\n * Controller that tracks the network balances for all user accounts.\n */\nexport class AccountTrackerController extends StaticIntervalPollingControllerV1<\n AccountTrackerConfig,\n AccountTrackerState\n> {\n private _provider?: Provider;\n\n private readonly refreshMutex = new Mutex();\n\n private handle?: ReturnType<typeof setTimeout>;\n\n private syncAccounts(newChainId: string) {\n const accounts = { ...this.state.accounts };\n const accountsByChainId = cloneDeep(this.state.accountsByChainId);\n\n const existing = Object.keys(accounts);\n if (!accountsByChainId[newChainId]) {\n accountsByChainId[newChainId] = {};\n existing.forEach((address) => {\n accountsByChainId[newChainId][address] = { balance: '0x0' };\n });\n }\n\n const addresses = Object.keys(this.getIdentities());\n const newAddresses = addresses.filter(\n (address) => !existing.includes(address),\n );\n const oldAddresses = existing.filter(\n (address) => !addresses.includes(address),\n );\n newAddresses.forEach((address) => {\n accounts[address] = { balance: '0x0' };\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n newAddresses.forEach((address) => {\n accountsByChainId[chainId][address] = {\n balance: '0x0',\n };\n });\n });\n\n oldAddresses.forEach((address) => {\n delete accounts[address];\n });\n Object.keys(accountsByChainId).forEach((chainId) => {\n oldAddresses.forEach((address) => {\n delete accountsByChainId[chainId][address];\n });\n });\n\n this.update({ accounts, accountsByChainId });\n }\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AccountTrackerController' as const;\n\n private readonly getIdentities: () => PreferencesState['identities'];\n\n private readonly getSelectedAddress: () => PreferencesState['selectedAddress'];\n\n private readonly getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n\n private readonly getCurrentChainId: () => NetworkState['providerConfig']['chainId'];\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates an AccountTracker instance.\n *\n * @param options - The controller options.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.getIdentities - Gets the identities from the Preferences store.\n * @param options.getSelectedAddress - Gets the selected address from the Preferences store.\n * @param options.getMultiAccountBalancesEnabled - Gets the multi account balances enabled flag from the Preferences store.\n * @param options.getCurrentChainId - Gets the chain ID for the current network from the Network store.\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n onPreferencesStateChange,\n getIdentities,\n getSelectedAddress,\n getMultiAccountBalancesEnabled,\n getCurrentChainId,\n getNetworkClientById,\n }: {\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n getIdentities: () => PreferencesState['identities'];\n getSelectedAddress: () => PreferencesState['selectedAddress'];\n getMultiAccountBalancesEnabled: () => PreferencesState['isMultiAccountBalancesEnabled'];\n getCurrentChainId: () => NetworkState['providerConfig']['chainId'];\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<AccountTrackerConfig>,\n state?: Partial<AccountTrackerState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n interval: 10000,\n };\n this.defaultState = {\n accounts: {},\n accountsByChainId: {\n [getCurrentChainId()]: {},\n },\n };\n this.initialize();\n this.setIntervalLength(this.config.interval);\n this.getIdentities = getIdentities;\n this.getSelectedAddress = getSelectedAddress;\n this.getMultiAccountBalancesEnabled = getMultiAccountBalancesEnabled;\n this.getCurrentChainId = getCurrentChainId;\n this.getNetworkClientById = getNetworkClientById;\n onPreferencesStateChange(() => {\n this.refresh();\n });\n this.poll();\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @param provider - Provider used to create a new underlying EthQuery instance.\n */\n set provider(provider: Provider) {\n this._provider = provider;\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Resolves a networkClientId to a network client config\n * or globally selected network config if not provided\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n * @returns network client config\n */\n #getCorrectNetworkClient(networkClientId?: NetworkClientId): {\n chainId: string;\n ethQuery?: EthQuery;\n } {\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n\n return {\n chainId: networkClient.configuration.chainId,\n ethQuery: new EthQuery(networkClient.provider),\n };\n }\n\n return {\n chainId: this.getCurrentChainId(),\n ethQuery: this._provider ? new EthQuery(this._provider) : undefined,\n };\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval trigger a 'refresh'.\n */\n async poll(interval?: number): Promise<void> {\n interval && this.configure({ interval }, false, false);\n this.handle && clearTimeout(this.handle);\n await this.refresh();\n this.handle = setTimeout(() => {\n this.poll(this.config.interval);\n }, this.config.interval);\n }\n\n /**\n * Refreshes the balances of the accounts using the networkClientId\n *\n * @param networkClientId - The network client ID used to get balances.\n */\n async _executePoll(networkClientId: string): Promise<void> {\n this.refresh(networkClientId);\n }\n\n /**\n * Refreshes the balances of the accounts depending on the multi-account setting.\n * If multi-account is disabled, only updates the selected account balance.\n * If multi-account is enabled, updates balances for all accounts.\n *\n * @param networkClientId - Optional networkClientId to fetch a network client with\n */\n refresh = async (networkClientId?: NetworkClientId) => {\n const releaseLock = await this.refreshMutex.acquire();\n try {\n const { chainId, ethQuery } =\n this.#getCorrectNetworkClient(networkClientId);\n this.syncAccounts(chainId);\n const { accounts, accountsByChainId } = this.state;\n const isMultiAccountBalancesEnabled =\n this.getMultiAccountBalancesEnabled();\n\n const accountsToUpdate = isMultiAccountBalancesEnabled\n ? Object.keys(accounts)\n : [this.getSelectedAddress()];\n\n const accountsForChain = { ...accountsByChainId[chainId] };\n for (const address of accountsToUpdate) {\n const balance = await this.getBalanceFromChain(address, ethQuery);\n if (balance) {\n accountsForChain[address] = {\n balance,\n };\n }\n }\n\n this.update({\n ...(chainId === this.getCurrentChainId() && {\n accounts: accountsForChain,\n }),\n accountsByChainId: {\n ...this.state.accountsByChainId,\n [chainId]: accountsForChain,\n },\n });\n } catch (err) {\n releaseLock();\n throw err;\n }\n };\n\n /**\n * Fetches the balance of a given address from the blockchain.\n *\n * @param address - The account address to fetch the balance for.\n * @param ethQuery - The EthQuery instance to query getBalnce with.\n * @returns A promise that resolves to the balance in a hex string format.\n */\n private async getBalanceFromChain(\n address: string,\n ethQuery?: EthQuery,\n ): Promise<string | undefined> {\n return await safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n return await query(ethQuery, 'getBalance', [address]);\n });\n }\n\n /**\n * Sync accounts balances with some additional addresses.\n *\n * @param addresses - the additional addresses, may be hardware wallet addresses.\n * @param networkClientId - Optional networkClientId to fetch a network client with.\n * @returns accounts - addresses with synced balance\n */\n async syncBalanceWithAddresses(\n addresses: string[],\n networkClientId?: NetworkClientId,\n ): Promise<Record<string, { balance: string }>> {\n const { ethQuery } = this.#getCorrectNetworkClient(networkClientId);\n\n return await Promise.all(\n addresses.map((address): Promise<[string, string] | undefined> => {\n return safelyExecuteWithTimeout(async () => {\n assert(ethQuery, 'Provider not set.');\n const balance = await query(ethQuery, 'getBalance', [address]);\n return [address, balance];\n });\n }),\n ).then((value) => {\n return value.reduce((obj, item) => {\n if (!item) {\n return obj;\n }\n\n const [address, balance] = item;\n return {\n ...obj,\n [address]: {\n balance,\n },\n };\n }, {});\n });\n }\n}\n\nexport default AccountTrackerController;\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/AssetsContractController.ts"],"sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { BaseControllerV1 } from '@metamask/base-controller';\nimport { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkState,\n NetworkController,\n Provider,\n} from '@metamask/network-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport abiSingleCallBalancesContract from 'single-call-balance-checker-abi';\n\nimport { SupportedTokenDetectionNetworks } from './assetsUtil';\nimport { ERC20Standard } from './Standards/ERC20Standard';\nimport { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';\nimport { ERC721Standard } from './Standards/NftStandards/ERC721/ERC721Standard';\n\n/**\n * Check if token detection is enabled for certain networks\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID: Record<Hex, string> = {\n [SupportedTokenDetectionNetworks.mainnet]:\n '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',\n [SupportedTokenDetectionNetworks.bsc]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.polygon]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.avax]:\n '0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',\n [SupportedTokenDetectionNetworks.aurora]:\n '0x1286415D333855237f89Df27D388127181448538',\n [SupportedTokenDetectionNetworks.linea_goerli]:\n '0x10dAd7Ca3921471f616db788D9300DC97Db01783',\n [SupportedTokenDetectionNetworks.linea_mainnet]:\n '0xF62e6a41561b3650a69Bb03199C735e3E3328c0D',\n [SupportedTokenDetectionNetworks.arbitrum]:\n '0x151E24A486D7258dd7C33Fb67E4bB01919B7B32c',\n [SupportedTokenDetectionNetworks.optimism]:\n '0xB1c568e9C3E6bdaf755A60c7418C269eb11524FC',\n [SupportedTokenDetectionNetworks.base]:\n '0x6AA75276052D96696134252587894ef5FFA520af',\n [SupportedTokenDetectionNetworks.zksync]:\n '0x458fEd3144680a5b8bcfaa0F9594aa19B4Ea2D34',\n [SupportedTokenDetectionNetworks.cronos]:\n '0x768ca200f0fc702ac9ea502498c18f5eff176378',\n [SupportedTokenDetectionNetworks.celo]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.gnosis]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.fantom]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.polygon_zkevm]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonbeam]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonriver]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n};\n\nexport const MISSING_PROVIDER_ERROR =\n 'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';\n\n/**\n * @type AssetsContractConfig\n *\n * Assets Contract controller configuration\n * @property provider - Provider used to create a new web3 instance\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AssetsContractConfig extends BaseConfig {\n provider: Provider | undefined;\n ipfsGateway: string;\n chainId: Hex;\n}\n\n/**\n * @type BalanceMap\n *\n * Key value object containing the balance for each tokenAddress\n * @property [tokenAddress] - Address of the token\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface BalanceMap {\n [tokenAddress: string]: BN;\n}\n\n/**\n * Controller that interacts with contracts on mainnet through web3\n */\nexport class AssetsContractController extends BaseControllerV1<\n AssetsContractConfig,\n BaseState\n> {\n private _provider?: Provider;\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AssetsContractController' as const;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates a AssetsContractController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.onNetworkDidChange - Allows subscribing to network controller networkDidChange events.\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n chainId: initialChainId,\n onPreferencesStateChange,\n onNetworkDidChange,\n getNetworkClientById,\n }: {\n chainId: Hex;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onNetworkDidChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<AssetsContractConfig>,\n state?: Partial<BaseState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n provider: undefined,\n ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,\n chainId: initialChainId,\n };\n this.initialize();\n this.getNetworkClientById = getNetworkClientById;\n\n onPreferencesStateChange(({ ipfsGateway }) => {\n this.configure({ ipfsGateway });\n });\n\n onNetworkDidChange((networkState) => {\n if (this.config.chainId !== networkState.providerConfig.chainId) {\n this.configure({\n chainId: networkState.providerConfig.chainId,\n });\n }\n });\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @property provider - Provider used to create a new underlying Web3 instance\n */\n set provider(provider: Provider) {\n this._provider = provider;\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Get the relevant provider instance.\n *\n * @param networkClientId - Network Client ID.\n * @returns Web3Provider instance.\n */\n getProvider(networkClientId?: NetworkClientId): Web3Provider {\n const provider = networkClientId\n ? this.getNetworkClientById(networkClientId).provider\n : this._provider;\n\n if (provider === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n\n // @ts-expect-error TODO: remove this annotation once the `Eip1193Provider` class is released\n return new Web3Provider(provider);\n }\n\n /**\n * Get the relevant chain ID.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns Hex chain ID.\n */\n getChainId(networkClientId?: NetworkClientId): Hex {\n return networkClientId\n ? this.getNetworkClientById(networkClientId).configuration.chainId\n : this.config.chainId;\n }\n\n /**\n * Get a ERC20Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC20Standard instance.\n */\n getERC20Standard(networkClientId?: NetworkClientId): ERC20Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC20Standard(provider);\n }\n\n /**\n * Get a ERC721Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC721Standard instance.\n */\n getERC721Standard(networkClientId?: NetworkClientId): ERC721Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC721Standard(provider);\n }\n\n /**\n * Get a ERC1155Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC1155Standard instance.\n */\n getERC1155Standard(networkClientId?: NetworkClientId): ERC1155Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC1155Standard(provider);\n }\n\n /**\n * Get balance or count for current account on specific asset contract.\n *\n * @param address - Asset ERC20 contract address.\n * @param selectedAddress - Current account public address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getERC20BalanceOf(\n address: string,\n selectedAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getBalanceOf(address, selectedAddress);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenDecimals(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenDecimals(address);\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenName(address);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param address - ERC721 asset contract address.\n * @param selectedAddress - Current account public address.\n * @param index - An NFT counter less than `balanceOf(selectedAddress)`.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.\n */\n getERC721NftTokenId(\n address: string,\n selectedAddress: string,\n index: number,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getNftTokenId(address, selectedAddress, index);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param tokenAddress - ERC721 asset contract address.\n * @param userAddress - Current account public address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.\n */\n async getTokenStandardAndDetails(\n tokenAddress: string,\n userAddress?: string,\n tokenId?: string,\n networkClientId?: NetworkClientId,\n ): Promise<{\n standard: string;\n tokenURI?: string | undefined;\n symbol?: string | undefined;\n name?: string | undefined;\n decimals?: string | undefined;\n balance?: BN | undefined;\n }> {\n // Asserts provider is available\n this.getProvider(networkClientId);\n\n const { ipfsGateway } = this.config;\n\n // ERC721\n try {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return {\n ...(await erc721Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC1155\n try {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return {\n ...(await erc1155Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC20\n try {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return {\n ...(await erc20Standard.getDetails(tokenAddress, userAddress)),\n };\n } catch {\n // Ignore\n }\n\n throw new Error('Unable to determine contract standard');\n }\n\n /**\n * Query for tokenURI for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC721TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'name'.\n */\n async getERC721AssetName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetName(address);\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'symbol'.\n */\n async getERC721AssetSymbol(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetSymbol(address);\n }\n\n /**\n * Query for owner for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the owner address.\n */\n async getERC721OwnerOf(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getOwnerOf(address, tokenId);\n }\n\n /**\n * Query for tokenURI for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @param tokenId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC1155TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for balance of a given ERC 1155 token.\n *\n * @param userAddress - Wallet public address.\n * @param nftAddress - ERC1155 asset contract address.\n * @param nftId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getERC1155BalanceOf(\n userAddress: string,\n nftAddress: string,\n nftId: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getBalanceOf(nftAddress, userAddress, nftId);\n }\n\n /**\n * Transfer single ERC1155 token.\n *\n * @param nftAddress - ERC1155 token address.\n * @param senderAddress - ERC1155 token sender.\n * @param recipientAddress - ERC1155 token recipient.\n * @param nftId - ERC1155 token id.\n * @param qty - Quantity of tokens to be sent.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'transferSingle' ERC1155 token.\n */\n async transferSingleERC1155(\n nftAddress: string,\n senderAddress: string,\n recipientAddress: string,\n nftId: string,\n qty: string,\n networkClientId?: NetworkClientId,\n ): Promise<void> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.transferSingle(\n nftAddress,\n senderAddress,\n recipientAddress,\n nftId,\n qty,\n );\n }\n\n /**\n * Get the token balance for a list of token addresses in a single call. Only non-zero balances\n * are returned.\n *\n * @param selectedAddress - The address to check token balances for.\n * @param tokensToDetect - The token addresses to detect balances for.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns The list of non-zero token balances.\n */\n async getBalancesInSingleCall(\n selectedAddress: string,\n tokensToDetect: string[],\n networkClientId?: NetworkClientId,\n ) {\n const chainId = this.getChainId(networkClientId);\n const provider = this.getProvider(networkClientId);\n if (!(chainId in SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)) {\n // Only fetch balance if contract address exists\n return {};\n }\n const contractAddress = SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[chainId];\n\n const contract = new Contract(\n contractAddress,\n abiSingleCallBalancesContract,\n provider,\n );\n const result = await contract.balances([selectedAddress], tokensToDetect);\n const nonZeroBalances: BalanceMap = {};\n /* istanbul ignore else */\n if (result.length > 0) {\n tokensToDetect.forEach((tokenAddress, index) => {\n const balance: BN = result[index];\n /* istanbul ignore else */\n if (String(balance) !== '0') {\n nonZeroBalances[tokenAddress] = balance;\n }\n });\n }\n return nonZeroBalances;\n }\n}\n\nexport default AssetsContractController;\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,oBAAoB;AAE7B,SAAS,wBAAwB;AACjC,SAAS,gCAAgC;AAUzC,OAAO,mCAAmC;AAanC,IAAM,0CAA+D;AAAA,EAC1E,oBAAwC,GACtC;AAAA,EACF,iBAAoC,GAClC;AAAA,EACF,qBAAwC,GACtC;AAAA,EACF,oBAAqC,GACnC;AAAA,EACF,0BAAuC,GACrC;AAAA,EACF,4BAA6C,GAC3C;AAAA,EACF,6BAA8C,GAC5C;AAAA,EACF,wBAAyC,GACvC;AAAA,EACF,qBAAyC,GACvC;AAAA,EACF,oBAAqC,GACnC;AAAA,EACF,qBAAuC,GACrC;AAAA,EACF,oBAAuC,GACrC;AAAA,EACF,oBAAqC,GACnC;AAAA,EACF,oBAAuC,GACrC;AAAA,EACF,oBAAuC,GACrC;AAAA,EACF,4BAA8C,GAC5C;AAAA,EACF,uBAAyC,GACvC;AAAA,EACF,wBAA0C,GACxC;AACJ;AAEO,IAAM,yBACX;AAiCK,IAAM,2BAAN,cAAuC,iBAG5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqBA,YACE;AAAA,IACE,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAUA,QACA,OACA;AACA,UAAM,QAAQ,KAAK;AAlCrB;AAAA;AAAA;AAAA,SAAS,OAAO;AAmCd,SAAK,gBAAgB;AAAA,MACnB,UAAU;AAAA,MACV,aAAa;AAAA,MACb,SAAS;AAAA,I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ACa;AACb,UAAM,kBAAkB,KAAK,mBAAmB,eAAe;AAC/D,WAAO,gBAAgB,aAAa,YAAY,aAAa,KAAK;AAAA,EACpE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,MAAM,sBACJ,YACA,eACA,kBACA,OACA,KACA,iBACe;AACf,UAAM,kBAAkB,KAAK,mBAAmB,eAAe;AAC/D,WAAO,gBAAgB;AAAA,MACrB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,wBACJ,iBACA,gBACA,iBACA;AACA,UAAM,UAAU,KAAK,WAAW,eAAe;AAC/C,UAAM,WAAW,KAAK,YAAY,eAAe;AACjD,QAAI,EAAE,WAAW,0CAA0C;AAEzD,aAAO,CAAC;AAAA,IACV;AACA,UAAM,kBAAkB,wCAAwC,OAAO;AAEvE,UAAM,WAAW,IAAI;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,UAAM,SAAS,MAAM,SAAS,SAAS,CAAC,eAAe,GAAG,cAAc;AACxE,UAAM,kBAA8B,CAAC;AAErC,QAAI,OAAO,SAAS,GAAG;AACrB,qBAAe,QAAQ,CAAC,cAAc,UAAU;AAC9C,cAAM,UAAc,OAAO,KAAK;AAEhC,YAAI,OAAO,OAAO,MAAM,KAAK;AAC3B,0BAAgB,YAAY,IAAI;AAAA,QAClC;AAAA,MACF,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AACF;AAEA,IAAO,mCAAQ;","names":[]}
|
|
@@ -103,20 +103,19 @@ var TokenBalancesController = class extends _basecontroller.BaseController {
|
|
|
103
103
|
if (_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _disabled)) {
|
|
104
104
|
return;
|
|
105
105
|
}
|
|
106
|
+
const { selectedAddress } = this.messagingSystem.call(
|
|
107
|
+
"PreferencesController:getState"
|
|
108
|
+
);
|
|
106
109
|
const newContractBalances = {};
|
|
107
110
|
for (const token of _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _tokens)) {
|
|
108
111
|
const { address } = token;
|
|
109
|
-
const { selectedAddress } = this.messagingSystem.call(
|
|
110
|
-
"PreferencesController:getState"
|
|
111
|
-
);
|
|
112
112
|
try {
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
token.balanceError = null;
|
|
113
|
+
const balance = await _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getERC20BalanceOf).call(this, address, selectedAddress);
|
|
114
|
+
newContractBalances[address] = _controllerutils.toHex.call(void 0, balance);
|
|
115
|
+
token.hasBalanceError = false;
|
|
117
116
|
} catch (error) {
|
|
118
117
|
newContractBalances[address] = _controllerutils.toHex.call(void 0, 0);
|
|
119
|
-
token.
|
|
118
|
+
token.hasBalanceError = true;
|
|
120
119
|
}
|
|
121
120
|
}
|
|
122
121
|
this.update((state) => {
|
|
@@ -136,4 +135,4 @@ var TokenBalancesController_default = TokenBalancesController;
|
|
|
136
135
|
|
|
137
136
|
|
|
138
137
|
exports.getDefaultTokenBalancesState = getDefaultTokenBalancesState; exports.TokenBalancesController = TokenBalancesController; exports.TokenBalancesController_default = TokenBalancesController_default;
|
|
139
|
-
//# sourceMappingURL=chunk-
|
|
138
|
+
//# sourceMappingURL=chunk-IBK6AXPP.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/TokenBalancesController.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA,EAIE;AAAA,OACK;AACP,SAAS,eAAe,aAAa;AAOrC,IAAM,mBAAmB;AAEzB,IAAM,iBAAiB;AAEvB,IAAM,WAAW;AAAA,EACf,kBAAkB,EAAE,SAAS,MAAM,WAAW,MAAM;AACtD;AAiEO,SAAS,+BAA6D;AAC3E,SAAO;AAAA,IACL,kBAAkB,CAAC;AAAA,EACrB;AACF;AAx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B;AAAA,IACF;AAEA,UAAM,EAAE,gBAAgB,IAAI,KAAK,gBAAgB;AAAA,MAC/C;AAAA,IACF;AAEA,UAAM,sBAAwC,CAAC;AAC/C,eAAW,SAAS,mBAAK,UAAS;AAChC,YAAM,EAAE,QAAQ,IAAI;AACpB,UAAI;AACF,cAAM,UAAU,MAAM,mBAAK,oBAAL,WAAwB,SAAS;AACvD,4BAAoB,OAAO,IAAI,MAAM,OAAO;AAC5C,cAAM,kBAAkB;AAAA,MAC1B,SAAS,OAAO;AACd,4BAAoB,OAAO,IAAI,MAAM,CAAC;AACtC,cAAM,kBAAkB;AAAA,MAC1B;AAAA,IACF;AAEA,SAAK,OAAO,CAAC,UAAU;AACrB,YAAM,mBAAmB;AAAA,IAC3B,CAAC;AAAA,EACH;AACF;AAxHE;AAEA;AAEA;AAEA;AAEA;AAkHF,IAAO,kCAAQ","sourcesContent":["import {\n type RestrictedControllerMessenger,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n BaseController,\n} from '@metamask/base-controller';\nimport { safelyExecute, toHex } from '@metamask/controller-utils';\nimport type { PreferencesControllerGetStateAction } from '@metamask/preferences-controller';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport type { Token } from './TokenRatesController';\nimport type { TokensControllerStateChangeEvent } from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst controllerName = 'TokenBalancesController';\n\nconst metadata = {\n contractBalances: { persist: true, anonymous: false },\n};\n\n/**\n * Token balances controller options\n * @property interval - Polling interval used to fetch new token balances.\n * @property tokens - List of tokens to track balances for.\n * @property disabled - If set to true, all tracked tokens contract balances updates are blocked.\n * @property getERC20BalanceOf - Gets the balance of the given account at the given contract address.\n */\ntype TokenBalancesControllerOptions = {\n interval?: number;\n tokens?: Token[];\n disabled?: boolean;\n getERC20BalanceOf: AssetsContractController['getERC20BalanceOf'];\n messenger: TokenBalancesControllerMessenger;\n state?: Partial<TokenBalancesControllerState>;\n};\n\n/**\n * Represents a mapping of hash token contract addresses to their balances.\n */\ntype ContractBalances = Record<string, string>;\n\n/**\n * Token balances controller state\n * @property contractBalances - Hash of token contract addresses to balances\n */\nexport type TokenBalancesControllerState = {\n contractBalances: ContractBalances;\n};\n\nexport type TokenBalancesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenBalancesControllerState\n>;\n\nexport type TokenBalancesControllerActions =\n TokenBalancesControllerGetStateAction;\n\nexport type AllowedActions = PreferencesControllerGetStateAction;\n\nexport type TokenBalancesControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenBalancesControllerState\n >;\n\nexport type TokenBalancesControllerEvents =\n TokenBalancesControllerStateChangeEvent;\n\nexport type AllowedEvents = TokensControllerStateChangeEvent;\n\nexport type TokenBalancesControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenBalancesControllerActions | AllowedActions,\n TokenBalancesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Get the default TokenBalancesController state.\n *\n * @returns The default TokenBalancesController state.\n */\nexport function getDefaultTokenBalancesState(): TokenBalancesControllerState {\n return {\n contractBalances: {},\n };\n}\n\n/**\n * Controller that passively polls on a set interval token balances\n * for tokens stored in the TokensController\n */\nexport class TokenBalancesController extends BaseController<\n typeof controllerName,\n TokenBalancesControllerState,\n TokenBalancesControllerMessenger\n> {\n #handle?: ReturnType<typeof setTimeout>;\n\n #getERC20BalanceOf: AssetsContractController['getERC20BalanceOf'];\n\n #interval: number;\n\n #tokens: Token[];\n\n #disabled: boolean;\n\n /**\n * Construct a Token Balances Controller.\n *\n * @param options - The controller options.\n * @param options.interval - Polling interval used to fetch new token balances.\n * @param options.tokens - List of tokens to track balances for.\n * @param options.disabled - If set to true, all tracked tokens contract balances updates are blocked.\n * @param options.getERC20BalanceOf - Gets the balance of the given account at the given contract address.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller restricted messenger.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n tokens = [],\n disabled = false,\n getERC20BalanceOf,\n messenger,\n state = {},\n }: TokenBalancesControllerOptions) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokenBalancesState(),\n ...state,\n },\n });\n\n this.#disabled = disabled;\n this.#interval = interval;\n this.#tokens = tokens;\n\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n ({ tokens: newTokens, detectedTokens }) => {\n this.#tokens = [...newTokens, ...detectedTokens];\n this.updateBalances();\n },\n );\n\n this.#getERC20BalanceOf = getERC20BalanceOf;\n\n this.poll();\n }\n\n /**\n * Allows controller to update tracked tokens contract balances.\n */\n enable() {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from updating tracked tokens contract balances.\n */\n disable() {\n this.#disabled = true;\n }\n\n /**\n * Starts a new polling interval.\n *\n * @param interval - Polling interval used to fetch new token balances.\n */\n async poll(interval?: number): Promise<void> {\n if (interval) {\n this.#interval = interval;\n }\n\n if (this.#handle) {\n clearTimeout(this.#handle);\n }\n\n await safelyExecute(() => this.updateBalances());\n\n this.#handle = setTimeout(() => {\n this.poll(this.#interval);\n }, this.#interval);\n }\n\n /**\n * Updates balances for all tokens.\n */\n async updateBalances() {\n if (this.#disabled) {\n return;\n }\n\n const { selectedAddress } = this.messagingSystem.call(\n 'PreferencesController:getState',\n );\n\n const newContractBalances: ContractBalances = {};\n for (const token of this.#tokens) {\n const { address } = token;\n try {\n const balance = await this.#getERC20BalanceOf(address, selectedAddress);\n newContractBalances[address] = toHex(balance);\n token.hasBalanceError = false;\n } catch (error) {\n newContractBalances[address] = toHex(0);\n token.hasBalanceError = true;\n }\n }\n\n this.update((state) => {\n state.contractBalances = newContractBalances;\n });\n }\n}\n\nexport default TokenBalancesController;\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkPYMUBJQXjs = require('./chunk-PYMUBJQX.js');
|
|
4
4
|
|
|
5
5
|
|
|
6
6
|
|
|
@@ -173,7 +173,7 @@ var TokenListController = class extends _pollingcontroller.StaticIntervalPolling
|
|
|
173
173
|
tokenList = { ...cachedTokens };
|
|
174
174
|
} else {
|
|
175
175
|
const tokensFromAPI = await _controllerutils.safelyExecute.call(void 0,
|
|
176
|
-
() =>
|
|
176
|
+
() => _chunkPYMUBJQXjs.fetchTokenListByChainId.call(void 0,
|
|
177
177
|
chainId,
|
|
178
178
|
this.abortController.signal
|
|
179
179
|
)
|
|
@@ -281,4 +281,4 @@ var TokenListController_default = TokenListController;
|
|
|
281
281
|
|
|
282
282
|
|
|
283
283
|
exports.getDefaultTokenListState = getDefaultTokenListState; exports.TokenListController = TokenListController; exports.TokenListController_default = TokenListController_default;
|
|
284
|
-
//# sourceMappingURL=chunk-
|
|
284
|
+
//# sourceMappingURL=chunk-JUI3XNEF.js.map
|
|
@@ -14,7 +14,7 @@ function getTokensURL(chainId) {
|
|
|
14
14
|
const occurrenceFloor = chainId === _controllerutils.ChainId["linea-mainnet"] ? 1 : 3;
|
|
15
15
|
return `${TOKEN_END_POINT_API}/tokens/${_controllerutils.convertHexToDecimal.call(void 0,
|
|
16
16
|
chainId
|
|
17
|
-
)}?occurrenceFloor=${occurrenceFloor}&includeNativeAssets=false&includeDuplicateSymbolAssets=false&includeTokenFees=false&includeAssetType=false`;
|
|
17
|
+
)}?occurrenceFloor=${occurrenceFloor}&includeNativeAssets=false&includeDuplicateSymbolAssets=false&includeTokenFees=false&includeAssetType=false&includeERC20Permit=false&includeStorage=false`;
|
|
18
18
|
}
|
|
19
19
|
function getTokenMetadataURL(chainId, tokenAddress) {
|
|
20
20
|
return `${TOKEN_END_POINT_API}/token/${_controllerutils.convertHexToDecimal.call(void 0,
|
|
@@ -82,4 +82,4 @@ async function parseJsonResponse(apiResponse) {
|
|
|
82
82
|
|
|
83
83
|
|
|
84
84
|
exports.TOKEN_END_POINT_API = TOKEN_END_POINT_API; exports.TOKEN_METADATA_NO_SUPPORT_ERROR = TOKEN_METADATA_NO_SUPPORT_ERROR; exports.fetchTokenListByChainId = fetchTokenListByChainId; exports.fetchTokenMetadata = fetchTokenMetadata;
|
|
85
|
-
//# sourceMappingURL=chunk-
|
|
85
|
+
//# sourceMappingURL=chunk-PYMUBJQX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/token-service.ts"],"names":[],"mappings":";;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKA,IAAM,sBAAsB;AAC5B,IAAM,kCACX;AAQF,SAAS,aAAa,SAAc;AAClC,QAAM,kBAAkB,YAAY,QAAQ,eAAe,IAAI,IAAI;AACnE,SAAO,GAAG,mBAAmB,WAAW;AAAA,IACtC;AAAA,EACF,CAAC,oBAAoB,eAAe;AACtC;AASA,SAAS,oBAAoB,SAAc,cAAsB;AAC/D,SAAO,GAAG,mBAAmB,UAAU;AAAA,IACrC;AAAA,EACF,CAAC,YAAY,YAAY;AAC3B;AAEA,IAAM,2BAA2B;AAIjC,IAAM,iBAAiB;AAYvB,eAAsB,wBACpB,SACA,aACA,EAAE,UAAU,eAAe,IAAI,CAAC,GACd;AAClB,QAAM,WAAW,aAAa,OAAO;AACrC,QAAM,WAAW,MAAM,SAAS,UAAU,aAAa,OAAO;AAC9D,MAAI,UAAU;AACZ,UAAM,SAAS,MAAM,kBAAkB,QAAQ;AAC/C,QAAI,MAAM,QAAQ,MAAM,KAAK,YAAY,QAAQ,eAAe,GAAG;AACjE,aAAO,OAAO;AAAA,QACZ,CAAC,QACC,IAAI,YAAY,SAAS,WAAW,KAAK,IAAI,YAAY,UAAU;AAAA,MACvE;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAaA,eAAsB,mBACpB,SACA,cACA,aACA,EAAE,UAAU,eAAe,IAAI,CAAC,GACR;AACxB,MAAI,CAAC,+BAA+B,OAAO,GAAG;AAC5C,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AACA,QAAM,mBAAmB,oBAAoB,SAAS,YAAY;AAClE,QAAM,WAAW,MAAM,SAAS,kBAAkB,aAAa,OAAO;AACtE,MAAI,UAAU;AACZ,WAAO,kBAAkB,QAAQ;AAAA,EACnC;AACA,SAAO;AACT;AAUA,eAAe,SACb,QACA,aACA,SAC+B;AAC/B,QAAM,eAA4B;AAAA,IAChC,UAAU;AAAA,IACV,gBAAgB;AAAA,IAChB,QAAQ;AAAA,IACR,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO;AAAA,EACT;AACA,eAAa,UAAU,IAAI,OAAO,QAAQ;AAC1C,eAAa,QAAQ,IAAI,gBAAgB,kBAAkB;AAC3D,MAAI;AACF,WAAO,MAAM,aAAa,QAAQ,cAAc,OAAO;AAAA,EACzD,SAAS,OAAO;AACd,QAAI,iBAAiB,SAAS,MAAM,SAAS,cAAc;AACzD,cAAQ,IAAI,oBAAoB;AAAA,IAClC;AAAA,EACF;AACA,SAAO;AACT;AASA,eAAe,kBAAkB,aAAyC;AACxE,QAAM,cAAc,MAAM,YAAY,KAAK;AAE3C,MAAI,aAAa,OAAO;AACtB,UAAM,IAAI,MAAM,uBAAuB,YAAY,KAAK,EAAE;AAAA,EAC5D;AACA,SAAO;AACT","sourcesContent":["import {\n ChainId,\n convertHexToDecimal,\n timeoutFetch,\n} from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\n\nimport { isTokenListSupportedForNetwork } from './assetsUtil';\n\nexport const TOKEN_END_POINT_API = 'https://token.api.cx.metamask.io';\nexport const TOKEN_METADATA_NO_SUPPORT_ERROR =\n 'TokenService Error: Network does not support fetchTokenMetadata';\n\n/**\n * Get the tokens URL for a specific network.\n *\n * @param chainId - The chain ID of the network the tokens requested are on.\n * @returns The tokens URL.\n */\nfunction getTokensURL(chainId: Hex) {\n const occurrenceFloor = chainId === ChainId['linea-mainnet'] ? 1 : 3;\n return `${TOKEN_END_POINT_API}/tokens/${convertHexToDecimal(\n chainId,\n )}?occurrenceFloor=${occurrenceFloor}&includeNativeAssets=false&includeDuplicateSymbolAssets=false&includeTokenFees=false&includeAssetType=false&includeERC20Permit=false&includeStorage=false`;\n}\n\n/**\n * Get the token metadata URL for the given network and token.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The token address.\n * @returns The token metadata URL.\n */\nfunction getTokenMetadataURL(chainId: Hex, tokenAddress: string) {\n return `${TOKEN_END_POINT_API}/token/${convertHexToDecimal(\n chainId,\n )}?address=${tokenAddress}`;\n}\n\nconst tenSecondsInMilliseconds = 10_000;\n\n// Token list averages 1.6 MB in size\n// timeoutFetch by default has a 500ms timeout, which will almost always timeout given the response size.\nconst defaultTimeout = tenSecondsInMilliseconds;\n\n/**\n * Fetch the list of token metadata for a given network. This request is cancellable using the\n * abort signal passed in.\n *\n * @param chainId - The chain ID of the network the requested tokens are on.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token list, or `undefined` if the request was cancelled.\n */\nexport async function fetchTokenListByChainId(\n chainId: Hex,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<unknown> {\n const tokenURL = getTokensURL(chainId);\n const response = await queryApi(tokenURL, abortSignal, timeout);\n if (response) {\n const result = await parseJsonResponse(response);\n if (Array.isArray(result) && chainId === ChainId['linea-mainnet']) {\n return result.filter(\n (elm) =>\n elm.aggregators.includes('lineaTeam') || elm.aggregators.length >= 3,\n );\n }\n return result;\n }\n return undefined;\n}\n\n/**\n * Fetch metadata for the token address provided for a given network. This request is cancellable\n * using the abort signal passed in.\n *\n * @param chainId - The chain ID of the network the token is on.\n * @param tokenAddress - The address of the token to fetch metadata for.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param options - Additional fetch options.\n * @param options.timeout - The fetch timeout.\n * @returns The token metadata, or `undefined` if the request was either aborted or failed.\n */\nexport async function fetchTokenMetadata<T>(\n chainId: Hex,\n tokenAddress: string,\n abortSignal: AbortSignal,\n { timeout = defaultTimeout } = {},\n): Promise<T | undefined> {\n if (!isTokenListSupportedForNetwork(chainId)) {\n throw new Error(TOKEN_METADATA_NO_SUPPORT_ERROR);\n }\n const tokenMetadataURL = getTokenMetadataURL(chainId, tokenAddress);\n const response = await queryApi(tokenMetadataURL, abortSignal, timeout);\n if (response) {\n return parseJsonResponse(response) as Promise<T>;\n }\n return undefined;\n}\n\n/**\n * Perform fetch request against the api.\n *\n * @param apiURL - The URL of the API to fetch.\n * @param abortSignal - The abort signal used to cancel the request if necessary.\n * @param timeout - The fetch timeout.\n * @returns Promise resolving request response.\n */\nasync function queryApi(\n apiURL: string,\n abortSignal: AbortSignal,\n timeout: number,\n): Promise<Response | undefined> {\n const fetchOptions: RequestInit = {\n referrer: apiURL,\n referrerPolicy: 'no-referrer-when-downgrade',\n method: 'GET',\n mode: 'cors',\n signal: abortSignal,\n cache: 'default',\n };\n fetchOptions.headers = new window.Headers();\n fetchOptions.headers.set('Content-Type', 'application/json');\n try {\n return await timeoutFetch(apiURL, fetchOptions, timeout);\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n console.log('Request is aborted');\n }\n }\n return undefined;\n}\n\n/**\n * Parse an API response and return the response JSON data.\n *\n * @param apiResponse - The API response to parse.\n * @returns The response JSON data.\n * @throws Will throw if the response includes an error.\n */\nasync function parseJsonResponse(apiResponse: Response): Promise<unknown> {\n const responseObj = await apiResponse.json();\n // api may return errors as json without setting an error http status code\n if (responseObj?.error) {\n throw new Error(`TokenService Error: ${responseObj.error}`);\n }\n return responseObj;\n}\n"]}
|