@metamask-previews/assets-controllers 32.0.0-preview-0f65e9e → 33.0.0-preview-b09c2ed

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +53 -1
  2. package/dist/AccountTrackerController.js +2 -2
  3. package/dist/AccountTrackerController.mjs +1 -1
  4. package/dist/NftDetectionController.js +2 -2
  5. package/dist/NftDetectionController.mjs +1 -1
  6. package/dist/TokenRatesController.js +2 -2
  7. package/dist/TokenRatesController.mjs +1 -1
  8. package/dist/chunk-2IIQTSLV.mjs +236 -0
  9. package/dist/chunk-2IIQTSLV.mjs.map +1 -0
  10. package/dist/chunk-354SINOH.js +236 -0
  11. package/dist/chunk-354SINOH.js.map +1 -0
  12. package/dist/{chunk-22BFLX4O.js → chunk-FGAZXVKS.js} +8 -4
  13. package/dist/chunk-FGAZXVKS.js.map +1 -0
  14. package/dist/chunk-HVOIBGYN.js +282 -0
  15. package/dist/chunk-HVOIBGYN.js.map +1 -0
  16. package/dist/{chunk-VVI7QTCA.mjs → chunk-P3O5CVAH.mjs} +8 -4
  17. package/dist/chunk-P3O5CVAH.mjs.map +1 -0
  18. package/dist/chunk-Z7RMCHD4.mjs +282 -0
  19. package/dist/chunk-Z7RMCHD4.mjs.map +1 -0
  20. package/dist/index.js +4 -4
  21. package/dist/index.mjs +3 -3
  22. package/dist/tsconfig.build.tsbuildinfo +1 -1
  23. package/dist/types/AccountTrackerController.d.ts +50 -66
  24. package/dist/types/AccountTrackerController.d.ts.map +1 -1
  25. package/dist/types/NftDetectionController.d.ts +5 -17
  26. package/dist/types/NftDetectionController.d.ts.map +1 -1
  27. package/dist/types/TokenRatesController.d.ts.map +1 -1
  28. package/dist/types/index.d.ts +2 -1
  29. package/dist/types/index.d.ts.map +1 -1
  30. package/package.json +5 -5
  31. package/dist/chunk-22BFLX4O.js.map +0 -1
  32. package/dist/chunk-42CNLFP5.js +0 -261
  33. package/dist/chunk-42CNLFP5.js.map +0 -1
  34. package/dist/chunk-526TATMH.mjs +0 -254
  35. package/dist/chunk-526TATMH.mjs.map +0 -1
  36. package/dist/chunk-AZ6SRJVI.js +0 -254
  37. package/dist/chunk-AZ6SRJVI.js.map +0 -1
  38. package/dist/chunk-RQDP72T7.mjs +0 -261
  39. package/dist/chunk-RQDP72T7.mjs.map +0 -1
  40. package/dist/chunk-VVI7QTCA.mjs.map +0 -1
@@ -0,0 +1,236 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+ var _chunkZ4BLTVTBjs = require('./chunk-Z4BLTVTB.js');
7
+
8
+ // src/NftDetectionController.ts
9
+ var _basecontroller = require('@metamask/base-controller');
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+ var _controllerutils = require('@metamask/controller-utils');
18
+ var _utils = require('@metamask/utils');
19
+ var controllerName = "NftDetectionController";
20
+ var supportedNftDetectionNetworks = [_controllerutils.ChainId.mainnet];
21
+ var BlockaidResultType = /* @__PURE__ */ ((BlockaidResultType2) => {
22
+ BlockaidResultType2["Benign"] = "Benign";
23
+ BlockaidResultType2["Spam"] = "Spam";
24
+ BlockaidResultType2["Warning"] = "Warning";
25
+ BlockaidResultType2["Malicious"] = "Malicious";
26
+ return BlockaidResultType2;
27
+ })(BlockaidResultType || {});
28
+ var _disabled, _addNft, _getNftState, _inProcessNftFetchingUpdates, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn, _getOwnerNftApi, getOwnerNftApi_fn, _getOwnerNfts, getOwnerNfts_fn;
29
+ var NftDetectionController = class extends _basecontroller.BaseController {
30
+ /**
31
+ * The controller options
32
+ *
33
+ * @param options - The controller options.
34
+ * @param options.messenger - A reference to the messaging system.
35
+ * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.
36
+ * @param options.addNft - Add an NFT.
37
+ * @param options.getNftState - Gets the current state of the Assets controller.
38
+ */
39
+ constructor({
40
+ messenger,
41
+ disabled = false,
42
+ addNft,
43
+ getNftState
44
+ }) {
45
+ super({
46
+ name: controllerName,
47
+ messenger,
48
+ metadata: {},
49
+ state: {}
50
+ });
51
+ /**
52
+ * Handles the state change of the preference controller.
53
+ * @param preferencesState - The new state of the preference controller.
54
+ * @param preferencesState.useNftDetection - Boolean indicating user preference on NFT detection.
55
+ */
56
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _onPreferencesControllerStateChange);
57
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getOwnerNftApi);
58
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getOwnerNfts);
59
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _disabled, void 0);
60
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _addNft, void 0);
61
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getNftState, void 0);
62
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _inProcessNftFetchingUpdates, void 0);
63
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _disabled, disabled);
64
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _inProcessNftFetchingUpdates, {});
65
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _getNftState, getNftState);
66
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _addNft, addNft);
67
+ this.messagingSystem.subscribe(
68
+ "PreferencesController:stateChange",
69
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _onPreferencesControllerStateChange, onPreferencesControllerStateChange_fn).bind(this)
70
+ );
71
+ }
72
+ /**
73
+ * Checks whether network is mainnet or not.
74
+ *
75
+ * @returns Whether current network is mainnet.
76
+ */
77
+ isMainnet() {
78
+ const { selectedNetworkClientId } = this.messagingSystem.call(
79
+ "NetworkController:getState"
80
+ );
81
+ const {
82
+ configuration: { chainId }
83
+ } = this.messagingSystem.call(
84
+ "NetworkController:getNetworkClientById",
85
+ selectedNetworkClientId
86
+ );
87
+ return chainId === _controllerutils.ChainId.mainnet;
88
+ }
89
+ isMainnetByNetworkClientId(networkClient) {
90
+ return networkClient.configuration.chainId === _controllerutils.ChainId.mainnet;
91
+ }
92
+ /**
93
+ * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are
94
+ * added.
95
+ *
96
+ * @param options - Options bag.
97
+ * @param options.networkClientId - The network client ID to detect NFTs on.
98
+ * @param options.userAddress - The address to detect NFTs for.
99
+ */
100
+ async detectNfts(options) {
101
+ const userAddress = options?.userAddress ?? this.messagingSystem.call("AccountsController:getSelectedAccount").address;
102
+ const { selectedNetworkClientId } = this.messagingSystem.call(
103
+ "NetworkController:getState"
104
+ );
105
+ const {
106
+ configuration: { chainId }
107
+ } = this.messagingSystem.call(
108
+ "NetworkController:getNetworkClientById",
109
+ selectedNetworkClientId
110
+ );
111
+ if (!supportedNftDetectionNetworks.includes(chainId) || _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _disabled)) {
112
+ return;
113
+ }
114
+ if (!userAddress) {
115
+ return;
116
+ }
117
+ const updateKey = `${chainId}:${userAddress}`;
118
+ if (updateKey in _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _inProcessNftFetchingUpdates)) {
119
+ await _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _inProcessNftFetchingUpdates)[updateKey];
120
+ return;
121
+ }
122
+ const {
123
+ promise: inProgressUpdate,
124
+ resolve: updateSucceeded,
125
+ reject: updateFailed
126
+ } = _utils.createDeferredPromise.call(void 0, { suppressUnhandledRejection: true });
127
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _inProcessNftFetchingUpdates)[updateKey] = inProgressUpdate;
128
+ let next;
129
+ let apiNfts = [];
130
+ let resultNftApi;
131
+ try {
132
+ do {
133
+ resultNftApi = await _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getOwnerNfts, getOwnerNfts_fn).call(this, userAddress, chainId, next);
134
+ apiNfts = resultNftApi.tokens.filter(
135
+ (elm) => elm.token.isSpam === false && (elm.blockaidResult?.result_type ? elm.blockaidResult?.result_type === "Benign" /* Benign */ : true)
136
+ );
137
+ const addNftPromises = apiNfts.map(async (nft) => {
138
+ const {
139
+ tokenId,
140
+ contract,
141
+ kind,
142
+ image: imageUrl,
143
+ imageSmall: imageThumbnailUrl,
144
+ metadata: { imageOriginal: imageOriginalUrl } = {},
145
+ name,
146
+ description,
147
+ attributes,
148
+ topBid,
149
+ lastSale,
150
+ rarityRank,
151
+ rarityScore,
152
+ collection
153
+ } = nft.token;
154
+ let ignored;
155
+ const { ignoredNfts } = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _getNftState).call(this);
156
+ if (ignoredNfts.length) {
157
+ ignored = ignoredNfts.find((c) => {
158
+ return c.address === _controllerutils.toChecksumHexAddress.call(void 0, contract) && c.tokenId === tokenId;
159
+ });
160
+ }
161
+ if (!ignored) {
162
+ const nftMetadata = Object.assign(
163
+ {},
164
+ { name },
165
+ description && { description },
166
+ imageUrl && { image: imageUrl },
167
+ imageThumbnailUrl && { imageThumbnail: imageThumbnailUrl },
168
+ imageOriginalUrl && { imageOriginal: imageOriginalUrl },
169
+ kind && { standard: kind.toUpperCase() },
170
+ lastSale && { lastSale },
171
+ attributes && { attributes },
172
+ topBid && { topBid },
173
+ rarityRank && { rarityRank },
174
+ rarityScore && { rarityScore },
175
+ collection && { collection }
176
+ );
177
+ await _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _addNft).call(this, contract, tokenId, {
178
+ nftMetadata,
179
+ userAddress,
180
+ source: "detected" /* Detected */,
181
+ networkClientId: options?.networkClientId
182
+ });
183
+ }
184
+ });
185
+ await Promise.all(addNftPromises);
186
+ } while (next = resultNftApi.continuation);
187
+ updateSucceeded();
188
+ } catch (error) {
189
+ updateFailed(error);
190
+ throw error;
191
+ } finally {
192
+ delete _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _inProcessNftFetchingUpdates)[updateKey];
193
+ }
194
+ }
195
+ };
196
+ _disabled = new WeakMap();
197
+ _addNft = new WeakMap();
198
+ _getNftState = new WeakMap();
199
+ _inProcessNftFetchingUpdates = new WeakMap();
200
+ _onPreferencesControllerStateChange = new WeakSet();
201
+ onPreferencesControllerStateChange_fn = function({ useNftDetection }) {
202
+ if (!useNftDetection !== _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _disabled)) {
203
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _disabled, !useNftDetection);
204
+ }
205
+ };
206
+ _getOwnerNftApi = new WeakSet();
207
+ getOwnerNftApi_fn = function({
208
+ chainId,
209
+ address,
210
+ next
211
+ }) {
212
+ return `${_controllerutils.NFT_API_BASE_URL}/users/${address}/tokens?chainIds=${chainId}&limit=50&includeTopBid=true&continuation=${next ?? ""}`;
213
+ };
214
+ _getOwnerNfts = new WeakSet();
215
+ getOwnerNfts_fn = async function(address, chainId, cursor) {
216
+ const convertedChainId = _controllerutils.convertHexToDecimal.call(void 0, chainId).toString();
217
+ const url = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getOwnerNftApi, getOwnerNftApi_fn).call(this, {
218
+ chainId: convertedChainId,
219
+ address,
220
+ next: cursor
221
+ });
222
+ const nftApiResponse = await _controllerutils.handleFetch.call(void 0, url, {
223
+ headers: {
224
+ Version: _controllerutils.NFT_API_VERSION
225
+ }
226
+ });
227
+ return nftApiResponse;
228
+ };
229
+ var NftDetectionController_default = NftDetectionController;
230
+
231
+
232
+
233
+
234
+
235
+ exports.BlockaidResultType = BlockaidResultType; exports.NftDetectionController = NftDetectionController; exports.NftDetectionController_default = NftDetectionController_default;
236
+ //# sourceMappingURL=chunk-354SINOH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/NftDetectionController.ts"],"names":["BlockaidResultType"],"mappings":";;;;;;;;AAGA,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAaP,SAAS,6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,SAAO,GACL,gBACF,UAAU,OAAO,oBAAoB,OAAO,6CAC1C,QAAQ,EACV;AACF;AAEM;AAAA,kBAAa,eACjB,SACA,SACA,QACA;AAEA,QAAM,mBAAmB,oBAAoB,OAAO,EAAE,SAAS;AAC/D,QAAM,MAAM,sBAAK,oCAAL,WAAqB;AAAA,IAC/B,SAAS;AAAA,IACT;AAAA,IACA,MAAM;AAAA,EACR;AACA,QAAM,iBAAoC,MAAM,YAAY,KAAK;AAAA,IAC/D,SAAS;AAAA,MACP,SAAS;AAAA,IACX;AAAA,EACF,CAAC;AACD,SAAO;AACT;AA0IF,IAAO,iCAAQ","sourcesContent":["import type { AccountsControllerGetSelectedAccountAction } from '@metamask/accounts-controller';\nimport type { AddApprovalRequest } from '@metamask/approval-controller';\nimport type { RestrictedControllerMessenger } from '@metamask/base-controller';\nimport { BaseController } from '@metamask/base-controller';\nimport {\n toChecksumHexAddress,\n ChainId,\n NFT_API_BASE_URL,\n NFT_API_VERSION,\n convertHexToDecimal,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkClient,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n NetworkControllerGetStateAction,\n} from '@metamask/network-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n PreferencesState,\n} from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\n\nimport { Source } from './constants';\nimport {\n type NftController,\n type NftControllerState,\n type NftMetadata,\n} from './NftController';\n\nconst controllerName = 'NftDetectionController';\n\nexport type NFTDetectionControllerState = Record<never, never>;\n\nexport type AllowedActions =\n | AddApprovalRequest\n | NetworkControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | PreferencesControllerGetStateAction\n | AccountsControllerGetSelectedAccountAction;\n\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\nexport type NftDetectionControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n AllowedActions,\n AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\nconst supportedNftDetectionNetworks: Hex[] = [ChainId.mainnet];\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 Collection = {\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};\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<`${Hex}:${string}`, Promise<void>>;\n\n /**\n * The controller options\n *\n * @param options - The controller options.\n * @param options.messenger - A reference to the messaging system.\n * @param options.disabled - Represents previous value of useNftDetection. Used to detect changes of useNftDetection. Default value is true.\n * @param options.addNft - Add an NFT.\n * @param options.getNftState - Gets the current state of the Assets controller.\n */\n constructor({\n messenger,\n disabled = false,\n addNft,\n getNftState,\n }: {\n messenger: NftDetectionControllerMessenger;\n disabled: boolean;\n addNft: NftController['addNft'];\n getNftState: () => NftControllerState;\n }) {\n super({\n name: controllerName,\n messenger,\n metadata: {},\n state: {},\n });\n this.#disabled = disabled;\n this.#inProcessNftFetchingUpdates = {};\n\n this.#getNftState = getNftState;\n this.#addNft = addNft;\n\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n this.#onPreferencesControllerStateChange.bind(this),\n );\n }\n\n /**\n * Checks whether network is mainnet or not.\n *\n * @returns Whether current network is mainnet.\n */\n isMainnet(): boolean {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return chainId === ChainId.mainnet;\n }\n\n isMainnetByNetworkClientId(networkClient: NetworkClient): boolean {\n return networkClient.configuration.chainId === ChainId.mainnet;\n }\n\n /**\n * Handles the state change of the preference controller.\n * @param preferencesState - The new state of the preference controller.\n * @param preferencesState.useNftDetection - Boolean indicating user preference on NFT detection.\n */\n #onPreferencesControllerStateChange({ useNftDetection }: PreferencesState) {\n if (!useNftDetection !== this.#disabled) {\n this.#disabled = !useNftDetection;\n }\n }\n\n #getOwnerNftApi({\n chainId,\n address,\n next,\n }: {\n chainId: string;\n address: string;\n next?: string;\n }) {\n return `${\n NFT_API_BASE_URL as string\n }/users/${address}/tokens?chainIds=${chainId}&limit=50&includeTopBid=true&continuation=${\n next ?? ''\n }`;\n }\n\n async #getOwnerNfts(\n address: string,\n chainId: Hex,\n cursor: string | undefined,\n ) {\n // Convert hex chainId to number\n const convertedChainId = convertHexToDecimal(chainId).toString();\n const url = this.#getOwnerNftApi({\n chainId: convertedChainId,\n address,\n next: cursor,\n });\n const nftApiResponse: ReservoirResponse = await handleFetch(url, {\n headers: {\n Version: NFT_API_VERSION,\n },\n });\n return nftApiResponse;\n }\n\n /**\n * Triggers asset ERC721 token auto detection on mainnet. Any newly detected NFTs are\n * added.\n *\n * @param options - Options bag.\n * @param options.networkClientId - The network client ID to detect NFTs on.\n * @param options.userAddress - The address to detect NFTs for.\n */\n async detectNfts(options?: {\n networkClientId?: NetworkClientId;\n userAddress?: string;\n }) {\n const userAddress =\n options?.userAddress ??\n this.messagingSystem.call('AccountsController:getSelectedAccount')\n .address;\n\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const {\n configuration: { chainId },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n\n /* istanbul ignore if */\n if (!supportedNftDetectionNetworks.includes(chainId) || this.#disabled) {\n return;\n }\n /* istanbul ignore else */\n if (!userAddress) {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n const updateKey: `${Hex}:${string}` = `${chainId}:${userAddress}`;\n if (updateKey in this.#inProcessNftFetchingUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessNftFetchingUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessNftFetchingUpdates[updateKey] = inProgressUpdate;\n\n let next;\n let apiNfts: TokensResponse[] = [];\n let resultNftApi: ReservoirResponse;\n try {\n do {\n resultNftApi = await this.#getOwnerNfts(userAddress, chainId, next);\n apiNfts = resultNftApi.tokens.filter(\n (elm) =>\n elm.token.isSpam === false &&\n (elm.blockaidResult?.result_type\n ? elm.blockaidResult?.result_type === BlockaidResultType.Benign\n : true),\n );\n const addNftPromises = apiNfts.map(async (nft) => {\n const {\n tokenId,\n contract,\n kind,\n image: imageUrl,\n imageSmall: imageThumbnailUrl,\n metadata: { imageOriginal: imageOriginalUrl } = {},\n name,\n description,\n attributes,\n topBid,\n lastSale,\n rarityRank,\n rarityScore,\n collection,\n } = nft.token;\n\n let ignored;\n /* istanbul ignore else */\n const { ignoredNfts } = this.#getNftState();\n if (ignoredNfts.length) {\n ignored = ignoredNfts.find((c) => {\n /* istanbul ignore next */\n return (\n c.address === toChecksumHexAddress(contract) &&\n c.tokenId === tokenId\n );\n });\n }\n\n /* istanbul ignore else */\n if (!ignored) {\n /* istanbul ignore next */\n const nftMetadata: NftMetadata = Object.assign(\n {},\n { name },\n description && { description },\n imageUrl && { image: imageUrl },\n imageThumbnailUrl && { imageThumbnail: imageThumbnailUrl },\n imageOriginalUrl && { imageOriginal: imageOriginalUrl },\n kind && { standard: kind.toUpperCase() },\n lastSale && { lastSale },\n attributes && { attributes },\n topBid && { topBid },\n rarityRank && { rarityRank },\n rarityScore && { rarityScore },\n collection && { collection },\n );\n\n await this.#addNft(contract, tokenId, {\n nftMetadata,\n userAddress,\n source: Source.Detected,\n networkClientId: options?.networkClientId,\n });\n }\n });\n await Promise.all(addNftPromises);\n } while ((next = resultNftApi.continuation));\n updateSucceeded();\n } catch (error) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessNftFetchingUpdates[updateKey];\n }\n }\n}\n\nexport default NftDetectionController;\n"]}
@@ -371,12 +371,16 @@ getSelectedAddress_fn = function() {
371
371
  };
372
372
  _getChainIdAndTicker = new WeakSet();
373
373
  getChainIdAndTicker_fn = function() {
374
- const { providerConfig } = this.messagingSystem.call(
374
+ const { selectedNetworkClientId } = this.messagingSystem.call(
375
375
  "NetworkController:getState"
376
376
  );
377
+ const networkClient = this.messagingSystem.call(
378
+ "NetworkController:getNetworkClientById",
379
+ selectedNetworkClientId
380
+ );
377
381
  return {
378
- chainId: providerConfig.chainId,
379
- ticker: providerConfig.ticker
382
+ chainId: networkClient.configuration.chainId,
383
+ ticker: networkClient.configuration.ticker
380
384
  };
381
385
  };
382
386
  _getTokensControllerState = new WeakSet();
@@ -521,4 +525,4 @@ var TokenRatesController_default = TokenRatesController;
521
525
 
522
526
 
523
527
  exports.controllerName = controllerName; exports.getDefaultTokenRatesControllerState = getDefaultTokenRatesControllerState; exports.TokenRatesController = TokenRatesController; exports.TokenRatesController_default = TokenRatesController_default;
524
- //# sourceMappingURL=chunk-22BFLX4O.js.map
528
+ //# sourceMappingURL=chunk-FGAZXVKS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/TokenRatesController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAKA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAOP,SAAS,uCAAuC;AAKhD,SAAS,6BAAuC;AACh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,MAC7B;AAEA,aAAO;AAAA,IACT;AAAA,IACA,CAAC;AAAA,EACH;AACF;AAcM;AAAA,0DAAqD,eAAC;AAAA,EAC1D;AAAA,EACA;AACF,GAGgC;AAC9B,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,EACF,IAAI,MAAM,QAAQ,IAAI;AAAA,IACpB,sBAAK,4GAAL,WAAyD;AAAA,MACvD;AAAA,MACA,SAAS,mBAAK;AAAA,MACd,gBAAgB;AAAA,IAClB;AAAA,IACA,0BAA0B;AAAA,MACxB,MAAM;AAAA,MACN,IAAI;AAAA,IACN,CAAC;AAAA,EACH,CAAC;AAED,MAAI,mDAAmD,MAAM;AAC3D,WAAO,CAAC;AAAA,EACV;AAEA,QAAM,+BAA+B,OAAO;AAAA,IAC1C;AAAA,EACF,EAAE,OAAO,CAAC,KAAK,CAAC,cAAc,KAAK,MAAM;AACvC,UAAM;AAAA,MACJ,GAAG;AAAA,MACH,CAAC,YAAY,GAAG;AAAA,QACd,GAAG;AAAA,QACH,OAAO,MAAM,QACT,MAAM,QAAQ,iDACd;AAAA,MACN;AAAA,IACF;AACA,WAAO;AAAA,EACT,GAAG,CAAC,CAAC;AAEL,SAAO;AACT;AAGF,IAAO,+BAAQ","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n safelyExecute,\n toChecksumHexAddress,\n FALL_BACK_VS_CURRENCY,\n toHex,\n} from '@metamask/controller-utils';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerGetStateAction,\n NetworkControllerStateChangeEvent,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n PreferencesControllerGetStateAction,\n PreferencesControllerStateChangeEvent,\n} from '@metamask/preferences-controller';\nimport { createDeferredPromise, type Hex } from '@metamask/utils';\nimport { isEqual } from 'lodash';\n\nimport { reduceInBatchesSerially, TOKEN_PRICES_BATCH_SIZE } from './assetsUtil';\nimport { fetchExchangeRate as fetchNativeCurrencyExchangeRate } from './crypto-compare-service';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\nimport { ZERO_ADDRESS } from './token-prices-service/codefi-v2';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n TokensControllerState,\n} from './TokensController';\n\n/**\n * @type Token\n *\n * Token representation\n * @property address - Hex address of the token contract\n * @property decimals - Number of decimals the token uses\n * @property symbol - Symbol of the token\n * @property aggregators - An array containing the token's aggregators\n * @property image - Image of the token, url or bit32 image\n * @property hasBalanceError - 'true' if there is an error while updating the token balance\n * @property isERC721 - 'true' if the token is a ERC721 token\n * @property name - Name of the token\n */\nexport type Token = {\n address: string;\n decimals: number;\n symbol: string;\n aggregators?: string[];\n image?: string;\n hasBalanceError?: boolean;\n isERC721?: boolean;\n name?: string;\n};\n\nconst DEFAULT_INTERVAL = 180000;\n\nexport type ContractExchangeRates = {\n [address: string]: number | undefined;\n};\n\ntype MarketDataDetails = {\n tokenAddress: `0x${string}`;\n currency: string;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\n\n/**\n * Represents a mapping of token contract addresses to their market data.\n */\nexport type ContractMarketData = Record<Hex, MarketDataDetails>;\n\nenum PollState {\n Active = 'Active',\n Inactive = 'Inactive',\n}\n\n/**\n * The external actions available to the {@link TokenRatesController}.\n */\nexport type AllowedActions =\n | TokensControllerGetStateAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetStateAction\n | PreferencesControllerGetStateAction;\n\n/**\n * The external events available to the {@link TokenRatesController}.\n */\nexport type AllowedEvents =\n | PreferencesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | NetworkControllerStateChangeEvent;\n\n/**\n * The name of the {@link TokenRatesController}.\n */\nexport const controllerName = 'TokenRatesController';\n\n/**\n * @type TokenRatesState\n *\n * Token rates controller state\n * @property marketData - Market data for tokens, keyed by chain ID and then token contract address.\n */\nexport type TokenRatesControllerState = {\n marketData: Record<Hex, Record<Hex, MarketDataDetails>>;\n};\n\n/**\n * The action that can be performed to get the state of the {@link TokenRatesController}.\n */\nexport type TokenRatesControllerGetStateAction = ControllerGetStateAction<\n typeof controllerName,\n TokenRatesControllerState\n>;\n\n/**\n * The actions that can be performed using the {@link TokenRatesController}.\n */\nexport type TokenRatesControllerActions = TokenRatesControllerGetStateAction;\n\n/**\n * The event that {@link TokenRatesController} can emit.\n */\nexport type TokenRatesControllerStateChangeEvent = ControllerStateChangeEvent<\n typeof controllerName,\n TokenRatesControllerState\n>;\n\n/**\n * The events that {@link TokenRatesController} can emit.\n */\nexport type TokenRatesControllerEvents = TokenRatesControllerStateChangeEvent;\n\n/**\n * The messenger of the {@link TokenRatesController} for communication.\n */\nexport type TokenRatesControllerMessenger = RestrictedControllerMessenger<\n typeof controllerName,\n TokenRatesControllerActions | AllowedActions,\n TokenRatesControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n>;\n\n/**\n * Uses the CryptoCompare API to fetch the exchange rate between one currency\n * and another, i.e., the multiplier to apply the amount of one currency in\n * order to convert it to another.\n *\n * @param args - The arguments to this function.\n * @param args.from - The currency to convert from.\n * @param args.to - The currency to convert to.\n * @returns The exchange rate between `fromCurrency` to `toCurrency` if one\n * exists, or null if one does not.\n */\nasync function getCurrencyConversionRate({\n from,\n to,\n}: {\n from: string;\n to: string;\n}) {\n const includeUSDRate = false;\n try {\n const result = await fetchNativeCurrencyExchangeRate(\n to,\n from,\n includeUSDRate,\n );\n return result.conversionRate;\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.includes('market does not exist for this coin pair')\n ) {\n return null;\n }\n throw error;\n }\n}\n\nconst tokenRatesControllerMetadata = {\n marketData: { persist: true, anonymous: false },\n};\n\n/**\n * Get the default {@link TokenRatesController} state.\n *\n * @returns The default {@link TokenRatesController} state.\n */\nexport const getDefaultTokenRatesControllerState =\n (): TokenRatesControllerState => {\n return {\n marketData: {},\n };\n };\n\n/**\n * Controller that passively polls on a set interval for token-to-fiat exchange rates\n * for tokens stored in the TokensController\n */\nexport class TokenRatesController extends StaticIntervalPollingController<\n typeof controllerName,\n TokenRatesControllerState,\n TokenRatesControllerMessenger\n> {\n #handle?: ReturnType<typeof setTimeout>;\n\n #pollState = PollState.Inactive;\n\n #tokenPricesService: AbstractTokenPricesService;\n\n #inProcessExchangeRateUpdates: Record<`${Hex}:${string}`, Promise<void>> = {};\n\n #selectedAddress: string;\n\n #disabled: boolean;\n\n #chainId: Hex;\n\n #ticker: string;\n\n #interval: number;\n\n #allTokens: TokensControllerState['allTokens'];\n\n #allDetectedTokens: TokensControllerState['allDetectedTokens'];\n\n /**\n * Creates a TokenRatesController instance.\n *\n * @param options - The controller options.\n * @param options.interval - The polling interval in ms\n * @param options.disabled - Boolean to track if network requests are blocked\n * @param options.tokenPricesService - An object in charge of retrieving token price\n * @param options.messenger - The controller messenger instance for communication\n * @param options.state - Initial state to set on this controller\n */\n constructor({\n interval = DEFAULT_INTERVAL,\n disabled = false,\n tokenPricesService,\n messenger,\n state,\n }: {\n interval?: number;\n disabled?: boolean;\n tokenPricesService: AbstractTokenPricesService;\n messenger: TokenRatesControllerMessenger;\n state?: Partial<TokenRatesControllerState>;\n }) {\n super({\n name: controllerName,\n messenger,\n state: { ...getDefaultTokenRatesControllerState(), ...state },\n metadata: tokenRatesControllerMetadata,\n });\n\n this.setIntervalLength(interval);\n this.#tokenPricesService = tokenPricesService;\n this.#disabled = disabled;\n this.#interval = interval;\n\n const { chainId: currentChainId, ticker: currentTicker } =\n this.#getChainIdAndTicker();\n this.#chainId = currentChainId;\n this.#ticker = currentTicker;\n\n this.#selectedAddress = this.#getSelectedAddress();\n\n const { allTokens, allDetectedTokens } = this.#getTokensControllerState();\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n\n this.#subscribeToPreferencesStateChange();\n\n this.#subscribeToTokensStateChange();\n\n this.#subscribeToNetworkStateChange();\n }\n\n #subscribeToPreferencesStateChange() {\n this.messagingSystem.subscribe(\n 'PreferencesController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async (selectedAddress: string) => {\n if (this.#selectedAddress !== selectedAddress) {\n this.#selectedAddress = selectedAddress;\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n },\n ({ selectedAddress }) => {\n return selectedAddress;\n },\n );\n }\n\n #subscribeToTokensStateChange() {\n this.messagingSystem.subscribe(\n 'TokensController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ allTokens, allDetectedTokens }) => {\n const previousTokenAddresses = this.#getTokenAddresses(this.#chainId);\n this.#allTokens = allTokens;\n this.#allDetectedTokens = allDetectedTokens;\n\n const newTokenAddresses = this.#getTokenAddresses(this.#chainId);\n if (\n !isEqual(previousTokenAddresses, newTokenAddresses) &&\n this.#pollState === PollState.Active\n ) {\n await this.updateExchangeRates();\n }\n },\n ({ allTokens, allDetectedTokens }) => {\n return { allTokens, allDetectedTokens };\n },\n );\n }\n\n #subscribeToNetworkStateChange() {\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n async ({ selectedNetworkClientId }) => {\n const {\n configuration: { chainId, ticker },\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n\n if (this.#chainId !== chainId || this.#ticker !== ticker) {\n this.update((state) => {\n state.marketData = {};\n });\n this.#chainId = chainId;\n this.#ticker = ticker;\n if (this.#pollState === PollState.Active) {\n await this.updateExchangeRates();\n }\n }\n },\n );\n }\n\n /**\n * Get the user's tokens for the given chain.\n *\n * @param chainId - The chain ID.\n * @returns The list of tokens addresses for the current chain\n */\n #getTokenAddresses(chainId: Hex): Hex[] {\n const tokens = this.#allTokens[chainId]?.[this.#selectedAddress] || [];\n const detectedTokens =\n this.#allDetectedTokens[chainId]?.[this.#selectedAddress] || [];\n\n return [\n ...new Set(\n [...tokens, ...detectedTokens].map((token) =>\n toHex(toChecksumHexAddress(token.address)),\n ),\n ),\n ].sort();\n }\n\n /**\n * Allows controller to make active and passive polling requests\n */\n enable(): void {\n this.#disabled = false;\n }\n\n /**\n * Blocks controller from making network calls\n */\n disable(): void {\n this.#disabled = true;\n }\n\n /**\n * Start (or restart) polling.\n */\n async start() {\n this.#stopPoll();\n this.#pollState = PollState.Active;\n await this.#poll();\n }\n\n /**\n * Stop polling.\n */\n stop() {\n this.#stopPoll();\n this.#pollState = PollState.Inactive;\n }\n\n #getSelectedAddress(): string {\n const { selectedAddress } = this.messagingSystem.call(\n 'PreferencesController:getState',\n );\n\n return selectedAddress;\n }\n\n #getChainIdAndTicker(): {\n chainId: Hex;\n ticker: string;\n } {\n const { selectedNetworkClientId } = this.messagingSystem.call(\n 'NetworkController:getState',\n );\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n return {\n chainId: networkClient.configuration.chainId,\n ticker: networkClient.configuration.ticker,\n };\n }\n\n #getTokensControllerState(): {\n allTokens: TokensControllerState['allTokens'];\n allDetectedTokens: TokensControllerState['allDetectedTokens'];\n } {\n const { allTokens, allDetectedTokens } = this.messagingSystem.call(\n 'TokensController:getState',\n );\n\n return {\n allTokens,\n allDetectedTokens,\n };\n }\n\n /**\n * Clear the active polling timer, if present.\n */\n #stopPoll() {\n if (this.#handle) {\n clearTimeout(this.#handle);\n }\n }\n\n /**\n * Poll for exchange rate updates.\n */\n async #poll() {\n await safelyExecute(() => this.updateExchangeRates());\n\n // Poll using recursive `setTimeout` instead of `setInterval` so that\n // requests don't stack if they take longer than the polling interval\n this.#handle = setTimeout(() => {\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.#poll();\n }, this.#interval);\n }\n\n /**\n * Updates exchange rates for all tokens.\n */\n async updateExchangeRates() {\n await this.updateExchangeRatesByChainId({\n chainId: this.#chainId,\n nativeCurrency: this.#ticker,\n });\n }\n\n /**\n * Updates exchange rates for all tokens.\n *\n * @param options - The options to fetch exchange rates.\n * @param options.chainId - The chain ID.\n * @param options.nativeCurrency - The ticker for the chain.\n */\n async updateExchangeRatesByChainId({\n chainId,\n nativeCurrency,\n }: {\n chainId: Hex;\n nativeCurrency: string;\n }) {\n if (this.#disabled) {\n return;\n }\n\n const tokenAddresses = this.#getTokenAddresses(chainId);\n\n const updateKey: `${Hex}:${string}` = `${chainId}:${nativeCurrency}`;\n if (updateKey in this.#inProcessExchangeRateUpdates) {\n // This prevents redundant updates\n // This promise is resolved after the in-progress update has finished,\n // and state has been updated.\n await this.#inProcessExchangeRateUpdates[updateKey];\n return;\n }\n\n const {\n promise: inProgressUpdate,\n resolve: updateSucceeded,\n reject: updateFailed,\n } = createDeferredPromise({ suppressUnhandledRejection: true });\n this.#inProcessExchangeRateUpdates[updateKey] = inProgressUpdate;\n\n try {\n const contractInformations = await this.#fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n\n const marketData = {\n [chainId]: {\n ...(contractInformations ?? {}),\n },\n };\n\n this.update((state) => {\n state.marketData = marketData;\n });\n updateSucceeded();\n } catch (error: unknown) {\n updateFailed(error);\n throw error;\n } finally {\n delete this.#inProcessExchangeRateUpdates[updateKey];\n }\n }\n\n /**\n * Uses the token prices service to retrieve exchange rates for tokens in a\n * particular currency.\n *\n * If the price API does not support the given chain ID, returns an empty\n * object.\n *\n * If the price API does not support the given currency, retrieves exchange\n * rates in a known currency instead, then converts those rates using the\n * exchange rate between the known currency and desired currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * exchange rates.\n * @returns A map from token address to its exchange rate in the native\n * currency, or an empty map if no exchange rates can be obtained for the\n * chain ID.\n */\n async #fetchAndMapExchangeRates({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n if (!this.#tokenPricesService.validateChainIdSupported(chainId)) {\n return tokenAddresses.reduce((obj, tokenAddress) => {\n obj = {\n ...obj,\n [tokenAddress]: undefined,\n };\n\n return obj;\n }, {});\n }\n\n if (this.#tokenPricesService.validateCurrencySupported(nativeCurrency)) {\n return await this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n });\n }\n\n return await this.#fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n });\n }\n\n /**\n * Updates token rates for the given networkClientId\n *\n * @param networkClientId - The network client ID used to get a ticker value.\n * @returns The controller state.\n */\n async _executePoll(networkClientId: NetworkClientId): Promise<void> {\n const networkClient = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n await this.updateExchangeRatesByChainId({\n chainId: networkClient.configuration.chainId,\n nativeCurrency: networkClient.configuration.ticker,\n });\n }\n\n /**\n * Retrieves prices in the given currency for the given tokens on the given\n * chain. Ensures that token addresses are checksum addresses.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.chainId - The EIP-155 ID of the chain where the tokens live.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n chainId: Hex;\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n let contractNativeInformations;\n const tokenPricesByTokenAddress = await reduceInBatchesSerially<\n Hex,\n Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>\n >({\n values: [...tokenAddresses].sort(),\n batchSize: TOKEN_PRICES_BATCH_SIZE,\n eachBatch: async (allTokenPricesByTokenAddress, batch) => {\n const tokenPricesByTokenAddressForBatch =\n await this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: batch,\n chainId,\n currency: nativeCurrency,\n });\n\n return {\n ...allTokenPricesByTokenAddress,\n ...tokenPricesByTokenAddressForBatch,\n };\n },\n initialResult: {},\n });\n contractNativeInformations = tokenPricesByTokenAddress;\n\n // fetch for native token\n if (tokenAddresses.length === 0) {\n const contractNativeInformationsNative =\n await this.#tokenPricesService.fetchTokenPrices({\n tokenAddresses: [],\n chainId,\n currency: nativeCurrency,\n });\n\n contractNativeInformations = {\n [ZERO_ADDRESS]: {\n currency: nativeCurrency,\n ...contractNativeInformationsNative[ZERO_ADDRESS],\n },\n };\n }\n return Object.entries(contractNativeInformations).reduce(\n (obj, [tokenAddress, token]) => {\n obj = {\n ...obj,\n [tokenAddress]: { ...token },\n };\n\n return obj;\n },\n {},\n );\n }\n\n /**\n * If the price API does not support a given native currency, then we need to\n * convert it to a fallback currency and feed that currency into the price\n * API, then convert the prices to our desired native currency.\n *\n * @param args - The arguments to this function.\n * @param args.tokenAddresses - Addresses for tokens.\n * @param args.nativeCurrency - The native currency in which to request\n * prices.\n * @returns A map of the token addresses (as checksums) to their prices in the\n * native currency.\n */\n async #fetchAndMapExchangeRatesForUnsupportedNativeCurrency({\n tokenAddresses,\n nativeCurrency,\n }: {\n tokenAddresses: Hex[];\n nativeCurrency: string;\n }): Promise<ContractMarketData> {\n const [\n contractExchangeInformations,\n fallbackCurrencyToNativeCurrencyConversionRate,\n ] = await Promise.all([\n this.#fetchAndMapExchangeRatesForSupportedNativeCurrency({\n tokenAddresses,\n chainId: this.#chainId,\n nativeCurrency: FALL_BACK_VS_CURRENCY,\n }),\n getCurrencyConversionRate({\n from: FALL_BACK_VS_CURRENCY,\n to: nativeCurrency,\n }),\n ]);\n\n if (fallbackCurrencyToNativeCurrencyConversionRate === null) {\n return {};\n }\n\n const updatedContractExchangeRates = Object.entries(\n contractExchangeInformations,\n ).reduce((acc, [tokenAddress, token]) => {\n acc = {\n ...acc,\n [tokenAddress]: {\n ...token,\n price: token.price\n ? token.price * fallbackCurrencyToNativeCurrencyConversionRate\n : undefined,\n },\n };\n return acc;\n }, {});\n\n return updatedContractExchangeRates;\n }\n}\n\nexport default TokenRatesController;\n"]}