@metamask/assets-controllers 33.0.0 → 35.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -1
- package/dist/AccountTrackerController.js +2 -2
- package/dist/AccountTrackerController.mjs +1 -1
- package/dist/AssetsContractController.js +2 -2
- package/dist/AssetsContractController.mjs +1 -1
- package/dist/NftController.js +2 -2
- package/dist/NftController.mjs +1 -1
- package/dist/TokenBalancesController.js +2 -2
- package/dist/TokenBalancesController.mjs +1 -1
- package/dist/TokenDetectionController.js +2 -2
- package/dist/TokenDetectionController.mjs +1 -1
- package/dist/TokenRatesController.js +2 -2
- package/dist/TokenRatesController.mjs +1 -1
- package/dist/TokensController.js +2 -2
- package/dist/TokensController.mjs +1 -1
- package/dist/{chunk-RJBYLTY5.js → chunk-2NQRWANM.js} +57 -30
- package/dist/chunk-2NQRWANM.js.map +1 -0
- package/dist/{chunk-3K3LE2CZ.mjs → chunk-2TSAUGE7.mjs} +30 -19
- package/dist/chunk-2TSAUGE7.mjs.map +1 -0
- package/dist/{chunk-7JWDWDXT.js → chunk-3GGCHDRG.js} +11 -1
- package/dist/chunk-3GGCHDRG.js.map +1 -0
- package/dist/{chunk-UVE4XY5Y.mjs → chunk-4JLB5OIJ.mjs} +57 -30
- package/dist/chunk-4JLB5OIJ.mjs.map +1 -0
- package/dist/{chunk-OEEFNXR7.mjs → chunk-6VQJFTNC.mjs} +4 -4
- package/dist/chunk-6VQJFTNC.mjs.map +1 -0
- package/dist/{chunk-VZF43NDM.js → chunk-GHKGU6GK.js} +30 -19
- package/dist/chunk-GHKGU6GK.js.map +1 -0
- package/dist/{chunk-P3O5CVAH.mjs → chunk-GJCTAKK5.mjs} +36 -34
- package/dist/chunk-GJCTAKK5.mjs.map +1 -0
- package/dist/chunk-HVOIBGYN.js +282 -0
- package/dist/chunk-HVOIBGYN.js.map +1 -0
- package/dist/{chunk-NWVMFCSC.js → chunk-NHFZIY2K.js} +4 -4
- package/dist/chunk-NHFZIY2K.js.map +1 -0
- package/dist/{chunk-TWR6P5WG.mjs → chunk-OMNBGY7O.mjs} +1 -1
- package/dist/chunk-OMNBGY7O.mjs.map +1 -0
- package/dist/{chunk-XSNGD5US.js → chunk-RIMQ5DR3.js} +1 -1
- package/dist/{chunk-XSNGD5US.js.map → chunk-RIMQ5DR3.js.map} +1 -1
- package/dist/{chunk-FGAZXVKS.js → chunk-RPQ737HL.js} +36 -34
- package/dist/chunk-RPQ737HL.js.map +1 -0
- package/dist/chunk-Z7RMCHD4.mjs +282 -0
- package/dist/chunk-Z7RMCHD4.mjs.map +1 -0
- package/dist/{chunk-W57QXOHJ.mjs → chunk-ZX5G3X74.mjs} +11 -1
- package/dist/chunk-ZX5G3X74.mjs.map +1 -0
- package/dist/index.js +8 -8
- package/dist/index.mjs +7 -7
- package/dist/tsconfig.build.tsbuildinfo +1 -1
- package/dist/types/AccountTrackerController.d.ts +50 -66
- package/dist/types/AccountTrackerController.d.ts.map +1 -1
- package/dist/types/AssetsContractController.d.ts.map +1 -1
- package/dist/types/NftController.d.ts.map +1 -1
- package/dist/types/TokenBalancesController.d.ts +2 -2
- package/dist/types/TokenBalancesController.d.ts.map +1 -1
- package/dist/types/TokenDetectionController.d.ts +4 -6
- package/dist/types/TokenDetectionController.d.ts.map +1 -1
- package/dist/types/TokenRatesController.d.ts +3 -3
- package/dist/types/TokenRatesController.d.ts.map +1 -1
- package/dist/types/TokensController.d.ts +4 -6
- package/dist/types/TokensController.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -1
- package/dist/types/index.d.ts.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-3K3LE2CZ.mjs.map +0 -1
- package/dist/chunk-526TATMH.mjs +0 -254
- package/dist/chunk-526TATMH.mjs.map +0 -1
- package/dist/chunk-7JWDWDXT.js.map +0 -1
- package/dist/chunk-AZ6SRJVI.js +0 -254
- package/dist/chunk-AZ6SRJVI.js.map +0 -1
- package/dist/chunk-FGAZXVKS.js.map +0 -1
- package/dist/chunk-NWVMFCSC.js.map +0 -1
- package/dist/chunk-OEEFNXR7.mjs.map +0 -1
- package/dist/chunk-P3O5CVAH.mjs.map +0 -1
- package/dist/chunk-RJBYLTY5.js.map +0 -1
- package/dist/chunk-TWR6P5WG.mjs.map +0 -1
- package/dist/chunk-UVE4XY5Y.mjs.map +0 -1
- package/dist/chunk-VZF43NDM.js.map +0 -1
- package/dist/chunk-W57QXOHJ.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/AssetsContractController.ts"],"sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider } from '@ethersproject/providers';\nimport type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { BaseControllerV1 } from '@metamask/base-controller';\nimport { IPFS_DEFAULT_GATEWAY_URL } from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkState,\n NetworkController,\n Provider,\n} from '@metamask/network-controller';\nimport type { PreferencesState } from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\nimport abiSingleCallBalancesContract from 'single-call-balance-checker-abi';\n\nimport { SupportedTokenDetectionNetworks } from './assetsUtil';\nimport { ERC20Standard } from './Standards/ERC20Standard';\nimport { ERC1155Standard } from './Standards/NftStandards/ERC1155/ERC1155Standard';\nimport { ERC721Standard } from './Standards/NftStandards/ERC721/ERC721Standard';\n\n/**\n * Check if token detection is enabled for certain networks\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport const SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID: Record<Hex, string> = {\n [SupportedTokenDetectionNetworks.mainnet]:\n '0xb1f8e55c7f64d203c1400b9d8555d050f94adf39',\n [SupportedTokenDetectionNetworks.bsc]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.polygon]:\n '0x2352c63A83f9Fd126af8676146721Fa00924d7e4',\n [SupportedTokenDetectionNetworks.avax]:\n '0xD023D153a0DFa485130ECFdE2FAA7e612EF94818',\n [SupportedTokenDetectionNetworks.aurora]:\n '0x1286415D333855237f89Df27D388127181448538',\n [SupportedTokenDetectionNetworks.linea_goerli]:\n '0x10dAd7Ca3921471f616db788D9300DC97Db01783',\n [SupportedTokenDetectionNetworks.linea_mainnet]:\n '0xF62e6a41561b3650a69Bb03199C735e3E3328c0D',\n [SupportedTokenDetectionNetworks.arbitrum]:\n '0x151E24A486D7258dd7C33Fb67E4bB01919B7B32c',\n [SupportedTokenDetectionNetworks.optimism]:\n '0xB1c568e9C3E6bdaf755A60c7418C269eb11524FC',\n [SupportedTokenDetectionNetworks.base]:\n '0x6AA75276052D96696134252587894ef5FFA520af',\n [SupportedTokenDetectionNetworks.zksync]:\n '0x458fEd3144680a5b8bcfaa0F9594aa19B4Ea2D34',\n [SupportedTokenDetectionNetworks.cronos]:\n '0x768ca200f0fc702ac9ea502498c18f5eff176378',\n [SupportedTokenDetectionNetworks.celo]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.gnosis]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.fantom]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.polygon_zkevm]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonbeam]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n [SupportedTokenDetectionNetworks.moonriver]:\n '0x6aa75276052d96696134252587894ef5ffa520af',\n};\n\nexport const MISSING_PROVIDER_ERROR =\n 'AssetsContractController failed to set the provider correctly. A provider must be set for this method to be available';\n\n/**\n * @type AssetsContractConfig\n *\n * Assets Contract controller configuration\n * @property provider - Provider used to create a new web3 instance\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface AssetsContractConfig extends BaseConfig {\n provider: Provider | undefined;\n ipfsGateway: string;\n chainId: Hex;\n}\n\n/**\n * @type BalanceMap\n *\n * Key value object containing the balance for each tokenAddress\n * @property [tokenAddress] - Address of the token\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface BalanceMap {\n [tokenAddress: string]: BN;\n}\n\n/**\n * Controller that interacts with contracts on mainnet through web3\n */\nexport class AssetsContractController extends BaseControllerV1<\n AssetsContractConfig,\n BaseState\n> {\n private _provider?: Provider;\n\n /**\n * Name of this controller used during composition\n */\n override name = 'AssetsContractController' as const;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /**\n * Creates a AssetsContractController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes.\n * @param options.onNetworkDidChange - Allows subscribing to network controller networkDidChange events.\n * @param options.getNetworkClientById - Gets the network client with the given id from the NetworkController.\n * @param config - Initial options used to configure this controller.\n * @param state - Initial state to set on this controller.\n */\n constructor(\n {\n chainId: initialChainId,\n onPreferencesStateChange,\n onNetworkDidChange,\n getNetworkClientById,\n }: {\n chainId: Hex;\n onPreferencesStateChange: (\n listener: (preferencesState: PreferencesState) => void,\n ) => void;\n onNetworkDidChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<AssetsContractConfig>,\n state?: Partial<BaseState>,\n ) {\n super(config, state);\n this.defaultConfig = {\n provider: undefined,\n ipfsGateway: IPFS_DEFAULT_GATEWAY_URL,\n chainId: initialChainId,\n };\n this.initialize();\n this.getNetworkClientById = getNetworkClientById;\n\n onPreferencesStateChange(({ ipfsGateway }) => {\n this.configure({ ipfsGateway });\n });\n\n onNetworkDidChange(({ selectedNetworkClientId }) => {\n const selectedNetworkClient = getNetworkClientById(\n selectedNetworkClientId,\n );\n const { chainId } = selectedNetworkClient.configuration;\n\n if (this.config.chainId !== chainId) {\n this.configure({\n chainId: selectedNetworkClient.configuration.chainId,\n });\n }\n });\n }\n\n /**\n * Sets a new provider.\n *\n * TODO: Replace this wth a method.\n *\n * @property provider - Provider used to create a new underlying Web3 instance\n */\n set provider(provider: Provider) {\n this._provider = provider;\n }\n\n get provider() {\n throw new Error('Property only used for setting');\n }\n\n /**\n * Get the relevant provider instance.\n *\n * @param networkClientId - Network Client ID.\n * @returns Web3Provider instance.\n */\n getProvider(networkClientId?: NetworkClientId): Web3Provider {\n const provider = networkClientId\n ? this.getNetworkClientById(networkClientId).provider\n : this._provider;\n\n if (provider === undefined) {\n throw new Error(MISSING_PROVIDER_ERROR);\n }\n\n // @ts-expect-error TODO: remove this annotation once the `Eip1193Provider` class is released\n return new Web3Provider(provider);\n }\n\n /**\n * Get the relevant chain ID.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns Hex chain ID.\n */\n getChainId(networkClientId?: NetworkClientId): Hex {\n return networkClientId\n ? this.getNetworkClientById(networkClientId).configuration.chainId\n : this.config.chainId;\n }\n\n /**\n * Get a ERC20Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC20Standard instance.\n */\n getERC20Standard(networkClientId?: NetworkClientId): ERC20Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC20Standard(provider);\n }\n\n /**\n * Get a ERC721Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC721Standard instance.\n */\n getERC721Standard(networkClientId?: NetworkClientId): ERC721Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC721Standard(provider);\n }\n\n /**\n * Get a ERC1155Standard instance using the relevant provider instance.\n *\n * @param networkClientId - Network Client ID used to get the provider.\n * @returns ERC1155Standard instance.\n */\n getERC1155Standard(networkClientId?: NetworkClientId): ERC1155Standard {\n const provider = this.getProvider(networkClientId);\n return new ERC1155Standard(provider);\n }\n\n /**\n * Get balance or count for current account on specific asset contract.\n *\n * @param address - Asset ERC20 contract address.\n * @param selectedAddress - Current account public address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getERC20BalanceOf(\n address: string,\n selectedAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getBalanceOf(address, selectedAddress);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenDecimals(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenDecimals(address);\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'decimals'.\n */\n async getERC20TokenName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return erc20Standard.getTokenName(address);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param address - ERC721 asset contract address.\n * @param selectedAddress - Current account public address.\n * @param index - An NFT counter less than `balanceOf(selectedAddress)`.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to token identifier for the 'index'th asset assigned to 'selectedAddress'.\n */\n getERC721NftTokenId(\n address: string,\n selectedAddress: string,\n index: number,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getNftTokenId(address, selectedAddress, index);\n }\n\n /**\n * Enumerate assets assigned to an owner.\n *\n * @param tokenAddress - ERC721 asset contract address.\n * @param userAddress - Current account public address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to an object containing the token standard and a set of details which depend on which standard the token supports.\n */\n async getTokenStandardAndDetails(\n tokenAddress: string,\n userAddress?: string,\n tokenId?: string,\n networkClientId?: NetworkClientId,\n ): Promise<{\n standard: string;\n tokenURI?: string | undefined;\n symbol?: string | undefined;\n name?: string | undefined;\n decimals?: string | undefined;\n balance?: BN | undefined;\n }> {\n // Asserts provider is available\n this.getProvider(networkClientId);\n\n const { ipfsGateway } = this.config;\n\n // ERC721\n try {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return {\n ...(await erc721Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC1155\n try {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return {\n ...(await erc1155Standard.getDetails(\n tokenAddress,\n ipfsGateway,\n tokenId,\n )),\n };\n } catch {\n // Ignore\n }\n\n // ERC20\n try {\n const erc20Standard = this.getERC20Standard(networkClientId);\n return {\n ...(await erc20Standard.getDetails(tokenAddress, userAddress)),\n };\n } catch {\n // Ignore\n }\n\n throw new Error('Unable to determine contract standard');\n }\n\n /**\n * Query for tokenURI for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC721TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'name'.\n */\n async getERC721AssetName(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetName(address);\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC721 or ERC20 asset contract address.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'symbol'.\n */\n async getERC721AssetSymbol(\n address: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getAssetSymbol(address);\n }\n\n /**\n * Query for owner for a given ERC721 asset.\n *\n * @param address - ERC721 asset contract address.\n * @param tokenId - ERC721 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the owner address.\n */\n async getERC721OwnerOf(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc721Standard = this.getERC721Standard(networkClientId);\n return erc721Standard.getOwnerOf(address, tokenId);\n }\n\n /**\n * Query for tokenURI for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @param tokenId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'tokenURI'.\n */\n async getERC1155TokenURI(\n address: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<string> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getTokenURI(address, tokenId);\n }\n\n /**\n * Query for balance of a given ERC 1155 token.\n *\n * @param userAddress - Wallet public address.\n * @param nftAddress - ERC1155 asset contract address.\n * @param nftId - ERC1155 asset identifier.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getERC1155BalanceOf(\n userAddress: string,\n nftAddress: string,\n nftId: string,\n networkClientId?: NetworkClientId,\n ): Promise<BN> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.getBalanceOf(nftAddress, userAddress, nftId);\n }\n\n /**\n * Transfer single ERC1155 token.\n *\n * @param nftAddress - ERC1155 token address.\n * @param senderAddress - ERC1155 token sender.\n * @param recipientAddress - ERC1155 token recipient.\n * @param nftId - ERC1155 token id.\n * @param qty - Quantity of tokens to be sent.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns Promise resolving to the 'transferSingle' ERC1155 token.\n */\n async transferSingleERC1155(\n nftAddress: string,\n senderAddress: string,\n recipientAddress: string,\n nftId: string,\n qty: string,\n networkClientId?: NetworkClientId,\n ): Promise<void> {\n const erc1155Standard = this.getERC1155Standard(networkClientId);\n return erc1155Standard.transferSingle(\n nftAddress,\n senderAddress,\n recipientAddress,\n nftId,\n qty,\n );\n }\n\n /**\n * Get the token balance for a list of token addresses in a single call. Only non-zero balances\n * are returned.\n *\n * @param selectedAddress - The address to check token balances for.\n * @param tokensToDetect - The token addresses to detect balances for.\n * @param networkClientId - Network Client ID to fetch the provider with.\n * @returns The list of non-zero token balances.\n */\n async getBalancesInSingleCall(\n selectedAddress: string,\n tokensToDetect: string[],\n networkClientId?: NetworkClientId,\n ) {\n const chainId = this.getChainId(networkClientId);\n const provider = this.getProvider(networkClientId);\n if (!(chainId in SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID)) {\n // Only fetch balance if contract address exists\n return {};\n }\n const contractAddress = SINGLE_CALL_BALANCES_ADDRESS_BY_CHAINID[chainId];\n\n const contract = new Contract(\n contractAddress,\n abiSingleCallBalancesContract,\n provider,\n );\n const result = await contract.balances([selectedAddress], tokensToDetect);\n const nonZeroBalances: BalanceMap = {};\n /* istanbul ignore else */\n if (result.length > 0) {\n tokensToDetect.forEach((tokenAddress, index) => {\n const balance: BN = result[index];\n /* istanbul ignore else */\n if (String(balance) !== '0') {\n nonZeroBalances[tokenAddress] = balance;\n }\n });\n }\n return nonZeroBalances;\n }\n}\n\nexport default AssetsContractController;\n"],"mappings":";;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,oBAAoB;AAE7B,SAAS,wBAAwB;AACjC,SAAS,gCAAgC;AAUzC,OAAO,mCAAmC;AAanC,IAAM,0CAA+D;AAAA,EAC1E,oBAAwC,GACtC;AAAA,EACF,iBAAoC,GAClC;AAAA,EACF,qBAAwC,GACtC;AAAA,EACF,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AAAA;AAAA,EAWA,MAAM,wBACJ,iBACA,gBACA,iBACA;AACA,UAAM,UAAU,KAAK,WAAW,eAAe;AAC/C,UAAM,WAAW,KAAK,YAAY,eAAe;AACjD,QAAI,EAAE,WAAW,0CAA0C;AAEzD,aAAO,CAAC;AAAA,IACV;AACA,UAAM,kBAAkB,wCAAwC,OAAO;AAEvE,UAAM,WAAW,IAAI;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,UAAM,SAAS,MAAM,SAAS,SAAS,CAAC,eAAe,GAAG,cAAc;AACxE,UAAM,kBAA8B,CAAC;AAErC,QAAI,OAAO,SAAS,GAAG;AACrB,qBAAe,QAAQ,CAAC,cAAc,UAAU;AAC9C,cAAM,UAAc,OAAO,KAAK;AAEhC,YAAI,OAAO,OAAO,MAAM,KAAK;AAC3B,0BAAgB,YAAY,IAAI;AAAA,QAClC;AAAA,MACF,CAAC;AAAA,IACH;AACA,WAAO;AAAA,EACT;AACF;AAEA,IAAO,mCAAQ;","names":[]}
|
|
@@ -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 RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport { BaseController } 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 NetworkState,\n Provider,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\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 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 TokensControllerState\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 TokensControllerState = {\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\nconst metadata = {\n tokens: {\n persist: true,\n anonymous: false,\n },\n ignoredTokens: {\n persist: true,\n anonymous: false,\n },\n detectedTokens: {\n persist: true,\n anonymous: false,\n },\n allTokens: {\n persist: true,\n anonymous: false,\n },\n allIgnoredTokens: {\n persist: true,\n anonymous: false,\n },\n allDetectedTokens: {\n persist: true,\n anonymous: false,\n },\n};\n\nconst controllerName = 'TokensController';\n\nexport type TokensControllerActions =\n | TokensControllerGetStateAction\n | TokensControllerAddDetectedTokensAction;\n\nexport type TokensControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokensControllerState\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\nexport type TokensControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n TokensControllerState\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 = (): TokensControllerState => {\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 BaseController<\n typeof controllerName,\n TokensControllerState,\n TokensControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n #chainId: Hex;\n\n #selectedAddress: string;\n\n #provider: Provider | undefined;\n\n #abortController: AbortController;\n\n /**\n * Tokens controller options\n * @param options - Constructor options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.selectedAddress - Vault selected address\n * @param options.provider - Network provider.\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 selectedAddress,\n provider,\n state,\n messenger,\n }: {\n chainId: Hex;\n selectedAddress: string;\n provider: Provider | undefined;\n state?: Partial<TokensControllerState>;\n messenger: TokensControllerMessenger;\n }) {\n super({\n name: controllerName,\n metadata,\n messenger,\n state: {\n ...getDefaultTokensState(),\n ...state,\n },\n });\n\n this.#chainId = initialChainId;\n\n this.#provider = provider;\n\n this.#selectedAddress = selectedAddress;\n\n this.#abortController = new AbortController();\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 this.#onPreferenceControllerStateChange.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n this.#onNetworkDidChange.bind(this),\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 * Handles the event when the network changes.\n *\n * @param networkState - The changed network state.\n * @param networkState.selectedNetworkClientId - The ID of the currently\n * selected network client.\n */\n #onNetworkDidChange({ selectedNetworkClientId }: NetworkState) {\n const selectedNetworkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;\n const { chainId } = selectedNetworkClient.configuration;\n this.#abortController.abort();\n this.#abortController = new AbortController();\n this.#chainId = chainId;\n this.update((state) => {\n state.tokens = allTokens[chainId]?.[this.#selectedAddress] || [];\n state.ignoredTokens =\n allIgnoredTokens[chainId]?.[this.#selectedAddress] || [];\n state.detectedTokens =\n allDetectedTokens[chainId]?.[this.#selectedAddress] || [];\n });\n }\n\n /**\n * Handles the state change of the preference controller.\n * @param preferencesState - The new state of the preference controller.\n * @param preferencesState.selectedAddress - The current selected address of the preference controller.\n */\n #onPreferenceControllerStateChange({ selectedAddress }: PreferencesState) {\n const { allTokens, allIgnoredTokens, allDetectedTokens } = this.state;\n this.#selectedAddress = selectedAddress;\n this.update((state) => {\n state.tokens = allTokens[this.#chainId]?.[selectedAddress] ?? [];\n state.ignoredTokens =\n allIgnoredTokens[this.#chainId]?.[selectedAddress] ?? [];\n state.detectedTokens =\n allDetectedTokens[this.#chainId]?.[selectedAddress] ?? [];\n });\n }\n\n /**\n * Fetch metadata for a token.\n *\n * @param tokenAddress - The address of the token.\n * @returns The token metadata.\n */\n async #fetchTokenMetadata(\n tokenAddress: string,\n ): Promise<TokenListToken | undefined> {\n try {\n const token = await fetchTokenMetadata<TokenListToken>(\n this.#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 * 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 = this.#chainId;\n const selectedAddress = this.#selectedAddress;\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.#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<TokensControllerState> = {\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((state) => {\n Object.assign(state, newState);\n });\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((state) => {\n state.tokens = newTokens;\n state.allTokens = newAllTokens;\n state.detectedTokens = newDetectedTokens;\n state.allDetectedTokens = newAllDetectedTokens;\n state.ignoredTokens = newIgnoredTokens;\n state.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((state) => {\n state.ignoredTokens = newIgnoredTokens;\n state.tokens = newTokens;\n state.detectedTokens = newDetectedTokens;\n state.allIgnoredTokens = newAllIgnoredTokens;\n state.allDetectedTokens = newAllDetectedTokens;\n state.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.#chainId;\n const accountAddress =\n detectionDetails?.selectedAddress ?? this.#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 newTokens = newAllTokens?.[this.#chainId]?.[this.#selectedAddress] || [];\n newDetectedTokens =\n newAllDetectedTokens?.[this.#chainId]?.[this.#selectedAddress] || [];\n\n this.update((state) => {\n state.tokens = newTokens;\n state.allTokens = newAllTokens;\n state.detectedTokens = newDetectedTokens;\n state.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.tokens];\n const tokenIndex = tokens.findIndex((token) => {\n return token.address.toLowerCase() === tokenAddress.toLowerCase();\n });\n const updatedToken = { ...tokens[tokenIndex], isERC721 };\n tokens[tokenIndex] = updatedToken;\n this.update((state) => {\n state.tokens = tokens;\n });\n return updatedToken;\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 #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((state) => {\n state.tokens = newTokens;\n });\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.#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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\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.#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\n const userAddressToAddTokens = interactingAddress ?? this.#selectedAddress;\n const chainIdToAddTokens = interactingChainId ?? this.#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((state) => {\n state.ignoredTokens = [];\n state.allIgnoredTokens = {};\n });\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,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ClC;AAAA,EACF;AAEA,QAAM,yBAAyB,CAAC;AAChC,WAAS,IAAI,GAAG,OAAO,KAAM,IAAI,eAAe,QAAQ,KAAK,MAAM;AACjE,2BAAuB,KAAK,eAAe,MAAM,GAAG,IAAI,IAAI,CAAC;AAAA,EAC/D;AAEA,SAAO;AACT;AAEM;AAAA,uBAAkB,eAAC;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAKkB;AAChB,QAAM,cAAc,YAAY;AAC9B,UAAM,WAAW,MAAM,mBAAK,0BAAL,WACrB,iBACA,aACA;AAGF,UAAM,oBAA6B,CAAC;AACpC,UAAM,qBAA+B,CAAC;AACtC,eAAW,uBAAuB,OAAO,KAAK,QAAQ,GAAG;AACvD,YAAM,EAAE,UAAU,QAAQ,aAAa,SAAS,KAAK,IACnD,mBAAK,YAAW,mBAAmB;AACrC,yBAAmB,KAAK,GAAG,MAAM,MAAM,mBAAmB,EAAE;AAC5D,wBAAkB,KAAK;AAAA,QACrB,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO;AAAA,QACP,UAAU;AAAA,QACV;AAAA,MACF,CAAC;AAAA,IACH;AAEA,QAAI,kBAAkB,QAAQ;AAC5B,yBAAK,wBAAL,WAA4B;AAAA,QAC1B,OAAO;AAAA,QACP,UAAU;AAAA,QACV,YAAY;AAAA,UACV,QAAQ;AAAA;AAAA;AAAA,UAGR,gBAAgB;AAAA;AAAA;AAAA,UAGhB,YAAY;AAAA,QACd;AAAA,MACF;AAEA,YAAM,KAAK,gBAAgB;AAAA,QACzB;AAAA,QACA;AAAA,QACA;AAAA,UACE;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAGF,IAAO,mCAAQ","sourcesContent":["import type {\n AccountsControllerGetSelectedAccountAction,\n AccountsControllerSelectedAccountChangeEvent,\n} from '@metamask/accounts-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport contractMap from '@metamask/contract-metadata';\nimport { ChainId, safelyExecute } from '@metamask/controller-utils';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerLockEvent,\n KeyringControllerUnlockEvent,\n} from '@metamask/keyring-controller';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetNetworkConfigurationByNetworkClientId,\n NetworkControllerGetStateAction,\n NetworkControllerNetworkDidChangeEvent,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n} from '@metamask/preferences-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport { isTokenDetectionSupportedForNetwork } from './assetsUtil';\nimport type {\n GetTokenListState,\n TokenListMap,\n TokenListStateChange,\n} from './TokenListController';\nimport type { Token } from './TokenRatesController';\nimport type {\n TokensControllerAddDetectedTokensAction,\n TokensControllerGetStateAction,\n} from './TokensController';\n\nconst DEFAULT_INTERVAL = 180000;\n\n/**\n * Compare 2 given strings and return boolean\n * eg: \"foo\" and \"FOO\" => true\n * eg: \"foo\" and \"bar\" => false\n * eg: \"foo\" and 123 => false\n *\n * @param value1 - first string to compare\n * @param value2 - first string to compare\n * @returns true if 2 strings are identical when they are lowercase\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n\ntype LegacyToken = {\n name: string;\n logo: `${string}.svg`;\n symbol: string;\n decimals: number;\n erc20?: boolean;\n erc721?: boolean;\n};\n\ntype TokenDetectionMap = {\n [P in keyof TokenListMap]: Omit<TokenListMap[P], 'occurrences'>;\n};\n\nexport const STATIC_MAINNET_TOKEN_LIST = Object.entries<LegacyToken>(\n contractMap,\n).reduce<TokenDetectionMap>((acc, [base, contract]) => {\n const { logo, erc20, erc721, ...tokenMetadata } = contract;\n return {\n ...acc,\n [base.toLowerCase()]: {\n ...tokenMetadata,\n address: base.toLowerCase(),\n iconUrl: `images/contract/${logo}`,\n aggregators: [],\n },\n };\n}, {});\n\nexport const controllerName = 'TokenDetectionController';\n\nexport type TokenDetectionState = Record<never, never>;\n\nexport type TokenDetectionControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenDetectionState\n>;\n\nexport type TokenDetectionControllerActions =\n TokenDetectionControllerGetStateAction;\n\nexport type AllowedActions =\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByNetworkClientId\n | NetworkControllerGetStateAction\n | GetTokenListState\n | KeyringControllerGetStateAction\n | PreferencesControllerGetStateAction\n | TokensControllerGetStateAction\n | TokensControllerAddDetectedTokensAction;\n\nexport type TokenDetectionControllerStateChangeEvent =\n ControllerStateChangeEvent<typeof controllerName, TokenDetectionState>;\n\nexport type TokenDetectionControllerEvents =\n TokenDetectionControllerStateChangeEvent;\n\nexport type AllowedEvents =\n | AccountsControllerSelectedAccountChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | TokenListStateChange\n | KeyringControllerLockEvent\n | KeyringControllerUnlockEvent\n | PreferencesControllerStateChangeEvent;\n\nexport type TokenDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenDetectionControllerActions | AllowedActions,\n TokenDetectionControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Controller that passively polls on a set interval for Tokens auto detection\n * @property intervalId - Polling interval used to fetch new token rates\n * @property selectedAddress - Vault selected address\n * @property networkClientId - The network client ID of the current selected network\n * @property disabled - Boolean to track if network requests are blocked\n * @property isUnlocked - Boolean to track if the keyring state is unlocked\n * @property isDetectionEnabledFromPreferences - Boolean to track if detection is enabled from PreferencesController\n * @property isDetectionEnabledForNetwork - Boolean to track if detected is enabled for current network\n */\nexport class TokenDetectionController extends StaticIntervalPollingController<\n typeof controllerName,\n TokenDetectionState,\n TokenDetectionControllerMessenger\n> {\n #intervalId?: ReturnType<typeof setTimeout>;\n\n #selectedAddress: string;\n\n #networkClientId: NetworkClientId;\n\n #tokenList: TokenDetectionMap = {};\n\n #disabled: boolean;\n\n #isUnlocked: boolean;\n\n #isDetectionEnabledFromPreferences: boolean;\n\n #isDetectionEnabledForNetwork: boolean;\n\n readonly #getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n\n readonly #trackMetaMetricsEvent: (options: {\n event: string;\n category: string;\n properties: {\n tokens: string[];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n token_standard: string;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_type: string;\n };\n }) => void;\n\n /**\n * Creates a TokenDetectionController instance.\n *\n * @param options - The controller options.\n * @param options.messenger - The controller messaging system.\n * @param options.disabled - If set to true, all network requests are blocked.\n * @param options.interval - Polling interval used to fetch new token rates\n * @param options.selectedAddress - Vault selected address\n * @param options.getBalancesInSingleCall - Gets the balances of a list of tokens for the given address.\n * @param options.trackMetaMetricsEvent - Sets options for MetaMetrics event tracking.\n */\n constructor({\n selectedAddress,\n interval = DEFAULT_INTERVAL,\n disabled = true,\n getBalancesInSingleCall,\n trackMetaMetricsEvent,\n messenger,\n }: {\n selectedAddress?: string;\n interval?: number;\n disabled?: boolean;\n getBalancesInSingleCall: AssetsContractController['getBalancesInSingleCall'];\n trackMetaMetricsEvent: (options: {\n event: string;\n category: string;\n properties: {\n tokens: string[];\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n token_standard: string;\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_type: string;\n };\n }) => void;\n messenger: TokenDetectionControllerMessenger;\n }) {\n super({\n name: controllerName,\n messenger,\n state: {},\n metadata: {},\n });\n\n this.#disabled = disabled;\n this.setIntervalLength(interval);\n\n this.#selectedAddress =\n selectedAddress ??\n this.messagingSystem.call('AccountsController:getSelectedAccount')\n .address;\n\n const { chainId, networkClientId } =\n this.#getCorrectChainIdAndNetworkClientId();\n this.#networkClientId = networkClientId;\n\n const { useTokenDetection: defaultUseTokenDetection } =\n this.messagingSystem.call('PreferencesController:getState');\n this.#isDetectionEnabledFromPreferences = defaultUseTokenDetection;\n this.#isDetectionEnabledForNetwork =\n isTokenDetectionSupportedForNetwork(chainId);\n\n this.#getBalancesInSingleCall = getBalancesInSingleCall;\n\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n\n const { isUnlocked } = this.messagingSystem.call(\n 'KeyringController:getState',\n );\n this.#isUnlocked = isUnlocked;\n\n this.#registerEventListeners();\n }\n\n /**\n * Constructor helper for registering this controller's messaging system subscriptions to controller events.\n */\n #registerEventListeners() {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.messagingSystem.subscribe('KeyringController:unlock', async () => {\n this.#isUnlocked = true;\n await this.#restartTokenDetection();\n });\n\n this.messagingSystem.subscribe('KeyringController:lock', () => {\n this.#isUnlocked = false;\n this.#stopPolling();\n });\n\n this.messagingSystem.subscribe(\n 'TokenListController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ tokenList }) => {\n const hasTokens = Object.keys(tokenList).length;\n\n if (hasTokens) {\n await this.#restartTokenDetection();\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ selectedAddress: newSelectedAddress, useTokenDetection }) => {\n const isSelectedAddressChanged =\n this.#selectedAddress !== newSelectedAddress;\n const isDetectionChangedFromPreferences =\n this.#isDetectionEnabledFromPreferences !== useTokenDetection;\n\n this.#selectedAddress = newSelectedAddress;\n this.#isDetectionEnabledFromPreferences = useTokenDetection;\n\n if (isSelectedAddressChanged || isDetectionChangedFromPreferences) {\n await this.#restartTokenDetection({\n selectedAddress: this.#selectedAddress,\n });\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:selectedAccountChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ address: newSelectedAddress }) => {\n const isSelectedAddressChanged =\n this.#selectedAddress !== newSelectedAddress;\n if (isSelectedAddressChanged) {\n this.#selectedAddress = newSelectedAddress;\n await this.#restartTokenDetection({\n selectedAddress: this.#selectedAddress,\n });\n }\n },\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ selectedNetworkClientId }) => {\n const isNetworkClientIdChanged =\n this.#networkClientId !== selectedNetworkClientId;\n\n const { chainId: newChainId } =\n this.#getCorrectChainIdAndNetworkClientId(selectedNetworkClientId);\n this.#isDetectionEnabledForNetwork =\n isTokenDetectionSupportedForNetwork(newChainId);\n\n if (isNetworkClientIdChanged && this.#isDetectionEnabledForNetwork) {\n this.#networkClientId = selectedNetworkClientId;\n await this.#restartTokenDetection({\n networkClientId: this.#networkClientId,\n });\n }\n },\n );\n }\n\n /**\n * Allows controller to make active and passive polling requests\n */\n enable(): void {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from making network calls\n */\n disable(): void {\n this.#disabled = true;\n }\n\n /**\n * Internal isActive state\n * @type {boolean}\n */\n get isActive(): boolean {\n return !this.#disabled && this.#isUnlocked;\n }\n\n /**\n * Start polling for detected tokens.\n */\n async start(): Promise<void> {\n this.enable();\n await this.#startPolling();\n }\n\n /**\n * Stop polling for detected tokens.\n */\n stop(): void {\n this.disable();\n this.#stopPolling();\n }\n\n #stopPolling(): void {\n if (this.#intervalId) {\n clearInterval(this.#intervalId);\n }\n }\n\n /**\n * Starts a new polling interval.\n */\n async #startPolling(): Promise<void> {\n if (!this.isActive) {\n return;\n }\n this.#stopPolling();\n await this.detectTokens();\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#intervalId = setInterval(async () => {\n await this.detectTokens();\n }, this.getIntervalLength());\n }\n\n #getCorrectChainIdAndNetworkClientId(networkClientId?: NetworkClientId): {\n chainId: Hex;\n networkClientId: NetworkClientId;\n } {\n if (networkClientId) {\n const networkConfiguration = this.messagingSystem.call(\n 'NetworkController:getNetworkConfigurationByNetworkClientId',\n networkClientId,\n );\n if (networkConfiguration) {\n return {\n chainId: networkConfiguration.chainId,\n networkClientId,\n };\n }\n }\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return {\n chainId,\n networkClientId: selectedNetworkClientId,\n };\n }\n\n async _executePoll(\n networkClientId: NetworkClientId,\n options: { address: string },\n ): Promise<void> {\n if (!this.isActive) {\n return;\n }\n await this.detectTokens({\n networkClientId,\n selectedAddress: options.address,\n });\n }\n\n /**\n * Restart token detection polling period and call detectNewTokens\n * in case of address change or user session initialization.\n *\n * @param options - Options for restart token detection.\n * @param options.selectedAddress - the selectedAddress against which to detect for token balances\n * @param options.networkClientId - The ID of the network client to use.\n */\n async #restartTokenDetection({\n selectedAddress,\n networkClientId,\n }: {\n selectedAddress?: string;\n networkClientId?: NetworkClientId;\n } = {}): Promise<void> {\n await this.detectTokens({\n networkClientId,\n selectedAddress,\n });\n this.setIntervalLength(DEFAULT_INTERVAL);\n }\n\n /**\n * For each token in the token list provided by the TokenListController, checks the token's balance for the selected account address on the active network.\n * On mainnet, if token detection is disabled in preferences, ERC20 token auto detection will be triggered for each contract address in the legacy token list from the @metamask/contract-metadata repo.\n *\n * @param options - Options for token detection.\n * @param options.networkClientId - The ID of the network client to use.\n * @param options.selectedAddress - the selectedAddress against which to detect for token balances.\n */\n async detectTokens({\n networkClientId,\n selectedAddress,\n }: {\n networkClientId?: NetworkClientId;\n selectedAddress?: string;\n } = {}): Promise<void> {\n if (!this.isActive) {\n return;\n }\n\n const addressAgainstWhichToDetect =\n selectedAddress ?? this.#selectedAddress;\n const { chainId, networkClientId: selectedNetworkClientId } =\n this.#getCorrectChainIdAndNetworkClientId(networkClientId);\n const chainIdAgainstWhichToDetect = chainId;\n const networkClientIdAgainstWhichToDetect = selectedNetworkClientId;\n\n if (!isTokenDetectionSupportedForNetwork(chainIdAgainstWhichToDetect)) {\n return;\n }\n if (\n !this.#isDetectionEnabledFromPreferences &&\n chainIdAgainstWhichToDetect !== ChainId.mainnet\n ) {\n return;\n }\n const isTokenDetectionInactiveInMainnet =\n !this.#isDetectionEnabledFromPreferences &&\n chainIdAgainstWhichToDetect === ChainId.mainnet;\n const { tokensChainsCache } = this.messagingSystem.call(\n 'TokenListController:getState',\n );\n this.#tokenList = isTokenDetectionInactiveInMainnet\n ? STATIC_MAINNET_TOKEN_LIST\n : tokensChainsCache[chainIdAgainstWhichToDetect]?.data ?? {};\n\n for (const tokensSlice of this.#getSlicesOfTokensToDetect({\n chainId: chainIdAgainstWhichToDetect,\n selectedAddress: addressAgainstWhichToDetect,\n })) {\n await this.#addDetectedTokens({\n tokensSlice,\n selectedAddress: addressAgainstWhichToDetect,\n networkClientId: networkClientIdAgainstWhichToDetect,\n chainId: chainIdAgainstWhichToDetect,\n });\n }\n }\n\n #getSlicesOfTokensToDetect({\n chainId,\n selectedAddress,\n }: {\n chainId: Hex;\n selectedAddress: string;\n }): string[][] {\n const { allTokens, allDetectedTokens, allIgnoredTokens } =\n this.messagingSystem.call('TokensController:getState');\n const [tokensAddresses, detectedTokensAddresses, ignoredTokensAddresses] = [\n allTokens,\n allDetectedTokens,\n allIgnoredTokens,\n ].map((tokens) =>\n (tokens[chainId]?.[selectedAddress] ?? []).map((value) =>\n typeof value === 'string' ? value : value.address,\n ),\n );\n\n const tokensToDetect: string[] = [];\n for (const tokenAddress of Object.keys(this.#tokenList)) {\n if (\n [\n tokensAddresses,\n detectedTokensAddresses,\n ignoredTokensAddresses,\n ].every(\n (addresses) =>\n !addresses.find((address) =>\n isEqualCaseInsensitive(address, tokenAddress),\n ),\n )\n ) {\n tokensToDetect.push(tokenAddress);\n }\n }\n\n const slicesOfTokensToDetect = [];\n for (let i = 0, size = 1000; i < tokensToDetect.length; i += size) {\n slicesOfTokensToDetect.push(tokensToDetect.slice(i, i + size));\n }\n\n return slicesOfTokensToDetect;\n }\n\n async #addDetectedTokens({\n tokensSlice,\n selectedAddress,\n networkClientId,\n chainId,\n }: {\n tokensSlice: string[];\n selectedAddress: string;\n networkClientId: NetworkClientId;\n chainId: Hex;\n }): Promise<void> {\n await safelyExecute(async () => {\n const balances = await this.#getBalancesInSingleCall(\n selectedAddress,\n tokensSlice,\n networkClientId,\n );\n\n const tokensWithBalance: Token[] = [];\n const eventTokensDetails: string[] = [];\n for (const nonZeroTokenAddress of Object.keys(balances)) {\n const { decimals, symbol, aggregators, iconUrl, name } =\n this.#tokenList[nonZeroTokenAddress];\n eventTokensDetails.push(`${symbol} - ${nonZeroTokenAddress}`);\n tokensWithBalance.push({\n address: nonZeroTokenAddress,\n decimals,\n symbol,\n aggregators,\n image: iconUrl,\n isERC721: false,\n name,\n });\n }\n\n if (tokensWithBalance.length) {\n this.#trackMetaMetricsEvent({\n event: 'Token Detected',\n category: 'Wallet',\n properties: {\n tokens: eventTokensDetails,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n token_standard: 'ERC20',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_type: 'TOKEN',\n },\n });\n\n await this.messagingSystem.call(\n 'TokensController:addDetectedTokens',\n tokensWithBalance,\n {\n selectedAddress,\n chainId,\n },\n );\n }\n });\n }\n}\n\nexport default TokenDetectionController;\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/NftController.ts"],"sourcesContent":["import { isAddress } from '@ethersproject/address';\nimport type {\n AccountsControllerSelectedEvmAccountChangeEvent,\n AccountsControllerGetAccountAction,\n AccountsControllerGetSelectedAccountAction,\n} from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type {\n RestrictedControllerMessenger,\n ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n} from '@metamask/base-controller';\nimport {\n safelyExecute,\n handleFetch,\n toChecksumHexAddress,\n BNToHex,\n fetchWithErrorHandling,\n IPFS_DEFAULT_GATEWAY_URL,\n ERC721,\n ERC1155,\n ApprovalType,\n NFT_API_BASE_URL,\n} from '@metamask/controller-utils';\nimport { type InternalAccount } from '@metamask/keyring-api';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerNetworkDidChangeEvent,\n NetworkState,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { remove0x } from '@metamask/utils';\nimport { Mutex } from 'async-mutex';\nimport BN from 'bn.js';\nimport { v4 as random } from 'uuid';\n\nimport type { AssetsContractController } from './AssetsContractController';\nimport { compareNftMetadata, getFormattedIpfsUrl } from './assetsUtil';\nimport { Source } from './constants';\nimport type {\n ApiNftContract,\n ReservoirResponse,\n Collection,\n Attributes,\n LastSale,\n} from './NftDetectionController';\n\ntype NFTStandardType = 'ERC721' | 'ERC1155';\n\ntype SuggestedNftMeta = {\n asset: { address: string; tokenId: string } & NftMetadata;\n id: string;\n time: number;\n type: NFTStandardType;\n interactingAddress: string;\n origin: string;\n};\n\n/**\n * @type Nft\n *\n * NFT representation\n * @property address - Hex address of a ERC721 contract\n * @property description - The NFT description\n * @property image - URI of custom NFT image associated with this tokenId\n * @property name - Name associated with this tokenId and contract address\n * @property tokenId - The NFT identifier\n * @property numberOfSales - Number of sales\n * @property backgroundColor - The background color to be displayed with the item\n * @property imagePreview - URI of a smaller image associated with this NFT\n * @property imageThumbnail - URI of a thumbnail image associated with this NFT\n * @property imageOriginal - URI of the original image associated with this NFT\n * @property animation - URI of a animation associated with this NFT\n * @property animationOriginal - URI of the original animation associated with this NFT\n * @property externalLink - External link containing additional information\n * @property creator - The NFT owner information object\n * @property isCurrentlyOwned - Boolean indicating whether the address/chainId combination where it's currently stored currently owns this NFT\n * @property transactionId - Transaction Id associated with the NFT\n */\nexport type Nft =\n | {\n tokenId: string;\n address: string;\n isCurrentlyOwned?: boolean;\n } & NftMetadata;\n\ntype NftUpdate = {\n nft: Nft;\n newMetadata: NftMetadata;\n};\n\n/**\n * @type NftContract\n *\n * NFT contract information representation\n * @property name - Contract name\n * @property logo - Contract logo\n * @property address - Contract address\n * @property symbol - Contract symbol\n * @property description - Contract description\n * @property totalSupply - Total supply of NFTs\n * @property assetContractType - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property createdDate - Creation date\n * @property schemaName - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property externalLink - External link containing additional information\n */\nexport type NftContract = {\n name?: string;\n logo?: string;\n address: string;\n symbol?: string;\n description?: string;\n totalSupply?: string;\n assetContractType?: string;\n createdDate?: string;\n schemaName?: string;\n externalLink?: string;\n};\n\n/**\n * @type NftMetadata\n *\n * NFT custom information\n * @property name - NFT custom name\n * @property description - The NFT description\n * @property numberOfSales - Number of sales\n * @property backgroundColor - The background color to be displayed with the item\n * @property image - Image custom image URI\n * @property imagePreview - URI of a smaller image associated with this NFT\n * @property imageThumbnail - URI of a thumbnail image associated with this NFT\n * @property imageOriginal - URI of the original image associated with this NFT\n * @property animation - URI of a animation associated with this NFT\n * @property animationOriginal - URI of the original animation associated with this NFT\n * @property externalLink - External link containing additional information\n * @property creator - The NFT owner information object\n * @property standard - NFT standard name for the NFT, e.g., ERC-721 or ERC-1155\n */\nexport type NftMetadata = {\n name: string | null;\n description: string | null;\n image: string | null;\n standard: string | null;\n favorite?: boolean;\n numberOfSales?: number;\n backgroundColor?: string;\n imagePreview?: string;\n imageThumbnail?: string;\n imageOriginal?: string;\n animation?: string;\n animationOriginal?: string;\n externalLink?: string;\n creator?: string;\n transactionId?: string;\n tokenURI?: string | null;\n collection?: Collection;\n address?: string;\n attributes?: Attributes;\n lastSale?: LastSale;\n rarityRank?: string;\n};\n\n/**\n * @type NftControllerState\n *\n * NFT controller state\n * @property allNftContracts - Object containing NFT contract information\n * @property allNfts - Object containing NFTs per account and network\n * @property ignoredNfts - List of NFTs that should be ignored\n */\nexport type NftControllerState = {\n allNftContracts: {\n [key: string]: {\n [chainId: Hex]: NftContract[];\n };\n };\n allNfts: {\n [key: string]: {\n [chainId: Hex]: Nft[];\n };\n };\n ignoredNfts: Nft[];\n};\n\nconst nftControllerMetadata = {\n allNftContracts: { persist: true, anonymous: false },\n allNfts: { persist: true, anonymous: false },\n ignoredNfts: { persist: true, anonymous: false },\n};\n\nconst ALL_NFTS_STATE_KEY = 'allNfts';\nconst ALL_NFTS_CONTRACTS_STATE_KEY = 'allNftContracts';\n\ntype NftAsset = {\n address: string;\n tokenId: string;\n};\n\n/**\n * The name of the {@link NftController}.\n */\nconst controllerName = 'NftController';\n\nexport type NftControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n NftControllerState\n>;\nexport type NftControllerActions = NftControllerGetStateAction;\n\n/**\n * The external actions available to the {@link NftController}.\n */\nexport type AllowedActions =\n | AddApprovalRequest\n | AccountsControllerGetAccountAction\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerGetNetworkClientByIdAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerNetworkDidChangeEvent\n | AccountsControllerSelectedEvmAccountChangeEvent;\n\nexport type NftControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n NftControllerState\n>;\n\nexport type NftControllerEvents = NftControllerStateChangeEvent;\n\n/**\n * The messenger of the {@link NftController}.\n */\nexport type NftControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n NftControllerActions | AllowedActions,\n NftControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\nexport const getDefaultNftControllerState = (): NftControllerState => ({\n allNftContracts: {},\n allNfts: {},\n ignoredNfts: [],\n});\n\n/**\n * Controller that stores assets and exposes convenience methods\n */\nexport class NftController extends BaseController<\n typeof controllerName,\n NftControllerState,\n NftControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n /**\n * Optional API key to use with opensea\n */\n openSeaApiKey?: string;\n\n #selectedAccountId: string;\n\n #chainId: Hex;\n\n #ipfsGateway: string;\n\n #openSeaEnabled: boolean;\n\n #useIpfsSubdomains: boolean;\n\n #isIpfsGatewayEnabled: boolean;\n\n readonly #getERC721AssetName: AssetsContractController['getERC721AssetName'];\n\n readonly #getERC721AssetSymbol: AssetsContractController['getERC721AssetSymbol'];\n\n readonly #getERC721TokenURI: AssetsContractController['getERC721TokenURI'];\n\n readonly #getERC721OwnerOf: AssetsContractController['getERC721OwnerOf'];\n\n readonly #getERC1155BalanceOf: AssetsContractController['getERC1155BalanceOf'];\n\n readonly #getERC1155TokenURI: AssetsContractController['getERC1155TokenURI'];\n\n readonly #onNftAdded?: (data: {\n address: string;\n symbol: string | undefined;\n tokenId: string;\n standard: string | null;\n source: Source;\n }) => void;\n\n /**\n * Creates an NftController instance.\n *\n * @param options - The controller options.\n * @param options.chainId - The chain ID of the current network.\n * @param options.ipfsGateway - The configured IPFS gateway.\n * @param options.openSeaEnabled - Controls whether the OpenSea API is used.\n * @param options.useIpfsSubdomains - Controls whether IPFS subdomains are used.\n * @param options.isIpfsGatewayEnabled - Controls whether IPFS is enabled or not.\n * @param options.getERC721AssetName - Gets the name of the asset at the given address.\n * @param options.getERC721AssetSymbol - Gets the symbol of the asset at the given address.\n * @param options.getERC721TokenURI - Gets the URI of the ERC721 token at the given address, with the given ID.\n * @param options.getERC721OwnerOf - Get the owner of a ERC-721 NFT.\n * @param options.getERC1155BalanceOf - Gets balance of a ERC-1155 NFT.\n * @param options.getERC1155TokenURI - Gets the URI of the ERC1155 token at the given address, with the given ID.\n * @param options.onNftAdded - Callback that is called when an NFT is added. Currently used pass data\n * for tracking the NFT added event.\n * @param options.messenger - The controller messenger.\n * @param options.state - Initial state to set on this controller.\n */\n constructor({\n chainId: initialChainId,\n ipfsGateway = IPFS_DEFAULT_GATEWAY_URL,\n openSeaEnabled = false,\n useIpfsSubdomains = true,\n isIpfsGatewayEnabled = true,\n getERC721AssetName,\n getERC721AssetSymbol,\n getERC721TokenURI,\n getERC721OwnerOf,\n getERC1155BalanceOf,\n getERC1155TokenURI,\n onNftAdded,\n messenger,\n state = {},\n }: {\n chainId: Hex;\n ipfsGateway?: string;\n openSeaEnabled?: boolean;\n useIpfsSubdomains?: boolean;\n isIpfsGatewayEnabled?: boolean;\n getERC721AssetName: AssetsContractController['getERC721AssetName'];\n getERC721AssetSymbol: AssetsContractController['getERC721AssetSymbol'];\n getERC721TokenURI: AssetsContractController['getERC721TokenURI'];\n getERC721OwnerOf: AssetsContractController['getERC721OwnerOf'];\n getERC1155BalanceOf: AssetsContractController['getERC1155BalanceOf'];\n getERC1155TokenURI: AssetsContractController['getERC1155TokenURI'];\n onNftAdded?: (data: {\n address: string;\n symbol: string | undefined;\n tokenId: string;\n standard: string | null;\n source: string;\n }) => void;\n messenger: NftControllerMessenger;\n state?: Partial<NftControllerState>;\n }) {\n super({\n name: controllerName,\n metadata: nftControllerMetadata,\n messenger,\n state: {\n ...getDefaultNftControllerState(),\n ...state,\n },\n });\n\n this.#selectedAccountId = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n ).id;\n this.#chainId = initialChainId;\n this.#ipfsGateway = ipfsGateway;\n this.#openSeaEnabled = openSeaEnabled;\n this.#useIpfsSubdomains = useIpfsSubdomains;\n this.#isIpfsGatewayEnabled = isIpfsGatewayEnabled;\n\n this.#getERC721AssetName = getERC721AssetName;\n this.#getERC721AssetSymbol = getERC721AssetSymbol;\n this.#getERC721TokenURI = getERC721TokenURI;\n this.#getERC721OwnerOf = getERC721OwnerOf;\n this.#getERC1155BalanceOf = getERC1155BalanceOf;\n this.#getERC1155TokenURI = getERC1155TokenURI;\n this.#onNftAdded = onNftAdded;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#onPreferencesControllerStateChange.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'NetworkController:networkDidChange',\n this.#onNetworkControllerNetworkDidChange.bind(this),\n );\n\n this.messagingSystem.subscribe(\n 'AccountsController:selectedEvmAccountChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n this.#onSelectedAccountChange.bind(this),\n );\n }\n\n /**\n * Handles the network change on the network controller.\n * @param networkState - The new state of the preference controller.\n * @param networkState.selectedNetworkClientId - The current selected network client id.\n */\n #onNetworkControllerNetworkDidChange({\n selectedNetworkClientId,\n }: NetworkState) {\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n this.#chainId = chainId;\n }\n\n /**\n * Handles the state change of the preference controller.\n * @param preferencesState - The new state of the preference controller.\n * @param preferencesState.ipfsGateway - The configured IPFS gateway.\n * @param preferencesState.openSeaEnabled - Controls whether the OpenSea API is used.\n * @param preferencesState.isIpfsGatewayEnabled - Controls whether IPFS is enabled or not.\n */\n async #onPreferencesControllerStateChange({\n ipfsGateway,\n openSeaEnabled,\n isIpfsGatewayEnabled,\n }: PreferencesState) {\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getSelectedAccount',\n );\n this.#selectedAccountId = selectedAccount.id;\n this.#ipfsGateway = ipfsGateway;\n this.#openSeaEnabled = openSeaEnabled;\n this.#isIpfsGatewayEnabled = isIpfsGatewayEnabled;\n\n const needsUpdateNftMetadata =\n (isIpfsGatewayEnabled && ipfsGateway !== '') || openSeaEnabled;\n\n if (needsUpdateNftMetadata && selectedAccount) {\n await this.#updateNftUpdateForAccount(selectedAccount);\n }\n }\n\n /**\n * Handles the selected account change on the accounts controller.\n * @param internalAccount - The new selected account.\n */\n async #onSelectedAccountChange(internalAccount: InternalAccount) {\n const oldSelectedAccountId = this.#selectedAccountId;\n this.#selectedAccountId = internalAccount.id;\n\n const needsUpdateNftMetadata =\n ((this.#isIpfsGatewayEnabled && this.#ipfsGateway !== '') ||\n this.#openSeaEnabled) &&\n oldSelectedAccountId !== internalAccount.id;\n\n if (needsUpdateNftMetadata) {\n await this.#updateNftUpdateForAccount(internalAccount);\n }\n }\n\n getNftApi() {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `${NFT_API_BASE_URL}/tokens`;\n }\n\n /**\n * Helper method to update nested state for allNfts and allNftContracts.\n *\n * @param newCollection - the modified piece of state to update in the controller's store\n * @param baseStateKey - The root key in the store to update.\n * @param passedConfig - An object containing the selectedAddress and chainId that are passed through the auto-detection flow.\n * @param passedConfig.userAddress - the address passed through the NFT detection flow to ensure assets are stored to the correct account\n * @param passedConfig.chainId - the chainId passed through the NFT detection flow to ensure assets are stored to the correct account\n */\n #updateNestedNftState<\n Key extends typeof ALL_NFTS_STATE_KEY | typeof ALL_NFTS_CONTRACTS_STATE_KEY,\n NftCollection extends Key extends typeof ALL_NFTS_STATE_KEY\n ? Nft[]\n : NftContract[],\n >(\n newCollection: NftCollection,\n baseStateKey: Key,\n { userAddress, chainId }: { userAddress: string; chainId: Hex },\n ) {\n // userAddress can be an empty string if it is not set via an account change or in constructor\n // while this doesn't cause any issues, we want to ensure that we don't store assets to an empty string address\n if (!userAddress) {\n return;\n }\n\n this.update((state) => {\n const oldState = state[baseStateKey];\n const addressState = oldState[userAddress] || {};\n const newAddressState = {\n ...addressState,\n [chainId]: newCollection,\n };\n state[baseStateKey] = {\n ...oldState,\n [userAddress]: newAddressState,\n };\n });\n }\n\n /**\n * Request individual NFT information from NFT API.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformationFromApi(\n contractAddress: string,\n tokenId: string,\n ): Promise<NftMetadata> {\n // TODO Parameterize this by chainId for non-mainnet token detection\n // Attempt to fetch the data with the nft-api\n const urlParams = new URLSearchParams({\n chainIds: '1',\n tokens: `${contractAddress}:${tokenId}`,\n includeTopBid: 'true',\n includeAttributes: 'true',\n includeLastSale: 'true',\n }).toString();\n const nftInformation: ReservoirResponse | undefined =\n await fetchWithErrorHandling({\n url: `${this.getNftApi()}?${urlParams}`,\n options: {\n headers: {\n Version: '1',\n },\n },\n });\n // if we were still unable to fetch the data we return out the default/null of `NftMetadata`\n if (!nftInformation?.tokens?.[0]?.token) {\n return {\n name: null,\n description: null,\n image: null,\n standard: null,\n };\n }\n\n // if we've reached this point, we have successfully fetched some data for nftInformation\n // now we reconfigure the data to conform to the `NftMetadata` type for storage.\n\n const {\n image,\n metadata: { imageOriginal } = {},\n name,\n description,\n collection,\n kind,\n rarityRank,\n rarity,\n attributes,\n lastSale,\n imageSmall,\n } = nftInformation.tokens[0].token;\n\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name: name || null },\n { description: description || null },\n { image: image || null },\n collection?.creator && { creator: collection.creator },\n imageOriginal && { imageOriginal },\n imageSmall && { imageThumbnail: imageSmall },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n nftInformation.tokens[0].market?.topBid && {\n topBid: nftInformation.tokens[0].market?.topBid,\n },\n rarityRank && { rarityRank },\n rarity && { rarity },\n collection && { collection },\n );\n\n return nftMetadata;\n }\n\n /**\n * Request individual NFT information from contracts that follows Metadata Interface.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformationFromTokenURI(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<NftMetadata> {\n const result = await this.#getNftURIAndStandard(\n contractAddress,\n tokenId,\n networkClientId,\n );\n let tokenURI = result[0];\n const standard = result[1];\n\n const hasIpfsTokenURI = tokenURI.startsWith('ipfs://');\n\n if (hasIpfsTokenURI && !this.#isIpfsGatewayEnabled) {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n\n const isDisplayNFTMediaToggleEnabled = this.#openSeaEnabled;\n if (!hasIpfsTokenURI && !isDisplayNFTMediaToggleEnabled) {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n\n if (hasIpfsTokenURI) {\n tokenURI = getFormattedIpfsUrl(\n this.#ipfsGateway,\n tokenURI,\n this.#useIpfsSubdomains,\n );\n }\n\n try {\n const object = await handleFetch(tokenURI);\n // TODO: Check image_url existence. This is not part of EIP721 nor EIP1155\n const image = Object.prototype.hasOwnProperty.call(object, 'image')\n ? 'image'\n : /* istanbul ignore next */ 'image_url';\n\n return {\n image: object[image],\n name: object.name,\n description: object.description,\n standard,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n } catch {\n return {\n image: null,\n name: null,\n description: null,\n standard: standard || null,\n favorite: false,\n tokenURI: tokenURI ?? null,\n };\n }\n }\n\n /**\n * Retrieve NFT uri with metadata. TODO Update method to use IPFS.\n *\n * @param contractAddress - NFT contract address.\n * @param tokenId - NFT token id.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving NFT uri and token standard.\n */\n async #getNftURIAndStandard(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<[string, string]> {\n // try ERC721 uri\n try {\n const uri = await this.#getERC721TokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n );\n return [uri, ERC721];\n } catch {\n // Ignore error\n }\n\n // try ERC1155 uri\n try {\n const tokenURI = await this.#getERC1155TokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n );\n\n /**\n * According to EIP1155 the URI value allows for ID substitution\n * in case the string `{id}` exists.\n * https://eips.ethereum.org/EIPS/eip-1155#metadata\n */\n\n if (!tokenURI.includes('{id}')) {\n return [tokenURI, ERC1155];\n }\n\n const hexTokenId = remove0x(BNToHex(new BN(tokenId)))\n .padStart(64, '0')\n .toLowerCase();\n return [tokenURI.replace('{id}', hexTokenId), ERC1155];\n } catch {\n // Ignore error\n }\n\n return ['', ''];\n }\n\n /**\n * Request individual NFT information (name, image url and description).\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftInformation(\n contractAddress: string,\n tokenId: string,\n networkClientId?: NetworkClientId,\n ): Promise<NftMetadata> {\n const chainId = this.#getCorrectChainId({\n networkClientId,\n });\n const [blockchainMetadata, nftApiMetadata] = await Promise.all([\n safelyExecute(() =>\n this.#getNftInformationFromTokenURI(\n contractAddress,\n tokenId,\n networkClientId,\n ),\n ),\n this.#openSeaEnabled && chainId === '0x1'\n ? safelyExecute(() =>\n this.#getNftInformationFromApi(contractAddress, tokenId),\n )\n : undefined,\n ]);\n return {\n ...nftApiMetadata,\n name: blockchainMetadata?.name ?? nftApiMetadata?.name ?? null,\n description:\n blockchainMetadata?.description ?? nftApiMetadata?.description ?? null,\n image: nftApiMetadata?.image ?? blockchainMetadata?.image ?? null,\n standard:\n blockchainMetadata?.standard ?? nftApiMetadata?.standard ?? null,\n tokenURI: blockchainMetadata?.tokenURI ?? null,\n };\n }\n\n /**\n * Request NFT contract information from the contract itself.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the current NFT name and image.\n */\n async #getNftContractInformationFromContract(\n contractAddress: string,\n networkClientId?: NetworkClientId,\n ): Promise<\n Partial<ApiNftContract> &\n Pick<ApiNftContract, 'address'> &\n Pick<ApiNftContract, 'collection'>\n > {\n const [name, symbol] = await Promise.all([\n this.#getERC721AssetName(contractAddress, networkClientId),\n this.#getERC721AssetSymbol(contractAddress, networkClientId),\n ]);\n\n return {\n collection: { name },\n symbol,\n address: contractAddress,\n };\n }\n\n /**\n * Request NFT contract information from Blockchain and aggregate with received data from NFTMetadata.\n *\n * @param contractAddress - Hex address of the NFT contract.\n * @param nftMetadataFromApi - Received NFT information to be aggregated with blockchain contract information.\n * @param networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns Promise resolving to the NFT contract name, image and description.\n */\n async #getNftContractInformation(\n contractAddress: string,\n nftMetadataFromApi: NftMetadata,\n networkClientId?: NetworkClientId,\n ): Promise<\n Partial<ApiNftContract> &\n Pick<ApiNftContract, 'address'> &\n Pick<ApiNftContract, 'collection'>\n > {\n const blockchainContractData = await safelyExecute(() =>\n this.#getNftContractInformationFromContract(\n contractAddress,\n networkClientId,\n ),\n );\n\n if (\n blockchainContractData ||\n !Object.values(nftMetadataFromApi).every((value) => value === null)\n ) {\n return {\n address: contractAddress,\n ...blockchainContractData,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n schema_name: nftMetadataFromApi?.standard ?? null,\n collection: {\n name: null,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\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 // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_contract_type: null,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n created_date: null,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n schema_name: null,\n symbol: null,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n total_supply: null,\n description: null,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n external_link: null,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n collection: { name: null, image_url: null },\n };\n }\n\n /**\n * Adds an individual NFT to the stored NFT list.\n *\n * @param tokenAddress - Hex address of the NFT contract.\n * @param tokenId - The NFT identifier.\n * @param nftMetadata - NFT optional information (name, image and description).\n * @param nftContract - An object containing contract data of the NFT being added.\n * @param chainId - The chainId of the network where the NFT is being added.\n * @param userAddress - The address of the account where the NFT is being added.\n * @param source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @returns A promise resolving to `undefined`.\n */\n async #addIndividualNft(\n tokenAddress: string,\n tokenId: string,\n nftMetadata: NftMetadata,\n nftContract: NftContract,\n chainId: Hex,\n userAddress: string,\n source: Source,\n ): Promise<void> {\n const releaseLock = await this.#mutex.acquire();\n try {\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n const { allNfts } = this.state;\n\n const nfts = [...(allNfts[userAddress]?.[chainId] ?? [])];\n\n const existingEntry = nfts.find(\n (nft) =>\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n nftMetadata,\n existingEntry,\n );\n\n if (!differentMetadata && existingEntry.isCurrentlyOwned) {\n return;\n }\n\n const indexToUpdate = nfts.findIndex(\n (nft) =>\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId,\n );\n\n if (indexToUpdate !== -1) {\n nfts[indexToUpdate] = {\n ...existingEntry,\n ...nftMetadata,\n };\n }\n } else {\n const newEntry: Nft = {\n address: checksumHexAddress,\n tokenId,\n favorite: false,\n isCurrentlyOwned: true,\n ...nftMetadata,\n };\n\n nfts.push(newEntry);\n }\n\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n if (this.#onNftAdded) {\n this.#onNftAdded({\n address: checksumHexAddress,\n symbol: nftContract.symbol,\n tokenId: tokenId.toString(),\n standard: nftMetadata.standard,\n source,\n });\n }\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Adds an NFT contract to the stored NFT contracts list.\n *\n * @param options - options.\n * @param options.tokenAddress - Hex address of the NFT contract.\n * @param options.userAddress - The address of the account where the NFT is being added.\n * @param options.nftMetadata - The retrieved NFTMetadata from API.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.source - Whether the NFT was detected, added manually or suggested by a dapp.\n * @returns Promise resolving to the current NFT contracts list.\n */\n async #addNftContract({\n tokenAddress,\n userAddress,\n networkClientId,\n source,\n nftMetadata,\n }: {\n tokenAddress: string;\n userAddress: string;\n nftMetadata: NftMetadata;\n networkClientId?: NetworkClientId;\n source?: Source;\n }): Promise<NftContract[]> {\n const releaseLock = await this.#mutex.acquire();\n try {\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n const { allNftContracts } = this.state;\n const chainId = this.#getCorrectChainId({\n networkClientId,\n });\n\n const nftContracts = allNftContracts[userAddress]?.[chainId] || [];\n\n const existingEntry = nftContracts.find(\n (nftContract) =>\n nftContract.address.toLowerCase() ===\n checksumHexAddress.toLowerCase(),\n );\n if (existingEntry) {\n return nftContracts;\n }\n\n // this doesn't work currently for detection if the user switches networks while the detection is processing\n // will be fixed once detection uses networkClientIds\n // get name and symbol if ERC721 then put together the metadata\n const contractInformation = await this.#getNftContractInformation(\n checksumHexAddress,\n nftMetadata,\n networkClientId,\n );\n const {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n asset_contract_type,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n created_date,\n symbol,\n description,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n external_link,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n schema_name,\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n collection: { name, image_url, tokenCount },\n } = contractInformation;\n\n // If the nft is auto-detected we want some valid metadata to be present\n if (\n source === Source.Detected &&\n 'address' in contractInformation &&\n typeof contractInformation.address === 'string' &&\n 'collection' in contractInformation &&\n contractInformation.collection.name === null &&\n 'image_url' in contractInformation.collection &&\n contractInformation.collection.image_url === null &&\n Object.entries(contractInformation).every(([key, value]) => {\n return key === 'address' || key === 'collection' || !value;\n })\n ) {\n return nftContracts;\n }\n\n /* istanbul ignore next */\n const newEntry: NftContract = Object.assign(\n {},\n { address: checksumHexAddress },\n description && { description },\n name && { name },\n image_url && { logo: image_url },\n symbol && { symbol },\n tokenCount !== null &&\n typeof tokenCount !== 'undefined' && { totalSupply: tokenCount },\n asset_contract_type && { assetContractType: asset_contract_type },\n created_date && { createdDate: created_date },\n schema_name && { schemaName: schema_name },\n external_link && { externalLink: external_link },\n );\n const newNftContracts = [...nftContracts, newEntry];\n this.#updateNestedNftState(\n newNftContracts,\n ALL_NFTS_CONTRACTS_STATE_KEY,\n {\n chainId,\n userAddress,\n },\n );\n\n return newNftContracts;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Removes an individual NFT from the stored token list and saves it in ignored NFTs list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n #removeAndIgnoreIndividualNft(\n address: string,\n tokenId: string,\n {\n chainId,\n userAddress,\n }: {\n chainId: Hex;\n userAddress: string;\n },\n ) {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNfts, ignoredNfts } = this.state;\n const newIgnoredNfts = [...ignoredNfts];\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const newNfts = nfts.filter((nft) => {\n if (\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId\n ) {\n const alreadyIgnored = newIgnoredNfts.find(\n (c) => c.address === checksumHexAddress && c.tokenId === tokenId,\n );\n !alreadyIgnored && newIgnoredNfts.push(nft);\n return false;\n }\n return true;\n });\n\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n\n this.update((state) => {\n state.ignoredNfts = newIgnoredNfts;\n });\n }\n\n /**\n * Removes an individual NFT from the stored token list.\n *\n * @param address - Hex address of the NFT contract.\n * @param tokenId - Token identifier of the NFT.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n */\n #removeIndividualNft(\n address: string,\n tokenId: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ) {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNfts } = this.state;\n const nfts = allNfts[userAddress]?.[chainId] || [];\n const newNfts = nfts.filter(\n (nft) =>\n !(\n nft.address.toLowerCase() === checksumHexAddress.toLowerCase() &&\n nft.tokenId === tokenId\n ),\n );\n this.#updateNestedNftState(newNfts, ALL_NFTS_STATE_KEY, {\n userAddress,\n chainId,\n });\n }\n\n /**\n * Removes an NFT contract to the stored NFT contracts list.\n *\n * @param address - Hex address of the NFT contract.\n * @param options - options.\n * @param options.chainId - The chainId of the network where the NFT is being removed.\n * @param options.userAddress - The address of the account where the NFT is being removed.\n * @returns Promise resolving to the current NFT contracts list.\n */\n #removeNftContract(\n address: string,\n { chainId, userAddress }: { chainId: Hex; userAddress: string },\n ): NftContract[] {\n const checksumHexAddress = toChecksumHexAddress(address);\n const { allNftContracts } = this.state;\n const nftContracts = allNftContracts[userAddress]?.[chainId] || [];\n\n const newNftContracts = nftContracts.filter(\n (nftContract) =>\n !(\n nftContract.address.toLowerCase() === checksumHexAddress.toLowerCase()\n ),\n );\n this.#updateNestedNftState(newNftContracts, ALL_NFTS_CONTRACTS_STATE_KEY, {\n chainId,\n userAddress,\n });\n\n return newNftContracts;\n }\n\n async #validateWatchNft(\n asset: NftAsset,\n type: NFTStandardType,\n userAddress: string,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ) {\n const { address: contractAddress, tokenId } = asset;\n\n // Validate parameters\n if (!type) {\n throw rpcErrors.invalidParams('Asset type is required');\n }\n\n if (type !== ERC721 && type !== ERC1155) {\n throw rpcErrors.invalidParams(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Non NFT asset type ${type} not supported by watchNft`,\n );\n }\n\n if (!contractAddress || !tokenId) {\n throw rpcErrors.invalidParams('Both address and tokenId are required');\n }\n\n if (!isAddress(contractAddress)) {\n throw rpcErrors.invalidParams('Invalid address');\n }\n\n if (!/^\\d+$/u.test(tokenId)) {\n throw rpcErrors.invalidParams('Invalid tokenId');\n }\n\n // Check if the user owns the suggested NFT\n try {\n const isOwner = await this.isNftOwner(\n userAddress,\n contractAddress,\n tokenId,\n { networkClientId },\n );\n if (!isOwner) {\n throw rpcErrors.invalidInput(\n 'Suggested NFT is not owned by the selected account',\n );\n }\n } catch (error) {\n // error thrown here: \"Unable to verify ownership. Possibly because the standard is not supported or the user's currently selected network does not match the chain of the asset in question.\"\n if (error instanceof Error) {\n throw rpcErrors.resourceUnavailable(error.message);\n }\n throw error;\n }\n }\n\n // temporary method to get the correct chainId until we remove chainId from the config & the chainId arg from the detection logic\n // Just a helper method to prefer the networkClient chainId first then the chainId argument and then finally the config chainId\n #getCorrectChainId({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n }) {\n if (networkClientId) {\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return chainId;\n }\n return this.#chainId;\n }\n\n /**\n * Adds a new suggestedAsset to state. Parameters will be validated according to\n * asset type being watched. A `<suggestedNftMeta.id>:pending` hub event will be emitted once added.\n *\n * @param asset - The asset to be watched. For now ERC721 and ERC1155 tokens are accepted.\n * @param asset.address - The address of the asset contract.\n * @param asset.tokenId - The ID of the asset.\n * @param type - The asset type.\n * @param origin - Domain origin to register the asset from.\n * @param options - Options bag.\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT is being added.\n * @returns Object containing a Promise resolving to the suggestedAsset address if accepted.\n */\n async watchNft(\n asset: NftAsset,\n type: NFTStandardType,\n origin: string,\n {\n networkClientId,\n userAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n if (!addressToSearch) {\n return;\n }\n\n await this.#validateWatchNft(asset, type, addressToSearch);\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: addressToSearch,\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,\n networkClientId,\n source,\n }: {\n userAddress?: string;\n networkClientId?: NetworkClientId;\n source?: Source;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n\n if (\n !(await this.isNftOwner(addressToSearch, 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: addressToSearch,\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,\n source = Source.Custom,\n networkClientId,\n }: {\n nftMetadata?: NftMetadata;\n userAddress?: string;\n source?: Source;\n networkClientId?: NetworkClientId;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n if (!addressToSearch) {\n return;\n }\n\n const checksumHexAddress = toChecksumHexAddress(tokenAddress);\n\n const chainId = this.#getCorrectChainId({ networkClientId });\n\n nftMetadata =\n nftMetadata ||\n (await this.#getNftInformation(\n checksumHexAddress,\n tokenId,\n networkClientId,\n ));\n\n const newNftContracts = await this.#addNftContract({\n tokenAddress: checksumHexAddress,\n userAddress: addressToSearch,\n networkClientId,\n source,\n nftMetadata,\n });\n\n // If NFT contract was not added, do not add individual NFT\n const nftContract = newNftContracts.find(\n (contract) =>\n contract.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n\n // If NFT contract information, add individual NFT\n if (nftContract) {\n await this.#addIndividualNft(\n checksumHexAddress,\n tokenId,\n nftMetadata,\n nftContract,\n chainId,\n addressToSearch,\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,\n networkClientId,\n }: {\n nfts: Nft[];\n userAddress?: string;\n networkClientId?: NetworkClientId;\n }) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n\n const releaseLock = await this.#mutex.acquire();\n\n try {\n const chainId = this.#getCorrectChainId({ networkClientId });\n\n const nftsWithChecksumAdr = nfts.map((nft) => {\n return {\n ...nft,\n address: toChecksumHexAddress(nft.address),\n };\n });\n const nftMetadataResults = await Promise.all(\n nftsWithChecksumAdr.map(async (nft) => {\n const resMetadata = await this.#getNftInformation(\n nft.address,\n nft.tokenId,\n networkClientId,\n );\n return {\n nft,\n newMetadata: resMetadata,\n };\n }),\n );\n\n // We want to avoid updating the state if the state and fetched nft info are the same\n const nftsWithDifferentMetadata: NftUpdate[] = [];\n const { allNfts } = this.state;\n const stateNfts = allNfts[addressToSearch]?.[chainId] || [];\n\n nftMetadataResults.forEach((singleNft) => {\n const existingEntry: Nft | undefined = stateNfts.find(\n (nft) =>\n nft.address.toLowerCase() === singleNft.nft.address.toLowerCase() &&\n nft.tokenId === singleNft.nft.tokenId,\n );\n\n if (existingEntry) {\n const differentMetadata = compareNftMetadata(\n singleNft.newMetadata,\n existingEntry,\n );\n\n if (differentMetadata) {\n nftsWithDifferentMetadata.push(singleNft);\n }\n }\n });\n\n if (nftsWithDifferentMetadata.length !== 0) {\n nftsWithDifferentMetadata.forEach((elm) =>\n this.updateNft(elm.nft, elm.newMetadata, addressToSearch, chainId),\n );\n }\n } finally {\n releaseLock();\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,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const checksumHexAddress = toChecksumHexAddress(address);\n this.#removeIndividualNft(checksumHexAddress, tokenId, {\n chainId,\n userAddress: addressToSearch,\n });\n const { allNfts } = this.state;\n const nfts = allNfts[addressToSearch]?.[chainId] || [];\n const remainingNft = nfts.find(\n (nft) => nft.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n\n if (!remainingNft) {\n this.#removeNftContract(checksumHexAddress, {\n chainId,\n userAddress: addressToSearch,\n });\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,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const checksumHexAddress = toChecksumHexAddress(address);\n this.#removeAndIgnoreIndividualNft(checksumHexAddress, tokenId, {\n chainId,\n userAddress: addressToSearch,\n });\n const { allNfts } = this.state;\n const nfts = allNfts[addressToSearch]?.[chainId] || [];\n const remainingNft = nfts.find(\n (nft) => nft.address.toLowerCase() === checksumHexAddress.toLowerCase(),\n );\n if (!remainingNft) {\n this.#removeNftContract(checksumHexAddress, {\n chainId,\n userAddress: addressToSearch,\n });\n }\n }\n\n /**\n * Removes all NFTs from the ignored list.\n */\n clearIgnoredNfts() {\n this.update((state) => {\n state.ignoredNfts = [];\n });\n }\n\n /**\n * Checks whether input NFT is still owned by the user\n * And updates the isCurrentlyOwned value on the NFT object accordingly.\n *\n * @param nft - The NFT object to check and update.\n * @param batch - A boolean indicating whether this method is being called as part of a batch or single update.\n * @param accountParams - The userAddress and chainId to check ownership against\n * @param accountParams.userAddress - the address passed through the confirmed transaction flow to ensure assets are stored to the correct account\n * @param accountParams.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @returns the NFT with the updated isCurrentlyOwned value\n */\n async checkAndUpdateSingleNftOwnershipStatus(\n nft: Nft,\n batch: boolean,\n {\n userAddress,\n networkClientId,\n }: { networkClientId?: NetworkClientId; userAddress?: string } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { address, tokenId } = nft;\n let isOwned = nft.isCurrentlyOwned;\n try {\n isOwned = await this.isNftOwner(addressToSearch, address, tokenId, {\n networkClientId,\n });\n } catch {\n // ignore error\n // this will only throw an error 'Unable to verify ownership' in which case\n // we want to keep the current value of isCurrentlyOwned for this flow.\n }\n\n const updatedNft = {\n ...nft,\n isCurrentlyOwned: isOwned,\n };\n\n if (batch) {\n return updatedNft;\n }\n\n // if this is not part of a batched update we update this one NFT in state\n const { allNfts } = this.state;\n const nfts = [...(allNfts[addressToSearch]?.[chainId] || [])];\n const indexToUpdate = nfts.findIndex(\n (item) =>\n item.tokenId === tokenId &&\n item.address.toLowerCase() === address.toLowerCase(),\n );\n\n if (indexToUpdate !== -1) {\n nfts[indexToUpdate] = updatedNft;\n this.update((state) => {\n state.allNfts[addressToSearch] = Object.assign(\n {},\n state.allNfts[addressToSearch],\n {\n [chainId]: nfts,\n },\n );\n });\n this.#updateNestedNftState(nfts, ALL_NFTS_STATE_KEY, {\n userAddress: addressToSearch,\n chainId,\n });\n }\n\n return updatedNft;\n }\n\n /**\n * Checks whether NFTs associated with current selectedAddress/chainId combination are still owned by the user\n * And updates the isCurrentlyOwned value on each accordingly.\n * @param options - an object of arguments\n * @param options.networkClientId - The networkClientId that can be used to identify the network client to use for this request.\n * @param options.userAddress - The address of the account where the NFT ownership status is checked/updated.\n */\n async checkAndUpdateAllNftsOwnershipStatus({\n networkClientId,\n userAddress,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {}) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { allNfts } = this.state;\n const nfts = allNfts[addressToSearch]?.[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: addressToSearch,\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,\n }: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n } = {},\n ) {\n const addressToSearch = this.#getAddressOrSelectedAddress(userAddress);\n const chainId = this.#getCorrectChainId({ networkClientId });\n const { allNfts } = this.state;\n const nfts = [...(allNfts[addressToSearch]?.[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: addressToSearch,\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 #getAddressOrSelectedAddress(address: string | undefined): string {\n if (address) {\n return address;\n }\n\n // If the address is not defined (or empty), we fallback to the currently selected account's address\n const selectedAccount = this.messagingSystem.call(\n 'AccountsController:getAccount',\n this.#selectedAccountId,\n );\n return selectedAccount?.address || '';\n }\n\n async #updateNftUpdateForAccount(account: InternalAccount) {\n const nfts: Nft[] =\n this.state.allNfts[account.address]?.[this.#chainId] ?? [];\n\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: account.address,\n });\n }\n }\n}\n\nexport default NftController;\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,iBAAiB;AAW1B;AAAA,EACE;AAAA,OAEK;AACP;AAAA,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