@metamask/assets-controllers 87.1.0 → 87.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 +12 -1
- package/dist/AccountTrackerController.cjs.map +1 -1
- package/dist/AccountTrackerController.d.cts +2 -2
- package/dist/AccountTrackerController.d.mts +2 -2
- package/dist/AccountTrackerController.mjs.map +1 -1
- package/dist/AssetsContractController.cjs.map +1 -1
- package/dist/AssetsContractController.mjs.map +1 -1
- package/dist/CurrencyRateController.cjs.map +1 -1
- package/dist/CurrencyRateController.d.cts +2 -2
- package/dist/CurrencyRateController.d.mts +2 -2
- package/dist/CurrencyRateController.mjs.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.cjs.map +1 -1
- package/dist/DeFiPositionsController/DeFiPositionsController.d.cts +2 -2
- package/dist/DeFiPositionsController/DeFiPositionsController.d.mts +2 -2
- package/dist/DeFiPositionsController/DeFiPositionsController.mjs.map +1 -1
- package/dist/DeFiPositionsController/fetch-positions.cjs.map +1 -1
- package/dist/DeFiPositionsController/fetch-positions.mjs.map +1 -1
- package/dist/DeFiPositionsController/group-defi-positions.cjs.map +1 -1
- package/dist/DeFiPositionsController/group-defi-positions.mjs.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
- package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
- package/dist/MultichainAssetsController/utils.cjs.map +1 -1
- package/dist/MultichainAssetsController/utils.mjs.map +1 -1
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.cjs.map +1 -1
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.cts +2 -2
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.d.mts +2 -2
- package/dist/MultichainAssetsRatesController/MultichainAssetsRatesController.mjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs +2 -2
- package/dist/MultichainBalancesController/MultichainBalancesController.cjs.map +1 -1
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs +2 -2
- package/dist/MultichainBalancesController/MultichainBalancesController.mjs.map +1 -1
- package/dist/NftController.cjs.map +1 -1
- package/dist/NftController.mjs.map +1 -1
- package/dist/NftDetectionController.cjs +2 -2
- package/dist/NftDetectionController.cjs.map +1 -1
- package/dist/NftDetectionController.mjs +2 -2
- package/dist/NftDetectionController.mjs.map +1 -1
- package/dist/RatesController/RatesController.cjs.map +1 -1
- package/dist/RatesController/RatesController.mjs.map +1 -1
- package/dist/Standards/ERC20Standard.cjs.map +1 -1
- package/dist/Standards/ERC20Standard.mjs.map +1 -1
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.cjs.map +1 -1
- package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.mjs.map +1 -1
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.cjs.map +1 -1
- package/dist/Standards/NftStandards/ERC721/ERC721Standard.mjs.map +1 -1
- package/dist/TokenBalancesController.cjs.map +1 -1
- package/dist/TokenBalancesController.d.cts +2 -2
- package/dist/TokenBalancesController.d.mts +2 -2
- package/dist/TokenBalancesController.mjs.map +1 -1
- package/dist/TokenDetectionController.cjs.map +1 -1
- package/dist/TokenDetectionController.d.cts +2 -2
- package/dist/TokenDetectionController.d.mts +2 -2
- package/dist/TokenDetectionController.mjs.map +1 -1
- package/dist/TokenListController.cjs.map +1 -1
- package/dist/TokenListController.d.cts +2 -2
- package/dist/TokenListController.d.mts +2 -2
- package/dist/TokenListController.mjs.map +1 -1
- package/dist/TokenRatesController.cjs.map +1 -1
- package/dist/TokenRatesController.d.cts +2 -2
- package/dist/TokenRatesController.d.mts +2 -2
- package/dist/TokenRatesController.mjs.map +1 -1
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -1
- package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -1
- package/dist/TokensController.cjs.map +1 -1
- package/dist/TokensController.mjs.map +1 -1
- package/dist/assetsUtil.cjs.map +1 -1
- package/dist/assetsUtil.d.cts +20 -20
- package/dist/assetsUtil.d.cts.map +1 -1
- package/dist/assetsUtil.d.mts +20 -20
- package/dist/assetsUtil.d.mts.map +1 -1
- package/dist/assetsUtil.mjs.map +1 -1
- package/dist/balances.cjs.map +1 -1
- package/dist/balances.mjs.map +1 -1
- package/dist/constants.cjs +9 -9
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.mjs +9 -9
- package/dist/constants.mjs.map +1 -1
- package/dist/crypto-compare-service/crypto-compare.cjs.map +1 -1
- package/dist/crypto-compare-service/crypto-compare.mjs.map +1 -1
- package/dist/multi-chain-accounts-service/api-balance-fetcher.cjs.map +1 -1
- package/dist/multi-chain-accounts-service/api-balance-fetcher.mjs.map +1 -1
- package/dist/multi-chain-accounts-service/multi-chain-accounts.cjs.map +1 -1
- package/dist/multi-chain-accounts-service/multi-chain-accounts.mjs.map +1 -1
- package/dist/multicall.cjs.map +1 -1
- package/dist/multicall.mjs.map +1 -1
- package/dist/rpc-service/rpc-balance-fetcher.cjs.map +1 -1
- package/dist/rpc-service/rpc-balance-fetcher.mjs.map +1 -1
- package/dist/selectors/stringify-balance.cjs.map +1 -1
- package/dist/selectors/stringify-balance.mjs.map +1 -1
- package/dist/selectors/token-selectors.cjs.map +1 -1
- package/dist/selectors/token-selectors.mjs.map +1 -1
- package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
- package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
- package/dist/token-service.cjs +0 -3
- package/dist/token-service.cjs.map +1 -1
- package/dist/token-service.d.cts.map +1 -1
- package/dist/token-service.d.mts.map +1 -1
- package/dist/token-service.mjs +0 -3
- package/dist/token-service.mjs.map +1 -1
- package/dist/utils/formatters.cjs.map +1 -1
- package/dist/utils/formatters.mjs.map +1 -1
- package/dist/utils/timeout-with-retry.cjs.map +1 -1
- package/dist/utils/timeout-with-retry.mjs.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NftDetectionController.cjs","sourceRoot":"","sources":["../src/NftDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,+DAImC;AACnC,iEAQoC;AAapC,2CAAkE;AAElE,+CAAqC;AAQrC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA2BhD;;GAEG;AACH,MAAM,6BAA6B,GAAa,IAAI,GAAG,CAAC;IACtD,4FAA4F;IAC5F,qEAAqE;IACrE,KAAK;IACL,QAAQ;IACR,OAAO,EAAE,MAAM;CAChB,CAAC,CAAC;AA0JH,IAAY,kBAKX;AALD,WAAY,kBAAkB;IAC5B,uCAAiB,CAAA;IACjB,mCAAa,CAAA;IACb,yCAAmB,CAAA;IACnB,6CAAuB,CAAA;AACzB,CAAC,EALW,kBAAkB,kCAAlB,kBAAkB,QAK7B;AAkOD;;GAEG;AACH,MAAa,sBAAuB,SAAQ,gCAI3C;IASC;;;;;;;;OAQG;IACH,YAAY,EACV,SAAS,EACT,QAAQ,GAAG,KAAK,EAChB,MAAM,EACN,WAAW,GAMZ;QACC,KAAK,CAAC;YACJ,IAAI,EAAE,cAAc;YACpB,SAAS;YACT,QAAQ,EAAE,EAAE;YACZ,KAAK,EAAE,EAAE;SACV,CAAC,CAAC;;QAjCL,mDAAmB;QAEV,iDAAiC;QAEjC,sDAAuC;QAEhD,sEAA2E;QA4BzE,uBAAA,IAAI,oCAAa,QAAQ,MAAA,CAAC;QAC1B,uBAAA,IAAI,uDAAgC,EAAE,MAAA,CAAC;QAEvC,uBAAA,IAAI,uCAAgB,WAAW,MAAA,CAAC;QAChC,uBAAA,IAAI,kCAAW,MAAM,MAAA,CAAC;QAEtB,IAAI,CAAC,SAAS,CAAC,SAAS,CACtB,mCAAmC,EACnC,uBAAA,IAAI,qGAAoC,CAAC,IAAI,CAAC,IAAI,CAAC,CACpD,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,SAAS;QACP,MAAM,EAAE,uBAAuB,EAAE,GAAG,IAA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e;SACzB;KACF,CAAC,CAAC;IACH,OAAO,cAAc,CAAC;AACxB,CAAC;AA8IH,kBAAe,sBAAsB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\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 { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '../../network-controller/src/NetworkController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | ControllerGetStateAction<typeof controllerName, NFTDetectionControllerState>\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerFindNetworkClientIdByChainIdAction;\n\nexport type AllowedEvents =\n | ControllerStateChangeEvent<\n typeof controllerName,\n NFTDetectionControllerState\n >\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = Messenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents\n>;\n\n/**\n * A set of supported networks for NFT detection.\n */\nconst supportedNftDetectionNetworks: Set<Hex> = new Set([\n // TODO: We should consider passing this constant from the NftDetectionController contructor\n // to reduce the complexity to add further network into this constant\n '0x1', // Mainnet\n '0xe708', // Linea Mainnet\n '0x531', // Sei\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 chainId?: number;\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\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<`${string}:${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.messenger.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.messenger.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messenger.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 chainIds,\n address,\n next,\n }: {\n chainIds: string[];\n address: string;\n next?: string;\n }) {\n // from chainIds construct a string of chainIds that can be used like chainIds=1&chainIds=56\n const chainIdsString = chainIds.join('&chainIds=');\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainIdsString}&limit=50&includeTopBid=true&continuation=${next ?? ''}`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainIds: Hex[],\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainIds = chainIds.map((chainId) =>\n convertHexToDecimal(chainId).toString(),\n );\n const url = this.#getOwnerNftApi({\n chainIds: convertedChainIds,\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 chainIds - The chain IDs to detect NFTs on.\n * @param options - Options bag.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(chainIds: Hex[], options?: { userAddress?: string }) {\n const userAddress =\n options?.userAddress ??\n this.messenger.call('AccountsController:getSelectedAccount').address;\n\n // filter out unsupported chainIds\n const supportedChainIds = chainIds.filter((chainId) =>\n supportedNftDetectionNetworks.has(chainId),\n );\n /* istanbul ignore if */\n if (supportedChainIds.length === 0 || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n // create a string of all chainIds\n const chainIdsString = chainIds.join(',');\n\n const updateKey: `${string}:${string}` = `${chainIdsString}:${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(\n userAddress,\n supportedChainIds,\n next,\n );\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\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 chainId,\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 chainId && { chainId },\n );\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n toHex(chainId),\n );\n await this.#addNft(contract, tokenId, networkClientId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\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.cjs","sourceRoot":"","sources":["../src/NftDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,+DAImC;AACnC,iEAQoC;AAapC,2CAAkE;AAElE,+CAAqC;AAQrC,MAAM,cAAc,GAAG,wBAAwB,CAAC;AA2BhD;;GAEG;AACH,MAAM,6BAA6B,GAAa,IAAI,GAAG,CAAC;IACtD,4FAA4F;IAC5F,qEAAqE;IACrE,KAA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E,CAAC;QACpB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,MAAM,KAAK,CAAC;QACd,CAAC;gBAAS,CAAC;YACT,OAAO,uBAAA,IAAI,2DAA6B,CAAC,SAAS,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;CACF;AApQD,wDAoQC;gZAtLqC,EAAE,eAAe,EAAoB;IACvE,IAAI,CAAC,eAAe,KAAK,uBAAA,IAAI,wCAAU,EAAE,CAAC;QACxC,uBAAA,IAAI,oCAAa,CAAC,eAAe,MAAA,CAAC;IACpC,CAAC;AACH,CAAC,2FAEe,EACd,QAAQ,EACR,OAAO,EACP,IAAI,GAKL;IACC,4FAA4F;IAC5F,MAAM,cAAc,GAAG,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;IACnD,OAAO,GACL,mCACF,UAAU,OAAO,oBAAoB,cAAc,6CAA6C,IAAI,IAAI,EAAE,EAAE,CAAC;AAC/G,CAAC,yCAED,KAAK,+CACH,OAAe,EACf,QAAe,EACf,MAA0B;IAE1B,gCAAgC;IAChC,MAAM,iBAAiB,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CACjD,IAAA,sCAAmB,EAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CACxC,CAAC;IACF,MAAM,GAAG,GAAG,uBAAA,IAAI,iFAAgB,MAApB,IAAI,EAAiB;QAC/B,QAAQ,EAAE,iBAAiB;QAC3B,OAAO;QACP,IAAI,EAAE,MAAM;KACb,CAAC,CAAC;IACH,MAAM,cAAc,GAAsB,MAAM,IAAA,8BAAW,EAAC,GAAG,EAAE;QAC/D,OAAO,EAAE;YACP,OAAO,EAAE,kCAAe;SACzB;KACF,CAAC,CAAC;IACH,OAAO,cAAc,CAAC;AACxB,CAAC;AA8IH,kBAAe,sBAAsB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\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 { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '../../network-controller/src/NetworkController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | ControllerGetStateAction<typeof controllerName, NFTDetectionControllerState>\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerFindNetworkClientIdByChainIdAction;\n\nexport type AllowedEvents =\n | ControllerStateChangeEvent<\n typeof controllerName,\n NFTDetectionControllerState\n >\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = Messenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents\n>;\n\n/**\n * A set of supported networks for NFT detection.\n */\nconst supportedNftDetectionNetworks: Set<Hex> = new Set([\n // TODO: We should consider passing this constant from the NftDetectionController contructor\n // to reduce the complexity to add further network into this constant\n '0x1', // Mainnet\n '0xe708', // Linea Mainnet\n '0x531', // Sei\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 chainId?: number;\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\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<`${string}:${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.messenger.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.messenger.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messenger.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 chainIds,\n address,\n next,\n }: {\n chainIds: string[];\n address: string;\n next?: string;\n }) {\n // from chainIds construct a string of chainIds that can be used like chainIds=1&chainIds=56\n const chainIdsString = chainIds.join('&chainIds=');\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainIdsString}&limit=50&includeTopBid=true&continuation=${next ?? ''}`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainIds: Hex[],\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainIds = chainIds.map((chainId) =>\n convertHexToDecimal(chainId).toString(),\n );\n const url = this.#getOwnerNftApi({\n chainIds: convertedChainIds,\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 chainIds - The chain IDs to detect NFTs on.\n * @param options - Options bag.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(chainIds: Hex[], options?: { userAddress?: string }) {\n const userAddress =\n options?.userAddress ??\n this.messenger.call('AccountsController:getSelectedAccount').address;\n\n // filter out unsupported chainIds\n const supportedChainIds = chainIds.filter((chainId) =>\n supportedNftDetectionNetworks.has(chainId),\n );\n /* istanbul ignore if */\n if (supportedChainIds.length === 0 || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n // create a string of all chainIds\n const chainIdsString = chainIds.join(',');\n\n const updateKey: `${string}:${string}` = `${chainIdsString}:${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(\n userAddress,\n supportedChainIds,\n next,\n );\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\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 chainId,\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 chainId && { chainId },\n );\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n toHex(chainId),\n );\n await this.#addNft(contract, tokenId, networkClientId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\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"]}
|
|
@@ -21,8 +21,8 @@ const controllerName = 'NftDetectionController';
|
|
|
21
21
|
const supportedNftDetectionNetworks = new Set([
|
|
22
22
|
// TODO: We should consider passing this constant from the NftDetectionController contructor
|
|
23
23
|
// to reduce the complexity to add further network into this constant
|
|
24
|
-
'0x1',
|
|
25
|
-
'0xe708',
|
|
24
|
+
'0x1', // Mainnet
|
|
25
|
+
'0xe708', // Linea Mainnet
|
|
26
26
|
'0x531', // Sei
|
|
27
27
|
]);
|
|
28
28
|
export var BlockaidResultType;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NftDetectionController.mjs","sourceRoot":"","sources":["../src/NftDetectionController.ts"],"names":[],"mappings":";;;;;;;;;;;;A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,OAAO,EAAE;YACP,OAAO,EAAE,eAAe;SACzB;KACF,CAAC,CAAC;IACH,OAAO,cAAc,CAAC;AACxB,CAAC;AA8IH,eAAe,sBAAsB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\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 { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '../../network-controller/src/NetworkController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | ControllerGetStateAction<typeof controllerName, NFTDetectionControllerState>\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerFindNetworkClientIdByChainIdAction;\n\nexport type AllowedEvents =\n | ControllerStateChangeEvent<\n typeof controllerName,\n NFTDetectionControllerState\n >\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = Messenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents\n>;\n\n/**\n * A set of supported networks for NFT detection.\n */\nconst supportedNftDetectionNetworks: Set<Hex> = new Set([\n // TODO: We should consider passing this constant from the NftDetectionController contructor\n // to reduce the complexity to add further network into this constant\n '0x1', // Mainnet\n '0xe708', // Linea Mainnet\n '0x531', // Sei\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 chainId?: number;\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\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<`${string}:${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.messenger.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.messenger.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messenger.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 chainIds,\n address,\n next,\n }: {\n chainIds: string[];\n address: string;\n next?: string;\n }) {\n // from chainIds construct a string of chainIds that can be used like chainIds=1&chainIds=56\n const chainIdsString = chainIds.join('&chainIds=');\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainIdsString}&limit=50&includeTopBid=true&continuation=${next ?? ''}`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainIds: Hex[],\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainIds = chainIds.map((chainId) =>\n convertHexToDecimal(chainId).toString(),\n );\n const url = this.#getOwnerNftApi({\n chainIds: convertedChainIds,\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 chainIds - The chain IDs to detect NFTs on.\n * @param options - Options bag.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(chainIds: Hex[], options?: { userAddress?: string }) {\n const userAddress =\n options?.userAddress ??\n this.messenger.call('AccountsController:getSelectedAccount').address;\n\n // filter out unsupported chainIds\n const supportedChainIds = chainIds.filter((chainId) =>\n supportedNftDetectionNetworks.has(chainId),\n );\n /* istanbul ignore if */\n if (supportedChainIds.length === 0 || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n // create a string of all chainIds\n const chainIdsString = chainIds.join(',');\n\n const updateKey: `${string}:${string}` = `${chainIdsString}:${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(\n userAddress,\n supportedChainIds,\n next,\n );\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\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 chainId,\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 chainId && { chainId },\n );\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n toHex(chainId),\n );\n await this.#addNft(contract, tokenId, networkClientId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\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":";;;;;;;;;;;;AAEA,OAAO,EACL,cAAc,EAGf,kCAAkC;AACnC,OAAO,EACL,oBAAoB,EACpB,OAAO,EACP,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,WAAW,EACX,KAAK,EACN,mCAAmC;AAapC,OAAO,EAAE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OAAO,EAAE,eAAe;SACzB;KACF,CAAC,CAAC;IACH,OAAO,cAAc,CAAC;AACxB,CAAC;AA8IH,eAAe,sBAAsB,CAAC","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport {\n BaseController,\n type ControllerGetStateAction,\n type ControllerStateChangeEvent,\n} from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n toHex,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type {\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 { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '../../network-controller/src/NetworkController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | ControllerGetStateAction<typeof controllerName, NFTDetectionControllerState>\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction\n | NetworkControllerFindNetworkClientIdByChainIdAction;\n\nexport type AllowedEvents =\n | ControllerStateChangeEvent<\n typeof controllerName,\n NFTDetectionControllerState\n >\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = Messenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents\n>;\n\n/**\n * A set of supported networks for NFT detection.\n */\nconst supportedNftDetectionNetworks: Set<Hex> = new Set([\n // TODO: We should consider passing this constant from the NftDetectionController contructor\n // to reduce the complexity to add further network into this constant\n '0x1', // Mainnet\n '0xe708', // Linea Mainnet\n '0x531', // Sei\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 chainId?: number;\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\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<`${string}:${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.messenger.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.messenger.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messenger.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 chainIds,\n address,\n next,\n }: {\n chainIds: string[];\n address: string;\n next?: string;\n }) {\n // from chainIds construct a string of chainIds that can be used like chainIds=1&chainIds=56\n const chainIdsString = chainIds.join('&chainIds=');\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainIdsString}&limit=50&includeTopBid=true&continuation=${next ?? ''}`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainIds: Hex[],\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainIds = chainIds.map((chainId) =>\n convertHexToDecimal(chainId).toString(),\n );\n const url = this.#getOwnerNftApi({\n chainIds: convertedChainIds,\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 chainIds - The chain IDs to detect NFTs on.\n * @param options - Options bag.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(chainIds: Hex[], options?: { userAddress?: string }) {\n const userAddress =\n options?.userAddress ??\n this.messenger.call('AccountsController:getSelectedAccount').address;\n\n // filter out unsupported chainIds\n const supportedChainIds = chainIds.filter((chainId) =>\n supportedNftDetectionNetworks.has(chainId),\n );\n /* istanbul ignore if */\n if (supportedChainIds.length === 0 || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n // create a string of all chainIds\n const chainIdsString = chainIds.join(',');\n\n const updateKey: `${string}:${string}` = `${chainIdsString}:${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(\n userAddress,\n supportedChainIds,\n next,\n );\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\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 chainId,\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 chainId && { chainId },\n );\n const networkClientId = this.messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n toHex(chainId),\n );\n await this.#addNft(contract, tokenId, networkClientId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RatesController.cjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAA+E;AAC/E,6CAAoC;AAGpC,gFAA+F;AAQlF,QAAA,IAAI,GAAG,iBAAiB,CAAC;AAEtC;;;;;GAKG;AACH,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,6BAAW,CAAA;I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KAAK,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC/D,YAAY,CAAC,cAAc,CAAC,GAAG;gBAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;gBAC1B,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC;gBACpC,GAAG,CAAC,uBAAA,IAAI,uCAAgB,IAAI,EAAE,iBAAiB,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;aAC/D,CAAC;SACH;QAED,IAAI,CAAC,MAAM,CACT,CAAC,KAAkC,EAAwB,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController, type StateMetadata } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\n/**\n * Supported cryptocurrencies that can be used as a base currency. The value needs to be compatible\n * with CryptoCompare's API which is the default source for the rates.\n *\n * See: https://min-api.cryptocompare.com/documentation?key=Price&cat=multipleSymbolsPriceEndpoint\n */\nexport enum Cryptocurrency {\n Btc = 'btc',\n Solana = 'sol',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata: StateMetadata<RatesControllerState> = {\n fiatCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n rates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n cryptocurrencies: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n [Cryptocurrency.Solana]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc, Cryptocurrency.Solana],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\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 async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, number>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messenger.publish(`${name}:pollingStarted`);\n\n await this.#updateRates();\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messenger.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RatesController.cjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,+DAA+E;AAC/E,6CAAoC;AAGpC,gFAA+F;AAQlF,QAAA,IAAI,GAAG,iBAAiB,CAAC;AAEtC;;;;;GAKG;AACH,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,6BAAW,CAAA;IACX,gCAAc,CAAA;AAChB,CAAC,EAHW,cAAc,8BAAd,cAAc,QAGzB;AAED,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,QAAQ,GAAwC;IACpD,YAAY,EAAE;QACZ,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,KAAK,EAAE;QACL,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,KAAK;KAChB;CACF,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,YAAY,EAAE,KAAK;IACnB,KAAK,EAAE;QACL,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;YACpB,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;SAClB;QACD,CAAC,cAAc,CAAC,MAAM,CAAC,E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8BAAO,CAAC,OAAO,EAAE,CAAC;IAChD,IAAI,CAAC;QACH,OAAO,QAAQ,EAAE,CAAC;IACpB,CAAC;YAAS,CAAC;QACT,WAAW,EAAE,CAAC;IAChB,CAAC;AACH,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,gEAAa,MAAjB,IAAI,CAAe,CAAC;AAC5B,CAAC;AAED;;GAEG;AACH,KAAK;IACH,MAAM,uBAAA,IAAI,6DAAU,MAAd,IAAI,EAAW,KAAK,IAAI,EAAE;QAC9B,MAAM,EAAE,YAAY,EAAE,gBAAgB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC;QACtD,MAAM,QAAQ,GAGV,MAAM,uBAAA,IAAI,+CAAwB,MAA5B,IAAI,EACZ,YAAY,EACZ,gBAAgB,EAChB,uBAAA,IAAI,uCAAgB,CACrB,CAAC;QAEF,MAAM,YAAY,GAAoB,EAAE,CAAC;QACzC,KAAK,MAAM,CAAC,cAAc,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;YAChE,YAAY,CAAC,cAAc,CAAC,GAAG;gBAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;gBAC1B,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC;gBACpC,GAAG,CAAC,uBAAA,IAAI,uCAAgB,IAAI,EAAE,iBAAiB,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;aAC/D,CAAC;QACJ,CAAC;QAED,IAAI,CAAC,MAAM,CACT,CAAC,KAAkC,EAAwB,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController, type StateMetadata } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\n/**\n * Supported cryptocurrencies that can be used as a base currency. The value needs to be compatible\n * with CryptoCompare's API which is the default source for the rates.\n *\n * See: https://min-api.cryptocompare.com/documentation?key=Price&cat=multipleSymbolsPriceEndpoint\n */\nexport enum Cryptocurrency {\n Btc = 'btc',\n Solana = 'sol',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata: StateMetadata<RatesControllerState> = {\n fiatCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n rates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n cryptocurrencies: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n [Cryptocurrency.Solana]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc, Cryptocurrency.Solana],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\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 async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, number>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messenger.publish(`${name}:pollingStarted`);\n\n await this.#updateRates();\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messenger.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RatesController.mjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAsB,kCAAkC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AAQ/F,MAAM,CAAC,MAAM,IAAI,GAAG,iBAAiB,CAAC;AAEtC;;;;;GAKG;AACH,MAAM,CAAN,IAAY,cAGX;AAHD,WAAY,cAAc;I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AAM,CAAC,cAAc,EAAE,MAAM,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;YAC/D,YAAY,CAAC,cAAc,CAAC,GAAG;gBAC7B,cAAc,EAAE,IAAI,CAAC,GAAG,EAAE;gBAC1B,cAAc,EAAE,MAAM,CAAC,YAAY,CAAC;gBACpC,GAAG,CAAC,uBAAA,IAAI,uCAAgB,IAAI,EAAE,iBAAiB,EAAE,MAAM,CAAC,GAAG,EAAE,CAAC;aAC/D,CAAC;SACH;QAED,IAAI,CAAC,MAAM,CACT,CAAC,KAAkC,EAAwB,EAAE;YAC3D,OAAO;gBACL,GAAG,KAAK;gBACR,KAAK,EAAE,YAAY;aACpB,CAAC;QACJ,CAAC,CACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { BaseController, type StateMetadata } from '@metamask/base-controller';\nimport { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\n/**\n * Supported cryptocurrencies that can be used as a base currency. The value needs to be compatible\n * with CryptoCompare's API which is the default source for the rates.\n *\n * See: https://min-api.cryptocompare.com/documentation?key=Price&cat=multipleSymbolsPriceEndpoint\n */\nexport enum Cryptocurrency {\n Btc = 'btc',\n Solana = 'sol',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata: StateMetadata<RatesControllerState> = {\n fiatCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n rates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n cryptocurrencies: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n [Cryptocurrency.Solana]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc, Cryptocurrency.Solana],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\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 async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, number>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messenger.publish(`${name}:pollingStarted`);\n\n await this.#updateRates();\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messenger.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"RatesController.mjs","sourceRoot":"","sources":["../../src/RatesController/RatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,cAAc,EAAsB,kCAAkC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAGpC,OAAO,EAAE,sBAAsB,IAAI,wBAAwB,EAAE,4CAAkC;AAQ/F,MAAM,CAAC,MAAM,IAAI,GAAG,iBAAiB,CAAC;AAEtC;;;;;GAKG;AACH,MAAM,CAAN,IAAY,cAGX;AAHD,WAAY,cAAc;IACxB,6BAAW,CAAA;IACX,gCAAc,CAAA;AAChB,CAAC,EAHW,cAAc,KAAd,cAAc,QAGzB;AAED,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAEhC,MAAM,QAAQ,GAAwC;IACpD,YAAY,EAAE;QACZ,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,KAAK,EAAE;QACL,kBAAkB,EAAE,KAAK;QACzB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,gBAAgB,EAAE;QAChB,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,KAAK;KAChB;CACF,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,YAAY,EAAE,KAAK;IACnB,KAAK,EAAE;QACL,CAAC,cAAc,CAAC,GAAG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port { Mutex } from 'async-mutex';\nimport type { Draft } from 'immer';\n\nimport { fetchMultiExchangeRate as defaultFetchExchangeRate } from '../crypto-compare-service';\nimport type {\n ConversionRates,\n RatesControllerState,\n RatesControllerOptions,\n RatesControllerMessenger,\n} from './types';\n\nexport const name = 'RatesController';\n\n/**\n * Supported cryptocurrencies that can be used as a base currency. The value needs to be compatible\n * with CryptoCompare's API which is the default source for the rates.\n *\n * See: https://min-api.cryptocompare.com/documentation?key=Price&cat=multipleSymbolsPriceEndpoint\n */\nexport enum Cryptocurrency {\n Btc = 'btc',\n Solana = 'sol',\n}\n\nconst DEFAULT_INTERVAL = 180000;\n\nconst metadata: StateMetadata<RatesControllerState> = {\n fiatCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n rates: {\n includeInStateLogs: false,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n cryptocurrencies: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: false,\n },\n};\n\nconst defaultState = {\n fiatCurrency: 'usd',\n rates: {\n [Cryptocurrency.Btc]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n [Cryptocurrency.Solana]: {\n conversionDate: 0,\n conversionRate: 0,\n },\n },\n cryptocurrencies: [Cryptocurrency.Btc, Cryptocurrency.Solana],\n};\n\nexport class RatesController extends BaseController<\n typeof name,\n RatesControllerState,\n RatesControllerMessenger\n> {\n readonly #mutex = new Mutex();\n\n readonly #fetchMultiExchangeRate;\n\n readonly #includeUsdRate;\n\n #intervalLength: number;\n\n #intervalId: NodeJS.Timeout | undefined;\n\n /**\n * Creates a RatesController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messaging system.\n * @param options.state - Initial state to set on this controller.\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n messenger,\n state,\n includeUsdRate,\n fetchMultiExchangeRate = defaultFetchExchangeRate,\n }: RatesControllerOptions) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.#includeUsdRate = includeUsdRate;\n this.#fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#intervalLength = interval;\n }\n\n /**\n * Executes a function `callback` within a mutex lock to ensure that only one instance of `callback` runs at a time across all invocations of `#withLock`.\n * This method is useful for synchronizing access to a resource or section of code that should not be executed concurrently.\n *\n * @template R - The return type of the function `callback`.\n * @param callback - A callback to execute once the lock is acquired. This callback can be synchronous or asynchronous.\n * @returns A promise that resolves to the result of the function `callback`. The promise is fulfilled once `callback` has completed execution.\n * @example\n * async function criticalLogic() {\n * // Critical logic code goes here.\n * }\n *\n * // Execute criticalLogic within a lock.\n * const result = await this.#withLock(criticalLogic);\n */\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 async #withLock<R>(callback: () => R) {\n const releaseLock = await this.#mutex.acquire();\n try {\n return callback();\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Executes the polling operation to update rates.\n */\n async #executePoll(): Promise<void> {\n await this.#updateRates();\n }\n\n /**\n * Updates the rates by fetching new data.\n */\n async #updateRates(): Promise<void> {\n await this.#withLock(async () => {\n const { fiatCurrency, cryptocurrencies } = this.state;\n const response: Record<\n Cryptocurrency,\n Record<string, number>\n > = await this.#fetchMultiExchangeRate(\n fiatCurrency,\n cryptocurrencies,\n this.#includeUsdRate,\n );\n\n const updatedRates: ConversionRates = {};\n for (const [cryptocurrency, values] of Object.entries(response)) {\n updatedRates[cryptocurrency] = {\n conversionDate: Date.now(),\n conversionRate: values[fiatCurrency],\n ...(this.#includeUsdRate && { usdConversionRate: values.usd }),\n };\n }\n\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n rates: updatedRates,\n };\n },\n );\n });\n }\n\n /**\n * Starts the polling process.\n */\n async start(): Promise<void> {\n if (this.#intervalId) {\n return;\n }\n\n this.messenger.publish(`${name}:pollingStarted`);\n\n await this.#updateRates();\n\n this.#intervalId = setInterval(() => {\n this.#executePoll().catch(console.error);\n }, this.#intervalLength);\n }\n\n /**\n * Stops the polling process.\n */\n async stop(): Promise<void> {\n if (!this.#intervalId) {\n return;\n }\n\n clearInterval(this.#intervalId);\n this.#intervalId = undefined;\n this.messenger.publish(`${name}:pollingStopped`);\n }\n\n /**\n * Returns the current list of cryptocurrency.\n * @returns The cryptocurrency list.\n */\n getCryptocurrencyList(): Cryptocurrency[] {\n const { cryptocurrencies } = this.state;\n return cryptocurrencies;\n }\n\n /**\n * Sets the list of supported cryptocurrencies.\n * @param cryptocurrencies - The list of supported cryptocurrencies.\n */\n async setCryptocurrencyList(\n cryptocurrencies: Cryptocurrency[],\n ): Promise<void> {\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n cryptocurrencies,\n };\n },\n );\n });\n }\n\n /**\n * Sets the internal fiat currency and update rates accordingly.\n * @param fiatCurrency - The fiat currency.\n */\n async setFiatCurrency(fiatCurrency: string): Promise<void> {\n if (fiatCurrency === '') {\n throw new Error('The currency can not be an empty string');\n }\n\n await this.#withLock(() => {\n this.update(\n (state: Draft<RatesControllerState>): RatesControllerState => {\n return {\n ...state,\n fiatCurrency,\n };\n },\n );\n });\n await this.#updateRates();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ERC20Standard.cjs","sourceRoot":"","sources":["../../src/Standards/ERC20Standard.ts"],"names":[],"mappings":";;;AAAA,2CAA+C;AAC/C,wDAAoD;AAEpD,mDAAmD;AACnD,iEAAmD;AACnD,mEAAuD;AACvD,2CAAsE;AAGtE,kDAAoD;AAEpD,MAAa,aAAa;IAGxB,YAAY,QAAsB;QAChC,IAAI,CAAC,QAAQ,GAAG,QAAQ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contract } from '@ethersproject/contracts';\nimport type { Web3Provider } from '@ethersproject/providers';\nimport { decodeSingle } from '@metamask/abi-utils';\nimport { ERC20 } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { assertIsStrictHexString, hexToBytes } from '@metamask/utils';\nimport type BN from 'bn.js';\n\nimport { ethersBigNumberToBN } from '../assetsUtil';\n\nexport class ERC20Standard {\n private readonly provider: Web3Provider;\n\n constructor(provider: Web3Provider) {\n this.provider = 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 * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getBalanceOf(address: string, selectedAddress: string): Promise<BN> {\n const contract = new Contract(address, abiERC20, this.provider);\n const balance = await contract.balanceOf(selectedAddress);\n return ethersBigNumberToBN(balance);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract string.\n * @returns Promise resolving to the 'decimals'.\n */\n async getTokenDecimals(address: string): Promise<string> {\n const contract = new Contract(address, abiERC20, this.provider);\n try {\n const decimals = await contract.decimals();\n return decimals.toString();\n } catch (err) {\n // Mirror previous implementation\n if (\n err instanceof Error &&\n err.message.includes('call revert exception')\n ) {\n throw new Error('Failed to parse token decimals');\n }\n throw err;\n }\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract string.\n * @returns Promise resolving to the 'name'.\n */\n async getTokenName(address: string): Promise<string> {\n const contract = new Contract(address, abiERC20, this.provider);\n try {\n const name = await contract.name();\n return name.toString();\n } catch (err) {\n // Mirror previous implementation\n if (\n err instanceof Error &&\n err.message.includes('call revert exception')\n ) {\n throw new Error('Failed to parse token name');\n }\n throw err;\n }\n }\n\n /**\n * Query for symbol for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @returns Promise resolving to the 'symbol'.\n */\n async getTokenSymbol(address: string): Promise<string> {\n // Signature for calling `symbol()`\n const payload = { to: address, data: '0x95d89b41' };\n const result = await this.provider.call(payload);\n assertIsStrictHexString(result);\n // Parse as string - treat empty string as failure\n try {\n const decoded = decodeSingle('string', result);\n if (decoded?.length > 0) {\n return decoded;\n }\n } catch {\n // Ignore error\n }\n\n // Parse as bytes - treat empty string as failure\n try {\n // Not done in bytesToUtf8 in ethereumjs/util.\n const regexPreceedingAndTrailingZeroes = /^(00)+|(00)+$/gu;\n\n const resultTrimmed = result?.replace(\n regexPreceedingAndTrailingZeroes,\n '',\n );\n\n const utf8 = bytesToUtf8(hexToBytes(resultTrimmed));\n if (utf8.length > 0) {\n return utf8;\n }\n } catch {\n // Ignore error\n }\n\n throw new Error('Failed to parse token symbol');\n }\n\n /**\n * Query if a contract implements an interface.\n *\n * @param address - Asset contract address.\n * @param userAddress - The public address for the currently active user's account.\n * @returns Promise resolving an object containing the standard, decimals, symbol and balance of the given contract/userAddress pair.\n */\n async getDetails(\n address: string,\n userAddress?: string,\n ): Promise<{\n standard: string;\n symbol: string | undefined;\n decimals: string | undefined;\n balance: BN | undefined;\n }> {\n const [decimals, symbol, balance] = await Promise.all([\n this.getTokenDecimals(address),\n this.getTokenSymbol(address),\n userAddress ? this.getBalanceOf(address, userAddress) : undefined,\n ]);\n return {\n decimals,\n symbol,\n balance,\n standard: ERC20,\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ERC20Standard.mjs","sourceRoot":"","sources":["../../src/Standards/ERC20Standard.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,yBAAyB;AAC/C,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AAEpD,OAAO,EAAE,YAAY,EAAE,4BAA4B;AACnD,OAAO,EAAE,KAAK,EAAE,mCAAmC;AACnD,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AACvD,OAAO,EAAE,uBAAuB,EAAE,UAAU,EAAE,wBAAwB;AAGtE,OAAO,EAAE,mBAAmB,EAAE,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CAAC,OAAO,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,SAAS;SAClE,CAAC,CAAC;QACH,OAAO;YACL,QAAQ;YACR,MAAM;YACN,OAAO;YACP,QAAQ,EAAE,KAAK;SAChB,CAAC;IACJ,CAAC;CACF","sourcesContent":["import { bytesToUtf8 } from '@ethereumjs/util';\nimport { Contract } from '@ethersproject/contracts';\nimport type { Web3Provider } from '@ethersproject/providers';\nimport { decodeSingle } from '@metamask/abi-utils';\nimport { ERC20 } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { assertIsStrictHexString, hexToBytes } from '@metamask/utils';\nimport type BN from 'bn.js';\n\nimport { ethersBigNumberToBN } from '../assetsUtil';\n\nexport class ERC20Standard {\n private readonly provider: Web3Provider;\n\n constructor(provider: Web3Provider) {\n this.provider = 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 * @returns Promise resolving to BN object containing balance for current account on specific asset contract.\n */\n async getBalanceOf(address: string, selectedAddress: string): Promise<BN> {\n const contract = new Contract(address, abiERC20, this.provider);\n const balance = await contract.balanceOf(selectedAddress);\n return ethersBigNumberToBN(balance);\n }\n\n /**\n * Query for the decimals for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract string.\n * @returns Promise resolving to the 'decimals'.\n */\n async getTokenDecimals(address: string): Promise<string> {\n const contract = new Contract(address, abiERC20, this.provider);\n try {\n const decimals = await contract.decimals();\n return decimals.toString();\n } catch (err) {\n // Mirror previous implementation\n if (\n err instanceof Error &&\n err.message.includes('call revert exception')\n ) {\n throw new Error('Failed to parse token decimals');\n }\n throw err;\n }\n }\n\n /**\n * Query for the name for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract string.\n * @returns Promise resolving to the 'name'.\n */\n async getTokenName(address: string): Promise<string> {\n const contract = new Contract(address, abiERC20, this.provider);\n try {\n const name = await contract.name();\n return name.toString();\n } catch (err) {\n // Mirror previous implementation\n if (\n err instanceof Error &&\n err.message.includes('call revert exception')\n ) {\n throw new Error('Failed to parse token name');\n }\n throw err;\n }\n }\n\n /**\n * Query for symbol for a given ERC20 asset.\n *\n * @param address - ERC20 asset contract address.\n * @returns Promise resolving to the 'symbol'.\n */\n async getTokenSymbol(address: string): Promise<string> {\n // Signature for calling `symbol()`\n const payload = { to: address, data: '0x95d89b41' };\n const result = await this.provider.call(payload);\n assertIsStrictHexString(result);\n // Parse as string - treat empty string as failure\n try {\n const decoded = decodeSingle('string', result);\n if (decoded?.length > 0) {\n return decoded;\n }\n } catch {\n // Ignore error\n }\n\n // Parse as bytes - treat empty string as failure\n try {\n // Not done in bytesToUtf8 in ethereumjs/util.\n const regexPreceedingAndTrailingZeroes = /^(00)+|(00)+$/gu;\n\n const resultTrimmed = result?.replace(\n regexPreceedingAndTrailingZeroes,\n '',\n );\n\n const utf8 = bytesToUtf8(hexToBytes(resultTrimmed));\n if (utf8.length > 0) {\n return utf8;\n }\n } catch {\n // Ignore error\n }\n\n throw new Error('Failed to parse token symbol');\n }\n\n /**\n * Query if a contract implements an interface.\n *\n * @param address - Asset contract address.\n * @param userAddress - The public address for the currently active user's account.\n * @returns Promise resolving an object containing the standard, decimals, symbol and balance of the given contract/userAddress pair.\n */\n async getDetails(\n address: string,\n userAddress?: string,\n ): Promise<{\n standard: string;\n symbol: string | undefined;\n decimals: string | undefined;\n balance: BN | undefined;\n }> {\n const [decimals, symbol, balance] = await Promise.all([\n this.getTokenDecimals(address),\n this.getTokenSymbol(address),\n userAddress ? this.getBalanceOf(address, userAddress) : undefined,\n ]);\n return {\n decimals,\n symbol,\n balance,\n standard: ERC20,\n };\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ERC1155Standard.cjs","sourceRoot":"","sources":["../../../../src/Standards/NftStandards/ERC1155/ERC1155Standard.ts"],"names":[],"mappings":";;;AAAA,wDAAoD;AAEpD,iEAOoC;AACpC,mEAAyD;AA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Z,IAAI;gBACF,MAAM,QAAQ,GAAG,MAAM,IAAA,+BAAY,EAAC,QAAQ,CAAC,CAAC;gBAC9C,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;gBACrC,KAAK,GAAG,MAAM,EAAE,KAAK,CAAC;gBACtB,IAAI,KAAK,EAAE,UAAU,CAAC,SAAS,CAAC,EAAE;oBAChC,KAAK,GAAG,IAAA,gCAAmB,EAAC,WAAW,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;iBACvD;aACF;YAAC,MAAM;gBACN,6DAA6D;gBAC7D,+DAA+D;aAChE;SACF;QAED,sDAAsD;QACtD,OAAO;YACL,QAAQ,EAAE,0BAAO;YACjB,QAAQ;YACR,KAAK;YACL,MAAM;YACN,IAAI;SACL,CAAC;IACJ,CAAC;CACF;AArPD,0CAqPC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport type { Web3Provider } from '@ethersproject/providers';\nimport {\n ERC1155,\n ERC1155_INTERFACE_ID,\n ERC1155_METADATA_URI_INTERFACE_ID,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n safelyExecute,\n timeoutFetch,\n} from '@metamask/controller-utils';\nimport { abiERC1155 } from '@metamask/metamask-eth-abis';\nimport type * as BN from 'bn.js';\n\nimport { getFormattedIpfsUrl, ethersBigNumberToBN } from '../../../assetsUtil';\n\nexport class ERC1155Standard {\n private readonly provider: Web3Provider;\n\n constructor(provider: Web3Provider) {\n this.provider = provider;\n }\n\n /**\n * Query if contract implements ERC1155 URI Metadata interface.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to whether the contract implements ERC1155 URI Metadata interface.\n */\n async contractSupportsURIMetadataInterface(\n address: string,\n ): Promise<boolean> {\n return this.contractSupportsInterface(\n address,\n ERC1155_METADATA_URI_INTERFACE_ID,\n );\n }\n\n /**\n * Query if contract implements ERC1155 Token Receiver interface.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to whether the contract implements ERC1155 Token Receiver interface.\n */\n async contractSupportsTokenReceiverInterface(\n address: string,\n ): Promise<boolean> {\n return this.contractSupportsInterface(\n address,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n );\n }\n\n /**\n * Query if contract implements ERC1155 interface.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to whether the contract implements the base ERC1155 interface.\n */\n async contractSupportsBase1155Interface(address: string): Promise<boolean> {\n return this.contractSupportsInterface(address, ERC1155_INTERFACE_ID);\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 * @returns Promise resolving to the 'tokenURI'.\n */\n async getTokenURI(address: string, tokenId: string): Promise<string> {\n const contract = new Contract(address, abiERC1155, this.provider);\n return contract.uri(tokenId);\n }\n\n /**\n * Query for balance of a given ERC1155 token.\n *\n * @param contractAddress - ERC1155 asset contract address.\n * @param address - Wallet public address.\n * @param tokenId - ERC1155 asset identifier.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getBalanceOf(\n contractAddress: string,\n address: string,\n tokenId: string,\n ): Promise<BN> {\n const contract = new Contract(contractAddress, abiERC1155, this.provider);\n const balance = await contract.balanceOf(address, tokenId);\n return ethersBigNumberToBN(balance);\n }\n\n /**\n * Transfer single ERC1155 token.\n * When minting/creating tokens, the from arg MUST be set to 0x0 (i.e. zero address).\n * When burning/destroying tokens, the to arg MUST be set to 0x0 (i.e. zero address).\n *\n * @param operator - ERC1155 token address.\n * @param from - ERC1155 token holder.\n * @param to - ERC1155 token recipient.\n * @param id - ERC1155 token id.\n * @param value - Number of tokens to be sent.\n * @returns Promise resolving to the 'transferSingle'.\n */\n async transferSingle(\n operator: string,\n from: string,\n to: string,\n id: string,\n value: string,\n ): Promise<void> {\n const contract = new Contract(operator, abiERC1155, this.provider);\n return new Promise<void>((resolve, reject) => {\n contract.transferSingle(\n operator,\n from,\n to,\n id,\n value,\n (error: Error, result: void) => {\n /* istanbul ignore if */\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n },\n );\n });\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to the 'symbol'.\n */\n async getAssetSymbol(address: string): Promise<string> {\n const contract = new Contract(\n address,\n // Contract ABI fragment containing only the symbol method to fetch the symbol of the contract.\n [\n {\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '_symbol', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n payable: false,\n },\n ],\n this.provider,\n );\n return contract.symbol();\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to the 'name'.\n */\n async getAssetName(address: string): Promise<string> {\n const contract = new Contract(\n address,\n // Contract ABI fragment containing only the name method to fetch the name of the contract.\n [\n {\n inputs: [],\n name: 'name',\n outputs: [{ name: '_name', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n payable: false,\n },\n ],\n this.provider,\n );\n return contract.name();\n }\n\n /**\n * Query if a contract implements an interface.\n *\n * @param address - ERC1155 asset contract address.\n * @param interfaceId - Interface identifier.\n * @returns Promise resolving to whether the contract implements `interfaceID`.\n */\n private async contractSupportsInterface(\n address: string,\n interfaceId: string,\n ): Promise<boolean> {\n const contract = new Contract(address, abiERC1155, this.provider);\n return contract.supportsInterface(interfaceId);\n }\n\n /**\n * Query if a contract implements an interface.\n *\n * @param address - Asset contract address.\n * @param ipfsGateway - The user's preferred IPFS gateway.\n * @param tokenId - tokenId of a given token in the contract.\n * @returns Promise resolving an object containing the standard, tokenURI, symbol and name of the given contract/tokenId pair.\n */\n async getDetails(\n address: string,\n ipfsGateway: string,\n tokenId?: string,\n ): Promise<{\n standard: string;\n tokenURI: string | undefined;\n image: string | undefined;\n name: string | undefined;\n symbol: string | undefined;\n }> {\n const isERC1155 = await this.contractSupportsBase1155Interface(address);\n\n if (!isERC1155) {\n throw new Error(\"This isn't a valid ERC1155 contract\");\n }\n\n let image;\n\n const [symbol, name, tokenURI] = await Promise.all([\n safelyExecute(() => this.getAssetSymbol(address)),\n safelyExecute(() => this.getAssetName(address)),\n tokenId\n ? safelyExecute(() =>\n this.getTokenURI(address, tokenId).then((uri) =>\n uri.startsWith('ipfs://')\n ? getFormattedIpfsUrl(ipfsGateway, uri, true)\n : uri,\n ),\n )\n : undefined,\n ]);\n\n if (tokenURI) {\n try {\n const response = await timeoutFetch(tokenURI);\n const object = await response.json();\n image = object?.image;\n if (image?.startsWith('ipfs://')) {\n image = getFormattedIpfsUrl(ipfsGateway, image, true);\n }\n } catch {\n // Catch block should be kept empty to ignore exceptions, and\n // pass as much information as possible to the return statement\n }\n }\n\n // TODO consider querying to the metadata to get name.\n return {\n standard: ERC1155,\n tokenURI,\n image,\n symbol,\n name,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ERC1155Standard.cjs","sourceRoot":"","sources":["../../../../src/Standards/NftStandards/ERC1155/ERC1155Standard.ts"],"names":[],"mappings":";;;AAAA,wDAAoD;AAEpD,iEAOoC;AACpC,mEAAyD;AAGzD,wDAA+E;AAE/E,MAAa,eAAe;IAG1B,YAAY,QAAsB;QAChC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,oCAAoC,CACxC,OAAe;QAEf,OAAO,IAAI,CAAC,yBAAyB,CACnC,OAAO,EACP,oDAAiC,CAClC,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,sCAAsC,CAC1C,OAAe;QAEf,OAAO,IAAI,CAAC,yBAAyB,CACnC,OAAO,EACP,sDAAmC,CACpC,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,iCAAiC,CAAC,OAAe;QACrD,OAAO,IAAI,CAAC,yBAAyB,CAAC,OAAO,EAAE,uCAAoB,CAAC,CAAC;IACvE,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,WAAW,CAAC,OAAe,EAAE,OAAe;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ACF;AArPD,0CAqPC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport type { Web3Provider } from '@ethersproject/providers';\nimport {\n ERC1155,\n ERC1155_INTERFACE_ID,\n ERC1155_METADATA_URI_INTERFACE_ID,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n safelyExecute,\n timeoutFetch,\n} from '@metamask/controller-utils';\nimport { abiERC1155 } from '@metamask/metamask-eth-abis';\nimport type * as BN from 'bn.js';\n\nimport { getFormattedIpfsUrl, ethersBigNumberToBN } from '../../../assetsUtil';\n\nexport class ERC1155Standard {\n private readonly provider: Web3Provider;\n\n constructor(provider: Web3Provider) {\n this.provider = provider;\n }\n\n /**\n * Query if contract implements ERC1155 URI Metadata interface.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to whether the contract implements ERC1155 URI Metadata interface.\n */\n async contractSupportsURIMetadataInterface(\n address: string,\n ): Promise<boolean> {\n return this.contractSupportsInterface(\n address,\n ERC1155_METADATA_URI_INTERFACE_ID,\n );\n }\n\n /**\n * Query if contract implements ERC1155 Token Receiver interface.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to whether the contract implements ERC1155 Token Receiver interface.\n */\n async contractSupportsTokenReceiverInterface(\n address: string,\n ): Promise<boolean> {\n return this.contractSupportsInterface(\n address,\n ERC1155_TOKEN_RECEIVER_INTERFACE_ID,\n );\n }\n\n /**\n * Query if contract implements ERC1155 interface.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to whether the contract implements the base ERC1155 interface.\n */\n async contractSupportsBase1155Interface(address: string): Promise<boolean> {\n return this.contractSupportsInterface(address, ERC1155_INTERFACE_ID);\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 * @returns Promise resolving to the 'tokenURI'.\n */\n async getTokenURI(address: string, tokenId: string): Promise<string> {\n const contract = new Contract(address, abiERC1155, this.provider);\n return contract.uri(tokenId);\n }\n\n /**\n * Query for balance of a given ERC1155 token.\n *\n * @param contractAddress - ERC1155 asset contract address.\n * @param address - Wallet public address.\n * @param tokenId - ERC1155 asset identifier.\n * @returns Promise resolving to the 'balanceOf'.\n */\n async getBalanceOf(\n contractAddress: string,\n address: string,\n tokenId: string,\n ): Promise<BN> {\n const contract = new Contract(contractAddress, abiERC1155, this.provider);\n const balance = await contract.balanceOf(address, tokenId);\n return ethersBigNumberToBN(balance);\n }\n\n /**\n * Transfer single ERC1155 token.\n * When minting/creating tokens, the from arg MUST be set to 0x0 (i.e. zero address).\n * When burning/destroying tokens, the to arg MUST be set to 0x0 (i.e. zero address).\n *\n * @param operator - ERC1155 token address.\n * @param from - ERC1155 token holder.\n * @param to - ERC1155 token recipient.\n * @param id - ERC1155 token id.\n * @param value - Number of tokens to be sent.\n * @returns Promise resolving to the 'transferSingle'.\n */\n async transferSingle(\n operator: string,\n from: string,\n to: string,\n id: string,\n value: string,\n ): Promise<void> {\n const contract = new Contract(operator, abiERC1155, this.provider);\n return new Promise<void>((resolve, reject) => {\n contract.transferSingle(\n operator,\n from,\n to,\n id,\n value,\n (error: Error, result: void) => {\n /* istanbul ignore if */\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n },\n );\n });\n }\n\n /**\n * Query for symbol for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to the 'symbol'.\n */\n async getAssetSymbol(address: string): Promise<string> {\n const contract = new Contract(\n address,\n // Contract ABI fragment containing only the symbol method to fetch the symbol of the contract.\n [\n {\n inputs: [],\n name: 'symbol',\n outputs: [{ name: '_symbol', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n payable: false,\n },\n ],\n this.provider,\n );\n return contract.symbol();\n }\n\n /**\n * Query for name for a given asset.\n *\n * @param address - ERC1155 asset contract address.\n * @returns Promise resolving to the 'name'.\n */\n async getAssetName(address: string): Promise<string> {\n const contract = new Contract(\n address,\n // Contract ABI fragment containing only the name method to fetch the name of the contract.\n [\n {\n inputs: [],\n name: 'name',\n outputs: [{ name: '_name', type: 'string' }],\n stateMutability: 'view',\n type: 'function',\n payable: false,\n },\n ],\n this.provider,\n );\n return contract.name();\n }\n\n /**\n * Query if a contract implements an interface.\n *\n * @param address - ERC1155 asset contract address.\n * @param interfaceId - Interface identifier.\n * @returns Promise resolving to whether the contract implements `interfaceID`.\n */\n private async contractSupportsInterface(\n address: string,\n interfaceId: string,\n ): Promise<boolean> {\n const contract = new Contract(address, abiERC1155, this.provider);\n return contract.supportsInterface(interfaceId);\n }\n\n /**\n * Query if a contract implements an interface.\n *\n * @param address - Asset contract address.\n * @param ipfsGateway - The user's preferred IPFS gateway.\n * @param tokenId - tokenId of a given token in the contract.\n * @returns Promise resolving an object containing the standard, tokenURI, symbol and name of the given contract/tokenId pair.\n */\n async getDetails(\n address: string,\n ipfsGateway: string,\n tokenId?: string,\n ): Promise<{\n standard: string;\n tokenURI: string | undefined;\n image: string | undefined;\n name: string | undefined;\n symbol: string | undefined;\n }> {\n const isERC1155 = await this.contractSupportsBase1155Interface(address);\n\n if (!isERC1155) {\n throw new Error(\"This isn't a valid ERC1155 contract\");\n }\n\n let image;\n\n const [symbol, name, tokenURI] = await Promise.all([\n safelyExecute(() => this.getAssetSymbol(address)),\n safelyExecute(() => this.getAssetName(address)),\n tokenId\n ? safelyExecute(() =>\n this.getTokenURI(address, tokenId).then((uri) =>\n uri.startsWith('ipfs://')\n ? getFormattedIpfsUrl(ipfsGateway, uri, true)\n : uri,\n ),\n )\n : undefined,\n ]);\n\n if (tokenURI) {\n try {\n const response = await timeoutFetch(tokenURI);\n const object = await response.json();\n image = object?.image;\n if (image?.startsWith('ipfs://')) {\n image = getFormattedIpfsUrl(ipfsGateway, image, true);\n }\n } catch {\n // Catch block should be kept empty to ignore exceptions, and\n // pass as much information as possible to the return statement\n }\n }\n\n // TODO consider querying to the metadata to get name.\n return {\n standard: ERC1155,\n tokenURI,\n image,\n symbol,\n name,\n };\n }\n}\n"]}
|