@metamask-previews/assets-controllers 95.3.0-preview-ab102d86 → 95.3.0-preview-3ec2a74
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/token-prices-service/codefi-v2.cjs +73 -3
- package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
- package/dist/token-prices-service/codefi-v2.d.cts +32 -1
- package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
- package/dist/token-prices-service/codefi-v2.d.mts +32 -1
- package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
- package/dist/token-prices-service/codefi-v2.mjs +69 -2
- package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- Add dynamic fetching of supported currencies from `/v1/supportedVsCurrencies` API endpoint with fallback to hardcoded list ([#7699](https://github.com/MetaMask/core/pull/7699))
|
|
13
|
+
|
|
10
14
|
### Changed
|
|
11
15
|
|
|
12
16
|
- Removed call to NFT collections endpoint ([#7687](https://github.com/MetaMask/core/pull/7687))
|
|
@@ -12,14 +12,15 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
12
12
|
};
|
|
13
13
|
var _CodefiTokenPricesServiceV2_policy;
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.CodefiTokenPricesServiceV2 = exports.SUPPORTED_CHAIN_IDS = exports.SPOT_PRICES_SUPPORT_INFO = exports.getNativeTokenAddress = exports.ZERO_ADDRESS = exports.SUPPORTED_CURRENCIES = void 0;
|
|
15
|
+
exports.CodefiTokenPricesServiceV2 = exports.resetSupportedCurrenciesCache = exports.getSupportedCurrencies = exports.fetchSupportedCurrencies = exports.SUPPORTED_CHAIN_IDS = exports.SPOT_PRICES_SUPPORT_INFO = exports.getNativeTokenAddress = exports.ZERO_ADDRESS = exports.SUPPORTED_CURRENCIES = exports.SUPPORTED_CURRENCIES_FALLBACK = void 0;
|
|
16
16
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
17
17
|
const utils_1 = require("@metamask/utils");
|
|
18
18
|
/**
|
|
19
19
|
* The list of currencies that can be supplied as the `vsCurrency` parameter to
|
|
20
20
|
* the `/spot-prices` endpoint, in lowercase form.
|
|
21
|
+
* This is the fallback list used when the API is unavailable.
|
|
21
22
|
*/
|
|
22
|
-
exports.
|
|
23
|
+
exports.SUPPORTED_CURRENCIES_FALLBACK = [
|
|
23
24
|
// Bitcoin
|
|
24
25
|
'btc',
|
|
25
26
|
// Ether
|
|
@@ -195,6 +196,11 @@ exports.SUPPORTED_CURRENCIES = [
|
|
|
195
196
|
// Apechain
|
|
196
197
|
'ape',
|
|
197
198
|
];
|
|
199
|
+
/**
|
|
200
|
+
* @deprecated Use `getSupportedCurrencies()` or `fetchSupportedCurrencies()` instead.
|
|
201
|
+
* This is an alias for backward compatibility.
|
|
202
|
+
*/
|
|
203
|
+
exports.SUPPORTED_CURRENCIES = exports.SUPPORTED_CURRENCIES_FALLBACK;
|
|
198
204
|
/**
|
|
199
205
|
* Represents the zero address, commonly used as a placeholder in blockchain transactions.
|
|
200
206
|
* In the context of fetching market data, the zero address is utilized to retrieve information
|
|
@@ -305,6 +311,57 @@ exports.SUPPORTED_CHAIN_IDS = Object.keys(exports.SPOT_PRICES_SUPPORT_INFO);
|
|
|
305
311
|
const SUPPORTED_CHAIN_IDS_V3 = Object.keys(exports.SPOT_PRICES_SUPPORT_INFO).filter((chainId) => exports.SPOT_PRICES_SUPPORT_INFO[chainId] !== null);
|
|
306
312
|
const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
|
|
307
313
|
const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
|
|
314
|
+
/**
|
|
315
|
+
* In-memory store for the last successfully fetched supported currencies.
|
|
316
|
+
*/
|
|
317
|
+
let lastFetchedCurrencies = null;
|
|
318
|
+
/**
|
|
319
|
+
* Fetches the list of supported currencies from the API.
|
|
320
|
+
* Falls back to the hardcoded list if the fetch fails.
|
|
321
|
+
*
|
|
322
|
+
* @returns The list of supported currencies in lowercase.
|
|
323
|
+
*/
|
|
324
|
+
async function fetchSupportedCurrencies() {
|
|
325
|
+
try {
|
|
326
|
+
const url = `${BASE_URL_V1}/supportedVsCurrencies`;
|
|
327
|
+
const response = await (0, controller_utils_1.handleFetch)(url, {
|
|
328
|
+
headers: { 'Cache-Control': 'no-cache' },
|
|
329
|
+
});
|
|
330
|
+
if (Array.isArray(response)) {
|
|
331
|
+
const currencies = response.map((currency) => currency.toLowerCase());
|
|
332
|
+
lastFetchedCurrencies = currencies;
|
|
333
|
+
return currencies;
|
|
334
|
+
}
|
|
335
|
+
// Invalid response format, fall back to hardcoded list
|
|
336
|
+
return [...exports.SUPPORTED_CURRENCIES_FALLBACK];
|
|
337
|
+
}
|
|
338
|
+
catch {
|
|
339
|
+
// On any error, fall back to the hardcoded list
|
|
340
|
+
return [...exports.SUPPORTED_CURRENCIES_FALLBACK];
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
exports.fetchSupportedCurrencies = fetchSupportedCurrencies;
|
|
344
|
+
/**
|
|
345
|
+
* Synchronously gets the list of supported currencies.
|
|
346
|
+
* Returns the last fetched value if available, otherwise returns the fallback list.
|
|
347
|
+
*
|
|
348
|
+
* @returns The list of supported currencies in lowercase.
|
|
349
|
+
*/
|
|
350
|
+
function getSupportedCurrencies() {
|
|
351
|
+
if (lastFetchedCurrencies !== null) {
|
|
352
|
+
return lastFetchedCurrencies;
|
|
353
|
+
}
|
|
354
|
+
return exports.SUPPORTED_CURRENCIES_FALLBACK;
|
|
355
|
+
}
|
|
356
|
+
exports.getSupportedCurrencies = getSupportedCurrencies;
|
|
357
|
+
/**
|
|
358
|
+
* Resets the supported currencies cache.
|
|
359
|
+
* This is primarily intended for testing purposes.
|
|
360
|
+
*/
|
|
361
|
+
function resetSupportedCurrenciesCache() {
|
|
362
|
+
lastFetchedCurrencies = null;
|
|
363
|
+
}
|
|
364
|
+
exports.resetSupportedCurrenciesCache = resetSupportedCurrenciesCache;
|
|
308
365
|
/**
|
|
309
366
|
* This version of the token prices service uses V2 of the Codefi Price API to
|
|
310
367
|
* fetch token prices.
|
|
@@ -402,6 +459,11 @@ class CodefiTokenPricesServiceV2 {
|
|
|
402
459
|
* @returns The exchange rates for the requested base currency.
|
|
403
460
|
*/
|
|
404
461
|
async fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }) {
|
|
462
|
+
// Refresh supported currencies in background (non-blocking)
|
|
463
|
+
// This ensures the list stays fresh during normal polling
|
|
464
|
+
// Note: fetchSupportedCurrencies handles errors internally and always resolves
|
|
465
|
+
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
|
466
|
+
fetchSupportedCurrencies();
|
|
405
467
|
const url = new URL(`${BASE_URL_V1}/exchange-rates`);
|
|
406
468
|
url.searchParams.append('baseCurrency', baseCurrency);
|
|
407
469
|
const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);
|
|
@@ -486,10 +548,18 @@ class CodefiTokenPricesServiceV2 {
|
|
|
486
548
|
* @returns True if the API supports the currency, false otherwise.
|
|
487
549
|
*/
|
|
488
550
|
validateCurrencySupported(currency) {
|
|
489
|
-
const supportedCurrencies =
|
|
551
|
+
const supportedCurrencies = getSupportedCurrencies();
|
|
490
552
|
return (typeof currency === 'string' &&
|
|
491
553
|
supportedCurrencies.includes(currency.toLowerCase()));
|
|
492
554
|
}
|
|
555
|
+
/**
|
|
556
|
+
* Fetches the list of supported currencies from the API.
|
|
557
|
+
*
|
|
558
|
+
* @returns The list of supported currencies.
|
|
559
|
+
*/
|
|
560
|
+
async updateSupportedCurrencies() {
|
|
561
|
+
return fetchSupportedCurrencies();
|
|
562
|
+
}
|
|
493
563
|
}
|
|
494
564
|
exports.CodefiTokenPricesServiceV2 = CodefiTokenPricesServiceV2;
|
|
495
565
|
_CodefiTokenPricesServiceV2_policy = new WeakMap();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codefi-v2.cjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAOoC;AAGpC,2CAIyB;AAWzB;;;GAGG;AACU,QAAA,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;IACnB,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe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_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 // Monad\n 'mon',\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 // Apechain\n 'ape',\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 '0x64': '0xe91d153e0b41518a2ce8dd3d7944fa863463a97d', // Gnosis\n '0x1e': '0x542fda317318ebf1d3deaf76e0b632741a7e677d', // Rootstock Mainnet - Native symbol: RBTC\n '0x2611': '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\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 '0x1e': 'eip155:30/slip44:137', // Rootstock Mainnet - Native symbol: RBTC\n '0x2a': 'eip155:42/erc20:0x0000000000000000000000000000000000000000', // Lukso - native symbol: LYX\n '0x32': 'eip155:50/erc20:0x0000000000000000000000000000000000000000', // xdc-network - native symbol: XDC\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 '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/erc20:0x0000000000000000000000000000000000000000', // 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: MON\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xc4': 'eip155:196/erc20:0x0000000000000000000000000000000000000000', // X Layer Mainnet - Native symbol: OKB\n '0xe8': 'eip155:232/erc20:0x0000000000000000000000000000000000000000', // Lens Mainnet - Native symbol: GHO\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0xfc': 'eip155:252/erc20:0x0000000000000000000000000000000000000000', // Fraxtal - native symbol: FRAX\n '0x10b3e': 'eip155:68414/erc20:0x0000000000000000000000000000000000000000', // MapleStory Universe - no slip44\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 '0x2eb': 'eip155:747/slip44:539', // Flow evm - Native symbol: Flow\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n '0x440': 'eip155:1088/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 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 '0x74c': 'eip155:1868/erc20:0x0000000000000000000000000000000000000000', // Soneium - Native symbol: ETH\n '0xa729': 'eip155:42793/erc20:0x0000000000000000000000000000000000000000', // Etherlink - Native symbol: XTZ (Tezos L2)\n '0xab5': 'eip155:2741/erc20:0x0000000000000000000000000000000000000000', // Abstract - Native symbol: ETH\n '0x10e6': 'eip155:4326/erc20:0x0000000000000000000000000000000000000000', // MegaETH Mainnet - Native symbol: ETH\n '0x1388': 'eip155:5000/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Mantle - Native symbol: MNT\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2611': 'eip155:9745/erc20:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\n '0x2710': 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n '0x8173': 'eip155:33139/erc20:0x0000000000000000000000000000000000000000', // Apechain Mainnet - Native symbol: APE\n '0xa3c3': 'eip155:41923/erc20:0x0000000000000000000000000000000000000000', // EDU Chain - Native symbol: EDU\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 '0xa867': 'eip155:43111/erc20:0x0000000000000000000000000000000000000000', // Hemi - Native symbol: ETH\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0xed88': 'eip155:60808/erc20:0x0000000000000000000000000000000000000000', // BOB - Native symbol: ETH\n '0x138de': 'eip155:80094/erc20:0x0000000000000000000000000000000000000000', // Berachain - Native symbol: Bera',\n '0x13c31': 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': 'eip155:97741/erc20:0x0000000000000000000000000000000000000000', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x18232': 'eip155:98866/erc20:0x0000000000000000000000000000000000000000', // Plume Mainnet - Narive symbol: Plume\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 '0xb67d2': 'eip155:747474/erc20:0x0000000000000000000000000000000000000000', // katana - Native symbol: ETH\n '0x15f900': 'eip155:1440000/erc20:0x0000000000000000000000000000000000000000', // xrpl-evm - native symbol: XRP\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// MISSING CHAINS WITH NO NATIVE ASSET PRICES\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x926': 'eip155:2342/erc20:0x0000000000000000000000000000000000000000', // Omnia Chain - Native symbol: OMNIA\n// '0x407b': 'eip155:16507/erc20:0x0000000000000000000000000000000000000000', // Genesys Mainnet - Native symbol: GSYS\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_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(\n ...args: Parameters<ServicePolicy['onBreak']>\n ): ReturnType<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(\n ...args: Parameters<ServicePolicy['onDegraded']>\n ): ReturnType<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 // 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 /**\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.cjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAOoC;AAGpC,2CAIyB;AAWzB;;;;GAIG;AACU,QAAA,6BAA6B,GAAG;IAC3C,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;IACnB,KAAK;IACL,eAAe;IACf,K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ULT_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 * This is the fallback list used when the API is unavailable.\n */\nexport const SUPPORTED_CURRENCIES_FALLBACK = [\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 // Monad\n 'mon',\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 // Apechain\n 'ape',\n] as const;\n\n/**\n * @deprecated Use `getSupportedCurrencies()` or `fetchSupportedCurrencies()` instead.\n * This is an alias for backward compatibility.\n */\nexport const SUPPORTED_CURRENCIES = SUPPORTED_CURRENCIES_FALLBACK;\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 '0x64': '0xe91d153e0b41518a2ce8dd3d7944fa863463a97d', // Gnosis\n '0x1e': '0x542fda317318ebf1d3deaf76e0b632741a7e677d', // Rootstock Mainnet - Native symbol: RBTC\n '0x2611': '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\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 '0x1e': 'eip155:30/slip44:137', // Rootstock Mainnet - Native symbol: RBTC\n '0x2a': 'eip155:42/erc20:0x0000000000000000000000000000000000000000', // Lukso - native symbol: LYX\n '0x32': 'eip155:50/erc20:0x0000000000000000000000000000000000000000', // xdc-network - native symbol: XDC\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 '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/erc20:0x0000000000000000000000000000000000000000', // 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: MON\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xc4': 'eip155:196/erc20:0x0000000000000000000000000000000000000000', // X Layer Mainnet - Native symbol: OKB\n '0xe8': 'eip155:232/erc20:0x0000000000000000000000000000000000000000', // Lens Mainnet - Native symbol: GHO\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0xfc': 'eip155:252/erc20:0x0000000000000000000000000000000000000000', // Fraxtal - native symbol: FRAX\n '0x10b3e': 'eip155:68414/erc20:0x0000000000000000000000000000000000000000', // MapleStory Universe - no slip44\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 '0x2eb': 'eip155:747/slip44:539', // Flow evm - Native symbol: Flow\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n '0x440': 'eip155:1088/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 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 '0x74c': 'eip155:1868/erc20:0x0000000000000000000000000000000000000000', // Soneium - Native symbol: ETH\n '0xa729': 'eip155:42793/erc20:0x0000000000000000000000000000000000000000', // Etherlink - Native symbol: XTZ (Tezos L2)\n '0xab5': 'eip155:2741/erc20:0x0000000000000000000000000000000000000000', // Abstract - Native symbol: ETH\n '0x10e6': 'eip155:4326/erc20:0x0000000000000000000000000000000000000000', // MegaETH Mainnet - Native symbol: ETH\n '0x1388': 'eip155:5000/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Mantle - Native symbol: MNT\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2611': 'eip155:9745/erc20:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\n '0x2710': 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n '0x8173': 'eip155:33139/erc20:0x0000000000000000000000000000000000000000', // Apechain Mainnet - Native symbol: APE\n '0xa3c3': 'eip155:41923/erc20:0x0000000000000000000000000000000000000000', // EDU Chain - Native symbol: EDU\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 '0xa867': 'eip155:43111/erc20:0x0000000000000000000000000000000000000000', // Hemi - Native symbol: ETH\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0xed88': 'eip155:60808/erc20:0x0000000000000000000000000000000000000000', // BOB - Native symbol: ETH\n '0x138de': 'eip155:80094/erc20:0x0000000000000000000000000000000000000000', // Berachain - Native symbol: Bera',\n '0x13c31': 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': 'eip155:97741/erc20:0x0000000000000000000000000000000000000000', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x18232': 'eip155:98866/erc20:0x0000000000000000000000000000000000000000', // Plume Mainnet - Narive symbol: Plume\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 '0xb67d2': 'eip155:747474/erc20:0x0000000000000000000000000000000000000000', // katana - Native symbol: ETH\n '0x15f900': 'eip155:1440000/erc20:0x0000000000000000000000000000000000000000', // xrpl-evm - native symbol: XRP\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// MISSING CHAINS WITH NO NATIVE ASSET PRICES\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x926': 'eip155:2342/erc20:0x0000000000000000000000000000000000000000', // Omnia Chain - Native symbol: OMNIA\n// '0x407b': 'eip155:16507/erc20:0x0000000000000000000000000000000000000000', // Genesys Mainnet - Native symbol: GSYS\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_FALLBACK)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES_FALLBACK)[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_V3 = 'https://price.api.cx.metamask.io/v3';\n\n/**\n * In-memory store for the last successfully fetched supported currencies.\n */\nlet lastFetchedCurrencies: string[] | null = null;\n\n/**\n * Fetches the list of supported currencies from the API.\n * Falls back to the hardcoded list if the fetch fails.\n *\n * @returns The list of supported currencies in lowercase.\n */\nexport async function fetchSupportedCurrencies(): Promise<string[]> {\n try {\n const url = `${BASE_URL_V1}/supportedVsCurrencies`;\n const response = await handleFetch(url, {\n headers: { 'Cache-Control': 'no-cache' },\n });\n\n if (Array.isArray(response)) {\n const currencies = response.map((currency: string) =>\n currency.toLowerCase(),\n );\n lastFetchedCurrencies = currencies;\n return currencies;\n }\n\n // Invalid response format, fall back to hardcoded list\n return [...SUPPORTED_CURRENCIES_FALLBACK];\n } catch {\n // On any error, fall back to the hardcoded list\n return [...SUPPORTED_CURRENCIES_FALLBACK];\n }\n}\n\n/**\n * Synchronously gets the list of supported currencies.\n * Returns the last fetched value if available, otherwise returns the fallback list.\n *\n * @returns The list of supported currencies in lowercase.\n */\nexport function getSupportedCurrencies(): readonly string[] {\n if (lastFetchedCurrencies !== null) {\n return lastFetchedCurrencies;\n }\n return SUPPORTED_CURRENCIES_FALLBACK;\n}\n\n/**\n * Resets the supported currencies cache.\n * This is primarily intended for testing purposes.\n */\nexport function resetSupportedCurrenciesCache(): void {\n lastFetchedCurrencies = null;\n}\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(\n ...args: Parameters<ServicePolicy['onBreak']>\n ): ReturnType<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(\n ...args: Parameters<ServicePolicy['onDegraded']>\n ): ReturnType<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 // 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 /**\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 // Refresh supported currencies in background (non-blocking)\n // This ensures the list stays fresh during normal polling\n // Note: fetchSupportedCurrencies handles errors internally and always resolves\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchSupportedCurrencies();\n\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 = getSupportedCurrencies();\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n\n /**\n * Fetches the list of supported currencies from the API.\n *\n * @returns The list of supported currencies.\n */\n async updateSupportedCurrencies(): Promise<string[]> {\n return fetchSupportedCurrencies();\n }\n}\n"]}
|
|
@@ -4,6 +4,12 @@ import type { AbstractTokenPricesService, EvmAssetAddressWithChain, EvmAssetWith
|
|
|
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
|
+
* This is the fallback list used when the API is unavailable.
|
|
8
|
+
*/
|
|
9
|
+
export declare const SUPPORTED_CURRENCIES_FALLBACK: 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", "mon", "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", "ape"];
|
|
10
|
+
/**
|
|
11
|
+
* @deprecated Use `getSupportedCurrencies()` or `fetchSupportedCurrencies()` instead.
|
|
12
|
+
* This is an alias for backward compatibility.
|
|
7
13
|
*/
|
|
8
14
|
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", "mon", "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", "ape"];
|
|
9
15
|
/**
|
|
@@ -90,7 +96,7 @@ export declare const SPOT_PRICES_SUPPORT_INFO: {
|
|
|
90
96
|
* A currency that can be supplied as the `vsCurrency` parameter to
|
|
91
97
|
* the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.
|
|
92
98
|
*/
|
|
93
|
-
type SupportedCurrency = (typeof
|
|
99
|
+
type SupportedCurrency = (typeof SUPPORTED_CURRENCIES_FALLBACK)[number] | Uppercase<(typeof SUPPORTED_CURRENCIES_FALLBACK)[number]>;
|
|
94
100
|
/**
|
|
95
101
|
* The list of chain IDs that can be supplied in the URL for the `/spot-prices`
|
|
96
102
|
* endpoint, but in hexadecimal form (for consistency with how we represent
|
|
@@ -105,6 +111,25 @@ export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" |
|
|
|
105
111
|
* other places).
|
|
106
112
|
*/
|
|
107
113
|
type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
|
|
114
|
+
/**
|
|
115
|
+
* Fetches the list of supported currencies from the API.
|
|
116
|
+
* Falls back to the hardcoded list if the fetch fails.
|
|
117
|
+
*
|
|
118
|
+
* @returns The list of supported currencies in lowercase.
|
|
119
|
+
*/
|
|
120
|
+
export declare function fetchSupportedCurrencies(): Promise<string[]>;
|
|
121
|
+
/**
|
|
122
|
+
* Synchronously gets the list of supported currencies.
|
|
123
|
+
* Returns the last fetched value if available, otherwise returns the fallback list.
|
|
124
|
+
*
|
|
125
|
+
* @returns The list of supported currencies in lowercase.
|
|
126
|
+
*/
|
|
127
|
+
export declare function getSupportedCurrencies(): readonly string[];
|
|
128
|
+
/**
|
|
129
|
+
* Resets the supported currencies cache.
|
|
130
|
+
* This is primarily intended for testing purposes.
|
|
131
|
+
*/
|
|
132
|
+
export declare function resetSupportedCurrenciesCache(): void;
|
|
108
133
|
/**
|
|
109
134
|
* This version of the token prices service uses V2 of the Codefi Price API to
|
|
110
135
|
* fetch token prices.
|
|
@@ -217,6 +242,12 @@ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesSe
|
|
|
217
242
|
* @returns True if the API supports the currency, false otherwise.
|
|
218
243
|
*/
|
|
219
244
|
validateCurrencySupported(currency: unknown): currency is SupportedCurrency;
|
|
245
|
+
/**
|
|
246
|
+
* Fetches the list of supported currencies from the API.
|
|
247
|
+
*
|
|
248
|
+
* @returns The list of supported currencies.
|
|
249
|
+
*/
|
|
250
|
+
updateSupportedCurrencies(): Promise<string[]>;
|
|
220
251
|
}
|
|
221
252
|
export {};
|
|
222
253
|
//# sourceMappingURL=codefi-v2.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codefi-v2.d.cts","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,
|
|
1
|
+
{"version":3,"file":"codefi-v2.d.cts","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,u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;;;OAIG;IACG,yBAAyB,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;CAGrD"}
|
|
@@ -4,6 +4,12 @@ import type { AbstractTokenPricesService, EvmAssetAddressWithChain, EvmAssetWith
|
|
|
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
|
+
* This is the fallback list used when the API is unavailable.
|
|
8
|
+
*/
|
|
9
|
+
export declare const SUPPORTED_CURRENCIES_FALLBACK: 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", "mon", "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", "ape"];
|
|
10
|
+
/**
|
|
11
|
+
* @deprecated Use `getSupportedCurrencies()` or `fetchSupportedCurrencies()` instead.
|
|
12
|
+
* This is an alias for backward compatibility.
|
|
7
13
|
*/
|
|
8
14
|
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", "mon", "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", "ape"];
|
|
9
15
|
/**
|
|
@@ -90,7 +96,7 @@ export declare const SPOT_PRICES_SUPPORT_INFO: {
|
|
|
90
96
|
* A currency that can be supplied as the `vsCurrency` parameter to
|
|
91
97
|
* the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.
|
|
92
98
|
*/
|
|
93
|
-
type SupportedCurrency = (typeof
|
|
99
|
+
type SupportedCurrency = (typeof SUPPORTED_CURRENCIES_FALLBACK)[number] | Uppercase<(typeof SUPPORTED_CURRENCIES_FALLBACK)[number]>;
|
|
94
100
|
/**
|
|
95
101
|
* The list of chain IDs that can be supplied in the URL for the `/spot-prices`
|
|
96
102
|
* endpoint, but in hexadecimal form (for consistency with how we represent
|
|
@@ -105,6 +111,25 @@ export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" |
|
|
|
105
111
|
* other places).
|
|
106
112
|
*/
|
|
107
113
|
type SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];
|
|
114
|
+
/**
|
|
115
|
+
* Fetches the list of supported currencies from the API.
|
|
116
|
+
* Falls back to the hardcoded list if the fetch fails.
|
|
117
|
+
*
|
|
118
|
+
* @returns The list of supported currencies in lowercase.
|
|
119
|
+
*/
|
|
120
|
+
export declare function fetchSupportedCurrencies(): Promise<string[]>;
|
|
121
|
+
/**
|
|
122
|
+
* Synchronously gets the list of supported currencies.
|
|
123
|
+
* Returns the last fetched value if available, otherwise returns the fallback list.
|
|
124
|
+
*
|
|
125
|
+
* @returns The list of supported currencies in lowercase.
|
|
126
|
+
*/
|
|
127
|
+
export declare function getSupportedCurrencies(): readonly string[];
|
|
128
|
+
/**
|
|
129
|
+
* Resets the supported currencies cache.
|
|
130
|
+
* This is primarily intended for testing purposes.
|
|
131
|
+
*/
|
|
132
|
+
export declare function resetSupportedCurrenciesCache(): void;
|
|
108
133
|
/**
|
|
109
134
|
* This version of the token prices service uses V2 of the Codefi Price API to
|
|
110
135
|
* fetch token prices.
|
|
@@ -217,6 +242,12 @@ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesSe
|
|
|
217
242
|
* @returns True if the API supports the currency, false otherwise.
|
|
218
243
|
*/
|
|
219
244
|
validateCurrencySupported(currency: unknown): currency is SupportedCurrency;
|
|
245
|
+
/**
|
|
246
|
+
* Fetches the list of supported currencies from the API.
|
|
247
|
+
*
|
|
248
|
+
* @returns The list of supported currencies.
|
|
249
|
+
*/
|
|
250
|
+
updateSupportedCurrencies(): Promise<string[]>;
|
|
220
251
|
}
|
|
221
252
|
export {};
|
|
222
253
|
//# sourceMappingURL=codefi-v2.d.mts.map
|
|
@@ -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,
|
|
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;;;;GAIG;AACH,eAAO,MAAM,6BAA6B,qnBA+KhC,CAAC;AAEX;;;G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@ 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.
|
|
18
|
+
* This is the fallback list used when the API is unavailable.
|
|
18
19
|
*/
|
|
19
|
-
export const
|
|
20
|
+
export const SUPPORTED_CURRENCIES_FALLBACK = [
|
|
20
21
|
// Bitcoin
|
|
21
22
|
'btc',
|
|
22
23
|
// Ether
|
|
@@ -192,6 +193,11 @@ export const SUPPORTED_CURRENCIES = [
|
|
|
192
193
|
// Apechain
|
|
193
194
|
'ape',
|
|
194
195
|
];
|
|
196
|
+
/**
|
|
197
|
+
* @deprecated Use `getSupportedCurrencies()` or `fetchSupportedCurrencies()` instead.
|
|
198
|
+
* This is an alias for backward compatibility.
|
|
199
|
+
*/
|
|
200
|
+
export const SUPPORTED_CURRENCIES = SUPPORTED_CURRENCIES_FALLBACK;
|
|
195
201
|
/**
|
|
196
202
|
* Represents the zero address, commonly used as a placeholder in blockchain transactions.
|
|
197
203
|
* In the context of fetching market data, the zero address is utilized to retrieve information
|
|
@@ -301,6 +307,54 @@ export const SUPPORTED_CHAIN_IDS = Object.keys(SPOT_PRICES_SUPPORT_INFO);
|
|
|
301
307
|
const SUPPORTED_CHAIN_IDS_V3 = Object.keys(SPOT_PRICES_SUPPORT_INFO).filter((chainId) => SPOT_PRICES_SUPPORT_INFO[chainId] !== null);
|
|
302
308
|
const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
|
|
303
309
|
const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
|
|
310
|
+
/**
|
|
311
|
+
* In-memory store for the last successfully fetched supported currencies.
|
|
312
|
+
*/
|
|
313
|
+
let lastFetchedCurrencies = null;
|
|
314
|
+
/**
|
|
315
|
+
* Fetches the list of supported currencies from the API.
|
|
316
|
+
* Falls back to the hardcoded list if the fetch fails.
|
|
317
|
+
*
|
|
318
|
+
* @returns The list of supported currencies in lowercase.
|
|
319
|
+
*/
|
|
320
|
+
export async function fetchSupportedCurrencies() {
|
|
321
|
+
try {
|
|
322
|
+
const url = `${BASE_URL_V1}/supportedVsCurrencies`;
|
|
323
|
+
const response = await handleFetch(url, {
|
|
324
|
+
headers: { 'Cache-Control': 'no-cache' },
|
|
325
|
+
});
|
|
326
|
+
if (Array.isArray(response)) {
|
|
327
|
+
const currencies = response.map((currency) => currency.toLowerCase());
|
|
328
|
+
lastFetchedCurrencies = currencies;
|
|
329
|
+
return currencies;
|
|
330
|
+
}
|
|
331
|
+
// Invalid response format, fall back to hardcoded list
|
|
332
|
+
return [...SUPPORTED_CURRENCIES_FALLBACK];
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
// On any error, fall back to the hardcoded list
|
|
336
|
+
return [...SUPPORTED_CURRENCIES_FALLBACK];
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Synchronously gets the list of supported currencies.
|
|
341
|
+
* Returns the last fetched value if available, otherwise returns the fallback list.
|
|
342
|
+
*
|
|
343
|
+
* @returns The list of supported currencies in lowercase.
|
|
344
|
+
*/
|
|
345
|
+
export function getSupportedCurrencies() {
|
|
346
|
+
if (lastFetchedCurrencies !== null) {
|
|
347
|
+
return lastFetchedCurrencies;
|
|
348
|
+
}
|
|
349
|
+
return SUPPORTED_CURRENCIES_FALLBACK;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Resets the supported currencies cache.
|
|
353
|
+
* This is primarily intended for testing purposes.
|
|
354
|
+
*/
|
|
355
|
+
export function resetSupportedCurrenciesCache() {
|
|
356
|
+
lastFetchedCurrencies = null;
|
|
357
|
+
}
|
|
304
358
|
/**
|
|
305
359
|
* This version of the token prices service uses V2 of the Codefi Price API to
|
|
306
360
|
* fetch token prices.
|
|
@@ -398,6 +452,11 @@ export class CodefiTokenPricesServiceV2 {
|
|
|
398
452
|
* @returns The exchange rates for the requested base currency.
|
|
399
453
|
*/
|
|
400
454
|
async fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }) {
|
|
455
|
+
// Refresh supported currencies in background (non-blocking)
|
|
456
|
+
// This ensures the list stays fresh during normal polling
|
|
457
|
+
// Note: fetchSupportedCurrencies handles errors internally and always resolves
|
|
458
|
+
// eslint-disable-next-line @typescript-eslint/no-floating-promises
|
|
459
|
+
fetchSupportedCurrencies();
|
|
401
460
|
const url = new URL(`${BASE_URL_V1}/exchange-rates`);
|
|
402
461
|
url.searchParams.append('baseCurrency', baseCurrency);
|
|
403
462
|
const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);
|
|
@@ -482,10 +541,18 @@ export class CodefiTokenPricesServiceV2 {
|
|
|
482
541
|
* @returns True if the API supports the currency, false otherwise.
|
|
483
542
|
*/
|
|
484
543
|
validateCurrencySupported(currency) {
|
|
485
|
-
const supportedCurrencies =
|
|
544
|
+
const supportedCurrencies = getSupportedCurrencies();
|
|
486
545
|
return (typeof currency === 'string' &&
|
|
487
546
|
supportedCurrencies.includes(currency.toLowerCase()));
|
|
488
547
|
}
|
|
548
|
+
/**
|
|
549
|
+
* Fetches the list of supported currencies from the API.
|
|
550
|
+
*
|
|
551
|
+
* @returns The list of supported currencies.
|
|
552
|
+
*/
|
|
553
|
+
async updateSupportedCurrencies() {
|
|
554
|
+
return fetchSupportedCurrencies();
|
|
555
|
+
}
|
|
489
556
|
}
|
|
490
557
|
_CodefiTokenPricesServiceV2_policy = new WeakMap();
|
|
491
558
|
//# 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,EACZ,mCAAmC;AAGpC,OAAO,EACL,WA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AAC,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 // Monad\n 'mon',\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 // Apechain\n 'ape',\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 '0x64': '0xe91d153e0b41518a2ce8dd3d7944fa863463a97d', // Gnosis\n '0x1e': '0x542fda317318ebf1d3deaf76e0b632741a7e677d', // Rootstock Mainnet - Native symbol: RBTC\n '0x2611': '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\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 '0x1e': 'eip155:30/slip44:137', // Rootstock Mainnet - Native symbol: RBTC\n '0x2a': 'eip155:42/erc20:0x0000000000000000000000000000000000000000', // Lukso - native symbol: LYX\n '0x32': 'eip155:50/erc20:0x0000000000000000000000000000000000000000', // xdc-network - native symbol: XDC\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 '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/erc20:0x0000000000000000000000000000000000000000', // 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: MON\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xc4': 'eip155:196/erc20:0x0000000000000000000000000000000000000000', // X Layer Mainnet - Native symbol: OKB\n '0xe8': 'eip155:232/erc20:0x0000000000000000000000000000000000000000', // Lens Mainnet - Native symbol: GHO\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0xfc': 'eip155:252/erc20:0x0000000000000000000000000000000000000000', // Fraxtal - native symbol: FRAX\n '0x10b3e': 'eip155:68414/erc20:0x0000000000000000000000000000000000000000', // MapleStory Universe - no slip44\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 '0x2eb': 'eip155:747/slip44:539', // Flow evm - Native symbol: Flow\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n '0x440': 'eip155:1088/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 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 '0x74c': 'eip155:1868/erc20:0x0000000000000000000000000000000000000000', // Soneium - Native symbol: ETH\n '0xa729': 'eip155:42793/erc20:0x0000000000000000000000000000000000000000', // Etherlink - Native symbol: XTZ (Tezos L2)\n '0xab5': 'eip155:2741/erc20:0x0000000000000000000000000000000000000000', // Abstract - Native symbol: ETH\n '0x10e6': 'eip155:4326/erc20:0x0000000000000000000000000000000000000000', // MegaETH Mainnet - Native symbol: ETH\n '0x1388': 'eip155:5000/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Mantle - Native symbol: MNT\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2611': 'eip155:9745/erc20:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\n '0x2710': 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n '0x8173': 'eip155:33139/erc20:0x0000000000000000000000000000000000000000', // Apechain Mainnet - Native symbol: APE\n '0xa3c3': 'eip155:41923/erc20:0x0000000000000000000000000000000000000000', // EDU Chain - Native symbol: EDU\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 '0xa867': 'eip155:43111/erc20:0x0000000000000000000000000000000000000000', // Hemi - Native symbol: ETH\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0xed88': 'eip155:60808/erc20:0x0000000000000000000000000000000000000000', // BOB - Native symbol: ETH\n '0x138de': 'eip155:80094/erc20:0x0000000000000000000000000000000000000000', // Berachain - Native symbol: Bera',\n '0x13c31': 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': 'eip155:97741/erc20:0x0000000000000000000000000000000000000000', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x18232': 'eip155:98866/erc20:0x0000000000000000000000000000000000000000', // Plume Mainnet - Narive symbol: Plume\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 '0xb67d2': 'eip155:747474/erc20:0x0000000000000000000000000000000000000000', // katana - Native symbol: ETH\n '0x15f900': 'eip155:1440000/erc20:0x0000000000000000000000000000000000000000', // xrpl-evm - native symbol: XRP\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// MISSING CHAINS WITH NO NATIVE ASSET PRICES\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x926': 'eip155:2342/erc20:0x0000000000000000000000000000000000000000', // Omnia Chain - Native symbol: OMNIA\n// '0x407b': 'eip155:16507/erc20:0x0000000000000000000000000000000000000000', // Genesys Mainnet - Native symbol: GSYS\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_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(\n ...args: Parameters<ServicePolicy['onBreak']>\n ): ReturnType<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(\n ...args: Parameters<ServicePolicy['onDegraded']>\n ): ReturnType<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 // 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 /**\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,O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AqB,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,GAAG,sBAAsB,EAAE,CAAC;QACrD,OAAO,CACL,OAAO,QAAQ,KAAK,QAAQ;YAC5B,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,yBAAyB;QAC7B,OAAO,wBAAwB,EAAE,CAAC;IACpC,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 * This is the fallback list used when the API is unavailable.\n */\nexport const SUPPORTED_CURRENCIES_FALLBACK = [\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 // Monad\n 'mon',\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 // Apechain\n 'ape',\n] as const;\n\n/**\n * @deprecated Use `getSupportedCurrencies()` or `fetchSupportedCurrencies()` instead.\n * This is an alias for backward compatibility.\n */\nexport const SUPPORTED_CURRENCIES = SUPPORTED_CURRENCIES_FALLBACK;\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 '0x64': '0xe91d153e0b41518a2ce8dd3d7944fa863463a97d', // Gnosis\n '0x1e': '0x542fda317318ebf1d3deaf76e0b632741a7e677d', // Rootstock Mainnet - Native symbol: RBTC\n '0x2611': '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\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 '0x1e': 'eip155:30/slip44:137', // Rootstock Mainnet - Native symbol: RBTC\n '0x2a': 'eip155:42/erc20:0x0000000000000000000000000000000000000000', // Lukso - native symbol: LYX\n '0x32': 'eip155:50/erc20:0x0000000000000000000000000000000000000000', // xdc-network - native symbol: XDC\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 '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/erc20:0x0000000000000000000000000000000000000000', // 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: MON\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xc4': 'eip155:196/erc20:0x0000000000000000000000000000000000000000', // X Layer Mainnet - Native symbol: OKB\n '0xe8': 'eip155:232/erc20:0x0000000000000000000000000000000000000000', // Lens Mainnet - Native symbol: GHO\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0xfc': 'eip155:252/erc20:0x0000000000000000000000000000000000000000', // Fraxtal - native symbol: FRAX\n '0x10b3e': 'eip155:68414/erc20:0x0000000000000000000000000000000000000000', // MapleStory Universe - no slip44\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 '0x2eb': 'eip155:747/slip44:539', // Flow evm - Native symbol: Flow\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n '0x440': 'eip155:1088/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // 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 '0x74c': 'eip155:1868/erc20:0x0000000000000000000000000000000000000000', // Soneium - Native symbol: ETH\n '0xa729': 'eip155:42793/erc20:0x0000000000000000000000000000000000000000', // Etherlink - Native symbol: XTZ (Tezos L2)\n '0xab5': 'eip155:2741/erc20:0x0000000000000000000000000000000000000000', // Abstract - Native symbol: ETH\n '0x10e6': 'eip155:4326/erc20:0x0000000000000000000000000000000000000000', // MegaETH Mainnet - Native symbol: ETH\n '0x1388': 'eip155:5000/erc20:0xdeaddeaddeaddeaddeaddeaddeaddeaddead0000', // Mantle - Native symbol: MNT\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2611': 'eip155:9745/erc20:0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee', // Plasma mainnet - native symbol: XPL\n '0x2710': 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n '0x8173': 'eip155:33139/erc20:0x0000000000000000000000000000000000000000', // Apechain Mainnet - Native symbol: APE\n '0xa3c3': 'eip155:41923/erc20:0x0000000000000000000000000000000000000000', // EDU Chain - Native symbol: EDU\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 '0xa867': 'eip155:43111/erc20:0x0000000000000000000000000000000000000000', // Hemi - Native symbol: ETH\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0xed88': 'eip155:60808/erc20:0x0000000000000000000000000000000000000000', // BOB - Native symbol: ETH\n '0x138de': 'eip155:80094/erc20:0x0000000000000000000000000000000000000000', // Berachain - Native symbol: Bera',\n '0x13c31': 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': 'eip155:97741/erc20:0x0000000000000000000000000000000000000000', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x18232': 'eip155:98866/erc20:0x0000000000000000000000000000000000000000', // Plume Mainnet - Narive symbol: Plume\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 '0xb67d2': 'eip155:747474/erc20:0x0000000000000000000000000000000000000000', // katana - Native symbol: ETH\n '0x15f900': 'eip155:1440000/erc20:0x0000000000000000000000000000000000000000', // xrpl-evm - native symbol: XRP\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// MISSING CHAINS WITH NO NATIVE ASSET PRICES\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x926': 'eip155:2342/erc20:0x0000000000000000000000000000000000000000', // Omnia Chain - Native symbol: OMNIA\n// '0x407b': 'eip155:16507/erc20:0x0000000000000000000000000000000000000000', // Genesys Mainnet - Native symbol: GSYS\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_FALLBACK)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES_FALLBACK)[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_V3 = 'https://price.api.cx.metamask.io/v3';\n\n/**\n * In-memory store for the last successfully fetched supported currencies.\n */\nlet lastFetchedCurrencies: string[] | null = null;\n\n/**\n * Fetches the list of supported currencies from the API.\n * Falls back to the hardcoded list if the fetch fails.\n *\n * @returns The list of supported currencies in lowercase.\n */\nexport async function fetchSupportedCurrencies(): Promise<string[]> {\n try {\n const url = `${BASE_URL_V1}/supportedVsCurrencies`;\n const response = await handleFetch(url, {\n headers: { 'Cache-Control': 'no-cache' },\n });\n\n if (Array.isArray(response)) {\n const currencies = response.map((currency: string) =>\n currency.toLowerCase(),\n );\n lastFetchedCurrencies = currencies;\n return currencies;\n }\n\n // Invalid response format, fall back to hardcoded list\n return [...SUPPORTED_CURRENCIES_FALLBACK];\n } catch {\n // On any error, fall back to the hardcoded list\n return [...SUPPORTED_CURRENCIES_FALLBACK];\n }\n}\n\n/**\n * Synchronously gets the list of supported currencies.\n * Returns the last fetched value if available, otherwise returns the fallback list.\n *\n * @returns The list of supported currencies in lowercase.\n */\nexport function getSupportedCurrencies(): readonly string[] {\n if (lastFetchedCurrencies !== null) {\n return lastFetchedCurrencies;\n }\n return SUPPORTED_CURRENCIES_FALLBACK;\n}\n\n/**\n * Resets the supported currencies cache.\n * This is primarily intended for testing purposes.\n */\nexport function resetSupportedCurrenciesCache(): void {\n lastFetchedCurrencies = null;\n}\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(\n ...args: Parameters<ServicePolicy['onBreak']>\n ): ReturnType<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(\n ...args: Parameters<ServicePolicy['onDegraded']>\n ): ReturnType<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 // 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 /**\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 // Refresh supported currencies in background (non-blocking)\n // This ensures the list stays fresh during normal polling\n // Note: fetchSupportedCurrencies handles errors internally and always resolves\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n fetchSupportedCurrencies();\n\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 = getSupportedCurrencies();\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n\n /**\n * Fetches the list of supported currencies from the API.\n *\n * @returns The list of supported currencies.\n */\n async updateSupportedCurrencies(): Promise<string[]> {\n return fetchSupportedCurrencies();\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/assets-controllers",
|
|
3
|
-
"version": "95.3.0-preview-
|
|
3
|
+
"version": "95.3.0-preview-3ec2a74",
|
|
4
4
|
"description": "Controllers which manage interactions involving ERC-20, ERC-721, and ERC-1155 tokens (including NFTs)",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"MetaMask",
|