@metamask/assets-controllers 30.0.0 → 31.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.
Files changed (93) hide show
  1. package/CHANGELOG.md +81 -1
  2. package/dist/AccountTrackerController.js +2 -2
  3. package/dist/AccountTrackerController.mjs +1 -1
  4. package/dist/AssetsContractController.js +2 -2
  5. package/dist/AssetsContractController.mjs +1 -1
  6. package/dist/NftController.js +2 -2
  7. package/dist/NftController.mjs +3 -3
  8. package/dist/NftDetectionController.js +2 -2
  9. package/dist/NftDetectionController.mjs +1 -1
  10. package/dist/TokenBalancesController.js +2 -2
  11. package/dist/TokenBalancesController.mjs +1 -1
  12. package/dist/TokenListController.js +3 -3
  13. package/dist/TokenListController.mjs +2 -2
  14. package/dist/TokenRatesController.js +2 -2
  15. package/dist/TokenRatesController.mjs +1 -1
  16. package/dist/TokensController.js +3 -3
  17. package/dist/TokensController.mjs +2 -2
  18. package/dist/chunk-4AC3X2U5.js +771 -0
  19. package/dist/chunk-4AC3X2U5.js.map +1 -0
  20. package/dist/chunk-543CC74T.mjs +253 -0
  21. package/dist/chunk-543CC74T.mjs.map +1 -0
  22. package/dist/{chunk-Z3OQU4XW.mjs → chunk-5W5OO2Q5.mjs} +2 -2
  23. package/dist/chunk-5W5OO2Q5.mjs.map +1 -0
  24. package/dist/chunk-62T7RKU3.mjs +1265 -0
  25. package/dist/chunk-62T7RKU3.mjs.map +1 -0
  26. package/dist/{chunk-PAJTKWEC.mjs → chunk-65PB33TE.mjs} +1 -1
  27. package/dist/chunk-65PB33TE.mjs.map +1 -0
  28. package/dist/{chunk-7MMEHAKG.mjs → chunk-73F3SN5O.mjs} +332 -265
  29. package/dist/chunk-73F3SN5O.mjs.map +1 -0
  30. package/dist/{chunk-XHMM35YT.mjs → chunk-A2DDWXMS.mjs} +2 -2
  31. package/dist/chunk-CGLUTXI7.js +1265 -0
  32. package/dist/chunk-CGLUTXI7.js.map +1 -0
  33. package/dist/{chunk-X4FFNQHE.mjs → chunk-E4ECCGJV.mjs} +1 -1
  34. package/dist/chunk-E4ECCGJV.mjs.map +1 -0
  35. package/dist/{chunk-V4ZO3F2S.js → chunk-GU53EI7A.js} +1 -1
  36. package/dist/chunk-GU53EI7A.js.map +1 -0
  37. package/dist/{chunk-MHN7CJCZ.mjs → chunk-HLCGZGPA.mjs} +1 -1
  38. package/dist/chunk-HLCGZGPA.mjs.map +1 -0
  39. package/dist/{chunk-LD4GC7OR.js → chunk-IBK6AXPP.js} +8 -9
  40. package/dist/chunk-IBK6AXPP.js.map +1 -0
  41. package/dist/{chunk-5F5EQAX5.js → chunk-JUI3XNEF.js} +3 -3
  42. package/dist/{chunk-3R43XIIX.js → chunk-PYMUBJQX.js} +2 -2
  43. package/dist/chunk-PYMUBJQX.js.map +1 -0
  44. package/dist/chunk-QFDTOEYR.js +253 -0
  45. package/dist/chunk-QFDTOEYR.js.map +1 -0
  46. package/dist/{chunk-4ODKGWYQ.js → chunk-QHWKLZUC.js} +1 -1
  47. package/dist/chunk-QHWKLZUC.js.map +1 -0
  48. package/dist/{chunk-6W5EQ3JQ.js → chunk-UEDNQBJN.js} +1 -1
  49. package/dist/chunk-UEDNQBJN.js.map +1 -0
  50. package/dist/{chunk-4LY47RPI.mjs → chunk-WCCLSUOI.mjs} +8 -9
  51. package/dist/{chunk-4LY47RPI.mjs.map → chunk-WCCLSUOI.mjs.map} +1 -1
  52. package/dist/index.js +10 -12
  53. package/dist/index.mjs +11 -13
  54. package/dist/token-service.js +2 -2
  55. package/dist/token-service.mjs +1 -1
  56. package/dist/tsconfig.build.tsbuildinfo +1 -1
  57. package/dist/types/AccountTrackerController.d.ts +1 -1
  58. package/dist/types/AccountTrackerController.d.ts.map +1 -1
  59. package/dist/types/AssetsContractController.d.ts +1 -1
  60. package/dist/types/AssetsContractController.d.ts.map +1 -1
  61. package/dist/types/NftController.d.ts +65 -184
  62. package/dist/types/NftController.d.ts.map +1 -1
  63. package/dist/types/NftDetectionController.d.ts +34 -75
  64. package/dist/types/NftDetectionController.d.ts.map +1 -1
  65. package/dist/types/TokenRatesController.d.ts +6 -6
  66. package/dist/types/TokenRatesController.d.ts.map +1 -1
  67. package/dist/types/TokensController.d.ts +27 -131
  68. package/dist/types/TokensController.d.ts.map +1 -1
  69. package/dist/types/index.d.ts +5 -3
  70. package/dist/types/index.d.ts.map +1 -1
  71. package/package.json +12 -12
  72. package/dist/chunk-3R43XIIX.js.map +0 -1
  73. package/dist/chunk-46UZDIXW.mjs +0 -1205
  74. package/dist/chunk-46UZDIXW.mjs.map +0 -1
  75. package/dist/chunk-4ODKGWYQ.js.map +0 -1
  76. package/dist/chunk-6W5EQ3JQ.js.map +0 -1
  77. package/dist/chunk-7MMEHAKG.mjs.map +0 -1
  78. package/dist/chunk-FMZML3V5.js +0 -237
  79. package/dist/chunk-FMZML3V5.js.map +0 -1
  80. package/dist/chunk-KOKB6U4Z.mjs +0 -237
  81. package/dist/chunk-KOKB6U4Z.mjs.map +0 -1
  82. package/dist/chunk-LAU6ZDZR.js +0 -1205
  83. package/dist/chunk-LAU6ZDZR.js.map +0 -1
  84. package/dist/chunk-LD4GC7OR.js.map +0 -1
  85. package/dist/chunk-MBCN3MNX.js +0 -704
  86. package/dist/chunk-MBCN3MNX.js.map +0 -1
  87. package/dist/chunk-MHN7CJCZ.mjs.map +0 -1
  88. package/dist/chunk-PAJTKWEC.mjs.map +0 -1
  89. package/dist/chunk-V4ZO3F2S.js.map +0 -1
  90. package/dist/chunk-X4FFNQHE.mjs.map +0 -1
  91. package/dist/chunk-Z3OQU4XW.mjs.map +0 -1
  92. /package/dist/{chunk-XHMM35YT.mjs.map → chunk-A2DDWXMS.mjs.map} +0 -0
  93. /package/dist/{chunk-5F5EQAX5.js.map → chunk-JUI3XNEF.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/NftController.ts"],"sourcesContent":["import { isAddress } from '@ethersproject/address';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type {\n BaseConfig,\n BaseState,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseControllerV1 } 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 NetworkController,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkState,\n} from '@metamask/network-controller';\nimport type { PreferencesState } 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 { EventEmitter } from 'events';\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 */\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 Nft extends NftMetadata {\n tokenId: string;\n address: string;\n isCurrentlyOwned?: boolean;\n}\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 */\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 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 */\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 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 NftConfig\n *\n * NFT controller configuration\n * @property selectedAddress - Vault selected 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 NftConfig extends BaseConfig {\n selectedAddress: string;\n chainId: Hex;\n ipfsGateway: string;\n openSeaEnabled: boolean;\n useIPFSSubdomains: boolean;\n isIpfsGatewayEnabled: boolean;\n}\n\n/**\n * @type NftState\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 */\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 NftState extends BaseState {\n allNftContracts: {\n [key: string]: { [chainId: Hex]: NftContract[] };\n };\n allNfts: { [key: string]: { [chainId: Hex]: Nft[] } };\n ignoredNfts: Nft[];\n}\n\nconst ALL_NFTS_STATE_KEY = 'allNfts';\nconst ALL_NFTS_CONTRACTS_STATE_KEY = 'allNftContracts';\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\ninterface NftAsset {\n address: string;\n tokenId: string;\n}\n\n/**\n * The name of the {@link NftController}.\n */\nconst controllerName = 'NftController';\n\n/**\n * The external actions available to the {@link NftController}.\n */\ntype AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetNetworkClientByIdAction;\n\n/**\n * The messenger of the {@link NftController}.\n */\nexport type NftControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n never,\n AllowedActions['type'],\n never\n>;\n\nexport const getDefaultNftState = (): NftState => {\n return {\n allNftContracts: {},\n allNfts: {},\n ignoredNfts: [],\n };\n};\n\n/**\n * Controller that stores assets and exposes convenience methods\n */\nexport class NftController extends BaseControllerV1<NftConfig, NftState> {\n private readonly mutex = new Mutex();\n\n private readonly messagingSystem: NftControllerMessenger;\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 private updateNestedNftState(\n newCollection: Nft[] | NftContract[],\n baseStateKey: 'allNfts' | 'allNftContracts',\n { userAddress, chainId }: { userAddress: string; chainId: Hex },\n ) {\n const { [baseStateKey]: oldState } = this.state;\n\n const addressState = oldState[userAddress];\n const newAddressState = {\n ...addressState,\n ...{ [chainId]: newCollection },\n };\n const newState = {\n ...oldState,\n ...{ [userAddress]: newAddressState },\n };\n this.update({\n [baseStateKey]: newState,\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 private 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 private async getNftInformationFromTokenURI(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<NftMetadata> {\n const { ipfsGateway, useIPFSSubdomains, isIpfsGatewayEnabled } =\n this.config;\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 && !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.config.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(ipfsGateway, tokenURI, useIPFSSubdomains);\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 private 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 private 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.config.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 private 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 private 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 Promise resolving to the current NFT list.\n */\n private 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<Nft[]> {\n // TODO: Remove unused return\n const releaseLock = await this.mutex.acquire();\n try {\n tokenAddress = toChecksumHexAddress(tokenAddress);\n const { allNfts } = this.state;\n\n const nfts = allNfts[userAddress]?.[chainId] || [];\n\n const existingEntry: Nft | undefined = nfts.find(\n (nft) =>\n nft.address.toLowerCase() === tokenAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n nftMetadata,\n existingEntry,\n );\n if (differentMetadata || !existingEntry.isCurrentlyOwned) {\n // TODO: Switch to indexToUpdate\n const indexToRemove = nfts.findIndex(\n (nft) =>\n nft.address.toLowerCase() === tokenAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n /* istanbul ignore next */\n if (indexToRemove !== -1) {\n nfts.splice(indexToRemove, 1);\n }\n } else {\n return nfts;\n }\n }\n\n const newEntry: Nft = {\n address: tokenAddress,\n tokenId,\n favorite: existingEntry?.favorite || false,\n isCurrentlyOwned: true,\n ...nftMetadata,\n };\n\n const newNfts = [...nfts, newEntry];\n this.updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n if (this.onNftAdded) {\n this.onNftAdded({\n address: tokenAddress,\n symbol: nftContract.symbol,\n tokenId: tokenId.toString(),\n standard: nftMetadata.standard,\n source,\n });\n }\n return newNfts;\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 private 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 tokenAddress = 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() === tokenAddress.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 tokenAddress,\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: tokenAddress },\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(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {\n chainId,\n userAddress,\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 private removeAndIgnoreIndividualNft(\n address: string,\n tokenId: string,\n {\n chainId,\n userAddress,\n }: {\n chainId: Hex;\n userAddress: string;\n },\n ) {\n address = 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() === address.toLowerCase() &&\n nft.tokenId === tokenId\n ) {\n const alreadyIgnored = newIgnoredNfts.find(\n (c) => c.address === address && 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({\n 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 private removeIndividualNft(\n address: string,\n tokenId: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ) {\n address = 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() === address.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 private removeNftContract(\n address: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ): NftContract[] {\n address = toChecksumHexAddress(address);\n const { allNftContracts } = this.state;\n const nftContracts = allNftContracts[userAddress]?.[chainId] || [];\n\n const newNftContracts = nftContracts.filter(\n (nftContract) =>\n !(nftContract.address.toLowerCase() === address.toLowerCase()),\n );\n this.updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n return newNftContracts;\n }\n\n /**\n * EventEmitter instance used to listen to specific EIP747 events\n */\n hub = new EventEmitter();\n\n /**\n * Optional API key to use with opensea\n */\n openSeaApiKey?: string;\n\n /**\n * Name of this controller used during composition\n */\n override name = 'NftController';\n\n private readonly getERC721AssetName: AssetsContractController['getERC721AssetName'];\n\n private readonly getERC721AssetSymbol: AssetsContractController['getERC721AssetSymbol'];\n\n private readonly getERC721TokenURI: AssetsContractController['getERC721TokenURI'];\n\n private readonly getERC721OwnerOf: AssetsContractController['getERC721OwnerOf'];\n\n private readonly getERC1155BalanceOf: AssetsContractController['getERC1155BalanceOf'];\n\n private readonly getERC1155TokenURI: AssetsContractController['getERC1155TokenURI'];\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n private 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.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.\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.getNetworkClientById - Gets the network client for the given networkClientId.\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 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 onNetworkStateChange,\n getERC721AssetName,\n getERC721AssetSymbol,\n getERC721TokenURI,\n getERC721OwnerOf,\n getERC1155BalanceOf,\n getERC1155TokenURI,\n getNetworkClientById,\n onNftAdded,\n messenger,\n }: {\n chainId: Hex;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\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 getNetworkClientById: NetworkController['getNetworkClientById'];\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 },\n config?: Partial<BaseConfig>,\n state?: Partial<NftState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n selectedAddress: '',\n chainId: initialChainId,\n ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,\n openSeaEnabled: false,\n useIPFSSubdomains: true,\n isIpfsGatewayEnabled: true,\n };\n\n this.defaultState = getDefaultNftState();\n this.initialize();\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.getNetworkClientById = getNetworkClientById;\n this.onNftAdded = onNftAdded;\n this.messagingSystem = messenger;\n\n onPreferencesStateChange(\n async ({\n selectedAddress,\n ipfsGateway,\n openSeaEnabled,\n isIpfsGatewayEnabled,\n }) => {\n this.configure({\n selectedAddress,\n ipfsGateway,\n openSeaEnabled,\n isIpfsGatewayEnabled,\n });\n\n const needsUpdateNftMetadata =\n (isIpfsGatewayEnabled && ipfsGateway !== '') || openSeaEnabled;\n\n if (needsUpdateNftMetadata) {\n const { chainId } = this.config;\n const nfts: Nft[] =\n this.state.allNfts[selectedAddress]?.[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\n onNetworkStateChange(({ selectedNetworkClientId }) => {\n const selectedNetworkClient = getNetworkClientById(\n selectedNetworkClientId,\n );\n const { chainId } = selectedNetworkClient.configuration;\n\n this.configure({ chainId });\n });\n }\n\n private 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 private getCorrectChainId({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n }) {\n if (networkClientId) {\n return this.getNetworkClientById(networkClientId).configuration.chainId;\n }\n return this.config.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.config.selectedAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {\n userAddress: this.config.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.config.selectedAddress,\n networkClientId,\n source,\n }: {\n userAddress?: string;\n networkClientId?: NetworkClientId;\n source?: Source;\n } = {\n userAddress: this.config.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.config.selectedAddress,\n source = Source.Custom,\n networkClientId,\n }: {\n nftMetadata?: NftMetadata;\n userAddress?: string;\n source?: Source;\n networkClientId?: NetworkClientId;\n } = { userAddress: this.config.selectedAddress },\n ) {\n tokenAddress = toChecksumHexAddress(tokenAddress);\n\n const chainId = this.getCorrectChainId({ networkClientId });\n\n nftMetadata =\n nftMetadata ||\n (await this.getNftInformation(tokenAddress, tokenId, networkClientId));\n\n const newNftContracts = await this.addNftContract({\n tokenAddress,\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() === tokenAddress.toLowerCase(),\n );\n\n // If NFT contract information, add individual NFT\n if (nftContract) {\n await this.addIndividualNft(\n tokenAddress,\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.config.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.allSettled(\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 const successfulNewFetchedNfts = nftMetadataResults.filter(\n (result): result is PromiseFulfilledResult<NftUpdate> =>\n result.status === 'fulfilled',\n );\n // We want to avoid updating the state if the state and fetched nft info are the same\n const nftsWithDifferentMetadata: PromiseFulfilledResult<NftUpdate>[] = [];\n const { allNfts } = this.state;\n const stateNfts = allNfts[userAddress]?.[chainId] || [];\n\n successfulNewFetchedNfts.forEach((singleNft) => {\n const existingEntry: Nft | undefined = stateNfts.find(\n (nft) =>\n nft.address.toLowerCase() ===\n singleNft.value.nft.address.toLowerCase() &&\n nft.tokenId === singleNft.value.nft.tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n singleNft.value.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(\n elm.value.nft,\n elm.value.newMetadata,\n userAddress,\n chainId,\n ),\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.config.selectedAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.config.selectedAddress,\n },\n ) {\n const chainId = this.getCorrectChainId({ networkClientId });\n address = toChecksumHexAddress(address);\n this.removeIndividualNft(address, tokenId, { chainId, userAddress });\n const { allNfts } = this.state;\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const remainingNft = nfts.find(\n (nft) => nft.address.toLowerCase() === address.toLowerCase(),\n );\n\n if (!remainingNft) {\n this.removeNftContract(address, { 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.config.selectedAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.config.selectedAddress,\n },\n ) {\n const chainId = this.getCorrectChainId({ networkClientId });\n address = toChecksumHexAddress(address);\n this.removeAndIgnoreIndividualNft(address, 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() === address.toLowerCase(),\n );\n if (!remainingNft) {\n this.removeNftContract(address, { chainId, userAddress });\n }\n }\n\n /**\n * Removes all NFTs from the ignored list.\n */\n clearIgnoredNfts() {\n this.update({ ignoredNfts: [] });\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.config.selectedAddress,\n networkClientId,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.config.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 nft.isCurrentlyOwned = isOwned;\n\n if (batch) {\n return nft;\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 nftToUpdate = nfts.find(\n (item) =>\n item.tokenId === tokenId &&\n item.address.toLowerCase() === address.toLowerCase(),\n );\n if (nftToUpdate) {\n nftToUpdate.isCurrentlyOwned = isOwned;\n this.updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n }\n return nft;\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.config.selectedAddress,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {\n userAddress: this.config.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.config.selectedAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {\n userAddress: this.config.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"],"mappings":";;;;;;AAAA,SAAS,iBAAiB;AAO1B,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAQP,SAAS,iBAAiB;AAE1B,SAAS,gBAAgB;AACzB,SAAS,aAAa;AACtB,OAAO,QAAQ;AACf,SAAS,oBAAoB;AAC7B,SAAS,MAAM,cAAc;AA4K7B,IAAM,qBAAqB;AAC3B,IAAM,+BAA+B;AAiC9B,IAAM,qBAAqB,MAAgB;AAChD,SAAO;AAAA,IACL,iBAAiB,CAAC;AAAA,IAClB,SAAS,CAAC;AAAA,IACV,aAAa,CAAC;AAAA,EAChB;AACF;AAKO,IAAM,gBAAN,cAA4B,iBAAsC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA2tBvE,YACE;AAAA,IACE,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAwBA,QACA,OACA;AACA,UAAM,QAAQ,KAAK;AAnwBrB,SAAiB,QAAQ,IAAI,MAAM;AAoqBnC;AAAA;AAAA;AAAA,eAAM,IAAI,aAAa;AAUvB;AAAA;AAAA;AAA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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","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';\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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/TokenRatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,yCAAyC;AAElD,SAAS,6BAAuC;AAChD,SAAS,eAAe;AAoHxB,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;AA3JA;AAiKO,IAAM,uBAAN,cAAmC,kCAGxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAiCA,YACE;AAAA,IACE,WAAW,IAAI,KAAK;AAAA,IACpB,YAAY,IAAI,KAAK,KAAK;AAAA,IAC1B;AAAA,IACA,SAAS;AAAA,IACT,QAAQ;AAAA,IACR,iBAAiB;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAkBA,QACA,OACA;AACA,UAAM,QAAQ,KAAK;AAwErB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmCA;AAAA;AAAA;AAAA;AASA;AAAA;AAAA;AAAA,uBAAM;AAsGN;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,uBAAM;AA2DN;AAAA;AAA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C3B,CAAC,YAAY,GAAG;AAAA,QACd,UAAU;AAAA,QACV,GAAG,iCAAiC,YAAY;AAAA,MAClD;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,QAAQ,0BAA0B,EAAE;AAAA,IAChD,CAAC,KAAK,CAAC,cAAc,KAAK,MAAM;AAC9B,YAAM;AAAA,QACJ,GAAG;AAAA,QACH,CAAC,aAAa,YAAY,CAAC,GAAG,EAAE,GAAG,MAAM;AAAA,MAC3C;AAEA,aAAO;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EACH;AACF;AAcM;AAAA,0DAAqD,eAAC;AAAA,EAC1D;AAAA,EACA;AACF,GAGgC;AAC9B,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,EACF,IAAI,MAAM,QAAQ,IAAI;AAAA,IACpB,sBAAK,4GAAL,WAAyD;AAAA,MACvD;AAAA,MACA,SAAS,KAAK,OAAO;AAAA,MACrB,gBAAgB;AAAA,IAClB;AAAA,IACA,0BAA0B;AAAA,MACxB,MAAM;AAAA,MACN,IAAI;AAAA,IACN,CAAC;AAAA,EACH,CAAC;AAED,MAAI,mDAAmD,MAAM;AAC3D,WAAO,CAAC;AAAA,EACV;AAEA,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","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 { TokensState } 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// 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 Token {\n address: string;\n decimals: number;\n symbol: string;\n aggregators?: string[];\n image?: string;\n balanceError?: unknown;\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';\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: TokensState) => 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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/TokensController.ts"],"sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type {\n BaseConfig,\n BaseState,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport { BaseControllerV1 } from '@metamask/base-controller';\nimport contractsMap from '@metamask/contract-metadata';\nimport {\n toChecksumHexAddress,\n ERC721_INTERFACE_ID,\n ORIGIN_METAMASK,\n ApprovalType,\n ERC20,\n ERC721,\n ERC1155,\n isValidHexAddress,\n safelyExecute,\n} from '@metamask/controller-utils';\nimport { abiERC721 } from '@metamask/metamask-eth-abis';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerNetworkDidChangeEvent,\n Provider,\n} from '@metamask/network-controller';\nimport type { PreferencesControllerStateChangeEvent } from '@metamask/preferences-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport { EventEmitter } from 'events';\nimport type { Patch } from 'immer/dist/immer';\nimport { v1 as random } from 'uuid';\n\nimport { formatAggregatorNames, formatIconUrlWithProxy } from './assetsUtil';\nimport { ERC20Standard } from './Standards/ERC20Standard';\nimport { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';\nimport {\n fetchTokenMetadata,\n TOKEN_METADATA_NO_SUPPORT_ERROR,\n} from './token-service';\nimport type {\n TokenListMap,\n TokenListStateChange,\n TokenListToken,\n} from './TokenListController';\nimport type { Token } from './TokenRatesController';\n\n/**\n * @type TokensConfig\n *\n * Tokens controller configuration\n * @property selectedAddress - Vault selected 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 TokensConfig extends BaseConfig {\n selectedAddress: string;\n chainId: Hex;\n provider: Provider | undefined;\n}\n\n/**\n * @type SuggestedAssetMeta\n *\n * Suggested asset by EIP747 meta data\n * @property id - Generated UUID associated with this suggested asset\n * @property time - Timestamp associated with this this suggested asset\n * @property type - Type type this suggested asset\n * @property asset - Asset suggested object\n * @property interactingAddress - Account address that requested watch asset\n */\ntype SuggestedAssetMeta = {\n id: string;\n time: number;\n type: string;\n asset: Token;\n interactingAddress: string;\n};\n\n/**\n * @type TokensState\n *\n * Assets controller state\n * @property tokens - List of tokens associated with the active network and address pair\n * @property ignoredTokens - List of ignoredTokens associated with the active network and address pair\n * @property detectedTokens - List of detected tokens associated with the active network and address pair\n * @property allTokens - Object containing tokens by network and account\n * @property allIgnoredTokens - Object containing hidden/ignored tokens by network and account\n * @property allDetectedTokens - Object containing tokens detected with non-zero balances\n */\nexport type TokensState = {\n tokens: Token[];\n ignoredTokens: string[];\n detectedTokens: Token[];\n allTokens: { [chainId: Hex]: { [key: string]: Token[] } };\n allIgnoredTokens: { [chainId: Hex]: { [key: string]: string[] } };\n allDetectedTokens: { [chainId: Hex]: { [key: string]: Token[] } };\n};\n\n/**\n * The name of the {@link TokensController}.\n */\nconst controllerName = 'TokensController';\n\nexport type TokensControllerActions =\n | TokensControllerGetStateAction\n | TokensControllerAddDetectedTokensAction;\n\n// TODO: Once `TokensController` is upgraded to V2, rewrite this type using the `ControllerGetStateAction` type, which constrains `TokensState` as `Record<string, Json>`.\nexport type TokensControllerGetStateAction = {\n type: `${typeof controllerName}:getState`;\n handler: () => TokensState;\n};\n\nexport type TokensControllerAddDetectedTokensAction = {\n type: `${typeof controllerName}:addDetectedTokens`;\n handler: TokensController['addDetectedTokens'];\n};\n\n/**\n * The external actions available to the {@link TokensController}.\n */\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetNetworkClientByIdAction;\n\n// TODO: Once `TokensController` is upgraded to V2, rewrite this type using the `ControllerStateChangeEvent` type, which constrains `TokensState` as `Record<string, Json>`.\nexport type TokensControllerStateChangeEvent = {\n type: `${typeof controllerName}:stateChange`;\n payload: [TokensState, Patch[]];\n};\n\nexport type TokensControllerEvents = TokensControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | NetworkControllerNetworkDidChangeEvent\n | PreferencesControllerStateChangeEvent\n | TokenListStateChange;\n\n/**\n * The messenger of the {@link TokensController}.\n */\nexport type TokensControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokensControllerActions | AllowedActions,\n TokensControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const getDefaultTokensState = (): TokensState => {\n return {\n tokens: [],\n ignoredTokens: [],\n detectedTokens: [],\n allTokens: {},\n allIgnoredTokens: {},\n allDetectedTokens: {},\n };\n};\n\n/**\n * Controller that stores assets and exposes convenience methods\n */\nexport class TokensController extends BaseControllerV1<\n TokensConfig,\n TokensState & BaseState\n> {\n private readonly mutex = new Mutex();\n\n private abortController: AbortController;\n\n private readonly messagingSystem: TokensControllerMessenger;\n\n /**\n * Fetch metadata for a token.\n *\n * @param tokenAddress - The address of the token.\n * @returns The token metadata.\n */\n private async fetchTokenMetadata(\n tokenAddress: string,\n ): Promise<TokenListToken | undefined> {\n try {\n const token = await fetchTokenMetadata<TokenListToken>(\n this.config.chainId,\n tokenAddress,\n this.abortController.signal,\n );\n return token;\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes(TOKEN_METADATA_NO_SUPPORT_ERROR)\n ) {\n return undefined;\n }\n throw error;\n }\n }\n\n /**\n * EventEmitter instance used to listen to specific EIP747 events\n */\n hub = new EventEmitter();\n\n /**\n * Name of this controller used during composition\n */\n override name = 'TokensController';\n\n /**\n * Creates a TokensController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.config - Initial options used to configure this controller.\n * @param options.state - Initial state to set on this controller.\n * @param options.messenger - The controller messenger.\n */\n constructor({\n chainId: initialChainId,\n config,\n state,\n messenger,\n }: {\n chainId: Hex;\n config?: Partial<TokensConfig>;\n state?: Partial<TokensState>;\n messenger: TokensControllerMessenger;\n }) {\n super(config, state);\n\n this.defaultConfig = {\n selectedAddress: '',\n chainId: initialChainId,\n provider: undefined,\n ...config,\n };\n\n this.defaultState = {\n ...getDefaultTokensState(),\n ...state,\n };\n\n this.initialize();\n this.abortController = new AbortController();\n\n this.messagingSystem = messenger;\n\n this.messagingSystem.registerActionHandler(\n `${controllerName}:addDetectedTokens` as const,\n this.addDetectedTokens.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n ({ selectedAddress }) => {\n const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;\n const { chainId } = this.config;\n this.configure({ selectedAddress });\n this.update({\n tokens: allTokens[chainId]?.[selectedAddress] ?? [],\n ignoredTokens: allIgnoredTokens[chainId]?.[selectedAddress] ?? [],\n detectedTokens: allDetectedTokens[chainId]?.[selectedAddress] ?? [],\n });\n },\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n ({ providerConfig }) => {\n const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;\n const { selectedAddress } = this.config;\n const { chainId } = providerConfig;\n this.abortController.abort();\n this.abortController = new AbortController();\n this.configure({ chainId });\n this.update({\n tokens: allTokens[chainId]?.[selectedAddress] || [],\n ignoredTokens: allIgnoredTokens[chainId]?.[selectedAddress] || [],\n detectedTokens: allDetectedTokens[chainId]?.[selectedAddress] || [],\n });\n },\n );\n\n this.messagingSystem.subscribe(\n 'TokenListController:stateChange',\n ({ tokenList }) => {\n const { tokens } = this.state;\n if (tokens.length && !tokens[0].name) {\n this.updateTokensAttribute(tokenList, 'name');\n }\n },\n );\n }\n\n /**\n * Adds a token to the stored token list.\n *\n * @param options - The method argument object.\n * @param options.address - Hex address of the token contract.\n * @param options.symbol - Symbol of the token.\n * @param options.decimals - Number of decimals the token uses.\n * @param options.name - Name of the token.\n * @param options.image - Image of the token.\n * @param options.interactingAddress - The address of the account to add a token to.\n * @param options.networkClientId - Network Client ID.\n * @returns Current token list.\n */\n async addToken({\n address,\n symbol,\n decimals,\n name,\n image,\n interactingAddress,\n networkClientId,\n }: {\n address: string;\n symbol: string;\n decimals: number;\n name?: string;\n image?: string;\n interactingAddress?: string;\n networkClientId?: NetworkClientId;\n }): Promise<Token[]> {\n const { chainId, selectedAddress } = this.config;\n const releaseLock = await this.mutex.acquire();\n const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;\n let currentChainId = chainId;\n if (networkClientId) {\n currentChainId = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n ).configuration.chainId;\n }\n\n const accountAddress = interactingAddress || selectedAddress;\n const isInteractingWithWalletAccount = accountAddress === selectedAddress;\n\n try {\n address = toChecksumHexAddress(address);\n const tokens = allTokens[currentChainId]?.[accountAddress] || [];\n const ignoredTokens =\n allIgnoredTokens[currentChainId]?.[accountAddress] || [];\n const detectedTokens =\n allDetectedTokens[currentChainId]?.[accountAddress] || [];\n const newTokens: Token[] = [...tokens];\n const [isERC721, tokenMetadata] = await Promise.all([\n this._detectIsERC721(address, networkClientId),\n // TODO parameterize the token metadata fetch by networkClientId\n this.fetchTokenMetadata(address),\n ]);\n // TODO remove this once this method is fully parameterized by networkClientId\n if (!networkClientId && currentChainId !== this.config.chainId) {\n throw new Error(\n 'TokensController Error: Switched networks while adding token',\n );\n }\n const newEntry: Token = {\n address,\n symbol,\n decimals,\n image:\n image ||\n formatIconUrlWithProxy({\n chainId: currentChainId,\n tokenAddress: address,\n }),\n isERC721,\n aggregators: formatAggregatorNames(tokenMetadata?.aggregators || []),\n name,\n };\n const previousIndex = newTokens.findIndex(\n (token) => token.address.toLowerCase() === address.toLowerCase(),\n );\n if (previousIndex !== -1) {\n newTokens[previousIndex] = newEntry;\n } else {\n newTokens.push(newEntry);\n }\n\n const newIgnoredTokens = ignoredTokens.filter(\n (tokenAddress) => tokenAddress.toLowerCase() !== address.toLowerCase(),\n );\n const newDetectedTokens = detectedTokens.filter(\n (token) => token.address.toLowerCase() !== address.toLowerCase(),\n );\n\n const { newAllTokens, newAllIgnoredTokens, newAllDetectedTokens } =\n this._getNewAllTokensState({\n newTokens,\n newIgnoredTokens,\n newDetectedTokens,\n interactingAddress: accountAddress,\n interactingChainId: currentChainId,\n });\n\n let newState: Partial<TokensState> = {\n allTokens: newAllTokens,\n allIgnoredTokens: newAllIgnoredTokens,\n allDetectedTokens: newAllDetectedTokens,\n };\n\n // Only update active tokens if user is interacting with their active wallet account.\n if (isInteractingWithWalletAccount) {\n newState = {\n ...newState,\n tokens: newTokens,\n ignoredTokens: newIgnoredTokens,\n detectedTokens: newDetectedTokens,\n };\n }\n\n this.update(newState);\n return newTokens;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Add a batch of tokens.\n *\n * @param tokensToImport - Array of tokens to import.\n * @param networkClientId - Optional network client ID used to determine interacting chain ID.\n */\n async addTokens(tokensToImport: Token[], networkClientId?: NetworkClientId) {\n const releaseLock = await this.mutex.acquire();\n const { tokens, detectedTokens, ignoredTokens } = this.state;\n const importedTokensMap: { [key: string]: true } = {};\n // Used later to dedupe imported tokens\n const newTokensMap = tokens.reduce((output, current) => {\n output[current.address] = current;\n return output;\n }, {} as { [address: string]: Token });\n try {\n tokensToImport.forEach((tokenToAdd) => {\n const { address, symbol, decimals, image, aggregators, name } =\n tokenToAdd;\n const checksumAddress = toChecksumHexAddress(address);\n const formattedToken: Token = {\n address: checksumAddress,\n symbol,\n decimals,\n image,\n aggregators,\n name,\n };\n newTokensMap[address] = formattedToken;\n importedTokensMap[address.toLowerCase()] = true;\n return formattedToken;\n });\n const newTokens = Object.values(newTokensMap);\n\n const newDetectedTokens = detectedTokens.filter(\n (token) => !importedTokensMap[token.address.toLowerCase()],\n );\n const newIgnoredTokens = ignoredTokens.filter(\n (tokenAddress) => !newTokensMap[tokenAddress.toLowerCase()],\n );\n\n let interactingChainId;\n if (networkClientId) {\n interactingChainId = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n ).configuration.chainId;\n }\n\n const { newAllTokens, newAllDetectedTokens, newAllIgnoredTokens } =\n this._getNewAllTokensState({\n newTokens,\n newDetectedTokens,\n newIgnoredTokens,\n interactingChainId,\n });\n\n this.update({\n tokens: newTokens,\n allTokens: newAllTokens,\n detectedTokens: newDetectedTokens,\n allDetectedTokens: newAllDetectedTokens,\n ignoredTokens: newIgnoredTokens,\n allIgnoredTokens: newAllIgnoredTokens,\n });\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Ignore a batch of tokens.\n *\n * @param tokenAddressesToIgnore - Array of token addresses to ignore.\n */\n ignoreTokens(tokenAddressesToIgnore: string[]) {\n const { ignoredTokens, detectedTokens, tokens } = this.state;\n const ignoredTokensMap: { [key: string]: true } = {};\n let newIgnoredTokens: string[] = [...ignoredTokens];\n\n const checksummedTokenAddresses = tokenAddressesToIgnore.map((address) => {\n const checksumAddress = toChecksumHexAddress(address);\n ignoredTokensMap[address.toLowerCase()] = true;\n return checksumAddress;\n });\n newIgnoredTokens = [...ignoredTokens, ...checksummedTokenAddresses];\n const newDetectedTokens = detectedTokens.filter(\n (token) => !ignoredTokensMap[token.address.toLowerCase()],\n );\n const newTokens = tokens.filter(\n (token) => !ignoredTokensMap[token.address.toLowerCase()],\n );\n\n const { newAllIgnoredTokens, newAllDetectedTokens, newAllTokens } =\n this._getNewAllTokensState({\n newIgnoredTokens,\n newDetectedTokens,\n newTokens,\n });\n\n this.update({\n ignoredTokens: newIgnoredTokens,\n tokens: newTokens,\n detectedTokens: newDetectedTokens,\n allIgnoredTokens: newAllIgnoredTokens,\n allDetectedTokens: newAllDetectedTokens,\n allTokens: newAllTokens,\n });\n }\n\n /**\n * Adds a batch of detected tokens to the stored token list.\n *\n * @param incomingDetectedTokens - Array of detected tokens to be added or updated.\n * @param detectionDetails - An object containing the chain ID and address of the currently selected network on which the incomingDetectedTokens were detected.\n * @param detectionDetails.selectedAddress - the account address on which the incomingDetectedTokens were detected.\n * @param detectionDetails.chainId - the chainId on which the incomingDetectedTokens were detected.\n */\n async addDetectedTokens(\n incomingDetectedTokens: Token[],\n detectionDetails?: { selectedAddress: string; chainId: Hex },\n ) {\n const releaseLock = await this.mutex.acquire();\n\n // Get existing tokens for the chain + account\n const chainId = detectionDetails?.chainId ?? this.config.chainId;\n const accountAddress =\n detectionDetails?.selectedAddress ?? this.config.selectedAddress;\n\n const { allTokens, allDetectedTokens, allIgnoredTokens } = this.state;\n let newTokens = [...(allTokens?.[chainId]?.[accountAddress] ?? [])];\n let newDetectedTokens = [\n ...(allDetectedTokens?.[chainId]?.[accountAddress] ?? []),\n ];\n\n try {\n incomingDetectedTokens.forEach((tokenToAdd) => {\n const {\n address,\n symbol,\n decimals,\n image,\n aggregators,\n isERC721,\n name,\n } = tokenToAdd;\n const checksumAddress = toChecksumHexAddress(address);\n const newEntry: Token = {\n address: checksumAddress,\n symbol,\n decimals,\n image,\n isERC721,\n aggregators,\n name,\n };\n const previousImportedIndex = newTokens.findIndex(\n (token) =>\n token.address.toLowerCase() === checksumAddress.toLowerCase(),\n );\n if (previousImportedIndex !== -1) {\n // Update existing data of imported token\n newTokens[previousImportedIndex] = newEntry;\n } else {\n const ignoredTokenIndex =\n allIgnoredTokens?.[chainId]?.[accountAddress]?.indexOf(address) ??\n -1;\n\n if (ignoredTokenIndex === -1) {\n // Add detected token\n const previousDetectedIndex = newDetectedTokens.findIndex(\n (token) =>\n token.address.toLowerCase() === checksumAddress.toLowerCase(),\n );\n if (previousDetectedIndex !== -1) {\n newDetectedTokens[previousDetectedIndex] = newEntry;\n } else {\n newDetectedTokens.push(newEntry);\n }\n }\n }\n });\n\n const { newAllTokens, newAllDetectedTokens } = this._getNewAllTokensState(\n {\n newTokens,\n newDetectedTokens,\n interactingAddress: accountAddress,\n interactingChainId: chainId,\n },\n );\n\n // We may be detecting tokens on a different chain/account pair than are currently configured.\n // Re-point `tokens` and `detectedTokens` to keep them referencing the current chain/account.\n const { chainId: currentChain, selectedAddress: currentAddress } =\n this.config;\n\n newTokens = newAllTokens?.[currentChain]?.[currentAddress] || [];\n newDetectedTokens =\n newAllDetectedTokens?.[currentChain]?.[currentAddress] || [];\n\n this.update({\n tokens: newTokens,\n allTokens: newAllTokens,\n detectedTokens: newDetectedTokens,\n allDetectedTokens: newAllDetectedTokens,\n });\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Adds isERC721 field to token object. This is called when a user attempts to add tokens that\n * were previously added which do not yet had isERC721 field.\n *\n * @param tokenAddress - The contract address of the token requiring the isERC721 field added.\n * @returns The new token object with the added isERC721 field.\n */\n async updateTokenType(tokenAddress: string) {\n const isERC721 = await this._detectIsERC721(tokenAddress);\n const { tokens } = this.state;\n const tokenIndex = tokens.findIndex((token) => {\n return token.address.toLowerCase() === tokenAddress.toLowerCase();\n });\n tokens[tokenIndex].isERC721 = isERC721;\n this.update({ tokens });\n return tokens[tokenIndex];\n }\n\n /**\n * This is a function that updates the tokens name for the tokens name if it is not defined.\n *\n * @param tokenList - Represents the fetched token list from service API\n * @param tokenAttribute - Represents the token attribute that we want to update on the token list\n */\n private updateTokensAttribute(\n tokenList: TokenListMap,\n tokenAttribute: keyof Token & keyof TokenListToken,\n ) {\n const { tokens } = this.state;\n\n const newTokens = tokens.map((token) => {\n const newToken = tokenList[token.address.toLowerCase()];\n\n return !token[tokenAttribute] && newToken?.[tokenAttribute]\n ? { ...token, [tokenAttribute]: newToken[tokenAttribute] }\n : { ...token };\n });\n\n this.update({ tokens: newTokens });\n }\n\n /**\n * Detects whether or not a token is ERC-721 compatible.\n *\n * @param tokenAddress - The token contract address.\n * @param networkClientId - Optional network client ID to fetch contract info with.\n * @returns A boolean indicating whether the token address passed in supports the EIP-721\n * interface.\n */\n async _detectIsERC721(\n tokenAddress: string,\n networkClientId?: NetworkClientId,\n ) {\n const checksumAddress = toChecksumHexAddress(tokenAddress);\n // if this token is already in our contract metadata map we don't need\n // to check against the contract\n if (contractsMap[checksumAddress]?.erc721 === true) {\n return Promise.resolve(true);\n } else if (contractsMap[checksumAddress]?.erc20 === true) {\n return Promise.resolve(false);\n }\n\n const tokenContract = this._createEthersContract(\n tokenAddress,\n abiERC721,\n networkClientId,\n );\n try {\n return await tokenContract.supportsInterface(ERC721_INTERFACE_ID);\n } catch (error) {\n // currently we see a variety of errors across different networks when\n // token contracts are not ERC721 compatible. We need to figure out a better\n // way of differentiating token interface types but for now if we get an error\n // we have to assume the token is not ERC721 compatible.\n return false;\n }\n }\n\n _getProvider(networkClientId?: NetworkClientId): Web3Provider {\n return new Web3Provider(\n // @ts-expect-error TODO: remove this annotation once the `Eip1193Provider` class is released\n networkClientId\n ? this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n ).provider\n : this.config.provider,\n );\n }\n\n _createEthersContract(\n tokenAddress: string,\n abi: string,\n networkClientId?: NetworkClientId,\n ): Contract {\n const web3provider = this._getProvider(networkClientId);\n const tokenContract = new Contract(tokenAddress, abi, web3provider);\n return tokenContract;\n }\n\n _generateRandomId(): string {\n return random();\n }\n\n /**\n * Adds a new suggestedAsset to the list of watched assets.\n * Parameters will be validated according to the asset type being watched.\n *\n * @param options - The method options.\n * @param options.asset - The asset to be watched. For now only ERC20 tokens are accepted.\n * @param options.type - The asset type.\n * @param options.interactingAddress - The address of the account that is requesting to watch the asset.\n * @param options.networkClientId - Network Client ID.\n * @returns A promise that resolves if the asset was watched successfully, and rejects otherwise.\n */\n async watchAsset({\n asset,\n type,\n interactingAddress,\n networkClientId,\n }: {\n asset: Token;\n type: string;\n interactingAddress?: string;\n networkClientId?: NetworkClientId;\n }): Promise<void> {\n if (type !== ERC20) {\n throw new Error(`Asset of type ${type} not supported`);\n }\n\n if (!asset.address) {\n throw rpcErrors.invalidParams('Address must be specified');\n }\n\n if (!isValidHexAddress(asset.address)) {\n throw rpcErrors.invalidParams(`Invalid address \"${asset.address}\"`);\n }\n\n // Validate contract\n\n if (await this._detectIsERC721(asset.address, networkClientId)) {\n throw rpcErrors.invalidParams(\n `Contract ${asset.address} must match type ${type}, but was detected as ${ERC721}`,\n );\n }\n\n const provider = this._getProvider(networkClientId);\n const isErc1155 = await safelyExecute(() =>\n new ERC1155Standard(provider).contractSupportsBase1155Interface(\n asset.address,\n ),\n );\n if (isErc1155) {\n throw rpcErrors.invalidParams(\n `Contract ${asset.address} must match type ${type}, but was detected as ${ERC1155}`,\n );\n }\n\n const erc20 = new ERC20Standard(provider);\n const [contractName, contractSymbol, contractDecimals] = await Promise.all([\n safelyExecute(() => erc20.getTokenName(asset.address)),\n safelyExecute(() => erc20.getTokenSymbol(asset.address)),\n safelyExecute(async () => erc20.getTokenDecimals(asset.address)),\n ]);\n\n asset.name = contractName;\n\n // Validate symbol\n\n if (!asset.symbol && !contractSymbol) {\n throw rpcErrors.invalidParams(\n 'A symbol is required, but was not found in either the request or contract',\n );\n }\n\n if (\n contractSymbol !== undefined &&\n asset.symbol !== undefined &&\n asset.symbol.toUpperCase() !== contractSymbol.toUpperCase()\n ) {\n throw rpcErrors.invalidParams(\n `The symbol in the request (${asset.symbol}) does not match the symbol in the contract (${contractSymbol})`,\n );\n }\n\n asset.symbol = contractSymbol ?? asset.symbol;\n if (typeof asset.symbol !== 'string') {\n throw rpcErrors.invalidParams(`Invalid symbol: not a string`);\n }\n\n if (asset.symbol.length > 11) {\n throw rpcErrors.invalidParams(\n `Invalid symbol \"${asset.symbol}\": longer than 11 characters`,\n );\n }\n\n // Validate decimals\n\n if (asset.decimals === undefined && contractDecimals === undefined) {\n throw rpcErrors.invalidParams(\n 'Decimals are required, but were not found in either the request or contract',\n );\n }\n\n if (\n contractDecimals !== undefined &&\n asset.decimals !== undefined &&\n String(asset.decimals) !== contractDecimals\n ) {\n throw rpcErrors.invalidParams(\n `The decimals in the request (${asset.decimals}) do not match the decimals in the contract (${contractDecimals})`,\n );\n }\n\n const decimalsStr = contractDecimals ?? asset.decimals;\n const decimalsNum = parseInt(decimalsStr as unknown as string, 10);\n if (!Number.isInteger(decimalsNum) || decimalsNum > 36 || decimalsNum < 0) {\n throw rpcErrors.invalidParams(\n `Invalid decimals \"${decimalsStr}\": must be an integer 0 <= 36`,\n );\n }\n asset.decimals = decimalsNum;\n\n const suggestedAssetMeta: SuggestedAssetMeta = {\n asset,\n id: this._generateRandomId(),\n time: Date.now(),\n type,\n interactingAddress: interactingAddress || this.config.selectedAddress,\n };\n\n await this._requestApproval(suggestedAssetMeta);\n\n const { address, symbol, decimals, name, image } = asset;\n await this.addToken({\n address,\n symbol,\n decimals,\n name,\n image,\n interactingAddress: suggestedAssetMeta.interactingAddress,\n networkClientId,\n });\n }\n\n /**\n * Takes a new tokens and ignoredTokens array for the current network/account combination\n * and returns new allTokens and allIgnoredTokens state to update to.\n *\n * @param params - Object that holds token params.\n * @param params.newTokens - The new tokens to set for the current network and selected account.\n * @param params.newIgnoredTokens - The new ignored tokens to set for the current network and selected account.\n * @param params.newDetectedTokens - The new detected tokens to set for the current network and selected account.\n * @param params.interactingAddress - The account address to use to store the tokens.\n * @param params.interactingChainId - The chainId to use to store the tokens.\n * @returns The updated `allTokens` and `allIgnoredTokens` state.\n */\n _getNewAllTokensState(params: {\n newTokens?: Token[];\n newIgnoredTokens?: string[];\n newDetectedTokens?: Token[];\n interactingAddress?: string;\n interactingChainId?: Hex;\n }) {\n const {\n newTokens,\n newIgnoredTokens,\n newDetectedTokens,\n interactingAddress,\n interactingChainId,\n } = params;\n const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;\n const { chainId, selectedAddress } = this.config;\n\n const userAddressToAddTokens = interactingAddress ?? selectedAddress;\n const chainIdToAddTokens = interactingChainId ?? chainId;\n\n let newAllTokens = allTokens;\n if (\n newTokens?.length ||\n (newTokens &&\n allTokens &&\n allTokens[chainIdToAddTokens] &&\n allTokens[chainIdToAddTokens][userAddressToAddTokens])\n ) {\n const networkTokens = allTokens[chainIdToAddTokens];\n const newNetworkTokens = {\n ...networkTokens,\n ...{ [userAddressToAddTokens]: newTokens },\n };\n newAllTokens = {\n ...allTokens,\n ...{ [chainIdToAddTokens]: newNetworkTokens },\n };\n }\n\n let newAllIgnoredTokens = allIgnoredTokens;\n if (\n newIgnoredTokens?.length ||\n (newIgnoredTokens &&\n allIgnoredTokens &&\n allIgnoredTokens[chainIdToAddTokens] &&\n allIgnoredTokens[chainIdToAddTokens][userAddressToAddTokens])\n ) {\n const networkIgnoredTokens = allIgnoredTokens[chainIdToAddTokens];\n const newIgnoredNetworkTokens = {\n ...networkIgnoredTokens,\n ...{ [userAddressToAddTokens]: newIgnoredTokens },\n };\n newAllIgnoredTokens = {\n ...allIgnoredTokens,\n ...{ [chainIdToAddTokens]: newIgnoredNetworkTokens },\n };\n }\n\n let newAllDetectedTokens = allDetectedTokens;\n if (\n newDetectedTokens?.length ||\n (newDetectedTokens &&\n allDetectedTokens &&\n allDetectedTokens[chainIdToAddTokens] &&\n allDetectedTokens[chainIdToAddTokens][userAddressToAddTokens])\n ) {\n const networkDetectedTokens = allDetectedTokens[chainIdToAddTokens];\n const newDetectedNetworkTokens = {\n ...networkDetectedTokens,\n ...{ [userAddressToAddTokens]: newDetectedTokens },\n };\n newAllDetectedTokens = {\n ...allDetectedTokens,\n ...{ [chainIdToAddTokens]: newDetectedNetworkTokens },\n };\n }\n return { newAllTokens, newAllIgnoredTokens, newAllDetectedTokens };\n }\n\n /**\n * Removes all tokens from the ignored list.\n */\n clearIgnoredTokens() {\n this.update({ ignoredTokens: [], allIgnoredTokens: {} });\n }\n\n async _requestApproval(suggestedAssetMeta: SuggestedAssetMeta) {\n return this.messagingSystem.call(\n 'ApprovalController:addRequest',\n {\n id: suggestedAssetMeta.id,\n origin: ORIGIN_METAMASK,\n type: ApprovalType.WatchAsset,\n requestData: {\n id: suggestedAssetMeta.id,\n interactingAddress: suggestedAssetMeta.interactingAddress,\n asset: {\n address: suggestedAssetMeta.asset.address,\n decimals: suggestedAssetMeta.asset.decimals,\n symbol: suggestedAssetMeta.asset.symbol,\n image: suggestedAssetMeta.asset.image || null,\n },\n },\n },\n true,\n );\n }\n}\n\nexport default TokensController;\n"],"mappings":";;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,oBAAoB;AAO7B,SAAS,wBAAwB;AACjC,OAAO,kBAAkB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB;AAQ1B,SAAS,iBAAiB;AAE1B,SAAS,aAAa;AACtB,SAAS,oBAAoB;AAE7B,SAAS,MAAM,cAAc;AAwE7B,IAAM,iBAAiB;AAgDhB,IAAM,wBAAwB,MAAmB;AACtD,SAAO;AAAA,IACL,QAAQ,CAAC;AAAA,IACT,eAAe,CAAC;AAAA,IAChB,gBAAgB,CAAC;AAAA,IACjB,WAAW,CAAC;AAAA,IACZ,kBAAkB,CAAC;AAAA,IACnB,mBAAmB,CAAC;AAAA,EACtB;AACF;AAKO,IAAM,mBAAN,cAA+B,iBAGpC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqDA,YAAY;AAAA,IACV,SAAS;AAAA,IACT;AAAA,IACA;AAAA,IACA;AAAA,EACF,GAKG;AACD,UAAM,QAAQ,KAAK;AA/DrB,SAA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