@metamask-previews/assets-controllers 89.0.1-preview-40ec088b → 89.0.1-preview-152da47f

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.
@@ -1 +1 @@
1
- {"version":3,"file":"abstract-token-prices-service.cjs","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"","sourcesContent":["import type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\n\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * Represents an exchange rate.\n */\nexport type ExchangeRate = {\n name: string;\n ticker: string;\n value: number;\n currencyType: string;\n usd?: number;\n};\n\n/**\n * A map of currency to its exchange rate.\n */\nexport type ExchangeRatesByCurrency<Currency extends string> = {\n [C in Currency]: ExchangeRate;\n};\n\nexport type EvmAssetAddressWithChain<ChainId extends Hex = Hex> = {\n tokenAddress: Hex;\n chainId: ChainId;\n};\n\nexport type EvmAssetWithId<ChainId extends Hex = Hex> =\n EvmAssetAddressWithChain<ChainId> & {\n assetId: CaipAssetType;\n };\n\nexport type EvmAssetWithMarketData<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = EvmAssetWithId<ChainId> & MarketDataDetails & { currency: Currency };\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = Partial<Pick<ServicePolicy, 'onBreak' | 'onDegraded'>> & {\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to this function.\n * @param args.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 fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<ChainId>[];\n currency: Currency;\n }): Promise<EvmAssetWithMarketData<ChainId, Currency>[]>;\n\n /**\n * Retrieves exchange rates in the given currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired currency of the token prices.\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 in the requested base currency.\n */\n fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: Currency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<Currency>>;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
1
+ {"version":3,"file":"abstract-token-prices-service.cjs","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"","sourcesContent":["import type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\n\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * Represents an exchange rate.\n */\nexport type ExchangeRate = {\n name: string;\n ticker: string;\n value: number;\n currencyType: string;\n usd?: number;\n};\n\n/**\n * A map of currency to its exchange rate.\n */\nexport type ExchangeRatesByCurrency<Currency extends string> = {\n [C in Currency]: ExchangeRate;\n};\n\nexport type EvmAssetAddressWithChain<ChainId extends Hex = Hex> = {\n tokenAddress: Hex;\n chainId: ChainId;\n};\n\nexport type EvmAssetWithId<ChainId extends Hex = Hex> =\n EvmAssetAddressWithChain<ChainId> & {\n assetId: CaipAssetType;\n };\n\nexport type EvmAssetWithMarketData<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = EvmAssetAddressWithChain<ChainId> &\n MarketDataDetails & { currency: Currency };\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = Partial<Pick<ServicePolicy, 'onBreak' | 'onDegraded'>> & {\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to this function.\n * @param args.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 fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<ChainId>[];\n currency: Currency;\n }): Promise<EvmAssetWithMarketData<ChainId, Currency>[]>;\n\n /**\n * Retrieves exchange rates in the given currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired currency of the token prices.\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 in the requested base currency.\n */\n fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: Currency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<Currency>>;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
@@ -24,7 +24,7 @@ export type EvmAssetAddressWithChain<ChainId extends Hex = Hex> = {
24
24
  export type EvmAssetWithId<ChainId extends Hex = Hex> = EvmAssetAddressWithChain<ChainId> & {
25
25
  assetId: CaipAssetType;
26
26
  };
27
- export type EvmAssetWithMarketData<ChainId extends Hex = Hex, Currency extends string = string> = EvmAssetWithId<ChainId> & MarketDataDetails & {
27
+ export type EvmAssetWithMarketData<ChainId extends Hex = Hex, Currency extends string = string> = EvmAssetAddressWithChain<ChainId> & MarketDataDetails & {
28
28
  currency: Currency;
29
29
  };
30
30
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"abstract-token-prices-service.d.cts","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,GAAG,EAAE,wBAAwB;AAE1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAgC;AAEjE;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,CAAC,QAAQ,SAAS,MAAM,IAAI;KAC5D,CAAC,IAAI,QAAQ,GAAG,YAAY;CAC9B,CAAC;AAEF,MAAM,MAAM,wBAAwB,CAAC,OAAO,SAAS,GAAG,GAAG,GAAG,IAAI;IAChE,YAAY,EAAE,GAAG,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,cAAc,CAAC,OAAO,SAAS,GAAG,GAAG,GAAG,IAClD,wBAAwB,CAAC,OAAO,CAAC,GAAG;IAClC,OAAO,EAAE,aAAa,CAAC;CACxB,CAAC;AAEJ,MAAM,MAAM,sBAAsB,CAChC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B,cAAc,CAAC,OAAO,CAAC,GAAG,iBAAiB,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC;AAEzE;;;;;;;;GAQG;AACH,MAAM,MAAM,0BAA0B,CACpC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG,YAAY,CAAC,CAAC,GAAG;IAC3D;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EACf,MAAM,EACN,QAAQ,GACT,EAAE;QACD,MAAM,EAAE,wBAAwB,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5C,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,sBAAsB,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;IAEzD;;;;;;;;OAQG;IACH,kBAAkB,CAAC,EACjB,YAAY,EACZ,cAAc,EACd,gBAAgB,GACjB,EAAE;QACD,YAAY,EAAE,QAAQ,CAAC;QACvB,cAAc,EAAE,OAAO,CAAC;QACxB,gBAAgB,EAAE,MAAM,EAAE,CAAC;KAC5B,GAAG,OAAO,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC,CAAC;IAE/C;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
1
+ {"version":3,"file":"abstract-token-prices-service.d.cts","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,G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,CAAC;KACpB,GAAG,OAAO,CAAC,sBAAsB,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;IAEzD;;;;;;;;OAQG;IACH,kBAAkB,CAAC,EACjB,YAAY,EACZ,cAAc,EACd,gBAAgB,GACjB,EAAE;QACD,YAAY,EAAE,QAAQ,CAAC;QACvB,cAAc,EAAE,OAAO,CAAC;QACxB,gBAAgB,EAAE,MAAM,EAAE,CAAC;KAC5B,GAAG,OAAO,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC,CAAC;IAE/C;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
@@ -24,7 +24,7 @@ export type EvmAssetAddressWithChain<ChainId extends Hex = Hex> = {
24
24
  export type EvmAssetWithId<ChainId extends Hex = Hex> = EvmAssetAddressWithChain<ChainId> & {
25
25
  assetId: CaipAssetType;
26
26
  };
27
- export type EvmAssetWithMarketData<ChainId extends Hex = Hex, Currency extends string = string> = EvmAssetWithId<ChainId> & MarketDataDetails & {
27
+ export type EvmAssetWithMarketData<ChainId extends Hex = Hex, Currency extends string = string> = EvmAssetAddressWithChain<ChainId> & MarketDataDetails & {
28
28
  currency: Currency;
29
29
  };
30
30
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"abstract-token-prices-service.d.mts","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,GAAG,EAAE,wBAAwB;AAE1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAgC;AAEjE;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,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,cAAc,EACd,gBAAgB,GACjB,EAAE;QACD,YAAY,EAAE,QAAQ,CAAC;QACvB,cAAc,EAAE,OAAO,CAAC;QACxB,gBAAgB,EAAE,MAAM,EAAE,CAAC;KAC5B,GAAG,OAAO,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC,CAAC;IAE/C;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
1
+ {"version":3,"file":"abstract-token-prices-service.d.mts","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,GAAG,EAAE,wBAAwB;AAE1D,OAAO,KAAK,EAAE,iBAAiB,EAAE,oCAAgC;AAEjE;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,uBAAuB,CAAC,QAAQ,SAAS,MAAM,IAAI;KAC5D,CAAC,IAAI,QAAQ,GAAG,YAAY;CAC9B,CAAC;AAEF,MAAM,MAAM,wBAAwB,CAAC,OAAO,SAAS,GAAG,GAAG,GAAG,IAAI;IAChE,YAAY,EAAE,GAAG,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,cAAc,CAAC,OAAO,SAAS,GAAG,GAAG,GAAG,IAClD,wBAAwB,CAAC,OAAO,CAAC,GAAG;IAClC,OAAO,EAAE,aAAa,CAAC;CACxB,CAAC;AAEJ,MAAM,MAAM,sBAAsB,CAChC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B,wBAAwB,CAAC,OAAO,CAAC,GACnC,iBAAiB,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAC;AAE7C;;;;;;;;GAQG;AACH,MAAM,MAAM,0BAA0B,CACpC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG,YAAY,CAAC,CAAC,GAAG;IAC3D;;;;;;;;OAQG;IACH,gBAAgB,CAAC,EACf,MAAM,EACN,QAAQ,GACT,EAAE;QACD,MAAM,EAAE,wBAAwB,CAAC,OAAO,CAAC,EAAE,CAAC;QAC5C,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,sBAAsB,CAAC,OAAO,EAAE,QAAQ,CAAC,EAAE,CAAC,CAAC;IAEzD;;;;;;;;OAQG;IACH,kBAAkB,CAAC,EACjB,YAAY,EACZ,cAAc,EACd,gBAAgB,GACjB,EAAE;QACD,YAAY,EAAE,QAAQ,CAAC;QACvB,cAAc,EAAE,OAAO,CAAC;QACxB,gBAAgB,EAAE,MAAM,EAAE,CAAC;KAC5B,GAAG,OAAO,CAAC,uBAAuB,CAAC,QAAQ,CAAC,CAAC,CAAC;IAE/C;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"abstract-token-prices-service.mjs","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"","sourcesContent":["import type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\n\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * Represents an exchange rate.\n */\nexport type ExchangeRate = {\n name: string;\n ticker: string;\n value: number;\n currencyType: string;\n usd?: number;\n};\n\n/**\n * A map of currency to its exchange rate.\n */\nexport type ExchangeRatesByCurrency<Currency extends string> = {\n [C in Currency]: ExchangeRate;\n};\n\nexport type EvmAssetAddressWithChain<ChainId extends Hex = Hex> = {\n tokenAddress: Hex;\n chainId: ChainId;\n};\n\nexport type EvmAssetWithId<ChainId extends Hex = Hex> =\n EvmAssetAddressWithChain<ChainId> & {\n assetId: CaipAssetType;\n };\n\nexport type EvmAssetWithMarketData<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = EvmAssetWithId<ChainId> & MarketDataDetails & { currency: Currency };\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = Partial<Pick<ServicePolicy, 'onBreak' | 'onDegraded'>> & {\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to this function.\n * @param args.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 fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<ChainId>[];\n currency: Currency;\n }): Promise<EvmAssetWithMarketData<ChainId, Currency>[]>;\n\n /**\n * Retrieves exchange rates in the given currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired currency of the token prices.\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 in the requested base currency.\n */\n fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: Currency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<Currency>>;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
1
+ {"version":3,"file":"abstract-token-prices-service.mjs","sourceRoot":"","sources":["../../src/token-prices-service/abstract-token-prices-service.ts"],"names":[],"mappings":"","sourcesContent":["import type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\n\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * Represents an exchange rate.\n */\nexport type ExchangeRate = {\n name: string;\n ticker: string;\n value: number;\n currencyType: string;\n usd?: number;\n};\n\n/**\n * A map of currency to its exchange rate.\n */\nexport type ExchangeRatesByCurrency<Currency extends string> = {\n [C in Currency]: ExchangeRate;\n};\n\nexport type EvmAssetAddressWithChain<ChainId extends Hex = Hex> = {\n tokenAddress: Hex;\n chainId: ChainId;\n};\n\nexport type EvmAssetWithId<ChainId extends Hex = Hex> =\n EvmAssetAddressWithChain<ChainId> & {\n assetId: CaipAssetType;\n };\n\nexport type EvmAssetWithMarketData<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = EvmAssetAddressWithChain<ChainId> &\n MarketDataDetails & { currency: Currency };\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n Currency extends string = string,\n> = Partial<Pick<ServicePolicy, 'onBreak' | 'onDegraded'>> & {\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to this function.\n * @param args.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 fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<ChainId>[];\n currency: Currency;\n }): Promise<EvmAssetWithMarketData<ChainId, Currency>[]>;\n\n /**\n * Retrieves exchange rates in the given currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired currency of the token prices.\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 in the requested base currency.\n */\n fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: Currency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<Currency>>;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
@@ -10,9 +10,9 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
10
10
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
11
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
12
  };
13
- var _CodefiTokenPricesServiceV2_policy;
13
+ var _CodefiTokenPricesServiceV2_instances, _CodefiTokenPricesServiceV2_policy, _CodefiTokenPricesServiceV2_fetchTokenPricesV3, _CodefiTokenPricesServiceV2_fetchTokenPricesV2;
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.CodefiTokenPricesServiceV2 = exports.SUPPORTED_CHAIN_IDS = exports.HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = exports.getNativeTokenAddress = exports.ZERO_ADDRESS = exports.SUPPORTED_CURRENCIES = void 0;
15
+ exports.CodefiTokenPricesServiceV2 = exports.SUPPORTED_CHAIN_IDS = exports.SPOT_PRICES_SUPPORT_INFO = exports.getNativeTokenAddress = exports.ZERO_ADDRESS = exports.SUPPORTED_CURRENCIES = void 0;
16
16
  const controller_utils_1 = require("@metamask/controller-utils");
17
17
  const utils_1 = require("@metamask/utils");
18
18
  /**
@@ -217,25 +217,37 @@ const getNativeTokenAddress = (chainId) => chainIdToNativeTokenAddress[chainId]
217
217
  exports.getNativeTokenAddress = getNativeTokenAddress;
218
218
  // Source: https://github.com/consensys-vertical-apps/va-mmcx-price-api/blob/main/src/constants/slip44.ts
219
219
  // We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.
220
- exports.HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {
220
+ exports.SPOT_PRICES_SUPPORT_INFO = {
221
221
  '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH
222
222
  '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH
223
223
  '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO
224
224
  '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB
225
+ '0x39': null, // 'eip155:57/slip44:57', // Syscoin Mainnet - Native symbol: SYS
226
+ '0x52': null, // 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR
227
+ '0x58': null, // 'eip155:88/slip44:889', // TomoChain - Native symbol: TOMO
225
228
  '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI
229
+ '0x6a': null, // 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX
230
+ '0x80': null, // 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT
226
231
  '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL
227
232
  '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S
228
233
  '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM
234
+ '0x141': null, // 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS
229
235
  '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH
236
+ '0x169': null, // 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL
230
237
  '0x44d': 'eip155:1101/slip44:60', // Polygon zkEVM mainnet - Native symbol: ETH
231
238
  '0x504': 'eip155:1284/slip44:1284', // Moonbeam - Native symbol: GLMR
232
239
  '0x505': 'eip155:1285/slip44:1285', // Moonriver - Native symbol: MOVR
233
240
  '0x531': 'eip155:1329/slip44:19000118', // Sei Mainnet - Native symbol: SEI
234
241
  '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH
242
+ '0x2710': null, // 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH
235
243
  '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH
236
244
  '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO
245
+ '0xa516': null, // 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE
237
246
  '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX
238
247
  '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH
248
+ '0x13c31': null, // 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH
249
+ '0x17dcd': null, // 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU
250
+ '0x518af': null, // 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS
239
251
  '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH
240
252
  '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH
241
253
  '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE
@@ -249,11 +261,14 @@ exports.HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {
249
261
  *
250
262
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
251
263
  */
252
- exports.SUPPORTED_CHAIN_IDS = Object.keys(exports.HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP);
264
+ exports.SUPPORTED_CHAIN_IDS = Object.keys(exports.SPOT_PRICES_SUPPORT_INFO);
253
265
  /**
254
- * All requests to V2 of the Price API start with this.
266
+ * The list of chain IDs that are supported by V3 of the Codefi Price API.
267
+ * Only includes chain IDs from SPOT_PRICES_SUPPORT_INFO that have a non-null CAIP-19 value.
255
268
  */
269
+ const SUPPORTED_CHAIN_IDS_V3 = Object.keys(exports.SPOT_PRICES_SUPPORT_INFO).filter((chainId) => exports.SPOT_PRICES_SUPPORT_INFO[chainId] !== null);
256
270
  const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
271
+ const BASE_URL_V2 = 'https://price.api.cx.metamask.io/v2';
257
272
  const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
258
273
  /**
259
274
  * This version of the token prices service uses V2 of the Codefi Price API to
@@ -261,6 +276,7 @@ const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
261
276
  */
262
277
  class CodefiTokenPricesServiceV2 {
263
278
  constructor({ degradedThreshold = controller_utils_1.DEFAULT_DEGRADED_THRESHOLD, retries = controller_utils_1.DEFAULT_MAX_RETRIES, maximumConsecutiveFailures = controller_utils_1.DEFAULT_MAX_CONSECUTIVE_FAILURES, onBreak, onDegraded, circuitBreakDuration = controller_utils_1.DEFAULT_CIRCUIT_BREAK_DURATION, } = {}) {
279
+ _CodefiTokenPricesServiceV2_instances.add(this);
264
280
  _CodefiTokenPricesServiceV2_policy.set(this, void 0);
265
281
  __classPrivateFieldSet(this, _CodefiTokenPricesServiceV2_policy, (0, controller_utils_1.createServicePolicy)({
266
282
  maxRetries: retries,
@@ -305,36 +321,9 @@ class CodefiTokenPricesServiceV2 {
305
321
  * @returns The prices for the requested tokens.
306
322
  */
307
323
  async fetchTokenPrices({ assets, currency, }) {
308
- const assetsWithIds = assets
309
- .map((asset) => {
310
- const caipChainId = (0, utils_1.toCaipChainId)(utils_1.KnownCaipNamespace.Eip155, (0, utils_1.hexToNumber)(asset.chainId).toString());
311
- const nativeAddress = (0, exports.getNativeTokenAddress)(asset.chainId);
312
- return {
313
- ...asset,
314
- assetId: nativeAddress.toLowerCase() === asset.tokenAddress.toLowerCase()
315
- ? exports.HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP[asset.chainId]
316
- : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`,
317
- };
318
- })
319
- .filter((asset) => asset.assetId);
320
- const url = new URL(`${BASE_URL_V3}/spot-prices`);
321
- url.searchParams.append('assetIds', assetsWithIds.map((asset) => asset.assetId).join(','));
322
- url.searchParams.append('vsCurrency', currency);
323
- url.searchParams.append('includeMarketData', 'true');
324
- const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => (0, controller_utils_1.handleFetch)(url, { headers: { 'Cache-Control': 'no-cache' } }));
325
- return assetsWithIds
326
- .map((assetWithId) => {
327
- const marketData = addressCryptoDataMap[assetWithId.assetId];
328
- if (!marketData) {
329
- return undefined;
330
- }
331
- return {
332
- ...marketData,
333
- ...assetWithId,
334
- currency,
335
- };
336
- })
337
- .filter((entry) => Boolean(entry));
324
+ const v3Assets = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_instances, "m", _CodefiTokenPricesServiceV2_fetchTokenPricesV3).call(this, assets, currency);
325
+ const v2Assets = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_instances, "m", _CodefiTokenPricesServiceV2_fetchTokenPricesV2).call(this, assets, currency);
326
+ return [...v3Assets, ...v2Assets];
338
327
  }
339
328
  /**
340
329
  * Retrieves exchange rates in the given base currency.
@@ -436,5 +425,78 @@ class CodefiTokenPricesServiceV2 {
436
425
  }
437
426
  }
438
427
  exports.CodefiTokenPricesServiceV2 = CodefiTokenPricesServiceV2;
439
- _CodefiTokenPricesServiceV2_policy = new WeakMap();
428
+ _CodefiTokenPricesServiceV2_policy = new WeakMap(), _CodefiTokenPricesServiceV2_instances = new WeakSet(), _CodefiTokenPricesServiceV2_fetchTokenPricesV3 = async function _CodefiTokenPricesServiceV2_fetchTokenPricesV3(assets, currency) {
429
+ const assetsWithIds = assets
430
+ // Filter out assets that are not supported by V3 of the Price API.
431
+ .filter((asset) => SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId))
432
+ .map((asset) => {
433
+ const caipChainId = (0, utils_1.toCaipChainId)(utils_1.KnownCaipNamespace.Eip155, (0, utils_1.hexToNumber)(asset.chainId).toString());
434
+ const nativeAddress = (0, exports.getNativeTokenAddress)(asset.chainId);
435
+ return {
436
+ ...asset,
437
+ assetId: (nativeAddress.toLowerCase() ===
438
+ asset.tokenAddress.toLowerCase()
439
+ ? exports.SPOT_PRICES_SUPPORT_INFO[asset.chainId]
440
+ : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`),
441
+ };
442
+ })
443
+ .filter((asset) => asset.assetId);
444
+ if (assetsWithIds.length === 0) {
445
+ return [];
446
+ }
447
+ const url = new URL(`${BASE_URL_V3}/spot-prices`);
448
+ url.searchParams.append('assetIds', assetsWithIds.map((asset) => asset.assetId).join(','));
449
+ url.searchParams.append('vsCurrency', currency);
450
+ url.searchParams.append('includeMarketData', 'true');
451
+ const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => (0, controller_utils_1.handleFetch)(url, { headers: { 'Cache-Control': 'no-cache' } }));
452
+ return assetsWithIds
453
+ .map((assetWithId) => {
454
+ const marketData = addressCryptoDataMap[assetWithId.assetId];
455
+ if (!marketData) {
456
+ return undefined;
457
+ }
458
+ return {
459
+ ...marketData,
460
+ ...assetWithId,
461
+ currency,
462
+ };
463
+ })
464
+ .filter((entry) => Boolean(entry));
465
+ }, _CodefiTokenPricesServiceV2_fetchTokenPricesV2 = async function _CodefiTokenPricesServiceV2_fetchTokenPricesV2(assets, currency) {
466
+ const v2SupportedAssets = assets.filter((asset) => !SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId));
467
+ console.log('DEBUG LEGACY ASSETS', { v2SupportedAssets, currency });
468
+ const assetsByChainId = v2SupportedAssets.reduce((acc, { chainId, tokenAddress }) => {
469
+ (acc[chainId] ?? (acc[chainId] = [])).push(tokenAddress);
470
+ return acc;
471
+ }, {});
472
+ const promises = Object.entries(assetsByChainId).map(async ([chainId, tokenAddresses]) => {
473
+ if (tokenAddresses.length === 0) {
474
+ return [];
475
+ }
476
+ const url = new URL(`${BASE_URL_V2}/chains/${chainId}/spot-prices`);
477
+ url.searchParams.append('tokenAddresses', tokenAddresses.join(','));
478
+ url.searchParams.append('vsCurrency', currency);
479
+ url.searchParams.append('includeMarketData', 'true');
480
+ const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => (0, controller_utils_1.handleFetch)(url, { headers: { 'Cache-Control': 'no-cache' } }));
481
+ console.log('DEBUG LEGACY CHAIN', {
482
+ chainId,
483
+ tokenAddresses,
484
+ });
485
+ return tokenAddresses
486
+ .map((tokenAddress) => {
487
+ const marketData = addressCryptoDataMap[tokenAddress.toLowerCase()];
488
+ if (!marketData) {
489
+ return undefined;
490
+ }
491
+ return {
492
+ ...marketData,
493
+ tokenAddress,
494
+ chainId: chainId,
495
+ currency,
496
+ };
497
+ })
498
+ .filter((entry) => Boolean(entry));
499
+ });
500
+ return await Promise.allSettled(promises).then((results) => results.flatMap((result) => result.status === 'fulfilled' ? result.value : []));
501
+ };
440
502
  //# sourceMappingURL=codefi-v2.cjs.map
@@ -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,eAA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,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF;AA/SD,gEA+SC","sourcesContent":["import {\n createServicePolicy,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\nimport {\n hexToNumber,\n KnownCaipNamespace,\n toCaipChainId,\n} from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n EvmAssetAddressWithChain,\n EvmAssetWithId,\n EvmAssetWithMarketData,\n ExchangeRatesByCurrency,\n} from './abstract-token-prices-service';\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Georgian Lari\n 'gel',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n // Colombian Peso\n 'cop',\n // Kenyan Shilling\n 'kes',\n // Romanian Leu\n 'ron',\n // Dominican Peso\n 'dop',\n // Costa Rican Colón\n 'crc',\n // Honduran Lempira\n 'hnl',\n // Zambian Kwacha\n 'zmw',\n // Salvadoran Colón\n 'svc',\n // Bosnia-Herzegovina Convertible Mark\n 'bam',\n // Peruvian Sol\n 'pen',\n // Guatemalan Quetzal\n 'gtq',\n // Lebanese Pound\n 'lbp',\n // Armenian Dram\n 'amd',\n // Solana\n 'sol',\n // Sei\n 'sei',\n // Sonic\n 'sonic',\n // Tron\n 'trx',\n // Taiko\n 'taiko',\n // Pepu\n 'pepu',\n // Polygon\n 'pol',\n // Mantle\n 'mnt',\n // Onomy\n 'nom',\n // Avalanche\n 'avax',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n *\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n// 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 HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {\n '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH\n '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH\n '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO\n '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB\n '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI\n '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH\n '0x44d': 'eip155:1101/slip44:60', // Polygon zkEVM mainnet - Native symbol: ETH\n '0x504': 'eip155:1284/slip44:1284', // Moonbeam - Native symbol: GLMR\n '0x505': 'eip155:1285/slip44:1285', // Moonriver - Native symbol: MOVR\n '0x531': 'eip155:1329/slip44:19000118', // Sei Mainnet - Native symbol: SEI\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH\n '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH\n '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH\n '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE\n '0x279f': 'eip155:143/slip44:268435779', // Monad Testnet - Native symbol: MON\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n};\n\n// MISSING CHAINS WITH NATIVE ASSET PRICES IN V2\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// '0x6a': 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX\n// '0x80': 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT\n// '0x141': 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS\n// '0x169': 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL\n// '0x2710': 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n// '0xa516': 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE\n// '0x13c31': 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n// '0x17dcd': 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU\n// '0x518af': 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS\n\n// MISSING CHAINS WITH NO NATIVE ASSET PRICES IN V2\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x7a': 'eip155:122/slip44:XXX', // Fuse Mainnet - Native symbol: FUSE\n// '0x120': 'eip155:288/slip44:60', // Boba Network (Ethereum L2) - Native symbol: ETH\n// '0x150': 'eip155:336/slip44:809', // Shiden - Native symbol: SDN\n// '0x440': 'eip155:1088/slip44:60', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: ETH\n// '0x1388': 'eip155:5000/slip44:XXX', // Mantle - Native symbol: MNT\n// '0x28c58': 'eip155:167000/slip44:60', // Taiko Mainnet - Native symbol: ETH\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n *\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = Object.keys(\n HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP,\n) as (keyof typeof HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP)[];\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';\n\nconst BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';\n\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements AbstractTokenPricesService<SupportedChainId, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.assets - The assets to get prices for.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<SupportedChainId>[];\n currency: SupportedCurrency;\n }): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const assetsWithIds: EvmAssetWithId<SupportedChainId>[] = assets\n .map((asset) => {\n const caipChainId = toCaipChainId(\n KnownCaipNamespace.Eip155,\n hexToNumber(asset.chainId).toString(),\n );\n\n const nativeAddress = getNativeTokenAddress(asset.chainId);\n\n return {\n ...asset,\n assetId:\n nativeAddress.toLowerCase() === asset.tokenAddress.toLowerCase()\n ? HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP[asset.chainId]\n : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`,\n } as EvmAssetWithId<SupportedChainId>;\n })\n .filter((asset) => asset.assetId);\n\n const url = new URL(`${BASE_URL_V3}/spot-prices`);\n url.searchParams.append(\n 'assetIds',\n assetsWithIds.map((asset) => asset.assetId).join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [assetId: CaipAssetType]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return assetsWithIds\n .map((assetWithId) => {\n const marketData = addressCryptoDataMap[assetWithId.assetId];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n ...assetWithId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));\n }\n\n /**\n * Retrieves exchange rates in the given base currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired base currency of the exchange rates.\n * @param args.includeUsdRate - Whether to include the USD rate in the response.\n * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.\n * @returns The exchange rates for the requested base currency.\n */\n async fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: SupportedCurrency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<SupportedCurrency>> {\n const url = new URL(`${BASE_URL_V1}/exchange-rates`);\n url.searchParams.append('baseCurrency', baseCurrency);\n\n const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);\n urlUsd.searchParams.append('baseCurrency', 'usd');\n\n const [exchangeRatesResult, exchangeRatesResultUsd] =\n await Promise.allSettled([\n this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n ),\n ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'\n ? [\n this.#policy.execute(() =>\n handleFetch(urlUsd, {\n headers: { 'Cache-Control': 'no-cache' },\n }),\n ),\n ]\n : []),\n ]);\n\n // Handle resolved/rejected\n const exchangeRates =\n exchangeRatesResult.status === 'fulfilled'\n ? exchangeRatesResult.value\n : {};\n const exchangeRatesUsd =\n exchangeRatesResultUsd?.status === 'fulfilled'\n ? exchangeRatesResultUsd.value\n : {};\n\n if (exchangeRatesResult.status === 'rejected') {\n throw new Error('Failed to fetch');\n }\n\n const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRates[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRates[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (Object.keys(filteredExchangeRates).length === 0) {\n throw new Error(\n 'None of the cryptocurrencies are supported by price api',\n );\n }\n\n const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRatesUsd[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRatesUsd[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (baseCurrency.toLowerCase() === 'usd') {\n Object.keys(filteredExchangeRates).forEach((key) => {\n filteredExchangeRates[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n usd: filteredExchangeRates[key as SupportedCurrency]?.value,\n };\n });\n return filteredExchangeRates;\n }\n if (!includeUsdRate) {\n return filteredExchangeRates;\n }\n\n const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {\n acc[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n ...(filteredUsdExchangeRates[key as SupportedCurrency]?.value\n ? { usd: filteredUsdExchangeRates[key as SupportedCurrency]?.value }\n : {}),\n };\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n return merged;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
1
+ {"version":3,"file":"codefi-v2.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,KAA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B,MAAM,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAClD,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n createServicePolicy,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\nimport {\n hexToNumber,\n KnownCaipNamespace,\n toCaipChainId,\n} from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n EvmAssetAddressWithChain,\n EvmAssetWithId,\n EvmAssetWithMarketData,\n ExchangeRatesByCurrency,\n} from './abstract-token-prices-service';\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Georgian Lari\n 'gel',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n // Colombian Peso\n 'cop',\n // Kenyan Shilling\n 'kes',\n // Romanian Leu\n 'ron',\n // Dominican Peso\n 'dop',\n // Costa Rican Colón\n 'crc',\n // Honduran Lempira\n 'hnl',\n // Zambian Kwacha\n 'zmw',\n // Salvadoran Colón\n 'svc',\n // Bosnia-Herzegovina Convertible Mark\n 'bam',\n // Peruvian Sol\n 'pen',\n // Guatemalan Quetzal\n 'gtq',\n // Lebanese Pound\n 'lbp',\n // Armenian Dram\n 'amd',\n // Solana\n 'sol',\n // Sei\n 'sei',\n // Sonic\n 'sonic',\n // Tron\n 'trx',\n // Taiko\n 'taiko',\n // Pepu\n 'pepu',\n // Polygon\n 'pol',\n // Mantle\n 'mnt',\n // Onomy\n 'nom',\n // Avalanche\n 'avax',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n *\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n// Source: https://github.com/consensys-vertical-apps/va-mmcx-price-api/blob/main/src/constants/slip44.ts\n// We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.\nexport const SPOT_PRICES_SUPPORT_INFO = {\n '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH\n '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH\n '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO\n '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB\n '0x39': null, // 'eip155:57/slip44:57', // Syscoin Mainnet - Native symbol: SYS\n '0x52': null, // 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR\n '0x58': null, // 'eip155:88/slip44:889', // TomoChain - Native symbol: TOMO\n '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI\n '0x6a': null, // 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX\n '0x80': null, // 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT\n '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0x141': null, // 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS\n '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH\n '0x169': null, // 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL\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 '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2710': null, // 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH\n '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO\n '0xa516': null, // 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0x13c31': null, // 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': null, // 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x518af': null, // 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS\n '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH\n '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH\n '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE\n '0x279f': 'eip155:143/slip44:268435779', // Monad Testnet - Native symbol: MON\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n} as const;\n\n// MISSING CHAINS WITH NO NATIVE ASSET PRICES IN V2\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x7a': 'eip155:122/slip44:XXX', // Fuse Mainnet - Native symbol: FUSE\n// '0x120': 'eip155:288/slip44:60', // Boba Network (Ethereum L2) - Native symbol: ETH\n// '0x150': 'eip155:336/slip44:809', // Shiden - Native symbol: SDN\n// '0x440': 'eip155:1088/slip44:60', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: ETH\n// '0x1388': 'eip155:5000/slip44:XXX', // Mantle - Native symbol: MNT\n// '0x28c58': 'eip155:167000/slip44:60', // Taiko Mainnet - Native symbol: ETH\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n *\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = Object.keys(\n SPOT_PRICES_SUPPORT_INFO,\n) as (keyof typeof SPOT_PRICES_SUPPORT_INFO)[];\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * The list of chain IDs that are supported by V3 of the Codefi Price API.\n * Only includes chain IDs from SPOT_PRICES_SUPPORT_INFO that have a non-null CAIP-19 value.\n */\nconst SUPPORTED_CHAIN_IDS_V3 = Object.keys(SPOT_PRICES_SUPPORT_INFO).filter(\n (chainId) =>\n SPOT_PRICES_SUPPORT_INFO[\n chainId as keyof typeof SPOT_PRICES_SUPPORT_INFO\n ] !== null,\n);\n\nconst BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';\n\nconst BASE_URL_V2 = 'https://price.api.cx.metamask.io/v2';\n\nconst BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';\n\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements AbstractTokenPricesService<SupportedChainId, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.assets - The assets to get prices for.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<SupportedChainId>[];\n currency: SupportedCurrency;\n }): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const v3Assets = await this.#fetchTokenPricesV3(assets, currency);\n const v2Assets = await this.#fetchTokenPricesV2(assets, currency);\n\n return [...v3Assets, ...v2Assets];\n }\n\n async #fetchTokenPricesV3(\n assets: EvmAssetAddressWithChain<SupportedChainId>[],\n currency: SupportedCurrency,\n ): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const assetsWithIds: EvmAssetWithId<SupportedChainId>[] = assets\n // Filter out assets that are not supported by V3 of the Price API.\n .filter((asset) => SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId))\n .map((asset) => {\n const caipChainId = toCaipChainId(\n KnownCaipNamespace.Eip155,\n hexToNumber(asset.chainId).toString(),\n );\n\n const nativeAddress = getNativeTokenAddress(asset.chainId);\n\n return {\n ...asset,\n assetId: (nativeAddress.toLowerCase() ===\n asset.tokenAddress.toLowerCase()\n ? SPOT_PRICES_SUPPORT_INFO[asset.chainId]\n : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`) as CaipAssetType,\n };\n })\n .filter((asset) => asset.assetId);\n\n if (assetsWithIds.length === 0) {\n return [];\n }\n\n const url = new URL(`${BASE_URL_V3}/spot-prices`);\n url.searchParams.append(\n 'assetIds',\n assetsWithIds.map((asset) => asset.assetId).join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [assetId: CaipAssetType]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return assetsWithIds\n .map((assetWithId) => {\n const marketData = addressCryptoDataMap[assetWithId.assetId];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n ...assetWithId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));\n }\n\n async #fetchTokenPricesV2(\n assets: EvmAssetAddressWithChain<SupportedChainId>[],\n currency: SupportedCurrency,\n ): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const v2SupportedAssets = assets.filter(\n (asset) => !SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId),\n );\n\n console.log('DEBUG LEGACY ASSETS', { v2SupportedAssets, currency });\n const assetsByChainId: Record<SupportedChainId, Hex[]> =\n v2SupportedAssets.reduce(\n (acc, { chainId, tokenAddress }) => {\n (acc[chainId] ??= []).push(tokenAddress);\n return acc;\n },\n {} as Record<SupportedChainId, Hex[]>,\n );\n\n const promises = Object.entries(assetsByChainId).map(\n async ([chainId, tokenAddresses]) => {\n if (tokenAddresses.length === 0) {\n return [];\n }\n\n const url = new URL(`${BASE_URL_V2}/chains/${chainId}/spot-prices`);\n url.searchParams.append('tokenAddresses', tokenAddresses.join(','));\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [tokenAddress: string]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n console.log('DEBUG LEGACY CHAIN', {\n chainId,\n tokenAddresses,\n });\n\n return tokenAddresses\n .map((tokenAddress) => {\n const marketData = addressCryptoDataMap[tokenAddress.toLowerCase()];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n tokenAddress,\n chainId: chainId as SupportedChainId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> =>\n Boolean(entry),\n );\n },\n );\n\n return await Promise.allSettled(promises).then((results) =>\n results.flatMap((result) =>\n result.status === 'fulfilled' ? result.value : [],\n ),\n );\n }\n\n /**\n * Retrieves exchange rates in the given base currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired base currency of the exchange rates.\n * @param args.includeUsdRate - Whether to include the USD rate in the response.\n * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.\n * @returns The exchange rates for the requested base currency.\n */\n async fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: SupportedCurrency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<SupportedCurrency>> {\n const url = new URL(`${BASE_URL_V1}/exchange-rates`);\n url.searchParams.append('baseCurrency', baseCurrency);\n\n const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);\n urlUsd.searchParams.append('baseCurrency', 'usd');\n\n const [exchangeRatesResult, exchangeRatesResultUsd] =\n await Promise.allSettled([\n this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n ),\n ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'\n ? [\n this.#policy.execute(() =>\n handleFetch(urlUsd, {\n headers: { 'Cache-Control': 'no-cache' },\n }),\n ),\n ]\n : []),\n ]);\n\n // Handle resolved/rejected\n const exchangeRates =\n exchangeRatesResult.status === 'fulfilled'\n ? exchangeRatesResult.value\n : {};\n const exchangeRatesUsd =\n exchangeRatesResultUsd?.status === 'fulfilled'\n ? exchangeRatesResultUsd.value\n : {};\n\n if (exchangeRatesResult.status === 'rejected') {\n throw new Error('Failed to fetch');\n }\n\n const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRates[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRates[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (Object.keys(filteredExchangeRates).length === 0) {\n throw new Error(\n 'None of the cryptocurrencies are supported by price api',\n );\n }\n\n const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRatesUsd[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRatesUsd[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (baseCurrency.toLowerCase() === 'usd') {\n Object.keys(filteredExchangeRates).forEach((key) => {\n filteredExchangeRates[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n usd: filteredExchangeRates[key as SupportedCurrency]?.value,\n };\n });\n return filteredExchangeRates;\n }\n if (!includeUsdRate) {\n return filteredExchangeRates;\n }\n\n const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {\n acc[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n ...(filteredUsdExchangeRates[key as SupportedCurrency]?.value\n ? { usd: filteredUsdExchangeRates[key as SupportedCurrency]?.value }\n : {}),\n };\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n return merged;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
@@ -22,30 +22,42 @@ export declare const ZERO_ADDRESS: Hex;
22
22
  * @returns The address of the chain's native token.
23
23
  */
24
24
  export declare const getNativeTokenAddress: (chainId: Hex) => Hex;
25
- export declare const HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP: {
26
- '0x1': string;
27
- '0xa': string;
28
- '0x19': string;
29
- '0x38': string;
30
- '0x64': string;
31
- '0x89': string;
32
- '0x92': string;
33
- '0xfa': string;
34
- '0x144': string;
35
- '0x44d': string;
36
- '0x504': string;
37
- '0x505': string;
38
- '0x531': string;
39
- '0x2105': string;
40
- '0xa4b1': string;
41
- '0xa4ec': string;
42
- '0xa86a': string;
43
- '0xe708': string;
44
- '0x82750': string;
45
- '0x4e454152': string;
46
- '0x63564c40': string;
47
- '0x279f': string;
48
- '0x3e7': string;
25
+ export declare const SPOT_PRICES_SUPPORT_INFO: {
26
+ readonly '0x1': "eip155:1/slip44:60";
27
+ readonly '0xa': "eip155:10/slip44:60";
28
+ readonly '0x19': "eip155:25/slip44:394";
29
+ readonly '0x38': "eip155:56/slip44:714";
30
+ readonly '0x39': null;
31
+ readonly '0x52': null;
32
+ readonly '0x58': null;
33
+ readonly '0x64': "eip155:100/slip44:700";
34
+ readonly '0x6a': null;
35
+ readonly '0x80': null;
36
+ readonly '0x89': "eip155:137/slip44:966";
37
+ readonly '0x92': "eip155:146/slip44:10007";
38
+ readonly '0xfa': "eip155:250/slip44:1007";
39
+ readonly '0x141': null;
40
+ readonly '0x144': "eip155:324/slip44:60";
41
+ readonly '0x169': null;
42
+ readonly '0x44d': "eip155:1101/slip44:60";
43
+ readonly '0x504': "eip155:1284/slip44:1284";
44
+ readonly '0x505': "eip155:1285/slip44:1285";
45
+ readonly '0x531': "eip155:1329/slip44:19000118";
46
+ readonly '0x2105': "eip155:8453/slip44:60";
47
+ readonly '0x2710': null;
48
+ readonly '0xa4b1': "eip155:42161/slip44:60";
49
+ readonly '0xa4ec': "eip155:42220/slip44:52752";
50
+ readonly '0xa516': null;
51
+ readonly '0xa86a': "eip155:43114/slip44:9005";
52
+ readonly '0xe708': "eip155:59144/slip44:60";
53
+ readonly '0x13c31': null;
54
+ readonly '0x17dcd': null;
55
+ readonly '0x518af': null;
56
+ readonly '0x82750': "eip155:534352/slip44:60";
57
+ readonly '0x4e454152': "eip155:60/slip44:60";
58
+ readonly '0x63564c40': "eip155:1666600000/slip44:1023";
59
+ readonly '0x279f': "eip155:143/slip44:268435779";
60
+ readonly '0x3e7': "eip155:999/slip44:2457";
49
61
  };
50
62
  /**
51
63
  * A currency that can be supplied as the `vsCurrency` parameter to
@@ -59,7 +71,7 @@ type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number] | Uppercase<(type
59
71
  *
60
72
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
61
73
  */
62
- export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" | "0xa" | "0xa4b1" | "0x82750" | "0x531" | "0xe708" | "0x19" | "0x64" | "0x92" | "0xfa" | "0x144" | "0x44d" | "0x504" | "0x505" | "0xa4ec" | "0xa86a" | "0x4e454152" | "0x63564c40" | "0x279f" | "0x3e7")[];
74
+ export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" | "0xa" | "0xa4b1" | "0x82750" | "0x531" | "0xe708" | "0x19" | "0x39" | "0x52" | "0x58" | "0x64" | "0x6a" | "0x80" | "0x92" | "0xfa" | "0x141" | "0x144" | "0x169" | "0x44d" | "0x504" | "0x505" | "0x2710" | "0xa4ec" | "0xa516" | "0xa86a" | "0x13c31" | "0x17dcd" | "0x518af" | "0x4e454152" | "0x63564c40" | "0x279f" | "0x3e7")[];
63
75
  /**
64
76
  * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,
65
77
  * but in hexadecimal form (for consistency with how we represent chain IDs in
@@ -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,EAC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;;;;;;;;OAQG;IACG,gBAAgB,CAAC,EACrB,MAAM,EACN,QAAQ,GACT,EAAE;QACD,MAAM,EAAE,wBAAwB,CAAC,gBAAgB,CAAC,EAAE,CAAC;QACrD,QAAQ,EAAE,iBAAiB,CAAC;KAC7B,GAAG,OAAO,CAAC,sBAAsB,CAAC,gBAAgB,EAAE,iBAAiB,CAAC,EAAE,CAAC;IA6I1E;;;;;;;;OAQG;IACG,kBAAkB,CAAC,EACvB,YAAY,EACZ,cAAc,EACd,gBAAgB,GACjB,EAAE;QACD,YAAY,EAAE,iBAAiB,CAAC;QAChC,cAAc,EAAE,OAAO,CAAC;QACxB,gBAAgB,EAAE,MAAM,EAAE,CAAC;KAC5B,GAAG,OAAO,CAAC,uBAAuB,CAAC,iBAAiB,CAAC,CAAC;IAqFvD;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,gBAAgB;IAKvE;;;;;;;OAOG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,iBAAiB;CAO5E"}
@@ -22,30 +22,42 @@ export declare const ZERO_ADDRESS: Hex;
22
22
  * @returns The address of the chain's native token.
23
23
  */
24
24
  export declare const getNativeTokenAddress: (chainId: Hex) => Hex;
25
- export declare const HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP: {
26
- '0x1': string;
27
- '0xa': string;
28
- '0x19': string;
29
- '0x38': string;
30
- '0x64': string;
31
- '0x89': string;
32
- '0x92': string;
33
- '0xfa': string;
34
- '0x144': string;
35
- '0x44d': string;
36
- '0x504': string;
37
- '0x505': string;
38
- '0x531': string;
39
- '0x2105': string;
40
- '0xa4b1': string;
41
- '0xa4ec': string;
42
- '0xa86a': string;
43
- '0xe708': string;
44
- '0x82750': string;
45
- '0x4e454152': string;
46
- '0x63564c40': string;
47
- '0x279f': string;
48
- '0x3e7': string;
25
+ export declare const SPOT_PRICES_SUPPORT_INFO: {
26
+ readonly '0x1': "eip155:1/slip44:60";
27
+ readonly '0xa': "eip155:10/slip44:60";
28
+ readonly '0x19': "eip155:25/slip44:394";
29
+ readonly '0x38': "eip155:56/slip44:714";
30
+ readonly '0x39': null;
31
+ readonly '0x52': null;
32
+ readonly '0x58': null;
33
+ readonly '0x64': "eip155:100/slip44:700";
34
+ readonly '0x6a': null;
35
+ readonly '0x80': null;
36
+ readonly '0x89': "eip155:137/slip44:966";
37
+ readonly '0x92': "eip155:146/slip44:10007";
38
+ readonly '0xfa': "eip155:250/slip44:1007";
39
+ readonly '0x141': null;
40
+ readonly '0x144': "eip155:324/slip44:60";
41
+ readonly '0x169': null;
42
+ readonly '0x44d': "eip155:1101/slip44:60";
43
+ readonly '0x504': "eip155:1284/slip44:1284";
44
+ readonly '0x505': "eip155:1285/slip44:1285";
45
+ readonly '0x531': "eip155:1329/slip44:19000118";
46
+ readonly '0x2105': "eip155:8453/slip44:60";
47
+ readonly '0x2710': null;
48
+ readonly '0xa4b1': "eip155:42161/slip44:60";
49
+ readonly '0xa4ec': "eip155:42220/slip44:52752";
50
+ readonly '0xa516': null;
51
+ readonly '0xa86a': "eip155:43114/slip44:9005";
52
+ readonly '0xe708': "eip155:59144/slip44:60";
53
+ readonly '0x13c31': null;
54
+ readonly '0x17dcd': null;
55
+ readonly '0x518af': null;
56
+ readonly '0x82750': "eip155:534352/slip44:60";
57
+ readonly '0x4e454152': "eip155:60/slip44:60";
58
+ readonly '0x63564c40': "eip155:1666600000/slip44:1023";
59
+ readonly '0x279f': "eip155:143/slip44:268435779";
60
+ readonly '0x3e7': "eip155:999/slip44:2457";
49
61
  };
50
62
  /**
51
63
  * A currency that can be supplied as the `vsCurrency` parameter to
@@ -59,7 +71,7 @@ type SupportedCurrency = (typeof SUPPORTED_CURRENCIES)[number] | Uppercase<(type
59
71
  *
60
72
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
61
73
  */
62
- export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" | "0xa" | "0xa4b1" | "0x82750" | "0x531" | "0xe708" | "0x19" | "0x64" | "0x92" | "0xfa" | "0x144" | "0x44d" | "0x504" | "0x505" | "0xa4ec" | "0xa86a" | "0x4e454152" | "0x63564c40" | "0x279f" | "0x3e7")[];
74
+ export declare const SUPPORTED_CHAIN_IDS: ("0x1" | "0x89" | "0x38" | "0x2105" | "0xa" | "0xa4b1" | "0x82750" | "0x531" | "0xe708" | "0x19" | "0x39" | "0x52" | "0x58" | "0x64" | "0x6a" | "0x80" | "0x92" | "0xfa" | "0x141" | "0x144" | "0x169" | "0x44d" | "0x504" | "0x505" | "0x2710" | "0xa4ec" | "0xa516" | "0xa86a" | "0x13c31" | "0x17dcd" | "0x518af" | "0x4e454152" | "0x63564c40" | "0x279f" | "0x3e7")[];
63
75
  /**
64
76
  * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,
65
77
  * but in hexadecimal form (for consistency with how we represent chain IDs in
@@ -1 +1 @@
1
- {"version":3,"file":"codefi-v2.d.mts","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAChE,OAAO,KAAK,EAAiB,GAAG,EAAE,wBAAwB;AAO1D,OAAO,KAAK,EACV,0BAA0B,EAC1B,wBAAwB,EAExB,sBAAsB,EACtB,uBAAuB,EACxB,4CAAwC;AAGzC;;;GAGG;AACH,eAAO,MAAM,oBAAoB,umBA2KvB,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,GAC4B,CAAC;AAUxD;;;;;;;GAOG;AACH,eAAO,MAAM,qBAAqB,YAAa,GAAG,KAAG,GACC,CAAC;AAIvD,eAAO,MAAM,uCAAuC;;;;;;;;;;;;;;;;;;;;;;;;CAwBnD,CAAC;AA0BF;;;GAGG;AACH,KAAK,iBAAiB,GAClB,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,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BAAiB,CAAC;QAChC,cAAc,EAAE,OAAO,CAAC;QACxB,gBAAgB,EAAE,MAAM,EAAE,CAAC;KAC5B,GAAG,OAAO,CAAC,uBAAuB,CAAC,iBAAiB,CAAC,CAAC;IAqFvD;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,gBAAgB;IAKvE;;;;;;;OAOG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,iBAAiB;CAO5E"}
@@ -9,7 +9,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
9
9
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
10
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
11
  };
12
- var _CodefiTokenPricesServiceV2_policy;
12
+ var _CodefiTokenPricesServiceV2_instances, _CodefiTokenPricesServiceV2_policy, _CodefiTokenPricesServiceV2_fetchTokenPricesV3, _CodefiTokenPricesServiceV2_fetchTokenPricesV2;
13
13
  import { createServicePolicy, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, handleFetch } from "@metamask/controller-utils";
14
14
  import { hexToNumber, KnownCaipNamespace, toCaipChainId } from "@metamask/utils";
15
15
  /**
@@ -213,25 +213,37 @@ const chainIdToNativeTokenAddress = {
213
213
  export const getNativeTokenAddress = (chainId) => chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;
214
214
  // Source: https://github.com/consensys-vertical-apps/va-mmcx-price-api/blob/main/src/constants/slip44.ts
215
215
  // We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.
216
- export const HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {
216
+ export const SPOT_PRICES_SUPPORT_INFO = {
217
217
  '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH
218
218
  '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH
219
219
  '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO
220
220
  '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB
221
+ '0x39': null, // 'eip155:57/slip44:57', // Syscoin Mainnet - Native symbol: SYS
222
+ '0x52': null, // 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR
223
+ '0x58': null, // 'eip155:88/slip44:889', // TomoChain - Native symbol: TOMO
221
224
  '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI
225
+ '0x6a': null, // 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX
226
+ '0x80': null, // 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT
222
227
  '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL
223
228
  '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S
224
229
  '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM
230
+ '0x141': null, // 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS
225
231
  '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH
232
+ '0x169': null, // 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL
226
233
  '0x44d': 'eip155:1101/slip44:60', // Polygon zkEVM mainnet - Native symbol: ETH
227
234
  '0x504': 'eip155:1284/slip44:1284', // Moonbeam - Native symbol: GLMR
228
235
  '0x505': 'eip155:1285/slip44:1285', // Moonriver - Native symbol: MOVR
229
236
  '0x531': 'eip155:1329/slip44:19000118', // Sei Mainnet - Native symbol: SEI
230
237
  '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH
238
+ '0x2710': null, // 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH
231
239
  '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH
232
240
  '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO
241
+ '0xa516': null, // 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE
233
242
  '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX
234
243
  '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH
244
+ '0x13c31': null, // 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH
245
+ '0x17dcd': null, // 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU
246
+ '0x518af': null, // 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS
235
247
  '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH
236
248
  '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH
237
249
  '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE
@@ -245,11 +257,14 @@ export const HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {
245
257
  *
246
258
  * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.
247
259
  */
248
- export const SUPPORTED_CHAIN_IDS = Object.keys(HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP);
260
+ export const SUPPORTED_CHAIN_IDS = Object.keys(SPOT_PRICES_SUPPORT_INFO);
249
261
  /**
250
- * All requests to V2 of the Price API start with this.
262
+ * The list of chain IDs that are supported by V3 of the Codefi Price API.
263
+ * Only includes chain IDs from SPOT_PRICES_SUPPORT_INFO that have a non-null CAIP-19 value.
251
264
  */
265
+ const SUPPORTED_CHAIN_IDS_V3 = Object.keys(SPOT_PRICES_SUPPORT_INFO).filter((chainId) => SPOT_PRICES_SUPPORT_INFO[chainId] !== null);
252
266
  const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
267
+ const BASE_URL_V2 = 'https://price.api.cx.metamask.io/v2';
253
268
  const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
254
269
  /**
255
270
  * This version of the token prices service uses V2 of the Codefi Price API to
@@ -257,6 +272,7 @@ const BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';
257
272
  */
258
273
  export class CodefiTokenPricesServiceV2 {
259
274
  constructor({ degradedThreshold = DEFAULT_DEGRADED_THRESHOLD, retries = DEFAULT_MAX_RETRIES, maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES, onBreak, onDegraded, circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION, } = {}) {
275
+ _CodefiTokenPricesServiceV2_instances.add(this);
260
276
  _CodefiTokenPricesServiceV2_policy.set(this, void 0);
261
277
  __classPrivateFieldSet(this, _CodefiTokenPricesServiceV2_policy, createServicePolicy({
262
278
  maxRetries: retries,
@@ -301,36 +317,9 @@ export class CodefiTokenPricesServiceV2 {
301
317
  * @returns The prices for the requested tokens.
302
318
  */
303
319
  async fetchTokenPrices({ assets, currency, }) {
304
- const assetsWithIds = assets
305
- .map((asset) => {
306
- const caipChainId = toCaipChainId(KnownCaipNamespace.Eip155, hexToNumber(asset.chainId).toString());
307
- const nativeAddress = getNativeTokenAddress(asset.chainId);
308
- return {
309
- ...asset,
310
- assetId: nativeAddress.toLowerCase() === asset.tokenAddress.toLowerCase()
311
- ? HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP[asset.chainId]
312
- : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`,
313
- };
314
- })
315
- .filter((asset) => asset.assetId);
316
- const url = new URL(`${BASE_URL_V3}/spot-prices`);
317
- url.searchParams.append('assetIds', assetsWithIds.map((asset) => asset.assetId).join(','));
318
- url.searchParams.append('vsCurrency', currency);
319
- url.searchParams.append('includeMarketData', 'true');
320
- const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }));
321
- return assetsWithIds
322
- .map((assetWithId) => {
323
- const marketData = addressCryptoDataMap[assetWithId.assetId];
324
- if (!marketData) {
325
- return undefined;
326
- }
327
- return {
328
- ...marketData,
329
- ...assetWithId,
330
- currency,
331
- };
332
- })
333
- .filter((entry) => Boolean(entry));
320
+ const v3Assets = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_instances, "m", _CodefiTokenPricesServiceV2_fetchTokenPricesV3).call(this, assets, currency);
321
+ const v2Assets = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_instances, "m", _CodefiTokenPricesServiceV2_fetchTokenPricesV2).call(this, assets, currency);
322
+ return [...v3Assets, ...v2Assets];
334
323
  }
335
324
  /**
336
325
  * Retrieves exchange rates in the given base currency.
@@ -431,5 +420,78 @@ export class CodefiTokenPricesServiceV2 {
431
420
  supportedCurrencies.includes(currency.toLowerCase()));
432
421
  }
433
422
  }
434
- _CodefiTokenPricesServiceV2_policy = new WeakMap();
423
+ _CodefiTokenPricesServiceV2_policy = new WeakMap(), _CodefiTokenPricesServiceV2_instances = new WeakSet(), _CodefiTokenPricesServiceV2_fetchTokenPricesV3 = async function _CodefiTokenPricesServiceV2_fetchTokenPricesV3(assets, currency) {
424
+ const assetsWithIds = assets
425
+ // Filter out assets that are not supported by V3 of the Price API.
426
+ .filter((asset) => SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId))
427
+ .map((asset) => {
428
+ const caipChainId = toCaipChainId(KnownCaipNamespace.Eip155, hexToNumber(asset.chainId).toString());
429
+ const nativeAddress = getNativeTokenAddress(asset.chainId);
430
+ return {
431
+ ...asset,
432
+ assetId: (nativeAddress.toLowerCase() ===
433
+ asset.tokenAddress.toLowerCase()
434
+ ? SPOT_PRICES_SUPPORT_INFO[asset.chainId]
435
+ : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`),
436
+ };
437
+ })
438
+ .filter((asset) => asset.assetId);
439
+ if (assetsWithIds.length === 0) {
440
+ return [];
441
+ }
442
+ const url = new URL(`${BASE_URL_V3}/spot-prices`);
443
+ url.searchParams.append('assetIds', assetsWithIds.map((asset) => asset.assetId).join(','));
444
+ url.searchParams.append('vsCurrency', currency);
445
+ url.searchParams.append('includeMarketData', 'true');
446
+ const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }));
447
+ return assetsWithIds
448
+ .map((assetWithId) => {
449
+ const marketData = addressCryptoDataMap[assetWithId.assetId];
450
+ if (!marketData) {
451
+ return undefined;
452
+ }
453
+ return {
454
+ ...marketData,
455
+ ...assetWithId,
456
+ currency,
457
+ };
458
+ })
459
+ .filter((entry) => Boolean(entry));
460
+ }, _CodefiTokenPricesServiceV2_fetchTokenPricesV2 = async function _CodefiTokenPricesServiceV2_fetchTokenPricesV2(assets, currency) {
461
+ const v2SupportedAssets = assets.filter((asset) => !SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId));
462
+ console.log('DEBUG LEGACY ASSETS', { v2SupportedAssets, currency });
463
+ const assetsByChainId = v2SupportedAssets.reduce((acc, { chainId, tokenAddress }) => {
464
+ (acc[chainId] ?? (acc[chainId] = [])).push(tokenAddress);
465
+ return acc;
466
+ }, {});
467
+ const promises = Object.entries(assetsByChainId).map(async ([chainId, tokenAddresses]) => {
468
+ if (tokenAddresses.length === 0) {
469
+ return [];
470
+ }
471
+ const url = new URL(`${BASE_URL_V2}/chains/${chainId}/spot-prices`);
472
+ url.searchParams.append('tokenAddresses', tokenAddresses.join(','));
473
+ url.searchParams.append('vsCurrency', currency);
474
+ url.searchParams.append('includeMarketData', 'true');
475
+ const addressCryptoDataMap = await __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }));
476
+ console.log('DEBUG LEGACY CHAIN', {
477
+ chainId,
478
+ tokenAddresses,
479
+ });
480
+ return tokenAddresses
481
+ .map((tokenAddress) => {
482
+ const marketData = addressCryptoDataMap[tokenAddress.toLowerCase()];
483
+ if (!marketData) {
484
+ return undefined;
485
+ }
486
+ return {
487
+ ...marketData,
488
+ tokenAddress,
489
+ chainId: chainId,
490
+ currency,
491
+ };
492
+ })
493
+ .filter((entry) => Boolean(entry));
494
+ });
495
+ return await Promise.allSettled(promises).then((results) => results.flatMap((result) => result.status === 'fulfilled' ? result.value : []));
496
+ };
435
497
  //# 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,WAAW,EACX,kBAAkB,EAClB,aAAa,EACd,wBAAwB;AAWzB;;;GAGG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,UAAU;IACV,KAAK;IACL,QAAQ;IACR,KAAK;IACL,WAAW;IACX,KAAK;IACL,eAAe;IACf,KAAK;IACL,eAAe;IACf,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,KAAK;IACL,SAAS;IACT,KAAK;IACL,YAAY;IACZ,MAAM;IACN,WAAW;IACX,KAAK;IACL,gBAAgB;IAChB,KAAK;IACL,YAAY;IACZ,KAAK;IACL,8BAA8B;IAC9B,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,oBAAoB;IACpB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,iBAAiB;IACjB,KAAK;IACL,mBAAmB;IACnB,KAAK;IACL,cAAc;IACd,KAAK;IACL,kBAAkB;IAClB,KAAK;IACL,cAAc;IACd,KAAK;IACL,eAAe;IACf,K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C;IAED;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAgB;QACvC,MAAM,iBAAiB,GAAsB,mBAAmB,CAAC;QACjE,OAAO,OAAO,OAAO,KAAK,QAAQ,IAAI,iBAAiB,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC5E,CAAC;IAED;;;;;;;OAOG;IACH,yBAAyB,CAAC,QAAiB;QACzC,MAAM,mBAAmB,GAAsB,oBAAoB,CAAC;QACpE,OAAO,CACL,OAAO,QAAQ,KAAK,QAAQ;YAC5B,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n createServicePolicy,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\nimport {\n hexToNumber,\n KnownCaipNamespace,\n toCaipChainId,\n} from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n EvmAssetAddressWithChain,\n EvmAssetWithId,\n EvmAssetWithMarketData,\n ExchangeRatesByCurrency,\n} from './abstract-token-prices-service';\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Georgian Lari\n 'gel',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n // Colombian Peso\n 'cop',\n // Kenyan Shilling\n 'kes',\n // Romanian Leu\n 'ron',\n // Dominican Peso\n 'dop',\n // Costa Rican Colón\n 'crc',\n // Honduran Lempira\n 'hnl',\n // Zambian Kwacha\n 'zmw',\n // Salvadoran Colón\n 'svc',\n // Bosnia-Herzegovina Convertible Mark\n 'bam',\n // Peruvian Sol\n 'pen',\n // Guatemalan Quetzal\n 'gtq',\n // Lebanese Pound\n 'lbp',\n // Armenian Dram\n 'amd',\n // Solana\n 'sol',\n // Sei\n 'sei',\n // Sonic\n 'sonic',\n // Tron\n 'trx',\n // Taiko\n 'taiko',\n // Pepu\n 'pepu',\n // Polygon\n 'pol',\n // Mantle\n 'mnt',\n // Onomy\n 'nom',\n // Avalanche\n 'avax',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n *\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n// 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 HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP = {\n '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH\n '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH\n '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO\n '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB\n '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI\n '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH\n '0x44d': 'eip155:1101/slip44:60', // Polygon zkEVM mainnet - Native symbol: ETH\n '0x504': 'eip155:1284/slip44:1284', // Moonbeam - Native symbol: GLMR\n '0x505': 'eip155:1285/slip44:1285', // Moonriver - Native symbol: MOVR\n '0x531': 'eip155:1329/slip44:19000118', // Sei Mainnet - Native symbol: SEI\n '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH\n '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH\n '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH\n '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE\n '0x279f': 'eip155:143/slip44:268435779', // Monad Testnet - Native symbol: MON\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n};\n\n// MISSING CHAINS WITH NATIVE ASSET PRICES IN V2\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// '0x6a': 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX\n// '0x80': 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT\n// '0x141': 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS\n// '0x169': 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL\n// '0x2710': 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n// '0xa516': 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE\n// '0x13c31': 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n// '0x17dcd': 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU\n// '0x518af': 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS\n\n// MISSING CHAINS WITH NO NATIVE ASSET PRICES IN V2\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x7a': 'eip155:122/slip44:XXX', // Fuse Mainnet - Native symbol: FUSE\n// '0x120': 'eip155:288/slip44:60', // Boba Network (Ethereum L2) - Native symbol: ETH\n// '0x150': 'eip155:336/slip44:809', // Shiden - Native symbol: SDN\n// '0x440': 'eip155:1088/slip44:60', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: ETH\n// '0x1388': 'eip155:5000/slip44:XXX', // Mantle - Native symbol: MNT\n// '0x28c58': 'eip155:167000/slip44:60', // Taiko Mainnet - Native symbol: ETH\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n *\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = Object.keys(\n HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP,\n) as (keyof typeof HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP)[];\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';\n\nconst BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';\n\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements AbstractTokenPricesService<SupportedChainId, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.assets - The assets to get prices for.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<SupportedChainId>[];\n currency: SupportedCurrency;\n }): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const assetsWithIds: EvmAssetWithId<SupportedChainId>[] = assets\n .map((asset) => {\n const caipChainId = toCaipChainId(\n KnownCaipNamespace.Eip155,\n hexToNumber(asset.chainId).toString(),\n );\n\n const nativeAddress = getNativeTokenAddress(asset.chainId);\n\n return {\n ...asset,\n assetId:\n nativeAddress.toLowerCase() === asset.tokenAddress.toLowerCase()\n ? HEX_CHAIN_ID_TO_CAIP19_NATIVE_ASSET_MAP[asset.chainId]\n : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`,\n } as EvmAssetWithId<SupportedChainId>;\n })\n .filter((asset) => asset.assetId);\n\n const url = new URL(`${BASE_URL_V3}/spot-prices`);\n url.searchParams.append(\n 'assetIds',\n assetsWithIds.map((asset) => asset.assetId).join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [assetId: CaipAssetType]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return assetsWithIds\n .map((assetWithId) => {\n const marketData = addressCryptoDataMap[assetWithId.assetId];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n ...assetWithId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));\n }\n\n /**\n * Retrieves exchange rates in the given base currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired base currency of the exchange rates.\n * @param args.includeUsdRate - Whether to include the USD rate in the response.\n * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.\n * @returns The exchange rates for the requested base currency.\n */\n async fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: SupportedCurrency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<SupportedCurrency>> {\n const url = new URL(`${BASE_URL_V1}/exchange-rates`);\n url.searchParams.append('baseCurrency', baseCurrency);\n\n const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);\n urlUsd.searchParams.append('baseCurrency', 'usd');\n\n const [exchangeRatesResult, exchangeRatesResultUsd] =\n await Promise.allSettled([\n this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n ),\n ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'\n ? [\n this.#policy.execute(() =>\n handleFetch(urlUsd, {\n headers: { 'Cache-Control': 'no-cache' },\n }),\n ),\n ]\n : []),\n ]);\n\n // Handle resolved/rejected\n const exchangeRates =\n exchangeRatesResult.status === 'fulfilled'\n ? exchangeRatesResult.value\n : {};\n const exchangeRatesUsd =\n exchangeRatesResultUsd?.status === 'fulfilled'\n ? exchangeRatesResultUsd.value\n : {};\n\n if (exchangeRatesResult.status === 'rejected') {\n throw new Error('Failed to fetch');\n }\n\n const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRates[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRates[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (Object.keys(filteredExchangeRates).length === 0) {\n throw new Error(\n 'None of the cryptocurrencies are supported by price api',\n );\n }\n\n const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRatesUsd[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRatesUsd[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (baseCurrency.toLowerCase() === 'usd') {\n Object.keys(filteredExchangeRates).forEach((key) => {\n filteredExchangeRates[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n usd: filteredExchangeRates[key as SupportedCurrency]?.value,\n };\n });\n return filteredExchangeRates;\n }\n if (!includeUsdRate) {\n return filteredExchangeRates;\n }\n\n const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {\n acc[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n ...(filteredUsdExchangeRates[key as SupportedCurrency]?.value\n ? { usd: filteredUsdExchangeRates[key as SupportedCurrency]?.value }\n : {}),\n };\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n return merged;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
1
+ {"version":3,"file":"codefi-v2.mjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EACL,mBAAmB,EACnB,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,WAAW,EACZ,mCAAmC;AAGpC,OAAO,EACL,WAAW,EACX,kBAAkB,EAClB,aAAa,EACd,wBAAwB;AAWzB;;;GAGG;AACH,MAAM,CAAC,MA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AAI,CAAC,UAAU,EAAE,CAAC;gBAChB,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,OAAO;gBACL,GAAG,UAAU;gBACb,YAAY;gBACZ,OAAO,EAAE,OAA2B;gBACpC,QAAQ;aACT,CAAC;QACJ,CAAC,CAAC;aACD,MAAM,CAAC,CAAC,KAAK,EAAsC,EAAE,CACpD,OAAO,CAAC,KAAK,CAAC,CACf,CAAC;IACN,CAAC,CACF,CAAC;IAEF,OAAO,MAAM,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CACzD,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CACzB,MAAM,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAClD,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n createServicePolicy,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { CaipAssetType, Hex } from '@metamask/utils';\nimport {\n hexToNumber,\n KnownCaipNamespace,\n toCaipChainId,\n} from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n EvmAssetAddressWithChain,\n EvmAssetWithId,\n EvmAssetWithMarketData,\n ExchangeRatesByCurrency,\n} from './abstract-token-prices-service';\nimport type { MarketDataDetails } from '../TokenRatesController';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Georgian Lari\n 'gel',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n // Colombian Peso\n 'cop',\n // Kenyan Shilling\n 'kes',\n // Romanian Leu\n 'ron',\n // Dominican Peso\n 'dop',\n // Costa Rican Colón\n 'crc',\n // Honduran Lempira\n 'hnl',\n // Zambian Kwacha\n 'zmw',\n // Salvadoran Colón\n 'svc',\n // Bosnia-Herzegovina Convertible Mark\n 'bam',\n // Peruvian Sol\n 'pen',\n // Guatemalan Quetzal\n 'gtq',\n // Lebanese Pound\n 'lbp',\n // Armenian Dram\n 'amd',\n // Solana\n 'sol',\n // Sei\n 'sei',\n // Sonic\n 'sonic',\n // Tron\n 'trx',\n // Taiko\n 'taiko',\n // Pepu\n 'pepu',\n // Polygon\n 'pol',\n // Mantle\n 'mnt',\n // Onomy\n 'nom',\n // Avalanche\n 'avax',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n *\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n// Source: https://github.com/consensys-vertical-apps/va-mmcx-price-api/blob/main/src/constants/slip44.ts\n// We can only support PricesAPI V3 for EVM chains that have a CAIP-19 native asset mapping.\nexport const SPOT_PRICES_SUPPORT_INFO = {\n '0x1': 'eip155:1/slip44:60', // Ethereum Mainnet - Native symbol: ETH\n '0xa': 'eip155:10/slip44:60', // OP Mainnet - Native symbol: ETH\n '0x19': 'eip155:25/slip44:394', // Cronos Mainnet - Native symbol: CRO\n '0x38': 'eip155:56/slip44:714', // BNB Smart Chain Mainnet - Native symbol: BNB\n '0x39': null, // 'eip155:57/slip44:57', // Syscoin Mainnet - Native symbol: SYS\n '0x52': null, // 'eip155:82/slip44:18000', // Meter Mainnet - Native symbol: MTR\n '0x58': null, // 'eip155:88/slip44:889', // TomoChain - Native symbol: TOMO\n '0x64': 'eip155:100/slip44:700', // Gnosis (formerly xDAI Chain) - Native symbol: xDAI\n '0x6a': null, // 'eip155:106/slip44:5655640', // Velas EVM Mainnet - Native symbol: VLX\n '0x80': null, // 'eip155:128/slip44:1010', // Huobi ECO Chain Mainnet - Native symbol: HT\n '0x89': 'eip155:137/slip44:966', // Polygon Mainnet - Native symbol: POL\n '0x92': 'eip155:146/slip44:10007', // Sonic Mainnet - Native symbol: S\n '0xfa': 'eip155:250/slip44:1007', // Fantom Opera - Native symbol: FTM\n '0x141': null, // 'eip155:321/slip44:641', // KCC Mainnet - Native symbol: KCS\n '0x144': 'eip155:324/slip44:60', // zkSync Era Mainnet (Ethereum L2) - Native symbol: ETH\n '0x169': null, // 'eip155:361/slip44:589', // Theta Mainnet - Native symbol: TFUEL\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 '0x2105': 'eip155:8453/slip44:60', // Base - Native symbol: ETH\n '0x2710': null, // 'eip155:10000/slip44:145', // Smart Bitcoin Cash - Native symbol: BCH\n '0xa4b1': 'eip155:42161/slip44:60', // Arbitrum One - Native symbol: ETH\n '0xa4ec': 'eip155:42220/slip44:52752', // Celo Mainnet - Native symbol: CELO\n '0xa516': null, // 'eip155:42262/slip44:474', // Oasis Emerald - Native symbol: ROSE\n '0xa86a': 'eip155:43114/slip44:9005', // Avalanche C-Chain - Native symbol: AVAX\n '0xe708': 'eip155:59144/slip44:60', // Linea Mainnet - Native symbol: ETH\n '0x13c31': null, // 'eip155:81457/slip44:60', // Blast Mainnet - Native symbol: ETH\n '0x17dcd': null, // 'eip155:97741/slip44:XXX', // Pepe Unchained Mainnet - Native symbol: PEPU\n '0x518af': null, // 'eip155:333999/slip44:1997', // Polis Mainnet - Native symbol: POLIS\n '0x82750': 'eip155:534352/slip44:60', // Scroll Mainnet - Native symbol: ETH\n '0x4e454152': 'eip155:60/slip44:60', // Aurora Mainnet (Ethereum L2 on NEAR) - Native symbol: ETH\n '0x63564c40': 'eip155:1666600000/slip44:1023', // Harmony Mainnet Shard 0 - Native symbol: ONE\n '0x279f': 'eip155:143/slip44:268435779', // Monad Testnet - Native symbol: MON\n '0x3e7': 'eip155:999/slip44:2457', // HyperEVM - Native symbol: ETH\n} as const;\n\n// MISSING CHAINS WITH NO NATIVE ASSET PRICES IN V2\n// '0x42': 'eip155:66/slip44:996', // OKXChain Mainnet - Native symbol: OKT\n// '0x46': 'eip155:70/slip44:1170', // Hoo Smart Chain - Native symbol: HOO\n// '0x7a': 'eip155:122/slip44:XXX', // Fuse Mainnet - Native symbol: FUSE\n// '0x120': 'eip155:288/slip44:60', // Boba Network (Ethereum L2) - Native symbol: ETH\n// '0x150': 'eip155:336/slip44:809', // Shiden - Native symbol: SDN\n// '0x440': 'eip155:1088/slip44:60', // Metis Andromeda Mainnet (Ethereum L2) - Native symbol: ETH\n// '0x1388': 'eip155:5000/slip44:XXX', // Mantle - Native symbol: MNT\n// '0x28c58': 'eip155:167000/slip44:60', // Taiko Mainnet - Native symbol: ETH\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n *\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = Object.keys(\n SPOT_PRICES_SUPPORT_INFO,\n) as (keyof typeof SPOT_PRICES_SUPPORT_INFO)[];\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * The list of chain IDs that are supported by V3 of the Codefi Price API.\n * Only includes chain IDs from SPOT_PRICES_SUPPORT_INFO that have a non-null CAIP-19 value.\n */\nconst SUPPORTED_CHAIN_IDS_V3 = Object.keys(SPOT_PRICES_SUPPORT_INFO).filter(\n (chainId) =>\n SPOT_PRICES_SUPPORT_INFO[\n chainId as keyof typeof SPOT_PRICES_SUPPORT_INFO\n ] !== null,\n);\n\nconst BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';\n\nconst BASE_URL_V2 = 'https://price.api.cx.metamask.io/v2';\n\nconst BASE_URL_V3 = 'https://price.api.cx.metamask.io/v3';\n\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements AbstractTokenPricesService<SupportedChainId, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.assets - The assets to get prices for.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n assets,\n currency,\n }: {\n assets: EvmAssetAddressWithChain<SupportedChainId>[];\n currency: SupportedCurrency;\n }): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const v3Assets = await this.#fetchTokenPricesV3(assets, currency);\n const v2Assets = await this.#fetchTokenPricesV2(assets, currency);\n\n return [...v3Assets, ...v2Assets];\n }\n\n async #fetchTokenPricesV3(\n assets: EvmAssetAddressWithChain<SupportedChainId>[],\n currency: SupportedCurrency,\n ): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const assetsWithIds: EvmAssetWithId<SupportedChainId>[] = assets\n // Filter out assets that are not supported by V3 of the Price API.\n .filter((asset) => SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId))\n .map((asset) => {\n const caipChainId = toCaipChainId(\n KnownCaipNamespace.Eip155,\n hexToNumber(asset.chainId).toString(),\n );\n\n const nativeAddress = getNativeTokenAddress(asset.chainId);\n\n return {\n ...asset,\n assetId: (nativeAddress.toLowerCase() ===\n asset.tokenAddress.toLowerCase()\n ? SPOT_PRICES_SUPPORT_INFO[asset.chainId]\n : `${caipChainId}/erc20:${asset.tokenAddress.toLowerCase()}`) as CaipAssetType,\n };\n })\n .filter((asset) => asset.assetId);\n\n if (assetsWithIds.length === 0) {\n return [];\n }\n\n const url = new URL(`${BASE_URL_V3}/spot-prices`);\n url.searchParams.append(\n 'assetIds',\n assetsWithIds.map((asset) => asset.assetId).join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [assetId: CaipAssetType]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return assetsWithIds\n .map((assetWithId) => {\n const marketData = addressCryptoDataMap[assetWithId.assetId];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n ...assetWithId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> => Boolean(entry));\n }\n\n async #fetchTokenPricesV2(\n assets: EvmAssetAddressWithChain<SupportedChainId>[],\n currency: SupportedCurrency,\n ): Promise<EvmAssetWithMarketData<SupportedChainId, SupportedCurrency>[]> {\n const v2SupportedAssets = assets.filter(\n (asset) => !SUPPORTED_CHAIN_IDS_V3.includes(asset.chainId),\n );\n\n console.log('DEBUG LEGACY ASSETS', { v2SupportedAssets, currency });\n const assetsByChainId: Record<SupportedChainId, Hex[]> =\n v2SupportedAssets.reduce(\n (acc, { chainId, tokenAddress }) => {\n (acc[chainId] ??= []).push(tokenAddress);\n return acc;\n },\n {} as Record<SupportedChainId, Hex[]>,\n );\n\n const promises = Object.entries(assetsByChainId).map(\n async ([chainId, tokenAddresses]) => {\n if (tokenAddresses.length === 0) {\n return [];\n }\n\n const url = new URL(`${BASE_URL_V2}/chains/${chainId}/spot-prices`);\n url.searchParams.append('tokenAddresses', tokenAddresses.join(','));\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: {\n [tokenAddress: string]: Omit<\n MarketDataDetails,\n 'currency' | 'tokenAddress'\n >;\n } = await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n console.log('DEBUG LEGACY CHAIN', {\n chainId,\n tokenAddresses,\n });\n\n return tokenAddresses\n .map((tokenAddress) => {\n const marketData = addressCryptoDataMap[tokenAddress.toLowerCase()];\n\n if (!marketData) {\n return undefined;\n }\n\n return {\n ...marketData,\n tokenAddress,\n chainId: chainId as SupportedChainId,\n currency,\n };\n })\n .filter((entry): entry is NonNullable<typeof entry> =>\n Boolean(entry),\n );\n },\n );\n\n return await Promise.allSettled(promises).then((results) =>\n results.flatMap((result) =>\n result.status === 'fulfilled' ? result.value : [],\n ),\n );\n }\n\n /**\n * Retrieves exchange rates in the given base currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired base currency of the exchange rates.\n * @param args.includeUsdRate - Whether to include the USD rate in the response.\n * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.\n * @returns The exchange rates for the requested base currency.\n */\n async fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: SupportedCurrency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<SupportedCurrency>> {\n const url = new URL(`${BASE_URL_V1}/exchange-rates`);\n url.searchParams.append('baseCurrency', baseCurrency);\n\n const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);\n urlUsd.searchParams.append('baseCurrency', 'usd');\n\n const [exchangeRatesResult, exchangeRatesResultUsd] =\n await Promise.allSettled([\n this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n ),\n ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'\n ? [\n this.#policy.execute(() =>\n handleFetch(urlUsd, {\n headers: { 'Cache-Control': 'no-cache' },\n }),\n ),\n ]\n : []),\n ]);\n\n // Handle resolved/rejected\n const exchangeRates =\n exchangeRatesResult.status === 'fulfilled'\n ? exchangeRatesResult.value\n : {};\n const exchangeRatesUsd =\n exchangeRatesResultUsd?.status === 'fulfilled'\n ? exchangeRatesResultUsd.value\n : {};\n\n if (exchangeRatesResult.status === 'rejected') {\n throw new Error('Failed to fetch');\n }\n\n const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRates[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRates[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (Object.keys(filteredExchangeRates).length === 0) {\n throw new Error(\n 'None of the cryptocurrencies are supported by price api',\n );\n }\n\n const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRatesUsd[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRatesUsd[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (baseCurrency.toLowerCase() === 'usd') {\n Object.keys(filteredExchangeRates).forEach((key) => {\n filteredExchangeRates[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n usd: filteredExchangeRates[key as SupportedCurrency]?.value,\n };\n });\n return filteredExchangeRates;\n }\n if (!includeUsdRate) {\n return filteredExchangeRates;\n }\n\n const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {\n acc[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n ...(filteredUsdExchangeRates[key as SupportedCurrency]?.value\n ? { usd: filteredUsdExchangeRates[key as SupportedCurrency]?.value }\n : {}),\n };\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n return merged;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/assets-controllers",
3
- "version": "89.0.1-preview-40ec088b",
3
+ "version": "89.0.1-preview-152da47f",
4
4
  "description": "Controllers which manage interactions involving ERC-20, ERC-721, and ERC-1155 tokens (including NFTs)",
5
5
  "keywords": [
6
6
  "MetaMask",