@metamask-previews/assets-controllers 89.0.0-preview-d356e047 → 89.0.0-preview-168b280

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 +2 -6
  2. package/dist/CurrencyRateController.cjs +4 -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 +4 -3
  7. package/dist/CurrencyRateController.mjs.map +1 -1
  8. package/dist/TokenRatesController.cjs +278 -82
  9. package/dist/TokenRatesController.cjs.map +1 -1
  10. package/dist/TokenRatesController.d.cts +35 -9
  11. package/dist/TokenRatesController.d.cts.map +1 -1
  12. package/dist/TokenRatesController.d.mts +35 -9
  13. package/dist/TokenRatesController.d.mts.map +1 -1
  14. package/dist/TokenRatesController.mjs +279 -83
  15. package/dist/TokenRatesController.mjs.map +1 -1
  16. package/dist/TokenSearchDiscoveryDataController/TokenSearchDiscoveryDataController.cjs +3 -2
  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 +3 -2
  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 +5 -11
  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 +5 -11
  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 +43 -17
  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 +43 -17
  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 +98 -121
  43. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  44. package/dist/token-prices-service/codefi-v2.d.cts +10 -52
  45. package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
  46. package/dist/token-prices-service/codefi-v2.d.mts +10 -52
  47. package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
  48. package/dist/token-prices-service/codefi-v2.mjs +98 -121
  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, EvmAssetAddressWithChain, EvmAssetWithMarketData, ExchangeRatesByCurrency } from "./abstract-token-prices-service.mjs";
3
+ import type { AbstractTokenPricesService, ExchangeRatesByCurrency, TokenPricesByTokenAddress } 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", "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"];
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"];
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,50 +22,6 @@ 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 HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP: {
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/slip44:57";
31
- readonly '0x42': "eip155:66/slip44:996";
32
- readonly '0x46': "eip155:70/slip44:1170";
33
- readonly '0x52': "eip155:82/slip44:18000";
34
- readonly '0x58': "eip155:88/slip44:889";
35
- readonly '0x64': "eip155:100/slip44:700";
36
- readonly '0x6a': "eip155:106/slip44:5655640";
37
- readonly '0x7a': "eip155:122/slip44:XXX";
38
- readonly '0x80': "eip155:128/slip44:1010";
39
- readonly '0x89': "eip155:137/slip44:966";
40
- readonly '0x8f': "eip155:143/slip44:268435779";
41
- readonly '0x92': "eip155:146/slip44:10007";
42
- readonly '0xfa': "eip155:250/slip44:1007";
43
- readonly '0x120': "eip155:288/slip44:60";
44
- readonly '0x141': "eip155:321/slip44:641";
45
- readonly '0x144': "eip155:324/slip44:60";
46
- readonly '0x150': "eip155:336/slip44:809";
47
- readonly '0x169': "eip155:361/slip44:589";
48
- readonly '0x440': "eip155:1088/slip44:60";
49
- readonly '0x44d': "eip155:1101/slip44:60";
50
- readonly '0x504': "eip155:1284/slip44:1284";
51
- readonly '0x505': "eip155:1285/slip44:1285";
52
- readonly '0x531': "eip155:1329/slip44:19000118";
53
- readonly '0x1388': "eip155:5000/slip44:XXX";
54
- readonly '0x2105': "eip155:8453/slip44:60";
55
- readonly '0x2710': "eip155:10000/slip44:145";
56
- readonly '0xa4b1': "eip155:42161/slip44:60";
57
- readonly '0xa4ec': "eip155:42220/slip44:52752";
58
- readonly '0xa516': "eip155:42262/slip44:474";
59
- readonly '0xa86a': "eip155:43114/slip44:9005";
60
- readonly '0xe708': "eip155:59144/slip44:60";
61
- readonly '0x13c31': "eip155:81457/slip44:60";
62
- readonly '0x17dcd': "eip155:97741/slip44:XXX";
63
- readonly '0x28c58': "eip155:167000/slip44:60";
64
- readonly '0x518af': "eip155:333999/slip44:1997";
65
- readonly '0x82750': "eip155:534352/slip44:60";
66
- readonly '0x4e454152': "eip155:1313161554/slip44:60";
67
- readonly '0x63564c40': "eip155:1666600000/slip44:1023";
68
- };
69
25
  /**
70
26
  * A currency that can be supplied as the `vsCurrency` parameter to
71
27
  * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.
@@ -78,7 +34,7 @@ type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number] | Uppercase<(type
78
34
  *
79
35
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
80
36
  */
81
- export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" | "0xa" | "0xa4b1" | "0x82750" | "0x531" | "0x8f" | "0xe708" | "0x19" | "0x39" | "0x42" | "0x46" | "0x52" | "0x58" | "0x64" | "0x6a" | "0x7a" | "0x80" | "0x92" | "0xfa" | "0x120" | "0x141" | "0x144" | "0x150" | "0x169" | "0x440" | "0x44d" | "0x504" | "0x505" | "0x1388" | "0x2710" | "0xa4ec" | "0xa516" | "0xa86a" | "0x13c31" | "0x17dcd" | "0x28c58" | "0x518af" | "0x4e454152" | "0x63564c40")[];
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"];
82
38
  /**
83
39
  * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,
84
40
  * but in hexadecimal form (for consistency with how we represent chain IDs in
@@ -89,7 +45,7 @@ type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
89
45
  * This version of the token prices service uses V2 of the Codefi Price API to
90
46
  * fetch token prices.
91
47
  */
92
- export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesService<SupportedChainId, SupportedCurrency> {
48
+ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency> {
93
49
  #private;
94
50
  /**
95
51
  * Construct a Codefi Token Price Service.
@@ -158,14 +114,16 @@ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesSe
158
114
  * given addresses which are expected to live on the given chain.
159
115
  *
160
116
  * @param args - The arguments to function.
161
- * @param args.assets - The assets to get prices for.
117
+ * @param args.chainId - An EIP-155 chain ID.
118
+ * @param args.tokenAddresses - Addresses for tokens that live on the chain.
162
119
  * @param args.currency - The desired currency of the token prices.
163
120
  * @returns The prices for the requested tokens.
164
121
  */
165
- fetchTokenPrices({ assets, currency, }: {
166
- assets: EvmAssetAddressWithChain<SupportedChainId>[];
122
+ fetchTokenPrices({ chainId, tokenAddresses, currency, }: {
123
+ chainId: SupportedChainId;
124
+ tokenAddresses: Hex[];
167
125
  currency: SupportedCurrency;
168
- }): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]>;
126
+ }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>>;
169
127
  /**
170
128
  * Retrieves exchange rates in the given base currency.
171
129
  *
@@ -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,EAAiB,GAAG,EAAE,wBAAwB;AAO1D,OAAO,KAAK,EACV,0BAA0B,EAC1B,wBAAwB,EAExB,sBAAsB,EACtB,uBAAuB,EACxB,4CAAwC;AAGzC;;;GAGG;AACH,eAAO,MAAM,oBAAoB,umBA2KvB,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,GAC4B,CAAC;AAUxD;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,YAAa,GAAG,KAAG,GACC,CAAC;AAGvD,eAAO,MAAM,uCAAuC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2C1C,CAAC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,EAAE;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"}
@@ -11,7 +11,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
11
11
  };
12
12
  var _CodefiTokenPricesServiceV2_policy;
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, KnownCaipNamespace, toCaipChainId } from "@metamask/utils";
14
+ import { hexToNumber } 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,8 +71,6 @@ export const SUPPORTED_CURRENCIES = [
71
71
  'eur',
72
72
  // British Pound Sterling
73
73
  'gbp',
74
- // Georgian Lari
75
- 'gel',
76
74
  // Hong Kong Dollar
77
75
  'hkd',
78
76
  // Hungarian Forint
@@ -141,52 +139,6 @@ export const SUPPORTED_CURRENCIES = [
141
139
  'bits',
142
140
  // Satoshi
143
141
  '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',
190
142
  ];
191
143
  /**
192
144
  * Represents the zero address, commonly used as a placeholder in blockchain transactions.
@@ -211,51 +163,6 @@ const chainIdToNativeTokenAddress = {
211
163
  * @returns The address of the chain's native token.
212
164
  */
213
165
  export const getNativeTokenAddress = (chainId) => chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;
214
- // We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.
215
- export const HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {
216
- '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH
217
- '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH
218
- '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO
219
- '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB
220
- '0x39': 'eip155:57/slip44:57', // Syscoin Mainnet - Native symbol: SYS
221
- '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT
222
- '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO
223
- '0x52': 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR
224
- '0x58': 'eip155:88/slip44:889', // TomoChain - Native symbol: TOMO
225
- '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI
226
- '0x6a': 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX
227
- '0x7a': 'eip155:122/slip44:XXX', // Fuse Mainnet - Native symbol: FUSE
228
- '0x80': 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT
229
- '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL
230
- '0x8f': 'eip155:143/slip44:268435779', // Monad Mainnet - Native symbol: MONAD
231
- '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S
232
- '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM
233
- '0x120': 'eip155:288/slip44:60', // Boba Network (Ethereum L2) - Native symbol: ETH
234
- '0x141': 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS
235
- '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH
236
- '0x150': 'eip155:336/slip44:809', // Shiden - Native symbol: SDN
237
- '0x169': 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL
238
- '0x440': 'eip155:1088/slip44:60', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: ETH
239
- '0x44d': 'eip155:1101/slip44:60', // Polygon zkEVM mainnet - Native symbol: ETH
240
- '0x504': 'eip155:1284/slip44:1284', // Moonbeam - Native symbol: GLMR
241
- '0x505': 'eip155:1285/slip44:1285', // Moonriver - Native symbol: MOVR
242
- '0x531': 'eip155:1329/slip44:19000118', // Sei Mainnet - Native symbol: SEI
243
- '0x1388': 'eip155:5000/slip44:XXX', // Mantle - Native symbol: MNT
244
- '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH
245
- '0x2710': 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH
246
- '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH
247
- '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO
248
- '0xa516': 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE
249
- '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX
250
- '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH
251
- '0x13c31': 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH
252
- '0x17dcd': 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU
253
- '0x28c58': 'eip155:167000/slip44:60', // Taiko Mainnet - Native symbol: ETH
254
- '0x518af': 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS
255
- '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH
256
- '0x4e454152': 'eip155:1313161554/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH
257
- '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE
258
- };
259
166
  /**
260
167
  * The list of chain IDs that can be supplied in the URL for the `/spot-prices`
261
168
  * endpoint, but in hexadecimal form (for consistency with how we represent
@@ -263,12 +170,87 @@ export const HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {
263
170
  *
264
171
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
265
172
  */
266
- export const SUPPORTED_CHAIN_IDS = Object.keys(HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP);
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
+ ];
267
249
  /**
268
250
  * All requests to V2 of the Price API start with this.
269
251
  */
252
+ const BASE_URL = 'https://price.api.cx.metamask.io/v2';
270
253
  const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
271
- const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
272
254
  /**
273
255
  * This version of the token prices service uses V2 of the Codefi Price API to
274
256
  * fetch token prices.
@@ -314,41 +296,36 @@ export class CodefiTokenPricesServiceV2 {
314
296
  * given addresses which are expected to live on the given chain.
315
297
  *
316
298
  * @param args - The arguments to function.
317
- * @param args.assets - The assets to get prices for.
299
+ * @param args.chainId - An EIP-155 chain ID.
300
+ * @param args.tokenAddresses - Addresses for tokens that live on the chain.
318
301
  * @param args.currency - The desired currency of the token prices.
319
302
  * @returns The prices for the requested tokens.
320
303
  */
321
- async fetchTokenPrices({ assets, currency, }) {
322
- const assetsWithIds = assets
323
- .map((asset) => {
324
- const caipChainId = toCaipChainId(KnownCaipNamespace.Eip155, hexToNumber(asset.chainId).toString());
325
- const nativeAddress = getNativeTokenAddress(asset.chainId);
326
- return {
327
- ...asset,
328
- assetId: nativeAddress.toLowerCase() === asset.tokenAddress.toLowerCase()
329
- ? HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP[asset.chainId]
330
- : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`,
331
- };
332
- })
333
- .filter((asset) => asset.assetId);
334
- const url = new URL(`${BASE_URL_V3}/spot-prices`);
335
- url.searchParams.append('assetIds', assetsWithIds.map((asset) => asset.assetId).join(','));
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(','));
336
308
  url.searchParams.append('vsCurrency', currency);
337
309
  url.searchParams.append('includeMarketData', 'true');
338
310
  const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }));
339
- return assetsWithIds
340
- .map((assetWithId) => {
341
- const marketData = addressCryptoDataMap[assetWithId.assetId];
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];
342
316
  if (!marketData) {
343
- return undefined;
317
+ return obj;
344
318
  }
345
- return {
346
- ...marketData,
347
- ...assetWithId,
319
+ const token = {
320
+ tokenAddress,
348
321
  currency,
322
+ ...marketData,
349
323
  };
350
- })
351
- .filter((entry) => Boolean(entry));
324
+ return {
325
+ ...obj,
326
+ [tokenAddress]: token,
327
+ };
328
+ }, {});
352
329
  }
353
330
  /**
354
331
  * Retrieves exchange rates in the given base currency.
@@ -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,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,oBAA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B,CAAC;QAC/B,CAAC;QACD,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,OAAO,qBAAqB,CAAC;QAC/B,CAAC;QAED,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;YACpE,GAAG,CAAC,GAAwB,CAAC,GAAG;gBAC9B,GAAG,qBAAqB,CAAC,GAAwB,CAAC;gBAClD,GAAG,CAAC,wBAAwB,CAAC,GAAwB,CAAC,EAAE,KAAK;oBAC3D,CAAC,CAAC,EAAE,GAAG,EAAE,wBAAwB,CAAC,GAAwB,CAAC,EAAE,KAAK,EAAE;oBACpE,CAAC,CAAC,EAAE,CAAC;aACR,CAAC;YACF,OAAO,GAAG,CAAC;QACb,CAAC,EAAE,EAAgD,CAAC,CAAC;QAErD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAgB;QACvC,MAAM,iBAAiB,GAAsB,mBAAmB,CAAC;QACjE,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,iBAAiB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC5E,CAAC;IAED;;;;;;;OAOG;IACH,yBAAyB,CAAC,QAAiB;QACzC,MAAM,mBAAmB,GAAsB,oBAAoB,CAAC;QACpE,OAAO,CACL,OAAO,QAAQ,KAAK,QAAQ;YAC5B,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF","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',\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// We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.\nexport const HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {\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/slip44:57', // Syscoin Mainnet - Native symbol: SYS\n '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n '0x52': 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR\n '0x58': '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/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX\n '0x7a': 'eip155:122/slip44:XXX', // Fuse Mainnet - Native symbol: FUSE\n '0x80': 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT\n '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL\n '0x8f': 'eip155:143/slip44:268435779', // Monad Mainnet - Native symbol: MONAD\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0x120': 'eip155:288/slip44:60', // Boba Network (Ethereum L2) - Native symbol: ETH\n '0x141': 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS\n '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH\n '0x150': 'eip155:336/slip44:809', // Shiden - Native symbol: SDN\n '0x169': 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL\n '0x440': 'eip155:1088/slip44:60', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: ETH\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/slip44:XXX', // Mantle - Native symbol: MNT\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2710': '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/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/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x28c58': 'eip155:167000/slip44:60', // Taiko Mainnet - Native symbol: ETH\n '0x518af': 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS\n '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH\n '0x4e454152': 'eip155:1313161554/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/**\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 HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP,\n) as (keyof typeof HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP)[];\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_V1 = 'https://price.api.cx.metamask.io/v1';\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 assetsWithIds: EvmAssetWithId<SupportedChainId>[] = assets\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:\n nativeAddress.toLowerCase() === asset.tokenAddress.toLowerCase()\n ? HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP[asset.chainId]\n : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`,\n } as EvmAssetWithId<SupportedChainId>;\n })\n .filter((asset) => asset.assetId);\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 /**\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,EAAE,WAAW,EAAE,wBAAwB;AAS9C;;;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,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;IACnB,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe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O,CACL,OAAO,QAAQ,KAAK,QAAQ;YAC5B,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF","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 { 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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/assets-controllers",
3
- "version": "89.0.0-preview-d356e047",
3
+ "version": "89.0.0-preview-168b280",
4
4
  "description": "Controllers which manage interactions involving ERC-20, ERC-721, and ERC-1155 tokens (including NFTs)",
5
5
  "keywords": [
6
6
  "MetaMask",