@metamask/assets-controllers 90.0.0 → 91.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +12 -1
  2. package/dist/CurrencyRateController.cjs +3 -3
  3. package/dist/CurrencyRateController.cjs.map +1 -1
  4. package/dist/CurrencyRateController.d.cts.map +1 -1
  5. package/dist/CurrencyRateController.d.mts.map +1 -1
  6. package/dist/CurrencyRateController.mjs +3 -3
  7. package/dist/CurrencyRateController.mjs.map +1 -1
  8. package/dist/TokenRatesController.cjs +82 -278
  9. package/dist/TokenRatesController.cjs.map +1 -1
  10. package/dist/TokenRatesController.d.cts +9 -35
  11. package/dist/TokenRatesController.d.cts.map +1 -1
  12. package/dist/TokenRatesController.d.mts +9 -35
  13. package/dist/TokenRatesController.d.mts.map +1 -1
  14. package/dist/TokenRatesController.mjs +83 -279
  15. package/dist/TokenRatesController.mjs.map +1 -1
  16. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs +2 -3
  17. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs.map +1 -1
  18. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.cts.map +1 -1
  19. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.d.mts.map +1 -1
  20. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs +2 -3
  21. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.mjs.map +1 -1
  22. package/dist/TokenSearchDiscoveryDataController/types.cjs.map +1 -1
  23. package/dist/TokenSearchDiscoveryDataController/types.d.cts +2 -2
  24. package/dist/TokenSearchDiscoveryDataController/types.d.cts.map +1 -1
  25. package/dist/TokenSearchDiscoveryDataController/types.d.mts +2 -2
  26. package/dist/TokenSearchDiscoveryDataController/types.d.mts.map +1 -1
  27. package/dist/TokenSearchDiscoveryDataController/types.mjs.map +1 -1
  28. package/dist/assetsUtil.cjs +11 -5
  29. package/dist/assetsUtil.cjs.map +1 -1
  30. package/dist/assetsUtil.d.cts +2 -2
  31. package/dist/assetsUtil.d.cts.map +1 -1
  32. package/dist/assetsUtil.d.mts +2 -2
  33. package/dist/assetsUtil.d.mts.map +1 -1
  34. package/dist/assetsUtil.mjs +11 -5
  35. package/dist/assetsUtil.mjs.map +1 -1
  36. package/dist/token-prices-service/abstract-token-prices-service.cjs.map +1 -1
  37. package/dist/token-prices-service/abstract-token-prices-service.d.cts +17 -43
  38. package/dist/token-prices-service/abstract-token-prices-service.d.cts.map +1 -1
  39. package/dist/token-prices-service/abstract-token-prices-service.d.mts +17 -43
  40. package/dist/token-prices-service/abstract-token-prices-service.d.mts.map +1 -1
  41. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -1
  42. package/dist/token-prices-service/codefi-v2.cjs +175 -109
  43. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  44. package/dist/token-prices-service/codefi-v2.d.cts +47 -10
  45. package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
  46. package/dist/token-prices-service/codefi-v2.d.mts +47 -10
  47. package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
  48. package/dist/token-prices-service/codefi-v2.mjs +175 -109
  49. package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
  50. package/package.json +1 -1
@@ -1,11 +1,11 @@
1
1
  import type { ServicePolicy } from "@metamask/controller-utils";
2
2
  import type { Hex } from "@metamask/utils";
3
- import type { AbstractTokenPricesService, ExchangeRatesByCurrency, TokenPricesByTokenAddress } from "./abstract-token-prices-service.mjs";
3
+ import type { AbstractTokenPricesService, EvmAssetAddressWithChain, EvmAssetWithMarketData, ExchangeRatesByCurrency } from "./abstract-token-prices-service.mjs";
4
4
  /**
5
5
  * The list of currencies that can be supplied as the `vsCurrency` parameter to
6
6
  * the `/spot-prices` endpoint, in lowercase form.
7
7
  */
8
- export declare const SUPPORTED_CURRENCIES: readonly ["btc", "eth", "ltc", "bch", "bnb", "eos", "xrp", "xlm", "link", "dot", "yfi", "usd", "aed", "ars", "aud", "bdt", "bhd", "bmd", "brl", "cad", "chf", "clp", "cny", "czk", "dkk", "eur", "gbp", "hkd", "huf", "idr", "ils", "inr", "jpy", "krw", "kwd", "lkr", "mmk", "mxn", "myr", "ngn", "nok", "nzd", "php", "pkr", "pln", "rub", "sar", "sek", "sgd", "thb", "try", "twd", "uah", "vef", "vnd", "zar", "xdr", "xag", "xau", "bits", "sats"];
8
+ export declare const SUPPORTED_CURRENCIES: readonly ["btc", "eth", "ltc", "bch", "bnb", "eos", "xrp", "xlm", "link", "dot", "yfi", "usd", "aed", "ars", "aud", "bdt", "bhd", "bmd", "brl", "cad", "chf", "clp", "cny", "czk", "dkk", "eur", "gbp", "gel", "hkd", "huf", "idr", "ils", "inr", "jpy", "krw", "kwd", "lkr", "mmk", "mxn", "myr", "ngn", "nok", "nzd", "php", "pkr", "pln", "rub", "sar", "sek", "sgd", "thb", "try", "twd", "uah", "vef", "vnd", "zar", "xdr", "xag", "xau", "bits", "sats", "cop", "kes", "ron", "dop", "crc", "hnl", "zmw", "svc", "bam", "pen", "gtq", "lbp", "amd", "sol", "sei", "sonic", "trx", "taiko", "pepu", "pol", "mnt", "nom", "avax"];
9
9
  /**
10
10
  * Represents the zero address, commonly used as a placeholder in blockchain transactions.
11
11
  * In the context of fetching market data, the zero address is utilized to retrieve information
@@ -22,6 +22,45 @@ export declare const ZERO_ADDRESS: Hex;
22
22
  * @returns The address of the chain's native token.
23
23
  */
24
24
  export declare const getNativeTokenAddress: (chainId: Hex) => Hex;
25
+ export declare const SPOT_PRICES_SUPPORT_INFO: {
26
+ readonly '0x1': "eip155:1/slip44:60";
27
+ readonly '0xa': "eip155:10/slip44:60";
28
+ readonly '0x19': "eip155:25/slip44:394";
29
+ readonly '0x38': "eip155:56/slip44:714";
30
+ readonly '0x39': "eip155:57/erc20:0x0000000000000000000000000000000000000000";
31
+ readonly '0x52': null;
32
+ readonly '0x58': "eip155:88/erc20:0x0000000000000000000000000000000000000000";
33
+ readonly '0x64': "eip155:100/slip44:700";
34
+ readonly '0x6a': "eip155:106/erc20:0x0000000000000000000000000000000000000000";
35
+ readonly '0x80': "eip155:128/erc20:0x0000000000000000000000000000000000000000";
36
+ readonly '0x89': "eip155:137/slip44:966";
37
+ readonly '0x8f': null;
38
+ readonly '0x92': "eip155:146/slip44:10007";
39
+ readonly '0xfa': "eip155:250/slip44:1007";
40
+ readonly '0x141': "eip155:321/erc20:0x0000000000000000000000000000000000000000";
41
+ readonly '0x144': "eip155:324/slip44:60";
42
+ readonly '0x169': "eip155:361/erc20:0x0000000000000000000000000000000000000000";
43
+ readonly '0x3e7': "eip155:999/slip44:2457";
44
+ readonly '0x440': "eip155:1088/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000";
45
+ readonly '0x44d': "eip155:1101/slip44:60";
46
+ readonly '0x504': "eip155:1284/slip44:1284";
47
+ readonly '0x505': "eip155:1285/slip44:1285";
48
+ readonly '0x531': "eip155:1329/slip44:19000118";
49
+ readonly '0x1388': "eip155:5000/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000";
50
+ readonly '0x2105': "eip155:8453/slip44:60";
51
+ readonly '0x2710': "eip155:10000/erc20:0x0000000000000000000000000000000000000000";
52
+ readonly '0xa4b1': "eip155:42161/slip44:60";
53
+ readonly '0xa4ec': "eip155:42220/slip44:52752";
54
+ readonly '0xa516': "eip155:42262/erc20:0x0000000000000000000000000000000000000000";
55
+ readonly '0xa86a': "eip155:43114/slip44:9005";
56
+ readonly '0xe708': "eip155:59144/slip44:60";
57
+ readonly '0x13c31': "eip155:81457/erc20:0x0000000000000000000000000000000000000000";
58
+ readonly '0x17dcd': "eip155:97741/erc20:0x0000000000000000000000000000000000000000";
59
+ readonly '0x518af': null;
60
+ readonly '0x82750': "eip155:534352/slip44:60";
61
+ readonly '0x4e454152': "eip155:60/slip44:60";
62
+ readonly '0x63564c40': "eip155:1666600000/slip44:1023";
63
+ };
25
64
  /**
26
65
  * A currency that can be supplied as the `vsCurrency` parameter to
27
66
  * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.
@@ -34,7 +73,7 @@ type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number] | Uppercase<(type
34
73
  *
35
74
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
36
75
  */
37
- 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", "0x1388", "0x2105", "0x150", "0x2710", "0xa4b1", "0xa4ec", "0xa516", "0xa86a", "0x518af", "0x4e454152", "0x63564c40", "0xe708", "0x531", "0x92", "0x8f"];
76
+ export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" | "0xa" | "0xa4b1" | "0x82750" | "0x531" | "0x8f" | "0xe708" | "0x440" | "0x1388" | "0x19" | "0x39" | "0x52" | "0x58" | "0x64" | "0x6a" | "0x80" | "0x92" | "0xfa" | "0x141" | "0x144" | "0x169" | "0x3e7" | "0x44d" | "0x504" | "0x505" | "0x2710" | "0xa4ec" | "0xa516" | "0xa86a" | "0x13c31" | "0x17dcd" | "0x518af" | "0x4e454152" | "0x63564c40")[];
38
77
  /**
39
78
  * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,
40
79
  * but in hexadecimal form (for consistency with how we represent chain IDs in
@@ -45,7 +84,7 @@ type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
45
84
  * This version of the token prices service uses V2 of the Codefi Price API to
46
85
  * fetch token prices.
47
86
  */
48
- export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency> {
87
+ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesService<SupportedChainId, SupportedCurrency> {
49
88
  #private;
50
89
  /**
51
90
  * Construct a Codefi Token Price Service.
@@ -114,16 +153,14 @@ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesSe
114
153
  * given addresses which are expected to live on the given chain.
115
154
  *
116
155
  * @param args - The arguments to function.
117
- * @param args.chainId - An EIP-155 chain ID.
118
- * @param args.tokenAddresses - Addresses for tokens that live on the chain.
156
+ * @param args.assets - The assets to get prices for.
119
157
  * @param args.currency - The desired currency of the token prices.
120
158
  * @returns The prices for the requested tokens.
121
159
  */
122
- fetchTokenPrices({ chainId, tokenAddresses, currency, }: {
123
- chainId: SupportedChainId;
124
- tokenAddresses: Hex[];
160
+ fetchTokenPrices({ assets, currency, }: {
161
+ assets: EvmAssetAddressWithChain<SupportedChainId>[];
125
162
  currency: SupportedCurrency;
126
- }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>>;
163
+ }): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]>;
127
164
  /**
128
165
  * Retrieves exchange rates in the given base currency.
129
166
  *
@@ -1 +1 @@
1
- {"version":3,"file":"codefi-v2.d.mts","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EACV,0BAA0B,EAC1B,uBAAuB,EAEvB,yBAAyB,EAC1B,4CAAwC;AAEzC;;;GAGG;AACH,eAAO,MAAM,oBAAoB,ybA2HvB,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,GAC4B,CAAC;AAUxD;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,YAAa,GAAG,KAAG,GACC,CAAC;AAEvD;;;GAGG;AACH,KAAK,iBAAiB,GAClB,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,GACrC,SAAS,CAA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AAE;QACD,YAAY,EAAE,iBAAiB,CAAC;QAChC,cAAc,EAAE,OAAO,CAAC;QACxB,gBAAgB,EAAE,MAAM,EAAE,CAAC;KAC5B,GAAG,OAAO,CAAC,uBAAuB,CAAC,iBAAiB,CAAC,CAAC;IAqFvD;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,gBAAgB;IAKvE;;;;;;;OAOG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,iBAAiB;CAO5E"}
@@ -9,9 +9,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _CodefiTokenPricesServiceV2_policy;
12
+ var _CodefiTokenPricesServiceV2_instances, _CodefiTokenPricesServiceV2_policy, _CodefiTokenPricesServiceV2_fetchTokenPricesV3, _CodefiTokenPricesServiceV2_fetchTokenPricesV2;
13
13
  import { createServicePolicy, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, handleFetch } from "@metamask/controller-utils";
14
- import { hexToNumber } from "@metamask/utils";
14
+ import { hexToNumber, KnownCaipNamespace, toCaipChainId } from "@metamask/utils";
15
15
  /**
16
16
  * The list of currencies that can be supplied as the `vsCurrency` parameter to
17
17
  * the `/spot-prices` endpoint, in lowercase form.
@@ -71,6 +71,8 @@ export const SUPPORTED_CURRENCIES = [
71
71
  'eur',
72
72
  // British Pound Sterling
73
73
  'gbp',
74
+ // Georgian Lari
75
+ 'gel',
74
76
  // Hong Kong Dollar
75
77
  'hkd',
76
78
  // Hungarian Forint
@@ -139,6 +141,52 @@ export const SUPPORTED_CURRENCIES = [
139
141
  'bits',
140
142
  // Satoshi
141
143
  'sats',
144
+ // Colombian Peso
145
+ 'cop',
146
+ // Kenyan Shilling
147
+ 'kes',
148
+ // Romanian Leu
149
+ 'ron',
150
+ // Dominican Peso
151
+ 'dop',
152
+ // Costa Rican Colón
153
+ 'crc',
154
+ // Honduran Lempira
155
+ 'hnl',
156
+ // Zambian Kwacha
157
+ 'zmw',
158
+ // Salvadoran Colón
159
+ 'svc',
160
+ // Bosnia-Herzegovina Convertible Mark
161
+ 'bam',
162
+ // Peruvian Sol
163
+ 'pen',
164
+ // Guatemalan Quetzal
165
+ 'gtq',
166
+ // Lebanese Pound
167
+ 'lbp',
168
+ // Armenian Dram
169
+ 'amd',
170
+ // Solana
171
+ 'sol',
172
+ // Sei
173
+ 'sei',
174
+ // Sonic
175
+ 'sonic',
176
+ // Tron
177
+ 'trx',
178
+ // Taiko
179
+ 'taiko',
180
+ // Pepu
181
+ 'pepu',
182
+ // Polygon
183
+ 'pol',
184
+ // Mantle
185
+ 'mnt',
186
+ // Onomy
187
+ 'nom',
188
+ // Avalanche
189
+ 'avax',
142
190
  ];
143
191
  /**
144
192
  * Represents the zero address, commonly used as a placeholder in blockchain transactions.
@@ -152,7 +200,9 @@ export const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
152
200
  * Only for chains whose native tokens have a specific address.
153
201
  */
154
202
  const chainIdToNativeTokenAddress = {
155
- '0x89': '0x0000000000000000000000000000000000001010',
203
+ '0x89': '0x0000000000000000000000000000000000001010', // Polygon
204
+ '0x440': '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Metis Andromeda
205
+ '0x1388': '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Mantle
156
206
  };
157
207
  /**
158
208
  * Returns the address that should be used to query the price api for the
@@ -163,6 +213,47 @@ const chainIdToNativeTokenAddress = {
163
213
  * @returns The address of the chain's native token.
164
214
  */
165
215
  export const getNativeTokenAddress = (chainId) => chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;
216
+ // Source: https://github.com/consensys-vertical-apps/va-mmcx-price-api/blob/main/src/constants/slip44.ts
217
+ // We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.
218
+ export const SPOT_PRICES_SUPPORT_INFO = {
219
+ '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH
220
+ '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH
221
+ '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO
222
+ '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB
223
+ '0x39': 'eip155:57/erc20:0x0000000000000000000000000000000000000000', // 'eip155:57/slip44:57', // Syscoin Mainnet - Native symbol: SYS
224
+ '0x52': null, // 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR
225
+ '0x58': 'eip155:88/erc20:0x0000000000000000000000000000000000000000', // 'eip155:88/slip44:889', // TomoChain - Native symbol: TOMO
226
+ '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI
227
+ '0x6a': 'eip155:106/erc20:0x0000000000000000000000000000000000000000', // 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX
228
+ '0x80': 'eip155:128/erc20:0x0000000000000000000000000000000000000000', // 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT
229
+ '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL
230
+ '0x8f': null, // 'eip155:143/slip44:268435779', // Monad Mainnet - Native symbol: MON
231
+ '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S
232
+ '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM
233
+ '0x141': 'eip155:321/erc20:0x0000000000000000000000000000000000000000', // 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS
234
+ '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH
235
+ '0x169': 'eip155:361/erc20:0x0000000000000000000000000000000000000000', // 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL
236
+ '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH
237
+ '0x440': 'eip155:1088/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 'eip155:1088/slip44:XXX', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: METIS
238
+ '0x44d': 'eip155:1101/slip44:60', // Polygon zkEVM mainnet - Native symbol: ETH
239
+ '0x504': 'eip155:1284/slip44:1284', // Moonbeam - Native symbol: GLMR
240
+ '0x505': 'eip155:1285/slip44:1285', // Moonriver - Native symbol: MOVR
241
+ '0x531': 'eip155:1329/slip44:19000118', // Sei Mainnet - Native symbol: SEI
242
+ '0x1388': 'eip155:5000/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 'eip155:5000/slip44:XXX', // Mantle - Native symbol: MNT
243
+ '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH
244
+ '0x2710': 'eip155:10000/erc20:0x0000000000000000000000000000000000000000', // 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH
245
+ '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH
246
+ '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO
247
+ '0xa516': 'eip155:42262/erc20:0x0000000000000000000000000000000000000000', // 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE
248
+ '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX
249
+ '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH
250
+ '0x13c31': 'eip155:81457/erc20:0x0000000000000000000000000000000000000000', // 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH
251
+ '0x17dcd': 'eip155:97741/erc20:0x0000000000000000000000000000000000000000', // 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU
252
+ '0x518af': null, // 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS
253
+ '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH
254
+ '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH
255
+ '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE
256
+ };
166
257
  /**
167
258
  * The list of chain IDs that can be supplied in the URL for the `/spot-prices`
168
259
  * endpoint, but in hexadecimal form (for consistency with how we represent
@@ -170,93 +261,22 @@ export const getNativeTokenAddress = (chainId) => chainIdToNativeTokenAddress[ch
170
261
  *
171
262
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
172
263
  */
173
- export const SUPPORTED_CHAIN_IDS = [
174
- // Ethereum Mainnet
175
- '0x1',
176
- // OP Mainnet
177
- '0xa',
178
- // Cronos Mainnet
179
- '0x19',
180
- // BNB Smart Chain Mainnet
181
- '0x38',
182
- // Syscoin Mainnet
183
- '0x39',
184
- // OKXChain Mainnet
185
- '0x42',
186
- // Hoo Smart Chain
187
- '0x46',
188
- // Meter Mainnet
189
- '0x52',
190
- // TomoChain
191
- '0x58',
192
- // Gnosis
193
- '0x64',
194
- // Velas EVM Mainnet
195
- '0x6a',
196
- // Fuse Mainnet
197
- '0x7a',
198
- // Huobi ECO Chain Mainnet
199
- '0x80',
200
- // Polygon Mainnet
201
- '0x89',
202
- // Fantom Opera
203
- '0xfa',
204
- // Boba Network
205
- '0x120',
206
- // KCC Mainnet
207
- '0x141',
208
- // zkSync Era Mainnet
209
- '0x144',
210
- // Theta Mainnet
211
- '0x169',
212
- // Metis Andromeda Mainnet
213
- '0x440',
214
- // Moonbeam
215
- '0x504',
216
- // Moonriver
217
- '0x505',
218
- // Mantle
219
- '0x1388',
220
- // Base
221
- '0x2105',
222
- // Shiden
223
- '0x150',
224
- // Smart Bitcoin Cash
225
- '0x2710',
226
- // Arbitrum One
227
- '0xa4b1',
228
- // Celo Mainnet
229
- '0xa4ec',
230
- // Oasis Emerald
231
- '0xa516',
232
- // Avalanche C-Chain
233
- '0xa86a',
234
- // Polis Mainnet
235
- '0x518af',
236
- // Aurora Mainnet
237
- '0x4e454152',
238
- // Harmony Mainnet Shard 0
239
- '0x63564c40',
240
- // Linea Mainnet
241
- '0xe708',
242
- // Sei Mainnet
243
- '0x531',
244
- // Sonic Mainnet
245
- '0x92',
246
- // Monad Mainnet
247
- '0x8f',
248
- ];
264
+ export const SUPPORTED_CHAIN_IDS = Object.keys(SPOT_PRICES_SUPPORT_INFO);
249
265
  /**
250
- * All requests to V2 of the Price API start with this.
266
+ * The list of chain IDs that are supported by V3 of the Codefi Price API.
267
+ * Only includes chain IDs from SPOT_PRICES_SUPPORT_INFO that have a non-null CAIP-19 value.
251
268
  */
252
- const BASE_URL = 'https://price.api.cx.metamask.io/v2';
269
+ const SUPPORTED_CHAIN_IDS_V3 = Object.keys(SPOT_PRICES_SUPPORT_INFO).filter((chainId) => SPOT_PRICES_SUPPORT_INFO[chainId] !== null);
253
270
  const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
271
+ const BASE_URL_V2 = 'https://price.api.cx.metamask.io/v2';
272
+ const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
254
273
  /**
255
274
  * This version of the token prices service uses V2 of the Codefi Price API to
256
275
  * fetch token prices.
257
276
  */
258
277
  export class CodefiTokenPricesServiceV2 {
259
278
  constructor({ degradedThreshold = DEFAULT_DEGRADED_THRESHOLD, retries = DEFAULT_MAX_RETRIES, maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES, onBreak, onDegraded, circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION, } = {}) {
279
+ _CodefiTokenPricesServiceV2_instances.add(this);
260
280
  _CodefiTokenPricesServiceV2_policy.set(this, void 0);
261
281
  __classPrivateFieldSet(this, _CodefiTokenPricesServiceV2_policy, createServicePolicy({
262
282
  maxRetries: retries,
@@ -296,36 +316,14 @@ export class CodefiTokenPricesServiceV2 {
296
316
  * given addresses which are expected to live on the given chain.
297
317
  *
298
318
  * @param args - The arguments to function.
299
- * @param args.chainId - An EIP-155 chain ID.
300
- * @param args.tokenAddresses - Addresses for tokens that live on the chain.
319
+ * @param args.assets - The assets to get prices for.
301
320
  * @param args.currency - The desired currency of the token prices.
302
321
  * @returns The prices for the requested tokens.
303
322
  */
304
- async fetchTokenPrices({ chainId, tokenAddresses, currency, }) {
305
- const chainIdAsNumber = hexToNumber(chainId);
306
- const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);
307
- url.searchParams.append('tokenAddresses', [getNativeTokenAddress(chainId), ...tokenAddresses].join(','));
308
- url.searchParams.append('vsCurrency', currency);
309
- url.searchParams.append('includeMarketData', 'true');
310
- const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }));
311
- return [getNativeTokenAddress(chainId), ...tokenAddresses].reduce((obj, tokenAddress) => {
312
- // The Price API lowercases both currency and token addresses, so we have
313
- // to keep track of them and make sure we return the original versions.
314
- const lowercasedTokenAddress = tokenAddress.toLowerCase();
315
- const marketData = addressCryptoDataMap[lowercasedTokenAddress];
316
- if (!marketData) {
317
- return obj;
318
- }
319
- const token = {
320
- tokenAddress,
321
- currency,
322
- ...marketData,
323
- };
324
- return {
325
- ...obj,
326
- [tokenAddress]: token,
327
- };
328
- }, {});
323
+ async fetchTokenPrices({ assets, currency, }) {
324
+ const v3Assets = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_instances, "m", _CodefiTokenPricesServiceV2_fetchTokenPricesV3).call(this, assets, currency);
325
+ const v2Assets = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_instances, "m", _CodefiTokenPricesServiceV2_fetchTokenPricesV2).call(this, assets, currency);
326
+ return [...v3Assets, ...v2Assets];
329
327
  }
330
328
  /**
331
329
  * Retrieves exchange rates in the given base currency.
@@ -426,5 +424,73 @@ export class CodefiTokenPricesServiceV2 {
426
424
  supportedCurrencies.includes(currency.toLowerCase()));
427
425
  }
428
426
  }
429
- _CodefiTokenPricesServiceV2_policy = new WeakMap();
427
+ _CodefiTokenPricesServiceV2_policy = new WeakMap(), _CodefiTokenPricesServiceV2_instances = new WeakSet(), _CodefiTokenPricesServiceV2_fetchTokenPricesV3 = async function _CodefiTokenPricesServiceV2_fetchTokenPricesV3(assets, currency) {
428
+ const assetsWithIds = assets
429
+ // Filter out assets that are not supported by V3 of the Price API.
430
+ .filter((asset) => SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId))
431
+ .map((asset) => {
432
+ const caipChainId = toCaipChainId(KnownCaipNamespace.Eip155, hexToNumber(asset.chainId).toString());
433
+ const nativeAddress = getNativeTokenAddress(asset.chainId);
434
+ return {
435
+ ...asset,
436
+ assetId: (nativeAddress.toLowerCase() ===
437
+ asset.tokenAddress.toLowerCase()
438
+ ? SPOT_PRICES_SUPPORT_INFO[asset.chainId]
439
+ : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`),
440
+ };
441
+ })
442
+ .filter((asset) => asset.assetId);
443
+ if (assetsWithIds.length === 0) {
444
+ return [];
445
+ }
446
+ const url = new URL(`${BASE_URL_V3}/spot-prices`);
447
+ url.searchParams.append('assetIds', assetsWithIds.map((asset) => asset.assetId).join(','));
448
+ url.searchParams.append('vsCurrency', currency);
449
+ url.searchParams.append('includeMarketData', 'true');
450
+ const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }));
451
+ return assetsWithIds
452
+ .map((assetWithId) => {
453
+ const marketData = addressCryptoDataMap[assetWithId.assetId];
454
+ if (!marketData) {
455
+ return undefined;
456
+ }
457
+ return {
458
+ ...marketData,
459
+ ...assetWithId,
460
+ currency,
461
+ };
462
+ })
463
+ .filter((entry) => Boolean(entry));
464
+ }, _CodefiTokenPricesServiceV2_fetchTokenPricesV2 = async function _CodefiTokenPricesServiceV2_fetchTokenPricesV2(assets, currency) {
465
+ const v2SupportedAssets = assets.filter((asset) => !SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId));
466
+ const assetsByChainId = v2SupportedAssets.reduce((acc, { chainId, tokenAddress }) => {
467
+ (acc[chainId] ?? (acc[chainId] = [])).push(tokenAddress);
468
+ return acc;
469
+ }, {});
470
+ const promises = Object.entries(assetsByChainId).map(async ([chainId, tokenAddresses]) => {
471
+ if (tokenAddresses.length === 0) {
472
+ return [];
473
+ }
474
+ const url = new URL(`${BASE_URL_V2}/chains/${chainId}/spot-prices`);
475
+ url.searchParams.append('tokenAddresses', tokenAddresses.join(','));
476
+ url.searchParams.append('vsCurrency', currency);
477
+ url.searchParams.append('includeMarketData', 'true');
478
+ const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }));
479
+ return tokenAddresses
480
+ .map((tokenAddress) => {
481
+ const marketData = addressCryptoDataMap[tokenAddress.toLowerCase()];
482
+ if (!marketData) {
483
+ return undefined;
484
+ }
485
+ return {
486
+ ...marketData,
487
+ tokenAddress,
488
+ chainId: chainId,
489
+ currency,
490
+ };
491
+ })
492
+ .filter((entry) => Boolean(entry));
493
+ });
494
+ return await Promise.allSettled(promises).then((results) => results.flatMap((result) => result.status === 'fulfilled' ? result.value : []));
495
+ };
430
496
  //# sourceMappingURL=codefi-v2.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"codefi-v2.mjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,mBAAmB,EACnB,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,WAAW,EAC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EFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n ExchangeRatesByCurrency,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n *\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n *\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Mantle\n '0x1388',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n // Sei Mainnet\n '0x531',\n // Sonic Mainnet\n '0x92',\n // Monad Mainnet\n '0x8f',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\nconst BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\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 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 async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [getNativeTokenAddress(chainId), ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [getNativeTokenAddress(chainId), ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (!marketData) {\n return obj;\n }\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Retrieves exchange rates in the given base currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired base currency of the exchange rates.\n * @param args.includeUsdRate - Whether to include the USD rate in the response.\n * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.\n * @returns The exchange rates for the requested base currency.\n */\n async fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: SupportedCurrency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<SupportedCurrency>> {\n const url = new URL(`${BASE_URL_V1}/exchange-rates`);\n url.searchParams.append('baseCurrency', baseCurrency);\n\n const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);\n urlUsd.searchParams.append('baseCurrency', 'usd');\n\n const [exchangeRatesResult, exchangeRatesResultUsd] =\n await Promise.allSettled([\n this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n ),\n ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'\n ? [\n this.#policy.execute(() =>\n handleFetch(urlUsd, {\n headers: { 'Cache-Control': 'no-cache' },\n }),\n ),\n ]\n : []),\n ]);\n\n // Handle resolved/rejected\n const exchangeRates =\n exchangeRatesResult.status === 'fulfilled'\n ? exchangeRatesResult.value\n : {};\n const exchangeRatesUsd =\n exchangeRatesResultUsd?.status === 'fulfilled'\n ? exchangeRatesResultUsd.value\n : {};\n\n if (exchangeRatesResult.status === 'rejected') {\n throw new Error('Failed to fetch');\n }\n\n const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRates[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRates[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (Object.keys(filteredExchangeRates).length === 0) {\n throw new Error(\n 'None of the cryptocurrencies are supported by price api',\n );\n }\n\n const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRatesUsd[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRatesUsd[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (baseCurrency.toLowerCase() === 'usd') {\n Object.keys(filteredExchangeRates).forEach((key) => {\n filteredExchangeRates[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n usd: filteredExchangeRates[key as SupportedCurrency]?.value,\n };\n });\n return filteredExchangeRates;\n }\n if (!includeUsdRate) {\n return filteredExchangeRates;\n }\n\n const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {\n acc[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n ...(filteredUsdExchangeRates[key as SupportedCurrency]?.value\n ? { usd: filteredUsdExchangeRates[key as SupportedCurrency]?.value }\n : {}),\n };\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n return merged;\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 SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\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. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
1
+ {"version":3,"file":"codefi-v2.mjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,mBAAmB,EACnB,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,WAAW,EACZ,mCAAmC;AAGpC,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,aAAa,EACd,wBAAwB;AAWzB;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,UAAU;IACV,KAAK;IACL,QAAQ;IACR,KAAK;IACL,WAAW;IACX,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,SAAS;IACT,KAAK;IACL,YAAY;IACZ,MAAM;IACN,WAAW;IACX,KAAK;IACL,gBAAgB;IAChB,KAAK;IACL,YAAY;IACZ,KAAK;IACL,8BAA8B;IAC9B,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,oBAAoB;IACpB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,cAAc;IACd,KAAK;IACL,kBAAkB;IAClB,KAAK;IACL,cAAc;IACd,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,OAAO;IACP,KAAK;IACL,yBAAyB;IACzB,KAAK;IACL,gBAAgB;IAChB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,oBAAoB;IACpB,KAAK;IACL,qBAAqB;IACrB,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,gBAAgB;IAChB,KAAK;IACL,mBAAmB;IACn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AAM,CAAC,mBAAmB,EAAE,MAAM,CAAC,CAAC;QAErD,MAAM,oBAAoB,GAKtB,MAAM,uBAAA,IAAI,0CAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,CAClC,WAAW,CAAC,GAAG,EAAE,EAAE,OAAO,EAAE,EAAE,eAAe,EAAE,UAAU,EAAE,EAAE,CAAC,CAC/D,CAAC;QAEF,OAAO,cAAc;aAClB,GAAG,CAAC,CAAC,YAAY,EAAE,EAAE;YACpB,MAAM,UAAU,GAAG,oBAAoB,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC;YAEpE,IAAI,CAAC,UAAU,EAAE,CAAC;gBAChB,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,OAAO;gBACL,GAAG,UAAU;gBACb,YAAY;gBACZ,OAAO,EAAE,OAA2B;gBACpC,QAAQ;aACT,CAAC;QACJ,CAAC,CAAC;aACD,MAAM,CAAC,CAAC,KAAK,EAAsC,EAAE,CACpD,OAAO,CAAC,KAAK,CAAC,CACf,CAAC;IACN,CAAC,CACF,CAAC;IAEF,OAAO,MAAM,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CACzD,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CACzB,MAAM,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAClD,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n createServicePolicy,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\nimport {\n hexToNumber,\n KnownCaipNamespace,\n toCaipChainId,\n} from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n EvmAssetAddressWithChain,\n EvmAssetWithId,\n EvmAssetWithMarketData,\n ExchangeRatesByCurrency,\n} from './abstract-token-prices-service';\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Georgian Lari\n 'gel',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n // Colombian Peso\n 'cop',\n // Kenyan Shilling\n 'kes',\n // Romanian Leu\n 'ron',\n // Dominican Peso\n 'dop',\n // Costa Rican Colón\n 'crc',\n // Honduran Lempira\n 'hnl',\n // Zambian Kwacha\n 'zmw',\n // Salvadoran Colón\n 'svc',\n // Bosnia-Herzegovina Convertible Mark\n 'bam',\n // Peruvian Sol\n 'pen',\n // Guatemalan Quetzal\n 'gtq',\n // Lebanese Pound\n 'lbp',\n // Armenian Dram\n 'amd',\n // Solana\n 'sol',\n // Sei\n 'sei',\n // Sonic\n 'sonic',\n // Tron\n 'trx',\n // Taiko\n 'taiko',\n // Pepu\n 'pepu',\n // Polygon\n 'pol',\n // Mantle\n 'mnt',\n // Onomy\n 'nom',\n // Avalanche\n 'avax',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010', // Polygon\n '0x440': '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Metis Andromeda\n '0x1388': '0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Mantle\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n *\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n// Source: https://github.com/consensys-vertical-apps/va-mmcx-price-api/blob/main/src/constants/slip44.ts\n// We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.\nexport const SPOT_PRICES_SUPPORT_INFO = {\n '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH\n '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH\n '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO\n '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB\n '0x39': 'eip155:57/erc20:0x0000000000000000000000000000000000000000', // 'eip155:57/slip44:57', // Syscoin Mainnet - Native symbol: SYS\n '0x52': null, // 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR\n '0x58': 'eip155:88/erc20:0x0000000000000000000000000000000000000000', // 'eip155:88/slip44:889', // TomoChain - Native symbol: TOMO\n '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI\n '0x6a': 'eip155:106/erc20:0x0000000000000000000000000000000000000000', // 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX\n '0x80': 'eip155:128/erc20:0x0000000000000000000000000000000000000000', // 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT\n '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL\n '0x8f': null, // 'eip155:143/slip44:268435779', // Monad Mainnet - Native symbol: MON\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0x141': 'eip155:321/erc20:0x0000000000000000000000000000000000000000', // 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS\n '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH\n '0x169': 'eip155:361/erc20:0x0000000000000000000000000000000000000000', // 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n '0x440': 'eip155:1088/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 'eip155:1088/slip44:XXX', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: METIS\n '0x44d': 'eip155:1101/slip44:60', // Polygon zkEVM mainnet - Native symbol: ETH\n '0x504': 'eip155:1284/slip44:1284', // Moonbeam - Native symbol: GLMR\n '0x505': 'eip155:1285/slip44:1285', // Moonriver - Native symbol: MOVR\n '0x531': 'eip155:1329/slip44:19000118', // Sei Mainnet - Native symbol: SEI\n '0x1388': 'eip155:5000/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 'eip155:5000/slip44:XXX', // Mantle - Native symbol: MNT\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2710': 'eip155:10000/erc20:0x0000000000000000000000000000000000000000', // 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH\n '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO\n '0xa516': 'eip155:42262/erc20:0x0000000000000000000000000000000000000000', // 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0x13c31': 'eip155:81457/erc20:0x0000000000000000000000000000000000000000', // 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': 'eip155:97741/erc20:0x0000000000000000000000000000000000000000', // 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x518af': null, // 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS\n '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH\n '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH\n '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE\n} as const;\n\n// MISSING CHAINS WITH NO NATIVE ASSET PRICES IN V2\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x7a': 'eip155:122/slip44:XXX', // Fuse Mainnet - Native symbol: FUSE\n// '0x120': 'eip155:288/slip44:60', // Boba Network (Ethereum L2) - Native symbol: ETH\n// '0x150': 'eip155:336/slip44:809', // Shiden - Native symbol: SDN\n// '0x28c58': 'eip155:167000/slip44:60', // Taiko Mainnet - Native symbol: ETH\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n *\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = Object.keys(\n SPOT_PRICES_SUPPORT_INFO,\n) as (keyof typeof SPOT_PRICES_SUPPORT_INFO)[];\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * The list of chain IDs that are supported by V3 of the Codefi Price API.\n * Only includes chain IDs from SPOT_PRICES_SUPPORT_INFO that have a non-null CAIP-19 value.\n */\nconst SUPPORTED_CHAIN_IDS_V3 = Object.keys(SPOT_PRICES_SUPPORT_INFO).filter(\n (chainId) =>\n SPOT_PRICES_SUPPORT_INFO[\n chainId as keyof typeof SPOT_PRICES_SUPPORT_INFO\n ] !== null,\n);\n\nconst BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';\n\nconst BASE_URL_V2 = 'https://price.api.cx.metamask.io/v2';\n\nconst BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';\n\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements AbstractTokenPricesService<SupportedChainId, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\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 function.\n * @param args.assets - The assets to get prices for.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<SupportedChainId>[];\n currency: SupportedCurrency;\n }): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const v3Assets = await this.#fetchTokenPricesV3(assets, currency);\n const v2Assets = await this.#fetchTokenPricesV2(assets, currency);\n\n return [...v3Assets, ...v2Assets];\n }\n\n async #fetchTokenPricesV3(\n assets: EvmAssetAddressWithChain<SupportedChainId>[],\n currency: SupportedCurrency,\n ): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const assetsWithIds: EvmAssetWithId<SupportedChainId>[] = assets\n // Filter out assets that are not supported by V3 of the Price API.\n .filter((asset) => SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId))\n .map((asset) => {\n const caipChainId = toCaipChainId(\n KnownCaipNamespace.Eip155,\n hexToNumber(asset.chainId).toString(),\n );\n\n const nativeAddress = getNativeTokenAddress(asset.chainId);\n\n return {\n ...asset,\n assetId: (nativeAddress.toLowerCase() ===\n asset.tokenAddress.toLowerCase()\n ? SPOT_PRICES_SUPPORT_INFO[asset.chainId]\n : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`) as CaipAssetType,\n };\n })\n .filter((asset) => asset.assetId);\n\n if (assetsWithIds.length === 0) {\n return [];\n }\n\n const url = new URL(`${BASE_URL_V3}/spot-prices`);\n url.searchParams.append(\n 'assetIds',\n assetsWithIds.map((asset) => asset.assetId).join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [assetId: CaipAssetType]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return assetsWithIds\n .map((assetWithId) => {\n const marketData = addressCryptoDataMap[assetWithId.assetId];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n ...assetWithId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));\n }\n\n async #fetchTokenPricesV2(\n assets: EvmAssetAddressWithChain<SupportedChainId>[],\n currency: SupportedCurrency,\n ): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const v2SupportedAssets = assets.filter(\n (asset) => !SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId),\n );\n\n const assetsByChainId: Record<SupportedChainId, Hex[]> =\n v2SupportedAssets.reduce(\n (acc, { chainId, tokenAddress }) => {\n (acc[chainId] ??= []).push(tokenAddress);\n return acc;\n },\n {} as Record<SupportedChainId, Hex[]>,\n );\n\n const promises = Object.entries(assetsByChainId).map(\n async ([chainId, tokenAddresses]) => {\n if (tokenAddresses.length === 0) {\n return [];\n }\n\n const url = new URL(`${BASE_URL_V2}/chains/${chainId}/spot-prices`);\n url.searchParams.append('tokenAddresses', tokenAddresses.join(','));\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [tokenAddress: string]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return tokenAddresses\n .map((tokenAddress) => {\n const marketData = addressCryptoDataMap[tokenAddress.toLowerCase()];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n tokenAddress,\n chainId: chainId as SupportedChainId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> =>\n Boolean(entry),\n );\n },\n );\n\n return await Promise.allSettled(promises).then((results) =>\n results.flatMap((result) =>\n result.status === 'fulfilled' ? result.value : [],\n ),\n );\n }\n\n /**\n * Retrieves exchange rates in the given base currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired base currency of the exchange rates.\n * @param args.includeUsdRate - Whether to include the USD rate in the response.\n * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.\n * @returns The exchange rates for the requested base currency.\n */\n async fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: SupportedCurrency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<SupportedCurrency>> {\n const url = new URL(`${BASE_URL_V1}/exchange-rates`);\n url.searchParams.append('baseCurrency', baseCurrency);\n\n const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);\n urlUsd.searchParams.append('baseCurrency', 'usd');\n\n const [exchangeRatesResult, exchangeRatesResultUsd] =\n await Promise.allSettled([\n this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n ),\n ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'\n ? [\n this.#policy.execute(() =>\n handleFetch(urlUsd, {\n headers: { 'Cache-Control': 'no-cache' },\n }),\n ),\n ]\n : []),\n ]);\n\n // Handle resolved/rejected\n const exchangeRates =\n exchangeRatesResult.status === 'fulfilled'\n ? exchangeRatesResult.value\n : {};\n const exchangeRatesUsd =\n exchangeRatesResultUsd?.status === 'fulfilled'\n ? exchangeRatesResultUsd.value\n : {};\n\n if (exchangeRatesResult.status === 'rejected') {\n throw new Error('Failed to fetch');\n }\n\n const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRates[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRates[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (Object.keys(filteredExchangeRates).length === 0) {\n throw new Error(\n 'None of the cryptocurrencies are supported by price api',\n );\n }\n\n const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRatesUsd[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRatesUsd[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (baseCurrency.toLowerCase() === 'usd') {\n Object.keys(filteredExchangeRates).forEach((key) => {\n filteredExchangeRates[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n usd: filteredExchangeRates[key as SupportedCurrency]?.value,\n };\n });\n return filteredExchangeRates;\n }\n if (!includeUsdRate) {\n return filteredExchangeRates;\n }\n\n const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {\n acc[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n ...(filteredUsdExchangeRates[key as SupportedCurrency]?.value\n ? { usd: filteredUsdExchangeRates[key as SupportedCurrency]?.value }\n : {}),\n };\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n return merged;\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 SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\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. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}