@metamask-previews/assets-controllers 20.0.0-preview.3fbb6b41 → 23.1.0-preview.353ee83b

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 (67) hide show
  1. package/CHANGELOG.md +103 -10
  2. package/dist/AccountTrackerController.d.ts +28 -7
  3. package/dist/AccountTrackerController.d.ts.map +1 -1
  4. package/dist/AccountTrackerController.js +104 -30
  5. package/dist/AccountTrackerController.js.map +1 -1
  6. package/dist/AssetsContractController.d.ts.map +1 -1
  7. package/dist/AssetsContractController.js +4 -0
  8. package/dist/AssetsContractController.js.map +1 -1
  9. package/dist/CurrencyRateController.d.ts +2 -2
  10. package/dist/CurrencyRateController.d.ts.map +1 -1
  11. package/dist/CurrencyRateController.js +1 -1
  12. package/dist/CurrencyRateController.js.map +1 -1
  13. package/dist/NftController.d.ts +75 -1
  14. package/dist/NftController.d.ts.map +1 -1
  15. package/dist/NftController.js +35 -14
  16. package/dist/NftController.js.map +1 -1
  17. package/dist/NftDetectionController.d.ts +7 -4
  18. package/dist/NftDetectionController.d.ts.map +1 -1
  19. package/dist/NftDetectionController.js +26 -14
  20. package/dist/NftDetectionController.js.map +1 -1
  21. package/dist/Standards/ERC20Standard.d.ts.map +1 -1
  22. package/dist/Standards/ERC20Standard.js +4 -0
  23. package/dist/Standards/ERC20Standard.js.map +1 -1
  24. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts +11 -10
  25. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.d.ts.map +1 -1
  26. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js +106 -85
  27. package/dist/Standards/NftStandards/ERC1155/ERC1155Standard.js.map +1 -1
  28. package/dist/Standards/NftStandards/ERC721/ERC721Standard.d.ts.map +1 -1
  29. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js +2 -0
  30. package/dist/Standards/NftStandards/ERC721/ERC721Standard.js.map +1 -1
  31. package/dist/Standards/standards-types.d.ts.map +1 -1
  32. package/dist/Standards/standards-types.js.map +1 -1
  33. package/dist/TokenDetectionController.d.ts +43 -56
  34. package/dist/TokenDetectionController.d.ts.map +1 -1
  35. package/dist/TokenDetectionController.js +132 -96
  36. package/dist/TokenDetectionController.js.map +1 -1
  37. package/dist/TokenListController.d.ts +6 -4
  38. package/dist/TokenListController.d.ts.map +1 -1
  39. package/dist/TokenListController.js +11 -10
  40. package/dist/TokenListController.js.map +1 -1
  41. package/dist/TokenRatesController.d.ts +6 -38
  42. package/dist/TokenRatesController.d.ts.map +1 -1
  43. package/dist/TokenRatesController.js +125 -93
  44. package/dist/TokenRatesController.js.map +1 -1
  45. package/dist/TokensController.d.ts +5 -6
  46. package/dist/TokensController.d.ts.map +1 -1
  47. package/dist/TokensController.js +81 -21
  48. package/dist/TokensController.js.map +1 -1
  49. package/dist/assetsUtil.d.ts +80 -9
  50. package/dist/assetsUtil.d.ts.map +1 -1
  51. package/dist/assetsUtil.js +177 -27
  52. package/dist/assetsUtil.js.map +1 -1
  53. package/dist/index.d.ts +4 -3
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +5 -3
  56. package/dist/index.js.map +1 -1
  57. package/dist/token-prices-service/abstract-token-prices-service.d.ts +15 -16
  58. package/dist/token-prices-service/abstract-token-prices-service.d.ts.map +1 -1
  59. package/dist/token-prices-service/abstract-token-prices-service.js.map +1 -1
  60. package/dist/token-prices-service/codefi-v2.d.ts +61 -3
  61. package/dist/token-prices-service/codefi-v2.d.ts.map +1 -1
  62. package/dist/token-prices-service/codefi-v2.js +86 -20
  63. package/dist/token-prices-service/codefi-v2.js.map +1 -1
  64. package/dist/token-prices-service/index.d.ts +1 -1
  65. package/dist/token-prices-service/index.js +2 -2
  66. package/dist/token-prices-service/index.js.map +1 -1
  67. package/package.json +15 -11
@@ -1,10 +1,23 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ethersBigNumberToBN = exports.addUrlProtocolPrefix = exports.getFormattedIpfsUrl = exports.getIpfsCIDv1AndPath = exports.removeIpfsProtocolPrefix = exports.isTokenListSupportedForNetwork = exports.isTokenDetectionSupportedForNetwork = exports.SupportedTokenDetectionNetworks = exports.validateTokenToWatch = exports.formatIconUrlWithProxy = exports.formatAggregatorNames = exports.compareNftMetadata = void 0;
12
+ exports.fetchTokenContractExchangeRates = exports.mapOpenSeaContractV2ToV1 = exports.mapOpenSeaDetailedNftV2ToV1 = exports.mapOpenSeaNftV2ToV1 = exports.reduceInBatchesSerially = exports.divideIntoBatches = exports.ethersBigNumberToBN = exports.addUrlProtocolPrefix = exports.getFormattedIpfsUrl = exports.getIpfsCIDv1AndPath = exports.removeIpfsProtocolPrefix = exports.isTokenListSupportedForNetwork = exports.isTokenDetectionSupportedForNetwork = exports.SupportedTokenDetectionNetworks = exports.formatIconUrlWithProxy = exports.formatAggregatorNames = exports.compareNftMetadata = exports.TOKEN_PRICES_BATCH_SIZE = void 0;
4
13
  const controller_utils_1 = require("@metamask/controller-utils");
5
- const rpc_errors_1 = require("@metamask/rpc-errors");
6
14
  const ethereumjs_util_1 = require("ethereumjs-util");
7
15
  const cid_1 = require("multiformats/cid");
16
+ /**
17
+ * The maximum number of token addresses that should be sent to the Price API in
18
+ * a single request.
19
+ */
20
+ exports.TOKEN_PRICES_BATCH_SIZE = 100;
8
21
  /**
9
22
  * Compares nft metadata entries to any nft entry.
10
23
  * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,
@@ -86,31 +99,6 @@ const formatIconUrlWithProxy = ({ chainId, tokenAddress, }) => {
86
99
  return `https://static.metafi.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;
87
100
  };
88
101
  exports.formatIconUrlWithProxy = formatIconUrlWithProxy;
89
- /**
90
- * Validates a ERC20 token to be added with EIP747.
91
- *
92
- * @param token - Token object to validate.
93
- */
94
- function validateTokenToWatch(token) {
95
- const { address, symbol, decimals } = token;
96
- if (!address || !symbol || typeof decimals === 'undefined') {
97
- throw rpc_errors_1.rpcErrors.invalidParams(`Must specify address, symbol, and decimals.`);
98
- }
99
- if (typeof symbol !== 'string') {
100
- throw rpc_errors_1.rpcErrors.invalidParams(`Invalid symbol: not a string.`);
101
- }
102
- if (symbol.length > 11) {
103
- throw rpc_errors_1.rpcErrors.invalidParams(`Invalid symbol "${symbol}": longer than 11 characters.`);
104
- }
105
- const numDecimals = parseInt(decimals, 10);
106
- if (isNaN(numDecimals) || numDecimals > 36 || numDecimals < 0) {
107
- throw rpc_errors_1.rpcErrors.invalidParams(`Invalid decimals "${decimals}": must be 0 <= 36.`);
108
- }
109
- if (!(0, controller_utils_1.isValidHexAddress)(address)) {
110
- throw rpc_errors_1.rpcErrors.invalidParams(`Invalid address "${address}".`);
111
- }
112
- }
113
- exports.validateTokenToWatch = validateTokenToWatch;
114
102
  /**
115
103
  * Networks where token detection is supported - Values are in decimal format
116
104
  */
@@ -125,6 +113,8 @@ var SupportedTokenDetectionNetworks;
125
113
  SupportedTokenDetectionNetworks["linea_mainnet"] = "0xe708";
126
114
  SupportedTokenDetectionNetworks["arbitrum"] = "0xa4b1";
127
115
  SupportedTokenDetectionNetworks["optimism"] = "0xa";
116
+ SupportedTokenDetectionNetworks["base"] = "0x2105";
117
+ SupportedTokenDetectionNetworks["zksync"] = "0x144";
128
118
  })(SupportedTokenDetectionNetworks = exports.SupportedTokenDetectionNetworks || (exports.SupportedTokenDetectionNetworks = {}));
129
119
  /**
130
120
  * Check if token detection is enabled for certain networks.
@@ -228,4 +218,164 @@ function ethersBigNumberToBN(bigNumber) {
228
218
  return new ethereumjs_util_1.BN((0, ethereumjs_util_1.stripHexPrefix)(bigNumber.toHexString()), 'hex');
229
219
  }
230
220
  exports.ethersBigNumberToBN = ethersBigNumberToBN;
221
+ /**
222
+ * Partitions a list of values into groups that are at most `batchSize` in
223
+ * length.
224
+ *
225
+ * @param values - The list of values.
226
+ * @param args - The remaining arguments.
227
+ * @param args.batchSize - The desired maximum number of values per batch.
228
+ * @returns The list of batches.
229
+ */
230
+ function divideIntoBatches(values, { batchSize }) {
231
+ const batches = [];
232
+ for (let i = 0; i < values.length; i += batchSize) {
233
+ batches.push(values.slice(i, i + batchSize));
234
+ }
235
+ return batches;
236
+ }
237
+ exports.divideIntoBatches = divideIntoBatches;
238
+ /**
239
+ * Constructs an object from processing batches of the given values
240
+ * sequentially.
241
+ *
242
+ * @param args - The arguments to this function.
243
+ * @param args.values - A list of values to iterate over.
244
+ * @param args.batchSize - The maximum number of values in each batch.
245
+ * @param args.eachBatch - A function to call for each batch. This function is
246
+ * similar to the function that `Array.prototype.reduce` takes, in that it
247
+ * receives the object that is being built, each batch in the list of batches
248
+ * and the index, and should return an updated version of the object.
249
+ * @param args.initialResult - The initial value of the final data structure,
250
+ * i.e., the value that will be fed into the first call of `eachBatch`.
251
+ * @returns The built object.
252
+ */
253
+ function reduceInBatchesSerially({ values, batchSize, eachBatch, initialResult, }) {
254
+ return __awaiter(this, void 0, void 0, function* () {
255
+ const batches = divideIntoBatches(values, { batchSize });
256
+ let workingResult = initialResult;
257
+ for (const [index, batch] of batches.entries()) {
258
+ workingResult = yield eachBatch(workingResult, batch, index);
259
+ }
260
+ // There's no way around this — we have to assume that in the end, the result
261
+ // matches the intended type.
262
+ const finalResult = workingResult;
263
+ return finalResult;
264
+ });
265
+ }
266
+ exports.reduceInBatchesSerially = reduceInBatchesSerially;
267
+ /**
268
+ * Maps an OpenSea V2 NFT to the V1 schema.
269
+ * @param nft - The V2 NFT to map.
270
+ * @returns The NFT in the V1 schema.
271
+ */
272
+ function mapOpenSeaNftV2ToV1(nft) {
273
+ var _a;
274
+ return {
275
+ token_id: nft.identifier,
276
+ num_sales: null,
277
+ background_color: null,
278
+ image_url: (_a = nft.image_url) !== null && _a !== void 0 ? _a : null,
279
+ image_preview_url: null,
280
+ image_thumbnail_url: null,
281
+ image_original_url: null,
282
+ animation_url: null,
283
+ animation_original_url: null,
284
+ name: nft.name,
285
+ description: nft.description,
286
+ external_link: null,
287
+ asset_contract: {
288
+ address: nft.contract,
289
+ asset_contract_type: null,
290
+ created_date: null,
291
+ schema_name: nft.token_standard.toUpperCase(),
292
+ symbol: null,
293
+ total_supply: null,
294
+ description: nft.description,
295
+ external_link: null,
296
+ collection: {
297
+ name: nft.collection,
298
+ image_url: null,
299
+ },
300
+ },
301
+ creator: {
302
+ user: { username: '' },
303
+ profile_img_url: '',
304
+ address: '',
305
+ },
306
+ last_sale: null,
307
+ };
308
+ }
309
+ exports.mapOpenSeaNftV2ToV1 = mapOpenSeaNftV2ToV1;
310
+ /**
311
+ * Maps an OpenSea V2 detailed NFT to the V1 schema.
312
+ * @param nft - The V2 detailed NFT to map.
313
+ * @returns The NFT in the V1 schema.
314
+ */
315
+ function mapOpenSeaDetailedNftV2ToV1(nft) {
316
+ var _a;
317
+ const mapped = mapOpenSeaNftV2ToV1(nft);
318
+ return Object.assign(Object.assign({}, mapped), { animation_url: (_a = nft.animation_url) !== null && _a !== void 0 ? _a : null, creator: Object.assign(Object.assign({}, mapped.creator), { address: nft.creator }) });
319
+ }
320
+ exports.mapOpenSeaDetailedNftV2ToV1 = mapOpenSeaDetailedNftV2ToV1;
321
+ /**
322
+ * Maps an OpenSea V2 contract to the V1 schema.
323
+ * @param contract - The v2 contract data.
324
+ * @param collection - The v2 collection data.
325
+ * @returns The contract in the v1 schema.
326
+ */
327
+ function mapOpenSeaContractV2ToV1(contract, collection) {
328
+ var _a, _b, _c, _d, _e, _f, _g;
329
+ return {
330
+ address: contract.address,
331
+ asset_contract_type: null,
332
+ created_date: null,
333
+ schema_name: contract.contract_standard.toUpperCase(),
334
+ symbol: null,
335
+ total_supply: (_d = (_b = (_a = collection === null || collection === void 0 ? void 0 : collection.total_supply) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : (_c = contract.total_supply) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : null,
336
+ description: (_e = collection === null || collection === void 0 ? void 0 : collection.description) !== null && _e !== void 0 ? _e : null,
337
+ external_link: (_f = collection === null || collection === void 0 ? void 0 : collection.project_url) !== null && _f !== void 0 ? _f : null,
338
+ collection: {
339
+ name: (_g = collection === null || collection === void 0 ? void 0 : collection.name) !== null && _g !== void 0 ? _g : contract.name,
340
+ image_url: collection === null || collection === void 0 ? void 0 : collection.image_url,
341
+ },
342
+ };
343
+ }
344
+ exports.mapOpenSeaContractV2ToV1 = mapOpenSeaContractV2ToV1;
345
+ /**
346
+ * Retrieves token prices for a set of contract addresses in a specific currency and chainId.
347
+ *
348
+ * @param args - The arguments to function.
349
+ * @param args.tokenPricesService - An object in charge of retrieving token prices.
350
+ * @param args.nativeCurrency - The native currency to request price in.
351
+ * @param args.tokenAddresses - The list of contract addresses.
352
+ * @param args.chainId - The chainId of the tokens.
353
+ * @returns The prices for the requested tokens.
354
+ */
355
+ function fetchTokenContractExchangeRates({ tokenPricesService, nativeCurrency, tokenAddresses, chainId, }) {
356
+ return __awaiter(this, void 0, void 0, function* () {
357
+ const isChainIdSupported = tokenPricesService.validateChainIdSupported(chainId);
358
+ const isCurrencySupported = tokenPricesService.validateCurrencySupported(nativeCurrency);
359
+ if (!isChainIdSupported || !isCurrencySupported) {
360
+ return {};
361
+ }
362
+ const tokenPricesByTokenAddress = yield reduceInBatchesSerially({
363
+ values: tokenAddresses,
364
+ batchSize: exports.TOKEN_PRICES_BATCH_SIZE,
365
+ eachBatch: (allTokenPricesByTokenAddress, batch) => __awaiter(this, void 0, void 0, function* () {
366
+ const tokenPricesByTokenAddressForBatch = yield tokenPricesService.fetchTokenPrices({
367
+ tokenAddresses: batch,
368
+ chainId,
369
+ currency: nativeCurrency,
370
+ });
371
+ return Object.assign(Object.assign({}, allTokenPricesByTokenAddress), tokenPricesByTokenAddressForBatch);
372
+ }),
373
+ initialResult: {},
374
+ });
375
+ return Object.entries(tokenPricesByTokenAddress).reduce((obj, [tokenAddress, tokenPrice]) => {
376
+ return Object.assign(Object.assign({}, obj), { [(0, controller_utils_1.toChecksumHexAddress)(tokenAddress)]: tokenPrice === null || tokenPrice === void 0 ? void 0 : tokenPrice.value });
377
+ }, {});
378
+ });
379
+ }
380
+ exports.fetchTokenContractExchangeRates = fetchTokenContractExchangeRates;
231
381
  //# sourceMappingURL=assetsUtil.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"assetsUtil.js","sourceRoot":"","sources":["../src/assetsUtil.ts"],"names":[],"mappings":";;;AACA,iEAIoC;AACpC,qDAAiD;AAEjD,qDAAqD;AACrD,0CAAuC;AAKvC;;;;;;;;GAQG;AACH,SAAgB,kBAAkB,CAAC,cAA2B,EAAE,GAAQ;IACtE,MAAM,IAAI,GAA0B;QAClC,OAAO;QACP,iBAAiB;QACjB,cAAc;QACd,gBAAgB;QAChB,eAAe;QACf,WAAW;QACX,mBAAmB;QACnB,cAAc;KACf,CAAC;IACF,MAAM,eAAe,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;QACjD,IAAI,cAAc,CAAC,GAAG,CAAC,IAAI,cAAc,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,EAAE;YAC3D,OAAO,KAAK,GAAG,CAAC,CAAC;SAClB;QACD,OAAO,KAAK,CAAC;IACf,CAAC,EAAE,CAAC,CAAC,CAAC;IACN,OAAO,eAAe,GAAG,CAAC,CAAC;AAC7B,CAAC;AAlBD,gDAkBC;AAED,MAAM,mB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AE7D,8GAA8G;IAC9G,sEAAsE;IACtE,OAAO;QACL,GAAG,EAAE,SAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,QAAQ,EAAE;QACrC,IAAI;KACL,CAAC;AACJ,CAAC;AAlBD,kDAkBC;AAED;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CACjC,WAAmB,EACnB,OAAe,EACf,kBAA2B;IAE3B,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,GAAG,CAAC,oBAAoB,CAAC,WAAW,CAAC,CAAC,CAAC;IAC9E,IAAI,kBAAkB,EAAE;QACtB,MAAM,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;QACnD,OAAO,GAAG,QAAQ,KAAK,GAAG,SAAS,IAAI,GAAG,IAAI,aAAJ,IAAI,cAAJ,IAAI,GAAI,EAAE,EAAE,CAAC;KACxD;IACD,MAAM,UAAU,GAAG,wBAAwB,CAAC,OAAO,CAAC,CAAC;IACrD,OAAO,GAAG,MAAM,SAAS,UAAU,EAAE,CAAC;AACxC,CAAC;AAZD,kDAYC;AAED;;;;;GAKG;AACH,SAAgB,oBAAoB,CAAC,SAAiB;IACpD,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,6BAA6B,CAAC,EAAE;QACnD,OAAO,WAAW,SAAS,EAAE,CAAC;KAC/B;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AALD,oDAKC;AAED;;;;;GAKG;AACH,SAAgB,mBAAmB,CAAC,SAAoB;IACtD,OAAO,IAAI,oBAAE,CAAC,IAAA,gCAAc,EAAC,SAAS,CAAC,WAAW,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;AAChE,CAAC;AAFD,kDAEC","sourcesContent":["import type { BigNumber } from '@ethersproject/bignumber';\nimport {\n convertHexToDecimal,\n isValidHexAddress,\n GANACHE_CHAIN_ID,\n} from '@metamask/controller-utils';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { BN, stripHexPrefix } from 'ethereumjs-util';\nimport { CID } from 'multiformats/cid';\n\nimport type { Nft, NftMetadata } from './NftController';\nimport type { Token } from './TokenRatesController';\n\n/**\n * Compares nft metadata entries to any nft entry.\n * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,\n * there's a need to update the nft in state.\n *\n * @param newNftMetadata - Nft metadata object.\n * @param nft - Nft object to compare with.\n * @returns Whether there are differences.\n */\nexport function compareNftMetadata(newNftMetadata: NftMetadata, nft: Nft) {\n const keys: (keyof NftMetadata)[] = [\n 'image',\n 'backgroundColor',\n 'imagePreview',\n 'imageThumbnail',\n 'imageOriginal',\n 'animation',\n 'animationOriginal',\n 'externalLink',\n ];\n const differentValues = keys.reduce((value, key) => {\n if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {\n return value + 1;\n }\n return value;\n }, 0);\n return differentValues > 0;\n}\n\nconst aggregatorNameByKey: Record<string, string> = {\n aave: 'Aave',\n bancor: 'Bancor',\n cmc: 'CMC',\n cryptocom: 'Crypto.com',\n coinGecko: 'CoinGecko',\n oneInch: '1inch',\n paraswap: 'Paraswap',\n pmm: 'PMM',\n zapper: 'Zapper',\n zerion: 'Zerion',\n zeroEx: '0x',\n synthetix: 'Synthetix',\n yearn: 'Yearn',\n apeswap: 'ApeSwap',\n binanceDex: 'BinanceDex',\n pancakeTop100: 'PancakeTop100',\n pancakeExtended: 'PancakeExtended',\n balancer: 'Balancer',\n quickswap: 'QuickSwap',\n matcha: 'Matcha',\n pangolinDex: 'PangolinDex',\n pangolinDexStableCoin: 'PangolinDexStableCoin',\n pangolinDexAvaxBridge: 'PangolinDexAvaxBridge',\n traderJoe: 'TraderJoe',\n airswapLight: 'AirswapLight',\n kleros: 'Kleros',\n};\n\n/**\n * Formats aggregator names to presentable format.\n *\n * @param aggregators - List of token list names in camelcase.\n * @returns Formatted aggregator names.\n */\nexport const formatAggregatorNames = (aggregators: string[]) => {\n return aggregators.map(\n (key) =>\n aggregatorNameByKey[key] ||\n `${key[0].toUpperCase()}${key.substring(1, key.length)}`,\n );\n};\n\n/**\n * Format token list assets to use image proxy from Codefi.\n *\n * @param params - Object that contains chainID and tokenAddress.\n * @param params.chainId - ChainID of network in 0x-prefixed hexadecimal format.\n * @param params.tokenAddress - Address of token in mixed or lowercase.\n * @returns Formatted image url\n */\nexport const formatIconUrlWithProxy = ({\n chainId,\n tokenAddress,\n}: {\n chainId: Hex;\n tokenAddress: string;\n}) => {\n const chainIdDecimal = convertHexToDecimal(chainId).toString();\n return `https://static.metafi.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;\n};\n\n/**\n * Validates a ERC20 token to be added with EIP747.\n *\n * @param token - Token object to validate.\n */\nexport function validateTokenToWatch(token: Token) {\n const { address, symbol, decimals } = token;\n if (!address || !symbol || typeof decimals === 'undefined') {\n throw rpcErrors.invalidParams(\n `Must specify address, symbol, and decimals.`,\n );\n }\n\n if (typeof symbol !== 'string') {\n throw rpcErrors.invalidParams(`Invalid symbol: not a string.`);\n }\n\n if (symbol.length > 11) {\n throw rpcErrors.invalidParams(\n `Invalid symbol \"${symbol}\": longer than 11 characters.`,\n );\n }\n const numDecimals = parseInt(decimals as unknown as string, 10);\n if (isNaN(numDecimals) || numDecimals > 36 || numDecimals < 0) {\n throw rpcErrors.invalidParams(\n `Invalid decimals \"${decimals}\": must be 0 <= 36.`,\n );\n }\n\n if (!isValidHexAddress(address)) {\n throw rpcErrors.invalidParams(`Invalid address \"${address}\".`);\n }\n}\n\n/**\n * Networks where token detection is supported - Values are in decimal format\n */\nexport enum SupportedTokenDetectionNetworks {\n mainnet = '0x1', // decimal: 1\n bsc = '0x38', // decimal: 56\n polygon = '0x89', // decimal: 137\n avax = '0xa86a', // decimal: 43114\n aurora = '0x4e454152', // decimal: 1313161554\n linea_goerli = '0xe704', // decimal: 59140\n linea_mainnet = '0xe708', // decimal: 59144\n arbitrum = '0xa4b1', // decimal: 42161\n optimism = '0xa', // decimal: 10\n}\n\n/**\n * Check if token detection is enabled for certain networks.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport function isTokenDetectionSupportedForNetwork(chainId: Hex): boolean {\n return Object.values<Hex>(SupportedTokenDetectionNetworks).includes(chainId);\n}\n\n/**\n * Check if token list polling is enabled for a given network.\n * Currently this method is used to support e2e testing for consumers of this package.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports tokenlists\n */\nexport function isTokenListSupportedForNetwork(chainId: Hex): boolean {\n return (\n isTokenDetectionSupportedForNetwork(chainId) || chainId === GANACHE_CHAIN_ID\n );\n}\n\n/**\n * Removes IPFS protocol prefix from input string.\n *\n * @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})\n * @returns IPFS content identifier and (possibly) path in a string\n * @throws Will throw if the url passed is not IPFS.\n */\nexport function removeIpfsProtocolPrefix(ipfsUrl: string) {\n if (ipfsUrl.startsWith('ipfs://ipfs/')) {\n return ipfsUrl.replace('ipfs://ipfs/', '');\n } else if (ipfsUrl.startsWith('ipfs://')) {\n return ipfsUrl.replace('ipfs://', '');\n }\n // this method should not be used with non-ipfs urls (i.e. startsWith('ipfs://') === true)\n throw new Error('this method should not be used with non ipfs urls');\n}\n\n/**\n * Extracts content identifier and path from an input string.\n *\n * @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix\n * @returns IFPS content identifier (cid) and sub path as string.\n * @throws Will throw if the url passed is not ipfs.\n */\nexport function getIpfsCIDv1AndPath(ipfsUrl: string): {\n cid: string;\n path?: string;\n} {\n const url = removeIpfsProtocolPrefix(ipfsUrl);\n\n // check if there is a path\n // (CID is everything preceding first forward slash, path is everything after)\n const index = url.indexOf('/');\n const cid = index !== -1 ? url.substring(0, index) : url;\n const path = index !== -1 ? url.substring(index) : undefined;\n\n // We want to ensure that the CID is v1 (https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)\n // because most cid v0s appear to be incompatible with IPFS subdomains\n return {\n cid: CID.parse(cid).toV1().toString(),\n path,\n };\n}\n\n/**\n * Formats URL correctly for use retrieving assets hosted on IPFS.\n *\n * @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).\n * @param ipfsUrl - The IFPS URL pointed at the asset.\n * @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.\n * @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.\n */\nexport function getFormattedIpfsUrl(\n ipfsGateway: string,\n ipfsUrl: string,\n subdomainSupported: boolean,\n): string {\n const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));\n if (subdomainSupported) {\n const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);\n return `${protocol}//${cid}.ipfs.${host}${path ?? ''}`;\n }\n const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);\n return `${origin}/ipfs/${cidAndPath}`;\n}\n\n/**\n * Adds URL protocol prefix to input URL string if missing.\n *\n * @param urlString - An IPFS URL.\n * @returns A URL with a https:// prepended.\n */\nexport function addUrlProtocolPrefix(urlString: string): string {\n if (!urlString.match(/(^http:\\/\\/)|(^https:\\/\\/)/u)) {\n return `https://${urlString}`;\n }\n return urlString;\n}\n\n/**\n * Converts an Ethers BigNumber to a BN.\n *\n * @param bigNumber - An Ethers BigNumber instance.\n * @returns A BN object.\n */\nexport function ethersBigNumberToBN(bigNumber: BigNumber): BN {\n return new BN(stripHexPrefix(bigNumber.toHexString()), 'hex');\n}\n"]}
1
+ {"version":3,"file":"assetsUtil.js","sourceRoot":"","sources":["../src/assetsUtil.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iEAIoC;AAEpC,qDAAqD;AACrD,0CAAuC;AAcvC;;;GAGG;AACU,QAAA,uBAAuB,GAAG,GAAG,CAAC;AAE3C;;;;;;;;GAQG;AACH,SAAgB,kBAAkB,CAAC,cAA2B,EAAE,GAAQ;IACtE,MAAM,IAAI,GAA0B;QAClC,OAAO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EACpD,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,OAAO,GAMR;;QACC,MAAM,kBAAkB,GACtB,kBAAkB,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAC;QACvD,MAAM,mBAAmB,GACvB,kBAAkB,CAAC,yBAAyB,CAAC,cAAc,CAAC,CAAC;QAE/D,IAAI,CAAC,kBAAkB,IAAI,CAAC,mBAAmB,EAAE;YAC/C,OAAO,EAAE,CAAC;SACX;QAED,MAAM,yBAAyB,GAAG,MAAM,uBAAuB,CAG7D;YACA,MAAM,EAAE,cAAc;YACtB,SAAS,EAAE,+BAAuB;YAClC,SAAS,EAAE,CAAO,4BAA4B,EAAE,KAAK,EAAE,EAAE;gBACvD,MAAM,iCAAiC,GACrC,MAAM,kBAAkB,CAAC,gBAAgB,CAAC;oBACxC,cAAc,EAAE,KAAK;oBACrB,OAAO;oBACP,QAAQ,EAAE,cAAc;iBACzB,CAAC,CAAC;gBAEL,uCACK,4BAA4B,GAC5B,iCAAiC,EACpC;YACJ,CAAC,CAAA;YACD,aAAa,EAAE,EAAE;SAClB,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC,OAAO,CAAC,yBAAyB,CAAC,CAAC,MAAM,CACrD,CAAC,GAAG,EAAE,CAAC,YAAY,EAAE,UAAU,CAAC,EAAE,EAAE;YAClC,uCACK,GAAG,KACN,CAAC,IAAA,uCAAoB,EAAC,YAAY,CAAC,CAAC,EAAE,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,KAAK,IACvD;QACJ,CAAC,EACD,EAAE,CACH,CAAC;IACJ,CAAC;CAAA;AAnDD,0EAmDC","sourcesContent":["import type { BigNumber } from '@ethersproject/bignumber';\nimport {\n convertHexToDecimal,\n GANACHE_CHAIN_ID,\n toChecksumHexAddress,\n} from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { BN, stripHexPrefix } from 'ethereumjs-util';\nimport { CID } from 'multiformats/cid';\n\nimport type {\n Nft,\n NftMetadata,\n OpenSeaV2Collection,\n OpenSeaV2Contract,\n OpenSeaV2DetailedNft,\n OpenSeaV2Nft,\n} from './NftController';\nimport type { ApiNft, ApiNftContract } from './NftDetectionController';\nimport type { AbstractTokenPricesService } from './token-prices-service';\nimport { type ContractExchangeRates } from './TokenRatesController';\n\n/**\n * The maximum number of token addresses that should be sent to the Price API in\n * a single request.\n */\nexport const TOKEN_PRICES_BATCH_SIZE = 100;\n\n/**\n * Compares nft metadata entries to any nft entry.\n * We need this method when comparing a new fetched nft metadata, in case a entry changed to a defined value,\n * there's a need to update the nft in state.\n *\n * @param newNftMetadata - Nft metadata object.\n * @param nft - Nft object to compare with.\n * @returns Whether there are differences.\n */\nexport function compareNftMetadata(newNftMetadata: NftMetadata, nft: Nft) {\n const keys: (keyof NftMetadata)[] = [\n 'image',\n 'backgroundColor',\n 'imagePreview',\n 'imageThumbnail',\n 'imageOriginal',\n 'animation',\n 'animationOriginal',\n 'externalLink',\n ];\n const differentValues = keys.reduce((value, key) => {\n if (newNftMetadata[key] && newNftMetadata[key] !== nft[key]) {\n return value + 1;\n }\n return value;\n }, 0);\n return differentValues > 0;\n}\n\nconst aggregatorNameByKey: Record<string, string> = {\n aave: 'Aave',\n bancor: 'Bancor',\n cmc: 'CMC',\n cryptocom: 'Crypto.com',\n coinGecko: 'CoinGecko',\n oneInch: '1inch',\n paraswap: 'Paraswap',\n pmm: 'PMM',\n zapper: 'Zapper',\n zerion: 'Zerion',\n zeroEx: '0x',\n synthetix: 'Synthetix',\n yearn: 'Yearn',\n apeswap: 'ApeSwap',\n binanceDex: 'BinanceDex',\n pancakeTop100: 'PancakeTop100',\n pancakeExtended: 'PancakeExtended',\n balancer: 'Balancer',\n quickswap: 'QuickSwap',\n matcha: 'Matcha',\n pangolinDex: 'PangolinDex',\n pangolinDexStableCoin: 'PangolinDexStableCoin',\n pangolinDexAvaxBridge: 'PangolinDexAvaxBridge',\n traderJoe: 'TraderJoe',\n airswapLight: 'AirswapLight',\n kleros: 'Kleros',\n};\n\n/**\n * Formats aggregator names to presentable format.\n *\n * @param aggregators - List of token list names in camelcase.\n * @returns Formatted aggregator names.\n */\nexport const formatAggregatorNames = (aggregators: string[]) => {\n return aggregators.map(\n (key) =>\n aggregatorNameByKey[key] ||\n `${key[0].toUpperCase()}${key.substring(1, key.length)}`,\n );\n};\n\n/**\n * Format token list assets to use image proxy from Codefi.\n *\n * @param params - Object that contains chainID and tokenAddress.\n * @param params.chainId - ChainID of network in 0x-prefixed hexadecimal format.\n * @param params.tokenAddress - Address of token in mixed or lowercase.\n * @returns Formatted image url\n */\nexport const formatIconUrlWithProxy = ({\n chainId,\n tokenAddress,\n}: {\n chainId: Hex;\n tokenAddress: string;\n}) => {\n const chainIdDecimal = convertHexToDecimal(chainId).toString();\n return `https://static.metafi.codefi.network/api/v1/tokenIcons/${chainIdDecimal}/${tokenAddress.toLowerCase()}.png`;\n};\n\n/**\n * Networks where token detection is supported - Values are in decimal format\n */\nexport enum SupportedTokenDetectionNetworks {\n mainnet = '0x1', // decimal: 1\n bsc = '0x38', // decimal: 56\n polygon = '0x89', // decimal: 137\n avax = '0xa86a', // decimal: 43114\n aurora = '0x4e454152', // decimal: 1313161554\n linea_goerli = '0xe704', // decimal: 59140\n linea_mainnet = '0xe708', // decimal: 59144\n arbitrum = '0xa4b1', // decimal: 42161\n optimism = '0xa', // decimal: 10\n base = '0x2105', // decimal: 8453\n zksync = '0x144', // decimal: 324\n}\n\n/**\n * Check if token detection is enabled for certain networks.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports token detection\n */\nexport function isTokenDetectionSupportedForNetwork(chainId: Hex): boolean {\n return Object.values<Hex>(SupportedTokenDetectionNetworks).includes(chainId);\n}\n\n/**\n * Check if token list polling is enabled for a given network.\n * Currently this method is used to support e2e testing for consumers of this package.\n *\n * @param chainId - ChainID of network\n * @returns Whether the current network supports tokenlists\n */\nexport function isTokenListSupportedForNetwork(chainId: Hex): boolean {\n return (\n isTokenDetectionSupportedForNetwork(chainId) || chainId === GANACHE_CHAIN_ID\n );\n}\n\n/**\n * Removes IPFS protocol prefix from input string.\n *\n * @param ipfsUrl - An IPFS url (e.g. ipfs://{content id})\n * @returns IPFS content identifier and (possibly) path in a string\n * @throws Will throw if the url passed is not IPFS.\n */\nexport function removeIpfsProtocolPrefix(ipfsUrl: string) {\n if (ipfsUrl.startsWith('ipfs://ipfs/')) {\n return ipfsUrl.replace('ipfs://ipfs/', '');\n } else if (ipfsUrl.startsWith('ipfs://')) {\n return ipfsUrl.replace('ipfs://', '');\n }\n // this method should not be used with non-ipfs urls (i.e. startsWith('ipfs://') === true)\n throw new Error('this method should not be used with non ipfs urls');\n}\n\n/**\n * Extracts content identifier and path from an input string.\n *\n * @param ipfsUrl - An IPFS URL minus the IPFS protocol prefix\n * @returns IFPS content identifier (cid) and sub path as string.\n * @throws Will throw if the url passed is not ipfs.\n */\nexport function getIpfsCIDv1AndPath(ipfsUrl: string): {\n cid: string;\n path?: string;\n} {\n const url = removeIpfsProtocolPrefix(ipfsUrl);\n\n // check if there is a path\n // (CID is everything preceding first forward slash, path is everything after)\n const index = url.indexOf('/');\n const cid = index !== -1 ? url.substring(0, index) : url;\n const path = index !== -1 ? url.substring(index) : undefined;\n\n // We want to ensure that the CID is v1 (https://docs.ipfs.io/concepts/content-addressing/#identifier-formats)\n // because most cid v0s appear to be incompatible with IPFS subdomains\n return {\n cid: CID.parse(cid).toV1().toString(),\n path,\n };\n}\n\n/**\n * Formats URL correctly for use retrieving assets hosted on IPFS.\n *\n * @param ipfsGateway - The users preferred IPFS gateway (full URL or just host).\n * @param ipfsUrl - The IFPS URL pointed at the asset.\n * @param subdomainSupported - Boolean indicating whether the URL should be formatted with subdomains or not.\n * @returns A formatted URL, with the user's preferred IPFS gateway and format (subdomain or not), pointing to an asset hosted on IPFS.\n */\nexport function getFormattedIpfsUrl(\n ipfsGateway: string,\n ipfsUrl: string,\n subdomainSupported: boolean,\n): string {\n const { host, protocol, origin } = new URL(addUrlProtocolPrefix(ipfsGateway));\n if (subdomainSupported) {\n const { cid, path } = getIpfsCIDv1AndPath(ipfsUrl);\n return `${protocol}//${cid}.ipfs.${host}${path ?? ''}`;\n }\n const cidAndPath = removeIpfsProtocolPrefix(ipfsUrl);\n return `${origin}/ipfs/${cidAndPath}`;\n}\n\n/**\n * Adds URL protocol prefix to input URL string if missing.\n *\n * @param urlString - An IPFS URL.\n * @returns A URL with a https:// prepended.\n */\nexport function addUrlProtocolPrefix(urlString: string): string {\n if (!urlString.match(/(^http:\\/\\/)|(^https:\\/\\/)/u)) {\n return `https://${urlString}`;\n }\n return urlString;\n}\n\n/**\n * Converts an Ethers BigNumber to a BN.\n *\n * @param bigNumber - An Ethers BigNumber instance.\n * @returns A BN object.\n */\nexport function ethersBigNumberToBN(bigNumber: BigNumber): BN {\n return new BN(stripHexPrefix(bigNumber.toHexString()), 'hex');\n}\n\n/**\n * Partitions a list of values into groups that are at most `batchSize` in\n * length.\n *\n * @param values - The list of values.\n * @param args - The remaining arguments.\n * @param args.batchSize - The desired maximum number of values per batch.\n * @returns The list of batches.\n */\nexport function divideIntoBatches<Value>(\n values: Value[],\n { batchSize }: { batchSize: number },\n): Value[][] {\n const batches = [];\n for (let i = 0; i < values.length; i += batchSize) {\n batches.push(values.slice(i, i + batchSize));\n }\n return batches;\n}\n\n/**\n * Constructs an object from processing batches of the given values\n * sequentially.\n *\n * @param args - The arguments to this function.\n * @param args.values - A list of values to iterate over.\n * @param args.batchSize - The maximum number of values in each batch.\n * @param args.eachBatch - A function to call for each batch. This function is\n * similar to the function that `Array.prototype.reduce` takes, in that it\n * receives the object that is being built, each batch in the list of batches\n * and the index, and should return an updated version of the object.\n * @param args.initialResult - The initial value of the final data structure,\n * i.e., the value that will be fed into the first call of `eachBatch`.\n * @returns The built object.\n */\nexport async function reduceInBatchesSerially<\n Value,\n Result extends Record<PropertyKey, unknown>,\n>({\n values,\n batchSize,\n eachBatch,\n initialResult,\n}: {\n values: Value[];\n batchSize: number;\n eachBatch: (\n workingResult: Partial<Result>,\n batch: Value[],\n index: number,\n ) => Partial<Result> | Promise<Partial<Result>>;\n initialResult: Partial<Result>;\n}): Promise<Result> {\n const batches = divideIntoBatches(values, { batchSize });\n let workingResult = initialResult;\n for (const [index, batch] of batches.entries()) {\n workingResult = await eachBatch(workingResult, batch, index);\n }\n // There's no way around this — we have to assume that in the end, the result\n // matches the intended type.\n const finalResult = workingResult as Result;\n return finalResult;\n}\n\n/**\n * Maps an OpenSea V2 NFT to the V1 schema.\n * @param nft - The V2 NFT to map.\n * @returns The NFT in the V1 schema.\n */\nexport function mapOpenSeaNftV2ToV1(nft: OpenSeaV2Nft): ApiNft {\n return {\n token_id: nft.identifier,\n num_sales: null,\n background_color: null,\n image_url: nft.image_url ?? null,\n image_preview_url: null,\n image_thumbnail_url: null,\n image_original_url: null,\n animation_url: null,\n animation_original_url: null,\n name: nft.name,\n description: nft.description,\n external_link: null,\n asset_contract: {\n address: nft.contract,\n asset_contract_type: null,\n created_date: null,\n schema_name: nft.token_standard.toUpperCase(),\n symbol: null,\n total_supply: null,\n description: nft.description,\n external_link: null,\n collection: {\n name: nft.collection,\n image_url: null,\n },\n },\n creator: {\n user: { username: '' },\n profile_img_url: '',\n address: '',\n },\n last_sale: null,\n };\n}\n\n/**\n * Maps an OpenSea V2 detailed NFT to the V1 schema.\n * @param nft - The V2 detailed NFT to map.\n * @returns The NFT in the V1 schema.\n */\nexport function mapOpenSeaDetailedNftV2ToV1(nft: OpenSeaV2DetailedNft): ApiNft {\n const mapped = mapOpenSeaNftV2ToV1(nft);\n return {\n ...mapped,\n animation_url: nft.animation_url ?? null,\n creator: {\n ...mapped.creator,\n address: nft.creator,\n },\n };\n}\n\n/**\n * Maps an OpenSea V2 contract to the V1 schema.\n * @param contract - The v2 contract data.\n * @param collection - The v2 collection data.\n * @returns The contract in the v1 schema.\n */\nexport function mapOpenSeaContractV2ToV1(\n contract: OpenSeaV2Contract,\n collection?: OpenSeaV2Collection,\n): ApiNftContract {\n return {\n address: contract.address,\n asset_contract_type: null,\n created_date: null,\n schema_name: contract.contract_standard.toUpperCase(),\n symbol: null,\n total_supply:\n collection?.total_supply?.toString() ??\n contract.total_supply?.toString() ??\n null,\n description: collection?.description ?? null,\n external_link: collection?.project_url ?? null,\n collection: {\n name: collection?.name ?? contract.name,\n image_url: collection?.image_url,\n },\n };\n}\n\n/**\n * Retrieves token prices for a set of contract addresses in a specific currency and chainId.\n *\n * @param args - The arguments to function.\n * @param args.tokenPricesService - An object in charge of retrieving token prices.\n * @param args.nativeCurrency - The native currency to request price in.\n * @param args.tokenAddresses - The list of contract addresses.\n * @param args.chainId - The chainId of the tokens.\n * @returns The prices for the requested tokens.\n */\nexport async function fetchTokenContractExchangeRates({\n tokenPricesService,\n nativeCurrency,\n tokenAddresses,\n chainId,\n}: {\n tokenPricesService: AbstractTokenPricesService;\n nativeCurrency: string;\n tokenAddresses: Hex[];\n chainId: Hex;\n}): Promise<ContractExchangeRates> {\n const isChainIdSupported =\n tokenPricesService.validateChainIdSupported(chainId);\n const isCurrencySupported =\n tokenPricesService.validateCurrencySupported(nativeCurrency);\n\n if (!isChainIdSupported || !isCurrencySupported) {\n return {};\n }\n\n const tokenPricesByTokenAddress = await reduceInBatchesSerially<\n Hex,\n Awaited<ReturnType<AbstractTokenPricesService['fetchTokenPrices']>>\n >({\n values: tokenAddresses,\n batchSize: TOKEN_PRICES_BATCH_SIZE,\n eachBatch: async (allTokenPricesByTokenAddress, batch) => {\n const tokenPricesByTokenAddressForBatch =\n await tokenPricesService.fetchTokenPrices({\n tokenAddresses: batch,\n chainId,\n currency: nativeCurrency,\n });\n\n return {\n ...allTokenPricesByTokenAddress,\n ...tokenPricesByTokenAddressForBatch,\n };\n },\n initialResult: {},\n });\n\n return Object.entries(tokenPricesByTokenAddress).reduce(\n (obj, [tokenAddress, tokenPrice]) => {\n return {\n ...obj,\n [toChecksumHexAddress(tokenAddress)]: tokenPrice?.value,\n };\n },\n {},\n );\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -4,10 +4,11 @@ export * from './CurrencyRateController';
4
4
  export * from './NftController';
5
5
  export * from './NftDetectionController';
6
6
  export * from './TokenBalancesController';
7
- export * from './TokenDetectionController';
7
+ export type { TokenDetectionControllerMessenger, TokenDetectionControllerActions, TokenDetectionControllerGetStateAction, TokenDetectionControllerEvents, TokenDetectionControllerStateChangeEvent, } from './TokenDetectionController';
8
+ export { TokenDetectionController } from './TokenDetectionController';
8
9
  export * from './TokenListController';
9
10
  export * from './TokenRatesController';
10
11
  export * from './TokensController';
11
- export { isTokenDetectionSupportedForNetwork, formatIconUrlWithProxy, getFormattedIpfsUrl, } from './assetsUtil';
12
- export { codefiTokenPricesServiceV2 } from './token-prices-service';
12
+ export { isTokenDetectionSupportedForNetwork, formatIconUrlWithProxy, getFormattedIpfsUrl, fetchTokenContractExchangeRates, } from './assetsUtil';
13
+ export { CodefiTokenPricesServiceV2 } from './token-prices-service';
13
14
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,oBAAoB,CAAC;AACnC,OAAO,EACL,mCAAmC,EACnC,sBAAsB,EACtB,mBAAmB,GACpB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,0BAA0B,CAAC;AACzC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,2BAA2B,CAAC;AAC1C,YAAY,EACV,iCAAiC,EACjC,+BAA+B,EAC/B,sCAAsC,EACtC,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,cAAc,uBAAuB,CAAC;AACtC,cAAc,wBAAwB,CAAC;AACvC,cAAc,oBAAoB,CAAC;AACnC,OAAO,EACL,mCAAmC,EACnC,sBAAsB,EACtB,mBAAmB,EACnB,+BAA+B,GAChC,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,0BAA0B,EAAE,MAAM,wBAAwB,CAAC"}
package/dist/index.js CHANGED
@@ -14,14 +14,15 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.codefiTokenPricesServiceV2 = exports.getFormattedIpfsUrl = exports.formatIconUrlWithProxy = exports.isTokenDetectionSupportedForNetwork = void 0;
17
+ exports.CodefiTokenPricesServiceV2 = exports.fetchTokenContractExchangeRates = exports.getFormattedIpfsUrl = exports.formatIconUrlWithProxy = exports.isTokenDetectionSupportedForNetwork = exports.TokenDetectionController = void 0;
18
18
  __exportStar(require("./AccountTrackerController"), exports);
19
19
  __exportStar(require("./AssetsContractController"), exports);
20
20
  __exportStar(require("./CurrencyRateController"), exports);
21
21
  __exportStar(require("./NftController"), exports);
22
22
  __exportStar(require("./NftDetectionController"), exports);
23
23
  __exportStar(require("./TokenBalancesController"), exports);
24
- __exportStar(require("./TokenDetectionController"), exports);
24
+ var TokenDetectionController_1 = require("./TokenDetectionController");
25
+ Object.defineProperty(exports, "TokenDetectionController", { enumerable: true, get: function () { return TokenDetectionController_1.TokenDetectionController; } });
25
26
  __exportStar(require("./TokenListController"), exports);
26
27
  __exportStar(require("./TokenRatesController"), exports);
27
28
  __exportStar(require("./TokensController"), exports);
@@ -29,6 +30,7 @@ var assetsUtil_1 = require("./assetsUtil");
29
30
  Object.defineProperty(exports, "isTokenDetectionSupportedForNetwork", { enumerable: true, get: function () { return assetsUtil_1.isTokenDetectionSupportedForNetwork; } });
30
31
  Object.defineProperty(exports, "formatIconUrlWithProxy", { enumerable: true, get: function () { return assetsUtil_1.formatIconUrlWithProxy; } });
31
32
  Object.defineProperty(exports, "getFormattedIpfsUrl", { enumerable: true, get: function () { return assetsUtil_1.getFormattedIpfsUrl; } });
33
+ Object.defineProperty(exports, "fetchTokenContractExchangeRates", { enumerable: true, get: function () { return assetsUtil_1.fetchTokenContractExchangeRates; } });
32
34
  var token_prices_service_1 = require("./token-prices-service");
33
- Object.defineProperty(exports, "codefiTokenPricesServiceV2", { enumerable: true, get: function () { return token_prices_service_1.codefiTokenPricesServiceV2; } });
35
+ Object.defineProperty(exports, "CodefiTokenPricesServiceV2", { enumerable: true, get: function () { return token_prices_service_1.CodefiTokenPricesServiceV2; } });
34
36
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,6DAA2C;AAC3C,6DAA2C;AAC3C,2DAAyC;AACzC,kDAAgC;AAChC,2DAAyC;AACzC,4DAA0C;AAC1C,6DAA2C;AAC3C,wDAAsC;AACtC,yDAAuC;AACvC,qDAAmC;AACnC,2CAIsB;AAHpB,iIAAA,mCAAmC,OAAA;AACnC,oHAAA,sBAAsB,OAAA;AACtB,iHAAA,mBAAmB,OAAA;AAErB,+DAAoE;AAA3D,kIAAA,0BAA0B,OAAA","sourcesContent":["export * from './AccountTrackerController';\nexport * from './AssetsContractController';\nexport * from './CurrencyRateController';\nexport * from './NftController';\nexport * from './NftDetectionController';\nexport * from './TokenBalancesController';\nexport * from './TokenDetectionController';\nexport * from './TokenListController';\nexport * from './TokenRatesController';\nexport * from './TokensController';\nexport {\n isTokenDetectionSupportedForNetwork,\n formatIconUrlWithProxy,\n getFormattedIpfsUrl,\n} from './assetsUtil';\nexport { codefiTokenPricesServiceV2 } from './token-prices-service';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,6DAA2C;AAC3C,6DAA2C;AAC3C,2DAAyC;AACzC,kDAAgC;AAChC,2DAAyC;AACzC,4DAA0C;AAQ1C,uEAAsE;AAA7D,oIAAA,wBAAwB,OAAA;AACjC,wDAAsC;AACtC,yDAAuC;AACvC,qDAAmC;AACnC,2CAKsB;AAJpB,iIAAA,mCAAmC,OAAA;AACnC,oHAAA,sBAAsB,OAAA;AACtB,iHAAA,mBAAmB,OAAA;AACnB,6HAAA,+BAA+B,OAAA;AAEjC,+DAAoE;AAA3D,kIAAA,0BAA0B,OAAA","sourcesContent":["export * from './AccountTrackerController';\nexport * from './AssetsContractController';\nexport * from './CurrencyRateController';\nexport * from './NftController';\nexport * from './NftDetectionController';\nexport * from './TokenBalancesController';\nexport type {\n TokenDetectionControllerMessenger,\n TokenDetectionControllerActions,\n TokenDetectionControllerGetStateAction,\n TokenDetectionControllerEvents,\n TokenDetectionControllerStateChangeEvent,\n} from './TokenDetectionController';\nexport { TokenDetectionController } from './TokenDetectionController';\nexport * from './TokenListController';\nexport * from './TokenRatesController';\nexport * from './TokensController';\nexport {\n isTokenDetectionSupportedForNetwork,\n formatIconUrlWithProxy,\n getFormattedIpfsUrl,\n fetchTokenContractExchangeRates,\n} from './assetsUtil';\nexport { CodefiTokenPricesServiceV2 } from './token-prices-service';\n"]}
@@ -2,16 +2,16 @@ import type { Hex } from '@metamask/utils';
2
2
  /**
3
3
  * Represents the price of a token in a currency.
4
4
  */
5
- export declare type TokenPrice<TokenContractAddress extends Hex, Currency extends string> = {
6
- tokenContractAddress: TokenContractAddress;
5
+ export declare type TokenPrice<TokenAddress extends Hex, Currency extends string> = {
6
+ tokenAddress: TokenAddress;
7
7
  value: number;
8
8
  currency: Currency;
9
9
  };
10
10
  /**
11
- * A map of token contract address to its price.
11
+ * A map of token address to its price.
12
12
  */
13
- export declare type TokenPricesByTokenContractAddress<TokenContractAddress extends Hex, Currency extends string> = {
14
- [A in TokenContractAddress]: TokenPrice<A, Currency>;
13
+ export declare type TokenPricesByTokenAddress<TokenAddress extends Hex, Currency extends string> = {
14
+ [A in TokenAddress]: TokenPrice<A, Currency>;
15
15
  };
16
16
  /**
17
17
  * An ideal token prices service. All implementations must confirm to this
@@ -19,30 +19,29 @@ export declare type TokenPricesByTokenContractAddress<TokenContractAddress exten
19
19
  *
20
20
  * @template ChainId - A type union of valid arguments for the `chainId`
21
21
  * argument to `fetchTokenPrices`.
22
- * @template TokenContractAddress - A type union of all token contract
23
- * addresses. The reason this type parameter exists is so that we can guarantee
24
- * that same addresses that `fetchTokenPrices` receives are the same addresses
25
- * that shown up in the return value.
22
+ * @template TokenAddress - A type union of all token addresses. The reason this
23
+ * type parameter exists is so that we can guarantee that same addresses that
24
+ * `fetchTokenPrices` receives are the same addresses that shown up in the
25
+ * return value.
26
26
  * @template Currency - A type union of valid arguments for the `currency`
27
27
  * argument to `fetchTokenPrices`.
28
28
  */
29
- export declare type AbstractTokenPricesService<ChainId extends Hex = Hex, TokenContractAddress extends Hex = Hex, Currency extends string = string> = {
29
+ export declare type AbstractTokenPricesService<ChainId extends Hex = Hex, TokenAddress extends Hex = Hex, Currency extends string = string> = {
30
30
  /**
31
31
  * Retrieves prices in the given currency for the tokens identified by the
32
- * given contract addresses which are expected to live on the given chain.
32
+ * given addresses which are expected to live on the given chain.
33
33
  *
34
34
  * @param args - The arguments to this function.
35
35
  * @param args.chainId - An EIP-155 chain ID.
36
- * @param args.tokenContractAddresses - Contract addresses for tokens that
37
- * live on the chain.
36
+ * @param args.tokenAddresses - Addresses for tokens that live on the chain.
38
37
  * @param args.currency - The desired currency of the token prices.
39
38
  * @returns The prices for the requested tokens.
40
39
  */
41
- fetchTokenPrices({ chainId, tokenContractAddresses, currency, }: {
40
+ fetchTokenPrices({ chainId, tokenAddresses, currency, }: {
42
41
  chainId: ChainId;
43
- tokenContractAddresses: TokenContractAddress[];
42
+ tokenAddresses: TokenAddress[];
44
43
  currency: Currency;
45
- }): Promise<TokenPricesByTokenContractAddress<TokenContractAddress, Currency>>;
44
+ }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;
46
45
  /**
47
46
  * Type guard for whether the API can return token prices for the given chain
48
47
  * ID.
@@ -1 +1 @@
1
- {"version":3,"file":"abstract-token-prices-service.d.ts","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C;;GAEG;AACH,oBAAY,UAAU,CACpB,oBAAoB,SAAS,GAAG,EAChC,QAAQ,SAAS,MAAM,IACrB;IACF,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,QAAQ,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,oBAAY,iCAAiC,CAC3C,oBAAoB,SAAS,GAAG,EAChC,QAAQ,SAAS,MAAM,IACrB;KACD,CAAC,IAAI,oBAAoB,GAAG,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC;CACrD,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,oBAAY,0BAA0B,CACpC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,oBAAoB,SAAS,GAAG,GAAG,GAAG,EACtC,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B;IACF;;;;;;;;;;OAUG;IACH,gBAAgB,CAAC,EACf,OAAO,EACP,sBAAsB,EACtB,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,OAAO,CAAC;QACjB,sBAAsB,EAAE,oBAAoB,EAAE,CAAC;QAC/C,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CACT,iCAAiC,CAAC,oBAAoB,EAAE,QAAQ,CAAC,CAClE,CAAC;IAEF;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
1
+ {"version":3,"file":"abstract-token-prices-service.d.ts","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C;;GAEG;AACH,oBAAY,UAAU,CAAC,YAAY,SAAS,GAAG,EAAE,QAAQ,SAAS,MAAM,IAAI;IAC1E,YAAY,EAAE,YAAY,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,QAAQ,CAAC;CACpB,CAAC;AAEF;;GAEG;AACH,oBAAY,yBAAyB,CACnC,YAAY,SAAS,GAAG,EACxB,QAAQ,SAAS,MAAM,IACrB;KACD,CAAC,IAAI,YAAY,GAAG,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,oBAAY,0BAA0B,CACpC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,YAAY,SAAS,GAAG,GAAG,GAAG,EAC9B,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B;IACF;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EACf,OAAO,EACP,cAAc,EACd,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,OAAO,CAAC;QACjB,cAAc,EAAE,YAAY,EAAE,CAAC;QAC/B,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,OAAO,CAAC,yBAAyB,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAExE;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"abstract-token-prices-service.js","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"","sourcesContent":["import type { Hex } from '@metamask/utils';\n\n/**\n * Represents the price of a token in a currency.\n */\nexport type TokenPrice<\n TokenContractAddress extends Hex,\n Currency extends string,\n> = {\n tokenContractAddress: TokenContractAddress;\n value: number;\n currency: Currency;\n};\n\n/**\n * A map of token contract address to its price.\n */\nexport type TokenPricesByTokenContractAddress<\n TokenContractAddress extends Hex,\n Currency extends string,\n> = {\n [A in TokenContractAddress]: TokenPrice<A, Currency>;\n};\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template TokenContractAddress - A type union of all token contract\n * addresses. The reason this type parameter exists is so that we can guarantee\n * that same addresses that `fetchTokenPrices` receives are the same addresses\n * that shown up in the return value.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n TokenContractAddress extends Hex = Hex,\n Currency extends string = string,\n> = {\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given contract addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to this function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenContractAddresses - Contract addresses for tokens that\n * live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n fetchTokenPrices({\n chainId,\n tokenContractAddresses,\n currency,\n }: {\n chainId: ChainId;\n tokenContractAddresses: TokenContractAddress[];\n currency: Currency;\n }): Promise<\n TokenPricesByTokenContractAddress<TokenContractAddress, Currency>\n >;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
1
+ {"version":3,"file":"abstract-token-prices-service.js","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"","sourcesContent":["import type { Hex } from '@metamask/utils';\n\n/**\n * Represents the price of a token in a currency.\n */\nexport type TokenPrice<TokenAddress extends Hex, Currency extends string> = {\n tokenAddress: TokenAddress;\n value: number;\n currency: Currency;\n};\n\n/**\n * A map of token address to its price.\n */\nexport type TokenPricesByTokenAddress<\n TokenAddress extends Hex,\n Currency extends string,\n> = {\n [A in TokenAddress]: TokenPrice<A, Currency>;\n};\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template TokenAddress - A type union of all token addresses. The reason this\n * type parameter exists is so that we can guarantee that same addresses that\n * `fetchTokenPrices` receives are the same addresses that shown up in the\n * return value.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n TokenAddress extends Hex = Hex,\n Currency extends string = string,\n> = {\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to this function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: ChainId;\n tokenAddresses: TokenAddress[];\n currency: Currency;\n }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { Hex } from '@metamask/utils';
2
- import type { AbstractTokenPricesService } from './abstract-token-prices-service';
2
+ import type { AbstractTokenPricesService, TokenPricesByTokenAddress } from './abstract-token-prices-service';
3
3
  /**
4
4
  * The list of currencies that can be supplied as the `vsCurrency` parameter to
5
5
  * the `/spot-prices` endpoint, in lowercase form.
@@ -15,7 +15,7 @@ declare type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number] | Upperca
15
15
  * endpoint, but in hexadecimal form (for consistency with how we represent
16
16
  * chain IDs in other places).
17
17
  */
18
- export declare const SUPPORTED_CHAIN_IDS: readonly ["0x1", "0xa", "0x19", "0x38", "0x39", "0x42", "0x46", "0x52", "0x58", "0x64", "0x6a", "0x7a", "0x80", "0x89", "0xfa", "0x120", "0x141", "0x144", "0x169", "0x440", "0x504", "0x505", "0x2105", "0x2107", "0x2710", "0xa4b1", "0xa4ec", "0xa516", "0xa86a", "0x518af", "0x4e454152", "0x63564c40"];
18
+ export declare const SUPPORTED_CHAIN_IDS: readonly ["0x1", "0xa", "0x19", "0x38", "0x39", "0x42", "0x46", "0x52", "0x58", "0x64", "0x6a", "0x7a", "0x80", "0x89", "0xfa", "0x120", "0x141", "0x144", "0x169", "0x440", "0x504", "0x505", "0x2105", "0x150", "0x2710", "0xa4b1", "0xa4ec", "0xa516", "0xa86a", "0x518af", "0x4e454152", "0x63564c40"];
19
19
  /**
20
20
  * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,
21
21
  * but in hexadecimal form (for consistency with how we represent chain IDs in
@@ -26,6 +26,64 @@ declare type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
26
26
  * This version of the token prices service uses V2 of the Codefi Price API to
27
27
  * fetch token prices.
28
28
  */
29
- export declare const codefiTokenPricesServiceV2: AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>;
29
+ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency> {
30
+ #private;
31
+ /**
32
+ * Construct a Codefi Token Price Service.
33
+ *
34
+ * @param options - Constructor options
35
+ * @param options.degradedThreshold - The threshold between "normal" and "degrated" service,
36
+ * in milliseconds.
37
+ * @param options.retries - Number of retry attempts for each token price update.
38
+ * @param options.maximumConsecutiveFailures - The maximum number of consecutive failures
39
+ * allowed before breaking the circuit and pausing further updates.
40
+ * @param options.onBreak - An event handler for when the circuit breaks, useful for capturing
41
+ * metrics about network failures.
42
+ * @param options.onDegraded - An event handler for when the circuit remains closed, but requests
43
+ * are failing or resolving too slowly (i.e. resolving more slowly than the `degradedThreshold).
44
+ * @param options.circuitBreakDuration - The amount of time to wait when the circuit breaks
45
+ * from too many consecutive failures.
46
+ */
47
+ constructor({ degradedThreshold, retries, maximumConsecutiveFailures, onBreak, onDegraded, circuitBreakDuration, }?: {
48
+ degradedThreshold?: number;
49
+ retries?: number;
50
+ maximumConsecutiveFailures?: number;
51
+ onBreak?: () => void;
52
+ onDegraded?: () => void;
53
+ circuitBreakDuration?: number;
54
+ });
55
+ /**
56
+ * Retrieves prices in the given currency for the tokens identified by the
57
+ * given addresses which are expected to live on the given chain.
58
+ *
59
+ * @param args - The arguments to function.
60
+ * @param args.chainId - An EIP-155 chain ID.
61
+ * @param args.tokenAddresses - Addresses for tokens that live on the chain.
62
+ * @param args.currency - The desired currency of the token prices.
63
+ * @returns The prices for the requested tokens.
64
+ */
65
+ fetchTokenPrices({ chainId, tokenAddresses, currency, }: {
66
+ chainId: SupportedChainId;
67
+ tokenAddresses: Hex[];
68
+ currency: SupportedCurrency;
69
+ }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>>;
70
+ /**
71
+ * Type guard for whether the API can return token prices for the given chain
72
+ * ID.
73
+ *
74
+ * @param chainId - The chain ID to check.
75
+ * @returns True if the API supports the chain ID, false otherwise.
76
+ */
77
+ validateChainIdSupported(chainId: unknown): chainId is SupportedChainId;
78
+ /**
79
+ * Type guard for whether the API can return token prices in the given
80
+ * currency.
81
+ *
82
+ * @param currency - The currency to check. If a string, can be either
83
+ * lowercase or uppercase.
84
+ * @returns True if the API supports the currency, false otherwise.
85
+ */
86
+ validateCurrencySupported(currency: unknown): currency is SupportedCurrency;
87
+ }
30
88
  export {};
31
89
  //# sourceMappingURL=codefi-v2.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"codefi-v2.d.ts","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAG3C,OAAO,KAAK,EACV,0BAA0B,EAG3B,MAAM,iCAAiC,CAAC;AAUzC;;;GAGG;AACH,eAAO,MAAM,oBAAoB,ybA2HvB,CAAC;AAEX;;;GAGG;AACH,aAAK,iBAAiB,GAClB,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,GACrC,SAAS,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AAErD;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,6SAkEtB,CAAC;AAEX;;;;GAIG;AACH,aAAK,gBAAgB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAO7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,EAAE,0BAA0B,CACjE,gBA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