@metamask/assets-controllers 53.0.0 → 53.1.1
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 +17 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs +4 -0
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.cts +2 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.cts.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.mts +2 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.d.mts.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs +4 -0
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
- package/dist/NftDetectionController.cjs +3 -1
- package/dist/NftDetectionController.cjs.map +1 -1
- package/dist/NftDetectionController.d.cts.map +1 -1
- package/dist/NftDetectionController.d.mts.map +1 -1
- package/dist/NftDetectionController.mjs +3 -1
- package/dist/NftDetectionController.mjs.map +1 -1
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs +170 -0
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts +77 -0
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts +77 -0
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs +165 -0
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/index.cjs +18 -0
- package/dist/TokenSearchDiscoveryDataController/index.cjs.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/index.d.cts +3 -0
- package/dist/TokenSearchDiscoveryDataController/index.d.cts.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/index.d.mts +3 -0
- package/dist/TokenSearchDiscoveryDataController/index.d.mts.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/index.mjs +2 -0
- package/dist/TokenSearchDiscoveryDataController/index.mjs.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/types.cjs +3 -0
- package/dist/TokenSearchDiscoveryDataController/types.cjs.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/types.d.cts +19 -0
- package/dist/TokenSearchDiscoveryDataController/types.d.cts.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/types.d.mts +19 -0
- package/dist/TokenSearchDiscoveryDataController/types.d.mts.map +1 -0
- package/dist/TokenSearchDiscoveryDataController/types.mjs +2 -0
- package/dist/TokenSearchDiscoveryDataController/types.mjs.map +1 -0
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NftDetectionController.mjs","sourceRoot":"","sources":["../src/NftDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EACL,oBAAoB,EACpB,OAAO,EACP,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,WAAW,EACX,sBAAsB,EACtB,eAAe,EAChB,mCAAmC;AAapC,OAAO,EAAE,qBAAqB,EAAY,wBAAwB;AAElE,OAAO,EAAE,uBAAuB,EAAE,yBAAqB;AACvD,OAAO,EAAE,MAAM,EAAE,wBAAoB;AAOrC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAsBhD,MAAM,6BAA6B,GAAU;I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A,IAAI,iFAAgB,MAApB,IAAI,EAAiB;QAC/B,OAAO,EAAE,gBAAgB;QACzB,OAAO;QACP,IAAI,EAAE,MAAM;KACb,CAAC,CAAC;IACH,MAAM,cAAc,GAAsB,MAAM,WAAW,CAAC,GAAG,EAAE;QAC/D,OAAO,EAAE;YACP,OAAO,EAAE,eAAe;SACzB;KACF,CAAC,CAAC;IACH,OAAO,cAAc,CAAC;AACxB,CAAC;AAiNH,eAAe,sBAAsB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type { RestrictedMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n fetchWithErrorHandling,\n NFT_API_TIMEOUT,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkClient,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\n\nimport { reduceInBatchesSerially } from './assetsUtil';\nimport { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\nconst supportedNftDetectionNetworks: Hex[] = [\n ChainId.mainnet,\n ChainId['linea-mainnet'],\n];\n\n/**\n * @type ApiNft\n *\n * NFT object coming from OpenSea api\n * @property token_id - The NFT identifier\n * @property num_sales - Number of sales\n * @property background_color - The background color to be displayed with the item\n * @property image_url - URI of an image associated with this NFT\n * @property image_preview_url - URI of a smaller image associated with this NFT\n * @property image_thumbnail_url - URI of a thumbnail image associated with this NFT\n * @property image_original_url - URI of the original image associated with this NFT\n * @property animation_url - URI of a animation associated with this NFT\n * @property animation_original_url - URI of the original animation associated with this NFT\n * @property name - The NFT name\n * @property description - The NFT description\n * @property external_link - External link containing additional information\n * @property assetContract - The NFT contract information object\n * @property creator - The NFT owner information object\n * @property lastSale - When this item was last sold\n */\nexport type ApiNft = {\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_id: 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 num_sales: number | 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 background_color: string | 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: string | 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_preview_url: string | 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_thumbnail_url: string | 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_original_url: string | 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 animation_url: string | 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 animation_original_url: string | null;\n name: string | null;\n description: string | 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: string | 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 asset_contract: ApiNftContract;\n creator: ApiNftCreator;\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 last_sale: ApiNftLastSale | null;\n};\n\n/**\n * @type ApiNftContract\n *\n * NFT contract object coming from OpenSea api\n * @property address - Address of the NFT contract\n * @property asset_contract_type - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property created_date - Creation date\n * @property collection - Object containing the contract name and URI of an image associated\n * @property schema_name - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property symbol - The NFT contract symbol\n * @property total_supply - Total supply of NFTs\n * @property description - The NFT contract description\n * @property external_link - External link containing additional information\n */\nexport type ApiNftContract = {\n address: 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_contract_type: string | 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: string | 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: string | null;\n symbol: string | 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: string | null;\n description: string | 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: string | null;\n collection: {\n name: string | 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?: string | null;\n tokenCount?: string | null;\n };\n};\n\n/**\n * @type ApiNftLastSale\n *\n * NFT sale object coming from OpenSea api\n * @property event_timestamp - Object containing a `username`\n * @property total_price - URI of NFT image associated with this owner\n * @property transaction - Object containing transaction_hash and block_hash\n */\nexport type ApiNftLastSale = {\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 event_timestamp: 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 total_price: 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 transaction: { transaction_hash: string; block_hash: string };\n};\n\n/**\n * @type ApiNftCreator\n *\n * NFT creator object coming from OpenSea api\n * @property user - Object containing a `username`\n * @property profile_img_url - URI of NFT image associated with this owner\n * @property address - The owner address\n */\nexport type ApiNftCreator = {\n user: { username: 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 profile_img_url: string;\n address: string;\n};\n\nexport type ReservoirResponse = {\n tokens: TokensResponse[];\n continuation?: string;\n};\n\nexport type TokensResponse = {\n token: TokenResponse;\n ownership: Ownership;\n market?: Market;\n blockaidResult?: Blockaid;\n};\n\nexport enum BlockaidResultType {\n Benign = 'Benign',\n Spam = 'Spam',\n Warning = 'Warning',\n Malicious = 'Malicious',\n}\n\nexport type Blockaid = {\n contract: string;\n chainId: number;\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 result_type: BlockaidResultType;\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 malicious_score: 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 attack_types: object;\n};\n\nexport type Market = {\n floorAsk?: FloorAsk;\n topBid?: TopBid;\n};\n\nexport type TokenResponse = {\n chainId: number;\n contract: string;\n tokenId: string;\n kind?: string;\n name?: string;\n image?: string;\n imageSmall?: string;\n imageLarge?: string;\n metadata?: Metadata;\n description?: string;\n supply?: number;\n remainingSupply?: number;\n rarityScore?: number;\n rarity?: number;\n rarityRank?: number;\n media?: string;\n isFlagged?: boolean;\n isSpam?: boolean;\n isNsfw?: boolean;\n metadataDisabled?: boolean;\n lastFlagUpdate?: string;\n lastFlagChange?: string;\n collection?: Collection;\n lastSale?: LastSale;\n topBid?: TopBid;\n lastAppraisalValue?: number;\n attributes?: Attributes[];\n};\n\nexport type TopBid = {\n id?: string;\n price?: Price;\n source?: {\n id?: string;\n domain?: string;\n name?: string;\n icon?: string;\n url?: string;\n };\n};\n\nexport type LastSale = {\n saleId?: string;\n token?: {\n contract?: string;\n tokenId?: string;\n name?: string;\n image?: string;\n collection?: {\n id?: string;\n name?: string;\n };\n };\n orderSource?: string;\n orderSide?: 'ask' | 'bid';\n orderKind?: string;\n orderId?: string;\n from?: string;\n to?: string;\n amount?: string;\n fillSource?: string;\n block?: number;\n txHash?: string;\n logIndex?: number;\n batchIndex?: number;\n timestamp?: number;\n price?: Price;\n washTradingScore?: number;\n royaltyFeeBps?: number;\n marketplaceFeeBps?: number;\n paidFullRoyalty?: boolean;\n feeBreakdown?: FeeBreakdown[];\n isDeleted?: boolean;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type FeeBreakdown = {\n kind?: string;\n bps?: number;\n recipient?: string;\n source?: string;\n rawAmount?: string;\n};\n\nexport type Attributes = {\n key?: string;\n kind?: string;\n value: string;\n tokenCount?: number;\n onSaleCount?: number;\n floorAskPrice?: Price | null;\n topBidValue?: number | null;\n createdAt?: string;\n};\n\nexport type GetCollectionsResponse = {\n collections: CollectionResponse[];\n};\n\nexport type CollectionResponse = {\n id?: string;\n openseaVerificationStatus?: string;\n contractDeployedAt?: string;\n creator?: string;\n ownerCount?: string;\n topBid?: TopBid & {\n sourceDomain?: string;\n };\n};\n\nexport type FloorAskCollection = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: SourceCollection;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type SourceCollection = {\n id: string;\n domain: string;\n name: string;\n icon: string;\n url: string;\n};\n\nexport type TokenCollection = {\n id?: string;\n name?: string;\n slug?: string;\n symbol?: string;\n imageUrl?: string;\n image?: string;\n isSpam?: boolean;\n isNsfw?: boolean;\n creator?: string;\n tokenCount?: string;\n metadataDisabled?: boolean;\n openseaVerificationStatus?: string;\n floorAskPrice?: Price;\n royaltiesBps?: number;\n royalties?: Royalties[];\n floorAsk?: FloorAskCollection;\n};\n\nexport type Collection = TokenCollection & CollectionResponse;\n\nexport type Royalties = {\n bps?: number;\n recipient?: string;\n};\n\nexport type Ownership = {\n tokenCount?: string;\n onSaleCount?: string;\n floorAsk?: FloorAsk;\n acquiredAt?: string;\n};\n\nexport type FloorAsk = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: Source;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type Price = {\n currency?: {\n contract?: string;\n name?: string;\n symbol?: string;\n decimals?: number;\n chainId?: number;\n };\n amount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n netAmount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n};\n\nexport type Metadata = {\n imageOriginal?: string;\n tokenURI?: string;\n};\n\nexport const MAX_GET_COLLECTION_BATCH_SIZE = 20;\n\n/**\n * Controller that passively detects nfts for a user address\n */\nexport class NftDetectionController extends BaseController<\n typeof controllerName,\n NFTDetectionControllerState,\n NftDetectionControllerMessenger\n> {\n #disabled: boolean;\n\n readonly #addNft: NftController['addNft'];\n\n readonly #getNftState: () => NftControllerState;\n\n #inProcessNftFetchingUpdates: Record<`${Hex}:${string}`, Promise<void>>;\n\n /**\n * The controller options\n *\n * @param options - The controller options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.\n * @param options.addNft - Add an NFT.\n * @param options.getNftState - Gets the current state of the Assets controller.\n */\n constructor({\n messenger,\n disabled = false,\n addNft,\n getNftState,\n }: {\n messenger: NftDetectionControllerMessenger;\n disabled: boolean;\n addNft: NftController['addNft'];\n getNftState: () => NftControllerState;\n }) {\n super({\n name: controllerName,\n messenger,\n metadata: {},\n state: {},\n });\n this.#disabled = disabled;\n this.#inProcessNftFetchingUpdates = {};\n\n this.#getNftState = getNftState;\n this.#addNft = addNft;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesControllerStateChange.bind(this),\n );\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet(): boolean {\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 chainId === ChainId.mainnet;\n }\n\n isMainnetByNetworkClientId(networkClient: NetworkClient): boolean {\n return networkClient.configuration.chainId === ChainId.mainnet;\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.useNftDetection - Boolean indicating user preference on NFT detection.\n */\n #onPreferencesControllerStateChange({ useNftDetection }: PreferencesState) {\n if (!useNftDetection !== this.#disabled) {\n this.#disabled = !useNftDetection;\n }\n }\n\n #getOwnerNftApi({\n chainId,\n address,\n next,\n }: {\n chainId: string;\n address: string;\n next?: string;\n }) {\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainId}&limit=50&includeTopBid=true&continuation=${\n next ?? ''\n }`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainId: Hex,\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainId = convertHexToDecimal(chainId).toString();\n const url = this.#getOwnerNftApi({\n chainId: convertedChainId,\n address,\n next: cursor,\n });\n const nftApiResponse: ReservoirResponse = await handleFetch(url, {\n headers: {\n Version: NFT_API_VERSION,\n },\n });\n return nftApiResponse;\n }\n\n /**\n * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are\n * added.\n *\n * @param options - Options bag.\n * @param options.networkClientId - The network client ID to detect NFTs on.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(options?: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n }) {\n const userAddress =\n options?.userAddress ??\n this.messagingSystem.call('AccountsController:getSelectedAccount')\n .address;\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\n /* istanbul ignore if */\n if (!supportedNftDetectionNetworks.includes(chainId) || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const updateKey: `${Hex}:${string}` = `${chainId}:${userAddress}`;\n if (updateKey in this.#inProcessNftFetchingUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessNftFetchingUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessNftFetchingUpdates[updateKey] = inProgressUpdate;\n\n let next;\n let apiNfts: TokensResponse[] = [];\n let resultNftApi: ReservoirResponse;\n try {\n do {\n resultNftApi = await this.#getOwnerNfts(userAddress, chainId, next);\n apiNfts = resultNftApi.tokens.filter(\n (elm) =>\n elm.token.isSpam === false &&\n (elm.blockaidResult?.result_type\n ? elm.blockaidResult?.result_type === BlockaidResultType.Benign\n : true),\n );\n // Retrieve collections from apiNfts\n // contract and collection.id are equal for simple contract addresses; this is to exclude cases for shared contracts\n const collections = apiNfts.reduce<string[]>((acc, currValue) => {\n if (\n !acc.includes(currValue.token.contract) &&\n currValue.token.contract === currValue?.token?.collection?.id\n ) {\n acc.push(currValue.token.contract);\n }\n return acc;\n }, []);\n\n if (collections.length !== 0) {\n // Call API to retrive collections infos\n // The api accept a max of 20 contracts\n const collectionResponse: GetCollectionsResponse =\n await reduceInBatchesSerially({\n values: collections,\n batchSize: MAX_GET_COLLECTION_BATCH_SIZE,\n eachBatch: async (allResponses, batch) => {\n const params = new URLSearchParams(\n batch.map((s) => ['contract', s]),\n );\n params.append('chainId', '1'); // Adding chainId 1 because we are only detecting for mainnet\n const collectionResponseForBatch = await fetchWithErrorHandling(\n {\n url: `${\n NFT_API_BASE_URL as string\n }/collections?${params.toString()}`,\n options: {\n headers: {\n Version: NFT_API_VERSION,\n },\n },\n timeout: NFT_API_TIMEOUT,\n },\n );\n\n return {\n ...allResponses,\n ...collectionResponseForBatch,\n };\n },\n initialResult: {},\n });\n\n // Add collections response fields to newnfts\n if (collectionResponse.collections?.length) {\n apiNfts.forEach((singleNFT) => {\n const found = collectionResponse.collections.find(\n (elm) =>\n elm.id?.toLowerCase() ===\n singleNFT.token.contract.toLowerCase(),\n );\n if (found) {\n singleNFT.token = {\n ...singleNFT.token,\n collection: {\n ...(singleNFT.token.collection ?? {}),\n creator: found?.creator,\n openseaVerificationStatus: found?.openseaVerificationStatus,\n contractDeployedAt: found.contractDeployedAt,\n ownerCount: found.ownerCount,\n topBid: found.topBid,\n },\n };\n }\n });\n }\n }\n\n // Proceed to add NFTs\n const addNftPromises = apiNfts.map(async (nft) => {\n const {\n tokenId,\n contract,\n kind,\n image: imageUrl,\n imageSmall: imageThumbnailUrl,\n metadata: { imageOriginal: imageOriginalUrl } = {},\n name,\n description,\n attributes,\n topBid,\n lastSale,\n rarityRank,\n rarityScore,\n collection,\n } = nft.token;\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.#getNftState();\n if (ignoredNfts.length) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(contract) &&\n c.tokenId === tokenId\n );\n });\n }\n\n /* istanbul ignore else */\n if (!ignored) {\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name },\n description && { description },\n imageUrl && { image: imageUrl },\n imageThumbnailUrl && { imageThumbnail: imageThumbnailUrl },\n imageOriginalUrl && { imageOriginal: imageOriginalUrl },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n topBid && { topBid },\n rarityRank && { rarityRank },\n rarityScore && { rarityScore },\n collection && { collection },\n );\n await this.#addNft(contract, tokenId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId: options?.networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n } while ((next = resultNftApi.continuation));\n updateSucceeded();\n } catch (error) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessNftFetchingUpdates[updateKey];\n }\n }\n}\n\nexport default NftDetectionController;\n"]}
|
|
1
|
+
{"version":3,"file":"NftDetectionController.mjs","sourceRoot":"","sources":["../src/NftDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,OAAO,EAAE,cAAc,EAAE,kCAAkC;AAC3D,OAAO,EACL,oBAAoB,EACpB,OAAO,EACP,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,WAAW,EACX,sBAAsB,EACtB,eAAe,EAChB,mCAAmC;AAapC,OAAO,EAAE,qBAAqB,EAAY,wBAAwB;AAElE,OAAO,EAAE,uBAAuB,EAAE,yBAAqB;AACvD,OAAO,EAAE,MAAM,EAAE,wBAAoB;AAOrC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AAsBhD,MAAM,6BAA6B,GAAU;IAC3C,OAAO,CAAC,OAAO;IACf,OAAO,CAAC,eAAe,CAAC;CACzB,CAAC;AA0JF,MAAM,CAAN,IAAY,kBAKX;AALD,WAAY,kBAAkB;IAC5B,uCAAiB,CAAA;IACjB,mCAAa,CAAA;IACb,yC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AM,cAAc,GAAsB,MAAM,WAAW,CAAC,GAAG,EAAE;QAC/D,OAAO,EAAE;YACP,OAAO,EAAE,eAAe;SACzB;KACF,CAAC,CAAC;IACH,OAAO,cAAc,CAAC;AACxB,CAAC;AAoNH,eAAe,sBAAsB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type { RestrictedMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n fetchWithErrorHandling,\n NFT_API_TIMEOUT,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkClient,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\n\nimport { reduceInBatchesSerially } from './assetsUtil';\nimport { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\nconst supportedNftDetectionNetworks: Hex[] = [\n ChainId.mainnet,\n ChainId['linea-mainnet'],\n];\n\n/**\n * @type ApiNft\n *\n * NFT object coming from OpenSea api\n * @property token_id - The NFT identifier\n * @property num_sales - Number of sales\n * @property background_color - The background color to be displayed with the item\n * @property image_url - URI of an image associated with this NFT\n * @property image_preview_url - URI of a smaller image associated with this NFT\n * @property image_thumbnail_url - URI of a thumbnail image associated with this NFT\n * @property image_original_url - URI of the original image associated with this NFT\n * @property animation_url - URI of a animation associated with this NFT\n * @property animation_original_url - URI of the original animation associated with this NFT\n * @property name - The NFT name\n * @property description - The NFT description\n * @property external_link - External link containing additional information\n * @property assetContract - The NFT contract information object\n * @property creator - The NFT owner information object\n * @property lastSale - When this item was last sold\n */\nexport type ApiNft = {\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_id: 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 num_sales: number | 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 background_color: string | 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: string | 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_preview_url: string | 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_thumbnail_url: string | 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_original_url: string | 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 animation_url: string | 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 animation_original_url: string | null;\n name: string | null;\n description: string | 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: string | 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 asset_contract: ApiNftContract;\n creator: ApiNftCreator;\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 last_sale: ApiNftLastSale | null;\n};\n\n/**\n * @type ApiNftContract\n *\n * NFT contract object coming from OpenSea api\n * @property address - Address of the NFT contract\n * @property asset_contract_type - The NFT type, it could be `semi-fungible` or `non-fungible`\n * @property created_date - Creation date\n * @property collection - Object containing the contract name and URI of an image associated\n * @property schema_name - The schema followed by the contract, it could be `ERC721` or `ERC1155`\n * @property symbol - The NFT contract symbol\n * @property total_supply - Total supply of NFTs\n * @property description - The NFT contract description\n * @property external_link - External link containing additional information\n */\nexport type ApiNftContract = {\n address: 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_contract_type: string | 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: string | 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: string | null;\n symbol: string | 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: string | null;\n description: string | 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: string | null;\n collection: {\n name: string | 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?: string | null;\n tokenCount?: string | null;\n };\n};\n\n/**\n * @type ApiNftLastSale\n *\n * NFT sale object coming from OpenSea api\n * @property event_timestamp - Object containing a `username`\n * @property total_price - URI of NFT image associated with this owner\n * @property transaction - Object containing transaction_hash and block_hash\n */\nexport type ApiNftLastSale = {\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 event_timestamp: 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 total_price: 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 transaction: { transaction_hash: string; block_hash: string };\n};\n\n/**\n * @type ApiNftCreator\n *\n * NFT creator object coming from OpenSea api\n * @property user - Object containing a `username`\n * @property profile_img_url - URI of NFT image associated with this owner\n * @property address - The owner address\n */\nexport type ApiNftCreator = {\n user: { username: 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 profile_img_url: string;\n address: string;\n};\n\nexport type ReservoirResponse = {\n tokens: TokensResponse[];\n continuation?: string;\n};\n\nexport type TokensResponse = {\n token: TokenResponse;\n ownership: Ownership;\n market?: Market;\n blockaidResult?: Blockaid;\n};\n\nexport enum BlockaidResultType {\n Benign = 'Benign',\n Spam = 'Spam',\n Warning = 'Warning',\n Malicious = 'Malicious',\n}\n\nexport type Blockaid = {\n contract: string;\n chainId: number;\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 result_type: BlockaidResultType;\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 malicious_score: 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 attack_types: object;\n};\n\nexport type Market = {\n floorAsk?: FloorAsk;\n topBid?: TopBid;\n};\n\nexport type TokenResponse = {\n chainId: number;\n contract: string;\n tokenId: string;\n kind?: string;\n name?: string;\n image?: string;\n imageSmall?: string;\n imageLarge?: string;\n metadata?: Metadata;\n description?: string;\n supply?: number;\n remainingSupply?: number;\n rarityScore?: number;\n rarity?: number;\n rarityRank?: number;\n media?: string;\n isFlagged?: boolean;\n isSpam?: boolean;\n isNsfw?: boolean;\n metadataDisabled?: boolean;\n lastFlagUpdate?: string;\n lastFlagChange?: string;\n collection?: Collection;\n lastSale?: LastSale;\n topBid?: TopBid;\n lastAppraisalValue?: number;\n attributes?: Attributes[];\n};\n\nexport type TopBid = {\n id?: string;\n price?: Price;\n source?: {\n id?: string;\n domain?: string;\n name?: string;\n icon?: string;\n url?: string;\n };\n};\n\nexport type LastSale = {\n saleId?: string;\n token?: {\n contract?: string;\n tokenId?: string;\n name?: string;\n image?: string;\n collection?: {\n id?: string;\n name?: string;\n };\n };\n orderSource?: string;\n orderSide?: 'ask' | 'bid';\n orderKind?: string;\n orderId?: string;\n from?: string;\n to?: string;\n amount?: string;\n fillSource?: string;\n block?: number;\n txHash?: string;\n logIndex?: number;\n batchIndex?: number;\n timestamp?: number;\n price?: Price;\n washTradingScore?: number;\n royaltyFeeBps?: number;\n marketplaceFeeBps?: number;\n paidFullRoyalty?: boolean;\n feeBreakdown?: FeeBreakdown[];\n isDeleted?: boolean;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type FeeBreakdown = {\n kind?: string;\n bps?: number;\n recipient?: string;\n source?: string;\n rawAmount?: string;\n};\n\nexport type Attributes = {\n key?: string;\n kind?: string;\n value: string;\n tokenCount?: number;\n onSaleCount?: number;\n floorAskPrice?: Price | null;\n topBidValue?: number | null;\n createdAt?: string;\n};\n\nexport type GetCollectionsResponse = {\n collections: CollectionResponse[];\n};\n\nexport type CollectionResponse = {\n id?: string;\n openseaVerificationStatus?: string;\n contractDeployedAt?: string;\n creator?: string;\n ownerCount?: string;\n topBid?: TopBid & {\n sourceDomain?: string;\n };\n};\n\nexport type FloorAskCollection = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: SourceCollection;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type SourceCollection = {\n id: string;\n domain: string;\n name: string;\n icon: string;\n url: string;\n};\n\nexport type TokenCollection = {\n id?: string;\n name?: string;\n slug?: string;\n symbol?: string;\n imageUrl?: string;\n image?: string;\n isSpam?: boolean;\n isNsfw?: boolean;\n creator?: string;\n tokenCount?: string;\n metadataDisabled?: boolean;\n openseaVerificationStatus?: string;\n floorAskPrice?: Price;\n royaltiesBps?: number;\n royalties?: Royalties[];\n floorAsk?: FloorAskCollection;\n};\n\nexport type Collection = TokenCollection & CollectionResponse;\n\nexport type Royalties = {\n bps?: number;\n recipient?: string;\n};\n\nexport type Ownership = {\n tokenCount?: string;\n onSaleCount?: string;\n floorAsk?: FloorAsk;\n acquiredAt?: string;\n};\n\nexport type FloorAsk = {\n id?: string;\n price?: Price;\n maker?: string;\n kind?: string;\n validFrom?: number;\n validUntil?: number;\n source?: Source;\n rawData?: Metadata;\n isNativeOffChainCancellable?: boolean;\n};\n\nexport type Price = {\n currency?: {\n contract?: string;\n name?: string;\n symbol?: string;\n decimals?: number;\n chainId?: number;\n };\n amount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n netAmount?: {\n raw?: string;\n decimal?: number;\n usd?: number;\n native?: number;\n };\n};\n\nexport type Metadata = {\n imageOriginal?: string;\n tokenURI?: string;\n};\n\nexport const MAX_GET_COLLECTION_BATCH_SIZE = 20;\n\n/**\n * Controller that passively detects nfts for a user address\n */\nexport class NftDetectionController extends BaseController<\n typeof controllerName,\n NFTDetectionControllerState,\n NftDetectionControllerMessenger\n> {\n #disabled: boolean;\n\n readonly #addNft: NftController['addNft'];\n\n readonly #getNftState: () => NftControllerState;\n\n #inProcessNftFetchingUpdates: Record<`${Hex}:${string}`, Promise<void>>;\n\n /**\n * The controller options\n *\n * @param options - The controller options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.\n * @param options.addNft - Add an NFT.\n * @param options.getNftState - Gets the current state of the Assets controller.\n */\n constructor({\n messenger,\n disabled = false,\n addNft,\n getNftState,\n }: {\n messenger: NftDetectionControllerMessenger;\n disabled: boolean;\n addNft: NftController['addNft'];\n getNftState: () => NftControllerState;\n }) {\n super({\n name: controllerName,\n messenger,\n metadata: {},\n state: {},\n });\n this.#disabled = disabled;\n this.#inProcessNftFetchingUpdates = {};\n\n this.#getNftState = getNftState;\n this.#addNft = addNft;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesControllerStateChange.bind(this),\n );\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet(): boolean {\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 chainId === ChainId.mainnet;\n }\n\n isMainnetByNetworkClientId(networkClient: NetworkClient): boolean {\n return networkClient.configuration.chainId === ChainId.mainnet;\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.useNftDetection - Boolean indicating user preference on NFT detection.\n */\n #onPreferencesControllerStateChange({ useNftDetection }: PreferencesState) {\n if (!useNftDetection !== this.#disabled) {\n this.#disabled = !useNftDetection;\n }\n }\n\n #getOwnerNftApi({\n chainId,\n address,\n next,\n }: {\n chainId: string;\n address: string;\n next?: string;\n }) {\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainId}&limit=50&includeTopBid=true&continuation=${\n next ?? ''\n }`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainId: Hex,\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainId = convertHexToDecimal(chainId).toString();\n const url = this.#getOwnerNftApi({\n chainId: convertedChainId,\n address,\n next: cursor,\n });\n const nftApiResponse: ReservoirResponse = await handleFetch(url, {\n headers: {\n Version: NFT_API_VERSION,\n },\n });\n return nftApiResponse;\n }\n\n /**\n * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are\n * added.\n *\n * @param options - Options bag.\n * @param options.networkClientId - The network client ID to detect NFTs on.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(options?: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n }) {\n const userAddress =\n options?.userAddress ??\n this.messagingSystem.call('AccountsController:getSelectedAccount')\n .address;\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\n /* istanbul ignore if */\n if (!supportedNftDetectionNetworks.includes(chainId) || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const updateKey: `${Hex}:${string}` = `${chainId}:${userAddress}`;\n if (updateKey in this.#inProcessNftFetchingUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessNftFetchingUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessNftFetchingUpdates[updateKey] = inProgressUpdate;\n\n let next;\n let apiNfts: TokensResponse[] = [];\n let resultNftApi: ReservoirResponse;\n try {\n do {\n resultNftApi = await this.#getOwnerNfts(userAddress, chainId, next);\n apiNfts = resultNftApi.tokens.filter(\n (elm) =>\n elm.token.isSpam === false &&\n (elm.blockaidResult?.result_type\n ? elm.blockaidResult?.result_type === BlockaidResultType.Benign\n : true),\n );\n // Retrieve collections from apiNfts\n // contract and collection.id are equal for simple contract addresses; this is to exclude cases for shared contracts\n const collections = apiNfts.reduce<string[]>((acc, currValue) => {\n if (\n !acc.includes(currValue.token.contract) &&\n currValue.token.contract === currValue?.token?.collection?.id\n ) {\n acc.push(currValue.token.contract);\n }\n return acc;\n }, []);\n\n if (collections.length !== 0) {\n // Call API to retrive collections infos\n // The api accept a max of 20 contracts\n const collectionResponse: GetCollectionsResponse =\n await reduceInBatchesSerially({\n values: collections,\n batchSize: MAX_GET_COLLECTION_BATCH_SIZE,\n eachBatch: async (allResponses, batch) => {\n const params = new URLSearchParams(\n batch.map((s) => ['contract', s]),\n );\n params.append('chainId', '1'); // Adding chainId 1 because we are only detecting for mainnet\n const collectionResponseForBatch = await fetchWithErrorHandling(\n {\n url: `${\n NFT_API_BASE_URL as string\n }/collections?${params.toString()}`,\n options: {\n headers: {\n Version: NFT_API_VERSION,\n },\n },\n timeout: NFT_API_TIMEOUT,\n },\n );\n\n return {\n ...allResponses,\n ...collectionResponseForBatch,\n };\n },\n initialResult: {},\n });\n\n // Add collections response fields to newnfts\n if (collectionResponse.collections?.length) {\n apiNfts.forEach((singleNFT) => {\n const found = collectionResponse.collections.find(\n (elm) =>\n elm.id?.toLowerCase() ===\n singleNFT.token.contract.toLowerCase(),\n );\n if (found) {\n singleNFT.token = {\n ...singleNFT.token,\n collection: {\n ...(singleNFT.token.collection ?? {}),\n creator: found?.creator,\n openseaVerificationStatus: found?.openseaVerificationStatus,\n contractDeployedAt: found.contractDeployedAt,\n ownerCount: found.ownerCount,\n topBid: found.topBid,\n },\n };\n }\n });\n }\n }\n\n // Proceed to add NFTs\n const addNftPromises = apiNfts.map(async (nft) => {\n const {\n tokenId,\n contract,\n kind,\n image: imageUrl,\n imageSmall: imageThumbnailUrl,\n metadata,\n name,\n description,\n attributes,\n topBid,\n lastSale,\n rarityRank,\n rarityScore,\n collection,\n } = nft.token;\n\n // Use a fallback if metadata is null\n const { imageOriginal: imageOriginalUrl } = metadata || {};\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.#getNftState();\n if (ignoredNfts.length) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(contract) &&\n c.tokenId === tokenId\n );\n });\n }\n\n /* istanbul ignore else */\n if (!ignored) {\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name },\n description && { description },\n imageUrl && { image: imageUrl },\n imageThumbnailUrl && { imageThumbnail: imageThumbnailUrl },\n imageOriginalUrl && { imageOriginal: imageOriginalUrl },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n topBid && { topBid },\n rarityRank && { rarityRank },\n rarityScore && { rarityScore },\n collection && { collection },\n );\n await this.#addNft(contract, tokenId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId: options?.networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n } while ((next = resultNftApi.continuation));\n updateSucceeded();\n } catch (error) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessNftFetchingUpdates[updateKey];\n }\n }\n}\n\nexport default NftDetectionController;\n"]}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
3
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
4
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
5
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
6
|
+
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
7
|
+
};
|
|
8
|
+
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
9
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
10
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
11
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
12
|
+
};
|
|
13
|
+
var _TokenSearchDiscoveryDataController_instances, _TokenSearchDiscoveryDataController_abortController, _TokenSearchDiscoveryDataController_tokenPricesService, _TokenSearchDiscoveryDataController_swapsSupportedChainIds, _TokenSearchDiscoveryDataController_fetchTokens, _TokenSearchDiscoveryDataController_fetchSwapsTokensThresholdMs, _TokenSearchDiscoveryDataController_fetchPriceData;
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.TokenSearchDiscoveryDataController = exports.getDefaultTokenSearchDiscoveryDataControllerState = exports.MAX_TOKEN_DISPLAY_DATA_LENGTH = exports.controllerName = void 0;
|
|
16
|
+
const base_controller_1 = require("@metamask/base-controller");
|
|
17
|
+
const assetsUtil_1 = require("../assetsUtil.cjs");
|
|
18
|
+
const token_service_1 = require("../token-service.cjs");
|
|
19
|
+
// === GENERAL ===
|
|
20
|
+
exports.controllerName = 'TokenSearchDiscoveryDataController';
|
|
21
|
+
exports.MAX_TOKEN_DISPLAY_DATA_LENGTH = 10;
|
|
22
|
+
const tokenSearchDiscoveryDataControllerMetadata = {
|
|
23
|
+
tokenDisplayData: { persist: true, anonymous: false },
|
|
24
|
+
swapsTokenAddressesByChainId: { persist: true, anonymous: false },
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Constructs the default {@link TokenSearchDiscoveryDataController} state. This allows
|
|
28
|
+
* consumers to provide a partial state object when initializing the controller
|
|
29
|
+
* and also helps in constructing complete state objects for this controller in
|
|
30
|
+
* tests.
|
|
31
|
+
*
|
|
32
|
+
* @returns The default {@link TokenSearchDiscoveryDataController} state.
|
|
33
|
+
*/
|
|
34
|
+
function getDefaultTokenSearchDiscoveryDataControllerState() {
|
|
35
|
+
return {
|
|
36
|
+
tokenDisplayData: [],
|
|
37
|
+
swapsTokenAddressesByChainId: {},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
exports.getDefaultTokenSearchDiscoveryDataControllerState = getDefaultTokenSearchDiscoveryDataControllerState;
|
|
41
|
+
/**
|
|
42
|
+
* The TokenSearchDiscoveryDataController manages the retrieval of token search results and token discovery.
|
|
43
|
+
* It fetches token search results and discovery data from the Portfolio API.
|
|
44
|
+
*/
|
|
45
|
+
class TokenSearchDiscoveryDataController extends base_controller_1.BaseController {
|
|
46
|
+
constructor({ state = {}, messenger, tokenPricesService, swapsSupportedChainIds, fetchTokens, fetchSwapsTokensThresholdMs, }) {
|
|
47
|
+
super({
|
|
48
|
+
name: exports.controllerName,
|
|
49
|
+
metadata: tokenSearchDiscoveryDataControllerMetadata,
|
|
50
|
+
messenger,
|
|
51
|
+
state: {
|
|
52
|
+
...getDefaultTokenSearchDiscoveryDataControllerState(),
|
|
53
|
+
...state,
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
_TokenSearchDiscoveryDataController_instances.add(this);
|
|
57
|
+
_TokenSearchDiscoveryDataController_abortController.set(this, void 0);
|
|
58
|
+
_TokenSearchDiscoveryDataController_tokenPricesService.set(this, void 0);
|
|
59
|
+
_TokenSearchDiscoveryDataController_swapsSupportedChainIds.set(this, void 0);
|
|
60
|
+
_TokenSearchDiscoveryDataController_fetchTokens.set(this, void 0);
|
|
61
|
+
_TokenSearchDiscoveryDataController_fetchSwapsTokensThresholdMs.set(this, void 0);
|
|
62
|
+
__classPrivateFieldSet(this, _TokenSearchDiscoveryDataController_abortController, new AbortController(), "f");
|
|
63
|
+
__classPrivateFieldSet(this, _TokenSearchDiscoveryDataController_tokenPricesService, tokenPricesService, "f");
|
|
64
|
+
__classPrivateFieldSet(this, _TokenSearchDiscoveryDataController_swapsSupportedChainIds, swapsSupportedChainIds, "f");
|
|
65
|
+
__classPrivateFieldSet(this, _TokenSearchDiscoveryDataController_fetchTokens, fetchTokens, "f");
|
|
66
|
+
__classPrivateFieldSet(this, _TokenSearchDiscoveryDataController_fetchSwapsTokensThresholdMs, fetchSwapsTokensThresholdMs, "f");
|
|
67
|
+
}
|
|
68
|
+
async fetchSwapsTokens(chainId) {
|
|
69
|
+
if (!__classPrivateFieldGet(this, _TokenSearchDiscoveryDataController_swapsSupportedChainIds, "f").includes(chainId)) {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const swapsTokens = this.state.swapsTokenAddressesByChainId[chainId];
|
|
73
|
+
if ((!swapsTokens ||
|
|
74
|
+
swapsTokens.lastFetched <
|
|
75
|
+
Date.now() - __classPrivateFieldGet(this, _TokenSearchDiscoveryDataController_fetchSwapsTokensThresholdMs, "f")) &&
|
|
76
|
+
!swapsTokens?.isFetching) {
|
|
77
|
+
try {
|
|
78
|
+
this.update((state) => {
|
|
79
|
+
if (!state.swapsTokenAddressesByChainId[chainId]) {
|
|
80
|
+
state.swapsTokenAddressesByChainId[chainId] = {
|
|
81
|
+
lastFetched: Date.now(),
|
|
82
|
+
addresses: [],
|
|
83
|
+
isFetching: true,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
state.swapsTokenAddressesByChainId[chainId].isFetching = true;
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
const tokens = await __classPrivateFieldGet(this, _TokenSearchDiscoveryDataController_fetchTokens, "f").call(this, chainId);
|
|
91
|
+
this.update((state) => {
|
|
92
|
+
state.swapsTokenAddressesByChainId[chainId] = {
|
|
93
|
+
lastFetched: Date.now(),
|
|
94
|
+
addresses: tokens.map((token) => token.address),
|
|
95
|
+
isFetching: false,
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
console.error(error);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async fetchTokenDisplayData(chainId, address) {
|
|
105
|
+
await this.fetchSwapsTokens(chainId);
|
|
106
|
+
let tokenMetadata;
|
|
107
|
+
try {
|
|
108
|
+
tokenMetadata = await (0, token_service_1.fetchTokenMetadata)(chainId, address, __classPrivateFieldGet(this, _TokenSearchDiscoveryDataController_abortController, "f").signal);
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (!(error instanceof Error) ||
|
|
112
|
+
!error.message.includes(token_service_1.TOKEN_METADATA_NO_SUPPORT_ERROR)) {
|
|
113
|
+
throw error;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const { currentCurrency } = this.messagingSystem.call('CurrencyRateController:getState');
|
|
117
|
+
let tokenDisplayData;
|
|
118
|
+
if (!tokenMetadata) {
|
|
119
|
+
tokenDisplayData = {
|
|
120
|
+
found: false,
|
|
121
|
+
address,
|
|
122
|
+
chainId,
|
|
123
|
+
currency: currentCurrency,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
else {
|
|
127
|
+
const priceData = await __classPrivateFieldGet(this, _TokenSearchDiscoveryDataController_instances, "m", _TokenSearchDiscoveryDataController_fetchPriceData).call(this, chainId, address);
|
|
128
|
+
tokenDisplayData = {
|
|
129
|
+
found: true,
|
|
130
|
+
address,
|
|
131
|
+
chainId,
|
|
132
|
+
currency: currentCurrency,
|
|
133
|
+
token: {
|
|
134
|
+
...tokenMetadata,
|
|
135
|
+
isERC721: false,
|
|
136
|
+
image: (0, assetsUtil_1.formatIconUrlWithProxy)({
|
|
137
|
+
chainId,
|
|
138
|
+
tokenAddress: address,
|
|
139
|
+
}),
|
|
140
|
+
},
|
|
141
|
+
price: priceData,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
this.update((state) => {
|
|
145
|
+
state.tokenDisplayData = [
|
|
146
|
+
tokenDisplayData,
|
|
147
|
+
...state.tokenDisplayData.filter((token) => token.address !== address ||
|
|
148
|
+
token.chainId !== chainId ||
|
|
149
|
+
token.currency !== currentCurrency),
|
|
150
|
+
].slice(0, exports.MAX_TOKEN_DISPLAY_DATA_LENGTH);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
exports.TokenSearchDiscoveryDataController = TokenSearchDiscoveryDataController;
|
|
155
|
+
_TokenSearchDiscoveryDataController_abortController = new WeakMap(), _TokenSearchDiscoveryDataController_tokenPricesService = new WeakMap(), _TokenSearchDiscoveryDataController_swapsSupportedChainIds = new WeakMap(), _TokenSearchDiscoveryDataController_fetchTokens = new WeakMap(), _TokenSearchDiscoveryDataController_fetchSwapsTokensThresholdMs = new WeakMap(), _TokenSearchDiscoveryDataController_instances = new WeakSet(), _TokenSearchDiscoveryDataController_fetchPriceData = async function _TokenSearchDiscoveryDataController_fetchPriceData(chainId, address) {
|
|
156
|
+
const { currentCurrency } = this.messagingSystem.call('CurrencyRateController:getState');
|
|
157
|
+
try {
|
|
158
|
+
const pricesData = await __classPrivateFieldGet(this, _TokenSearchDiscoveryDataController_tokenPricesService, "f").fetchTokenPrices({
|
|
159
|
+
chainId,
|
|
160
|
+
tokenAddresses: [address],
|
|
161
|
+
currency: currentCurrency,
|
|
162
|
+
});
|
|
163
|
+
return pricesData[address] ?? null;
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
console.error(error);
|
|
167
|
+
return null;
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
//# sourceMappingURL=TokenSearchDiscoveryDataController.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TokenSearchDiscoveryDataController.cjs","sourceRoot":"","sources":["../../src/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAKmC;AAInC,kDAAuD;AAIvD,wDAG0B;AAG1B,kBAAkB;AAEL,QAAA,cAAc,GAAG,oCAAoC,CAAC;AAEtD,QAAA,6BAA6B,GAAG,EAAE,CAAC;AAYhD,MAAM,0CAA0C,GAAG;IACjD,gBAAgB,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;IACrD,4BAA4B,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE;CACzD,CAAC;AA4DX;;;;;;;GAOG;AACH,SAAgB,iDAAiD;IAC/D,OAAO;QACL,gBAAgB,EAAE,EAAE;QACpB,4BAA4B,EAAE,EAA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AC;YACjE,OAAO;YACP,cAAc,EAAE,CAAC,OAAc,CAAC;YAChC,QAAQ,EAAE,eAAe;SAC1B,CAAC,CAAC;QAEH,OAAO,UAAU,CAAC,OAAc,CAAC,IAAI,IAAI,CAAC;KAC3C;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACrB,OAAO,IAAI,CAAC;KACb;AACH,CAAC","sourcesContent":["import {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n type RestrictedMessenger,\n} from '@metamask/base-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type { TokenDisplayData } from './types';\nimport { formatIconUrlWithProxy } from '../assetsUtil';\nimport type { GetCurrencyRateState } from '../CurrencyRateController';\nimport type { AbstractTokenPricesService } from '../token-prices-service';\nimport type { TokenPrice } from '../token-prices-service/abstract-token-prices-service';\nimport {\n fetchTokenMetadata,\n TOKEN_METADATA_NO_SUPPORT_ERROR,\n} from '../token-service';\nimport type { TokenListToken } from '../TokenListController';\n\n// === GENERAL ===\n\nexport const controllerName = 'TokenSearchDiscoveryDataController';\n\nexport const MAX_TOKEN_DISPLAY_DATA_LENGTH = 10;\n\n// === STATE ===\n\nexport type TokenSearchDiscoveryDataControllerState = {\n tokenDisplayData: TokenDisplayData[];\n swapsTokenAddressesByChainId: Record<\n Hex,\n { lastFetched: number; addresses: string[]; isFetching: boolean }\n >;\n};\n\nconst tokenSearchDiscoveryDataControllerMetadata = {\n tokenDisplayData: { persist: true, anonymous: false },\n swapsTokenAddressesByChainId: { persist: true, anonymous: false },\n} as const;\n\n// === MESSENGER ===\n\n/**\n * The action which can be used to retrieve the state of the\n * {@link TokenSearchDiscoveryDataController}.\n */\nexport type TokenSearchDiscoveryDataControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n TokenSearchDiscoveryDataControllerState\n >;\n\n/**\n * All actions that {@link TokenSearchDiscoveryDataController} registers, to be\n * called externally.\n */\nexport type TokenSearchDiscoveryDataControllerActions =\n TokenSearchDiscoveryDataControllerGetStateAction;\n\n/**\n * All actions that {@link TokenSearchDiscoveryDataController} calls internally.\n */\nexport type AllowedActions = GetCurrencyRateState;\n\n/**\n * The event that {@link TokenSearchDiscoveryDataController} publishes when updating\n * state.\n */\nexport type TokenSearchDiscoveryDataControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n TokenSearchDiscoveryDataControllerState\n >;\n\n/**\n * All events that {@link TokenSearchDiscoveryDataController} publishes, to be\n * subscribed to externally.\n */\nexport type TokenSearchDiscoveryDataControllerEvents =\n TokenSearchDiscoveryDataControllerStateChangeEvent;\n\n/**\n * All events that {@link TokenSearchDiscoveryDataController} subscribes to internally.\n */\nexport type AllowedEvents = never;\n\n/**\n * The messenger which is restricted to actions and events accessed by\n * {@link TokenSearchDiscoveryDataController}.\n */\nexport type TokenSearchDiscoveryDataControllerMessenger = RestrictedMessenger<\n typeof controllerName,\n TokenSearchDiscoveryDataControllerActions | AllowedActions,\n TokenSearchDiscoveryDataControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Constructs the default {@link TokenSearchDiscoveryDataController} state. This allows\n * consumers to provide a partial state object when initializing the controller\n * and also helps in constructing complete state objects for this controller in\n * tests.\n *\n * @returns The default {@link TokenSearchDiscoveryDataController} state.\n */\nexport function getDefaultTokenSearchDiscoveryDataControllerState(): TokenSearchDiscoveryDataControllerState {\n return {\n tokenDisplayData: [],\n swapsTokenAddressesByChainId: {},\n };\n}\n\n/**\n * The TokenSearchDiscoveryDataController manages the retrieval of token search results and token discovery.\n * It fetches token search results and discovery data from the Portfolio API.\n */\nexport class TokenSearchDiscoveryDataController extends BaseController<\n typeof controllerName,\n TokenSearchDiscoveryDataControllerState,\n TokenSearchDiscoveryDataControllerMessenger\n> {\n readonly #abortController: AbortController;\n\n readonly #tokenPricesService: AbstractTokenPricesService;\n\n readonly #swapsSupportedChainIds: Hex[];\n\n readonly #fetchTokens: (chainId: Hex) => Promise<{ address: string }[]>;\n\n readonly #fetchSwapsTokensThresholdMs: number;\n\n constructor({\n state = {},\n messenger,\n tokenPricesService,\n swapsSupportedChainIds,\n fetchTokens,\n fetchSwapsTokensThresholdMs,\n }: {\n state?: Partial<TokenSearchDiscoveryDataControllerState>;\n messenger: TokenSearchDiscoveryDataControllerMessenger;\n tokenPricesService: AbstractTokenPricesService;\n swapsSupportedChainIds: Hex[];\n fetchTokens: (chainId: Hex) => Promise<{ address: string }[]>;\n fetchSwapsTokensThresholdMs: number;\n }) {\n super({\n name: controllerName,\n metadata: tokenSearchDiscoveryDataControllerMetadata,\n messenger,\n state: {\n ...getDefaultTokenSearchDiscoveryDataControllerState(),\n ...state,\n },\n });\n\n this.#abortController = new AbortController();\n this.#tokenPricesService = tokenPricesService;\n this.#swapsSupportedChainIds = swapsSupportedChainIds;\n this.#fetchTokens = fetchTokens;\n this.#fetchSwapsTokensThresholdMs = fetchSwapsTokensThresholdMs;\n }\n\n async #fetchPriceData(\n chainId: Hex,\n address: string,\n ): Promise<TokenPrice<Hex, string> | null> {\n const { currentCurrency } = this.messagingSystem.call(\n 'CurrencyRateController:getState',\n );\n\n try {\n const pricesData = await this.#tokenPricesService.fetchTokenPrices({\n chainId,\n tokenAddresses: [address as Hex],\n currency: currentCurrency,\n });\n\n return pricesData[address as Hex] ?? null;\n } catch (error) {\n console.error(error);\n return null;\n }\n }\n\n async fetchSwapsTokens(chainId: Hex): Promise<void> {\n if (!this.#swapsSupportedChainIds.includes(chainId)) {\n return;\n }\n\n const swapsTokens = this.state.swapsTokenAddressesByChainId[chainId];\n if (\n (!swapsTokens ||\n swapsTokens.lastFetched <\n Date.now() - this.#fetchSwapsTokensThresholdMs) &&\n !swapsTokens?.isFetching\n ) {\n try {\n this.update((state) => {\n if (!state.swapsTokenAddressesByChainId[chainId]) {\n state.swapsTokenAddressesByChainId[chainId] = {\n lastFetched: Date.now(),\n addresses: [],\n isFetching: true,\n };\n } else {\n state.swapsTokenAddressesByChainId[chainId].isFetching = true;\n }\n });\n const tokens = await this.#fetchTokens(chainId);\n this.update((state) => {\n state.swapsTokenAddressesByChainId[chainId] = {\n lastFetched: Date.now(),\n addresses: tokens.map((token) => token.address),\n isFetching: false,\n };\n });\n } catch (error) {\n console.error(error);\n }\n }\n }\n\n async fetchTokenDisplayData(chainId: Hex, address: string): Promise<void> {\n await this.fetchSwapsTokens(chainId);\n\n let tokenMetadata: TokenListToken | undefined;\n try {\n tokenMetadata = await fetchTokenMetadata<TokenListToken>(\n chainId,\n address,\n this.#abortController.signal,\n );\n } catch (error) {\n if (\n !(error instanceof Error) ||\n !error.message.includes(TOKEN_METADATA_NO_SUPPORT_ERROR)\n ) {\n throw error;\n }\n }\n\n const { currentCurrency } = this.messagingSystem.call(\n 'CurrencyRateController:getState',\n );\n\n let tokenDisplayData: TokenDisplayData;\n if (!tokenMetadata) {\n tokenDisplayData = {\n found: false,\n address,\n chainId,\n currency: currentCurrency,\n };\n } else {\n const priceData = await this.#fetchPriceData(chainId, address);\n tokenDisplayData = {\n found: true,\n address,\n chainId,\n currency: currentCurrency,\n token: {\n ...tokenMetadata,\n isERC721: false,\n image: formatIconUrlWithProxy({\n chainId,\n tokenAddress: address,\n }),\n },\n price: priceData,\n };\n }\n\n this.update((state) => {\n state.tokenDisplayData = [\n tokenDisplayData,\n ...state.tokenDisplayData.filter(\n (token) =>\n token.address !== address ||\n token.chainId !== chainId ||\n token.currency !== currentCurrency,\n ),\n ].slice(0, MAX_TOKEN_DISPLAY_DATA_LENGTH);\n });\n }\n}\n"]}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { BaseController, type ControllerGetStateAction, type ControllerStateChangeEvent, type RestrictedMessenger } from "@metamask/base-controller";
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
|
+
import type { TokenDisplayData } from "./types.cjs";
|
|
4
|
+
import type { GetCurrencyRateState } from "../CurrencyRateController.cjs";
|
|
5
|
+
import type { AbstractTokenPricesService } from "../token-prices-service/index.cjs";
|
|
6
|
+
export declare const controllerName = "TokenSearchDiscoveryDataController";
|
|
7
|
+
export declare const MAX_TOKEN_DISPLAY_DATA_LENGTH = 10;
|
|
8
|
+
export type TokenSearchDiscoveryDataControllerState = {
|
|
9
|
+
tokenDisplayData: TokenDisplayData[];
|
|
10
|
+
swapsTokenAddressesByChainId: Record<Hex, {
|
|
11
|
+
lastFetched: number;
|
|
12
|
+
addresses: string[];
|
|
13
|
+
isFetching: boolean;
|
|
14
|
+
}>;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The action which can be used to retrieve the state of the
|
|
18
|
+
* {@link TokenSearchDiscoveryDataController}.
|
|
19
|
+
*/
|
|
20
|
+
export type TokenSearchDiscoveryDataControllerGetStateAction = ControllerGetStateAction<typeof controllerName, TokenSearchDiscoveryDataControllerState>;
|
|
21
|
+
/**
|
|
22
|
+
* All actions that {@link TokenSearchDiscoveryDataController} registers, to be
|
|
23
|
+
* called externally.
|
|
24
|
+
*/
|
|
25
|
+
export type TokenSearchDiscoveryDataControllerActions = TokenSearchDiscoveryDataControllerGetStateAction;
|
|
26
|
+
/**
|
|
27
|
+
* All actions that {@link TokenSearchDiscoveryDataController} calls internally.
|
|
28
|
+
*/
|
|
29
|
+
export type AllowedActions = GetCurrencyRateState;
|
|
30
|
+
/**
|
|
31
|
+
* The event that {@link TokenSearchDiscoveryDataController} publishes when updating
|
|
32
|
+
* state.
|
|
33
|
+
*/
|
|
34
|
+
export type TokenSearchDiscoveryDataControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, TokenSearchDiscoveryDataControllerState>;
|
|
35
|
+
/**
|
|
36
|
+
* All events that {@link TokenSearchDiscoveryDataController} publishes, to be
|
|
37
|
+
* subscribed to externally.
|
|
38
|
+
*/
|
|
39
|
+
export type TokenSearchDiscoveryDataControllerEvents = TokenSearchDiscoveryDataControllerStateChangeEvent;
|
|
40
|
+
/**
|
|
41
|
+
* All events that {@link TokenSearchDiscoveryDataController} subscribes to internally.
|
|
42
|
+
*/
|
|
43
|
+
export type AllowedEvents = never;
|
|
44
|
+
/**
|
|
45
|
+
* The messenger which is restricted to actions and events accessed by
|
|
46
|
+
* {@link TokenSearchDiscoveryDataController}.
|
|
47
|
+
*/
|
|
48
|
+
export type TokenSearchDiscoveryDataControllerMessenger = RestrictedMessenger<typeof controllerName, TokenSearchDiscoveryDataControllerActions | AllowedActions, TokenSearchDiscoveryDataControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
|
49
|
+
/**
|
|
50
|
+
* Constructs the default {@link TokenSearchDiscoveryDataController} state. This allows
|
|
51
|
+
* consumers to provide a partial state object when initializing the controller
|
|
52
|
+
* and also helps in constructing complete state objects for this controller in
|
|
53
|
+
* tests.
|
|
54
|
+
*
|
|
55
|
+
* @returns The default {@link TokenSearchDiscoveryDataController} state.
|
|
56
|
+
*/
|
|
57
|
+
export declare function getDefaultTokenSearchDiscoveryDataControllerState(): TokenSearchDiscoveryDataControllerState;
|
|
58
|
+
/**
|
|
59
|
+
* The TokenSearchDiscoveryDataController manages the retrieval of token search results and token discovery.
|
|
60
|
+
* It fetches token search results and discovery data from the Portfolio API.
|
|
61
|
+
*/
|
|
62
|
+
export declare class TokenSearchDiscoveryDataController extends BaseController<typeof controllerName, TokenSearchDiscoveryDataControllerState, TokenSearchDiscoveryDataControllerMessenger> {
|
|
63
|
+
#private;
|
|
64
|
+
constructor({ state, messenger, tokenPricesService, swapsSupportedChainIds, fetchTokens, fetchSwapsTokensThresholdMs, }: {
|
|
65
|
+
state?: Partial<TokenSearchDiscoveryDataControllerState>;
|
|
66
|
+
messenger: TokenSearchDiscoveryDataControllerMessenger;
|
|
67
|
+
tokenPricesService: AbstractTokenPricesService;
|
|
68
|
+
swapsSupportedChainIds: Hex[];
|
|
69
|
+
fetchTokens: (chainId: Hex) => Promise<{
|
|
70
|
+
address: string;
|
|
71
|
+
}[]>;
|
|
72
|
+
fetchSwapsTokensThresholdMs: number;
|
|
73
|
+
});
|
|
74
|
+
fetchSwapsTokens(chainId: Hex): Promise<void>;
|
|
75
|
+
fetchTokenDisplayData(chainId: Hex, address: string): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=TokenSearchDiscoveryDataController.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TokenSearchDiscoveryDataController.d.cts","sourceRoot":"","sources":["../../src/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAC/B,KAAK,mBAAmB,EACzB,kCAAkC;AACnC,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAE3C,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAgB;AAEhD,OAAO,KAAK,EAAE,oBAAoB,EAAE,sCAAkC;AACtE,OAAO,KAAK,EAAE,0BAA0B,EAAE,0CAAgC;AAU1E,eAAO,MAAM,cAAc,uCAAuC,CAAC;AAEnE,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAIhD,MAAM,MAAM,uCAAuC,GAAG;IACpD,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;IACrC,4BAA4B,EAAE,MAAM,CAClC,GAAG,EACH;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAC;QAAC,UAAU,EAAE,OAAO,CAAA;KAAE,CAClE,CAAC;CACH,CAAC;AASF;;;GAGG;AACH,MAAM,MAAM,gDAAgD,GAC1D,wBAAwB,CACtB,OAAO,cAAc,EACrB,uCAAuC,CACxC,CAAC;AAEJ;;;GAGG;AACH,MAAM,MAAM,yCAAyC,GACnD,gDAAgD,CAAC;AAEnD;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAElD;;;GAGG;AACH,MAAM,MAAM,kDAAkD,GAC5D,0BAA0B,CACxB,OAAO,cAAc,EACrB,uCAAuC,CACxC,CAAC;AAEJ;;;GAGG;AACH,MAAM,MAAM,wCAAwC,GAClD,kDAAkD,CAAC;AAErD;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC;AAElC;;;GAGG;AACH,MAAM,MAAM,2CAA2C,GAAG,mBAAmB,CAC3E,OAAO,cAAc,EACrB,yCAAyC,GAAG,cAAc,EAC1D,wCAAwC,GAAG,aAAa,EACxD,cAAc,CAAC,MAAM,CAAC,EACtB,aAAa,CAAC,MAAM,CAAC,CACtB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAgB,iDAAiD,IAAI,uCAAuC,CAK3G;AAED;;;GAGG;AACH,qBAAa,kCAAmC,SAAQ,cAAc,CACpE,OAAO,cAAc,EACrB,uCAAuC,EACvC,2CAA2C,CAC5C;;gBAWa,EACV,KAAU,EACV,SAAS,EACT,kBAAkB,EAClB,sBAAsB,EACtB,WAAW,EACX,2BAA2B,GAC5B,EAAE;QACD,KAAK,CAAC,EAAE,OAAO,CAAC,uCAAuC,CAAC,CAAC;QACzD,SAAS,EAAE,2CAA2C,CAAC;QACvD,kBAAkB,EAAE,0BAA0B,CAAC;QAC/C,sBAAsB,EAAE,GAAG,EAAE,CAAC;QAC9B,WAAW,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,OAAO,CAAC;YAAE,OAAO,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC,CAAC;QAC9D,2BAA2B,EAAE,MAAM,CAAC;KACrC;IAwCK,gBAAgB,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;IAsC7C,qBAAqB,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CA8D1E"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { BaseController, type ControllerGetStateAction, type ControllerStateChangeEvent, type RestrictedMessenger } from "@metamask/base-controller";
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
|
+
import type { TokenDisplayData } from "./types.mjs";
|
|
4
|
+
import type { GetCurrencyRateState } from "../CurrencyRateController.mjs";
|
|
5
|
+
import type { AbstractTokenPricesService } from "../token-prices-service/index.mjs";
|
|
6
|
+
export declare const controllerName = "TokenSearchDiscoveryDataController";
|
|
7
|
+
export declare const MAX_TOKEN_DISPLAY_DATA_LENGTH = 10;
|
|
8
|
+
export type TokenSearchDiscoveryDataControllerState = {
|
|
9
|
+
tokenDisplayData: TokenDisplayData[];
|
|
10
|
+
swapsTokenAddressesByChainId: Record<Hex, {
|
|
11
|
+
lastFetched: number;
|
|
12
|
+
addresses: string[];
|
|
13
|
+
isFetching: boolean;
|
|
14
|
+
}>;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The action which can be used to retrieve the state of the
|
|
18
|
+
* {@link TokenSearchDiscoveryDataController}.
|
|
19
|
+
*/
|
|
20
|
+
export type TokenSearchDiscoveryDataControllerGetStateAction = ControllerGetStateAction<typeof controllerName, TokenSearchDiscoveryDataControllerState>;
|
|
21
|
+
/**
|
|
22
|
+
* All actions that {@link TokenSearchDiscoveryDataController} registers, to be
|
|
23
|
+
* called externally.
|
|
24
|
+
*/
|
|
25
|
+
export type TokenSearchDiscoveryDataControllerActions = TokenSearchDiscoveryDataControllerGetStateAction;
|
|
26
|
+
/**
|
|
27
|
+
* All actions that {@link TokenSearchDiscoveryDataController} calls internally.
|
|
28
|
+
*/
|
|
29
|
+
export type AllowedActions = GetCurrencyRateState;
|
|
30
|
+
/**
|
|
31
|
+
* The event that {@link TokenSearchDiscoveryDataController} publishes when updating
|
|
32
|
+
* state.
|
|
33
|
+
*/
|
|
34
|
+
export type TokenSearchDiscoveryDataControllerStateChangeEvent = ControllerStateChangeEvent<typeof controllerName, TokenSearchDiscoveryDataControllerState>;
|
|
35
|
+
/**
|
|
36
|
+
* All events that {@link TokenSearchDiscoveryDataController} publishes, to be
|
|
37
|
+
* subscribed to externally.
|
|
38
|
+
*/
|
|
39
|
+
export type TokenSearchDiscoveryDataControllerEvents = TokenSearchDiscoveryDataControllerStateChangeEvent;
|
|
40
|
+
/**
|
|
41
|
+
* All events that {@link TokenSearchDiscoveryDataController} subscribes to internally.
|
|
42
|
+
*/
|
|
43
|
+
export type AllowedEvents = never;
|
|
44
|
+
/**
|
|
45
|
+
* The messenger which is restricted to actions and events accessed by
|
|
46
|
+
* {@link TokenSearchDiscoveryDataController}.
|
|
47
|
+
*/
|
|
48
|
+
export type TokenSearchDiscoveryDataControllerMessenger = RestrictedMessenger<typeof controllerName, TokenSearchDiscoveryDataControllerActions | AllowedActions, TokenSearchDiscoveryDataControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
|
49
|
+
/**
|
|
50
|
+
* Constructs the default {@link TokenSearchDiscoveryDataController} state. This allows
|
|
51
|
+
* consumers to provide a partial state object when initializing the controller
|
|
52
|
+
* and also helps in constructing complete state objects for this controller in
|
|
53
|
+
* tests.
|
|
54
|
+
*
|
|
55
|
+
* @returns The default {@link TokenSearchDiscoveryDataController} state.
|
|
56
|
+
*/
|
|
57
|
+
export declare function getDefaultTokenSearchDiscoveryDataControllerState(): TokenSearchDiscoveryDataControllerState;
|
|
58
|
+
/**
|
|
59
|
+
* The TokenSearchDiscoveryDataController manages the retrieval of token search results and token discovery.
|
|
60
|
+
* It fetches token search results and discovery data from the Portfolio API.
|
|
61
|
+
*/
|
|
62
|
+
export declare class TokenSearchDiscoveryDataController extends BaseController<typeof controllerName, TokenSearchDiscoveryDataControllerState, TokenSearchDiscoveryDataControllerMessenger> {
|
|
63
|
+
#private;
|
|
64
|
+
constructor({ state, messenger, tokenPricesService, swapsSupportedChainIds, fetchTokens, fetchSwapsTokensThresholdMs, }: {
|
|
65
|
+
state?: Partial<TokenSearchDiscoveryDataControllerState>;
|
|
66
|
+
messenger: TokenSearchDiscoveryDataControllerMessenger;
|
|
67
|
+
tokenPricesService: AbstractTokenPricesService;
|
|
68
|
+
swapsSupportedChainIds: Hex[];
|
|
69
|
+
fetchTokens: (chainId: Hex) => Promise<{
|
|
70
|
+
address: string;
|
|
71
|
+
}[]>;
|
|
72
|
+
fetchSwapsTokensThresholdMs: number;
|
|
73
|
+
});
|
|
74
|
+
fetchSwapsTokens(chainId: Hex): Promise<void>;
|
|
75
|
+
fetchTokenDisplayData(chainId: Hex, address: string): Promise<void>;
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=TokenSearchDiscoveryDataController.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"TokenSearchDiscoveryDataController.d.mts","sourceRoot":"","sources":["../../src/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,KAAK,wBAAwB,EAC7B,KAAK,0BAA0B,EAC/B,KAAK,mBAAmB,EACzB,kCAAkC;AACnC,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAE3C,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAgB;AAEhD,OAAO,KAAK,EAAE,oBAAoB,EAAE,sCAAkC;AACtE,OAAO,KAAK,EAAE,0BAA0B,EAAE,0CAAgC;AAU1E,eAAO,MAAM,cAAc,uCAAuC,CAAC;AAEnE,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAIhD,MAAM,MAAM,uCAAuC,GAAG;IACpD,gBAAgB,EAAE,gBAAgB,EAAE,CAAC;IACrC,4BAA4B,EAAE,MAAM,CAClC,GAAG,EACH;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,EAAE,CAAC;QAAC,UAAU,EAAE,OAAO,CAAA;KAAE,CAClE,CAAC;CACH,CAAC;AASF;;;GAGG;AACH,MAAM,MAAM,gDAAgD,GAC1D,wBAAwB,CACtB,OAAO,cAAc,EACrB,uCAAuC,CACxC,CAAC;AAEJ;;;GAGG;AACH,MAAM,MAAM,yCAAyC,GACnD,gDAAgD,CAAC;AAEnD;;GAEG;AACH,M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