@metamask/assets-controllers 84.0.0 → 86.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +30 -1
  2. package/dist/AccountTrackerController.cjs +43 -13
  3. package/dist/AccountTrackerController.cjs.map +1 -1
  4. package/dist/AccountTrackerController.d.cts +17 -6
  5. package/dist/AccountTrackerController.d.cts.map +1 -1
  6. package/dist/AccountTrackerController.d.mts +17 -6
  7. package/dist/AccountTrackerController.d.mts.map +1 -1
  8. package/dist/AccountTrackerController.mjs +43 -13
  9. package/dist/AccountTrackerController.mjs.map +1 -1
  10. package/dist/CurrencyRateController.cjs +65 -12
  11. package/dist/CurrencyRateController.cjs.map +1 -1
  12. package/dist/CurrencyRateController.d.cts +14 -7
  13. package/dist/CurrencyRateController.d.cts.map +1 -1
  14. package/dist/CurrencyRateController.d.mts +14 -7
  15. package/dist/CurrencyRateController.d.mts.map +1 -1
  16. package/dist/CurrencyRateController.mjs +65 -12
  17. package/dist/CurrencyRateController.mjs.map +1 -1
  18. package/dist/MultichainAssetsController/MultichainAssetsController.cjs +42 -10
  19. package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
  20. package/dist/MultichainAssetsController/MultichainAssetsController.d.cts +15 -1
  21. package/dist/MultichainAssetsController/MultichainAssetsController.d.cts.map +1 -1
  22. package/dist/MultichainAssetsController/MultichainAssetsController.d.mts +15 -1
  23. package/dist/MultichainAssetsController/MultichainAssetsController.d.mts.map +1 -1
  24. package/dist/MultichainAssetsController/MultichainAssetsController.mjs +42 -10
  25. package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
  26. package/dist/balances.cjs +20 -12
  27. package/dist/balances.cjs.map +1 -1
  28. package/dist/balances.d.cts +7 -3
  29. package/dist/balances.d.cts.map +1 -1
  30. package/dist/balances.d.mts +7 -3
  31. package/dist/balances.d.mts.map +1 -1
  32. package/dist/balances.mjs +20 -12
  33. package/dist/balances.mjs.map +1 -1
  34. package/dist/index.cjs +3 -1
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +1 -0
  37. package/dist/index.d.cts.map +1 -1
  38. package/dist/index.d.mts +1 -0
  39. package/dist/index.d.mts.map +1 -1
  40. package/dist/index.mjs +1 -0
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/selectors/token-selectors.cjs +5 -1
  43. package/dist/selectors/token-selectors.cjs.map +1 -1
  44. package/dist/selectors/token-selectors.d.cts +13 -6
  45. package/dist/selectors/token-selectors.d.cts.map +1 -1
  46. package/dist/selectors/token-selectors.d.mts +13 -6
  47. package/dist/selectors/token-selectors.d.mts.map +1 -1
  48. package/dist/selectors/token-selectors.mjs +5 -1
  49. package/dist/selectors/token-selectors.mjs.map +1 -1
  50. package/dist/token-prices-service/abstract-token-prices-service.cjs.map +1 -1
  51. package/dist/token-prices-service/abstract-token-prices-service.d.cts +30 -0
  52. package/dist/token-prices-service/abstract-token-prices-service.d.cts.map +1 -1
  53. package/dist/token-prices-service/abstract-token-prices-service.d.mts +30 -0
  54. package/dist/token-prices-service/abstract-token-prices-service.d.mts.map +1 -1
  55. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -1
  56. package/dist/token-prices-service/codefi-v2.cjs +75 -0
  57. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  58. package/dist/token-prices-service/codefi-v2.d.cts +15 -1
  59. package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
  60. package/dist/token-prices-service/codefi-v2.d.mts +15 -1
  61. package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
  62. package/dist/token-prices-service/codefi-v2.mjs +75 -0
  63. package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
  64. package/dist/token-service.cjs +49 -1
  65. package/dist/token-service.cjs.map +1 -1
  66. package/dist/token-service.d.cts +16 -1
  67. package/dist/token-service.d.cts.map +1 -1
  68. package/dist/token-service.d.mts +16 -1
  69. package/dist/token-service.d.mts.map +1 -1
  70. package/dist/token-service.mjs +48 -1
  71. package/dist/token-service.mjs.map +1 -1
  72. package/package.json +4 -4
@@ -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 { Hex } from '@metamask/utils';\n\n/**\n * Represents the price of a token in a currency.\n */\nexport type TokenPrice<TokenAddress extends Hex, Currency extends string> = {\n tokenAddress: TokenAddress;\n currency: Currency;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\n\n/**\n * A map of token address to its price.\n */\nexport type TokenPricesByTokenAddress<\n TokenAddress extends Hex,\n Currency extends string,\n> = {\n [A in TokenAddress]: TokenPrice<A, Currency>;\n};\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template TokenAddress - A type union of all token addresses. The reason this\n * type parameter exists is so that we can guarantee that same addresses that\n * `fetchTokenPrices` receives are the same addresses that shown up in the\n * return value.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n TokenAddress extends Hex = Hex,\n Currency extends string = string,\n> = 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.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: ChainId;\n tokenAddresses: TokenAddress[];\n currency: Currency;\n }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
1
+ {"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 { Hex } from '@metamask/utils';\n\n/**\n * Represents the price of a token in a currency.\n */\nexport type TokenPrice<TokenAddress extends Hex, Currency extends string> = {\n tokenAddress: TokenAddress;\n currency: Currency;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\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 token address to its price.\n */\nexport type TokenPricesByTokenAddress<\n TokenAddress extends Hex,\n Currency extends string,\n> = {\n [A in TokenAddress]: TokenPrice<A, Currency>;\n};\n\n/**\n * A map of currency to its exchange rate.\n */\nexport type ExchangeRatesByCurrency<Currency extends string> = {\n [C in Currency]: ExchangeRate;\n};\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template TokenAddress - A type union of all token addresses. The reason this\n * type parameter exists is so that we can guarantee that same addresses that\n * `fetchTokenPrices` receives are the same addresses that shown up in the\n * return value.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n TokenAddress extends Hex = Hex,\n Currency extends string = string,\n> = 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.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: ChainId;\n tokenAddresses: TokenAddress[];\n currency: Currency;\n }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;\n\n /**\n * 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"]}
@@ -25,12 +25,28 @@ export type TokenPrice<TokenAddress extends Hex, Currency extends string> = {
25
25
  pricePercentChange200d: number;
26
26
  totalVolume: number;
27
27
  };
28
+ /**
29
+ * Represents an exchange rate.
30
+ */
31
+ export type ExchangeRate = {
32
+ name: string;
33
+ ticker: string;
34
+ value: number;
35
+ currencyType: string;
36
+ usd?: number;
37
+ };
28
38
  /**
29
39
  * A map of token address to its price.
30
40
  */
31
41
  export type TokenPricesByTokenAddress<TokenAddress extends Hex, Currency extends string> = {
32
42
  [A in TokenAddress]: TokenPrice<A, Currency>;
33
43
  };
44
+ /**
45
+ * A map of currency to its exchange rate.
46
+ */
47
+ export type ExchangeRatesByCurrency<Currency extends string> = {
48
+ [C in Currency]: ExchangeRate;
49
+ };
34
50
  /**
35
51
  * An ideal token prices service. All implementations must confirm to this
36
52
  * interface.
@@ -60,6 +76,20 @@ export type AbstractTokenPricesService<ChainId extends Hex = Hex, TokenAddress e
60
76
  tokenAddresses: TokenAddress[];
61
77
  currency: Currency;
62
78
  }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;
79
+ /**
80
+ * Retrieves exchange rates in the given currency.
81
+ *
82
+ * @param args - The arguments to this function.
83
+ * @param args.baseCurrency - The desired currency of the token prices.
84
+ * @param args.includeUsdRate - Whether to include the USD rate in the response.
85
+ * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.
86
+ * @returns The exchange rates in the requested base currency.
87
+ */
88
+ fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }: {
89
+ baseCurrency: Currency;
90
+ includeUsdRate: boolean;
91
+ cryptocurrencies: string[];
92
+ }): Promise<ExchangeRatesByCurrency<Currency>>;
63
93
  /**
64
94
  * Type guard for whether the API can return token prices for the given chain
65
95
  * ID.
@@ -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,GAAG,EAAE,wBAAwB;AAE3C;;GAEG;AACH,MAAM,MAAM,UAAU,CAAC,YAAY,SAAS,GAAG,EAAE,QAAQ,SAAS,MAAM,IAAI;IAC1E,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,EAAE,QAAQ,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,wBAAwB,EAAE,MAAM,CAAC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,sBAAsB,EAAE,MAAM,CAAC;IAC/B,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,yBAAyB,CACnC,YAAY,SAAS,GAAG,EACxB,QAAQ,SAAS,MAAM,IACrB;KACD,CAAC,IAAI,YAAY,GAAG,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,0BAA0B,CACpC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,YAAY,SAAS,GAAG,GAAG,GAAG,EAC9B,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG,YAAY,CAAC,CAAC,GAAG;IAC3D;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EACf,OAAO,EACP,cAAc,EACd,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,OAAO,CAAC;QACjB,cAAc,EAAE,YAAY,EAAE,CAAC;QAC/B,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,OAAO,CAAC,yBAAyB,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAExE;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
1
+ {"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,GAAG,EAAE,wBAAwB;AAE3C;;GAEG;AACH,MAAM,MAAM,UAAU,CAAC,YAAY,SAAS,GAAG,EAAE,QAAQ,SAAS,MAAM,IAAI;IAC1E,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,EAAE,QAAQ,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,wBAAwB,EAAE,MAAM,CAAC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,oBA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AAyB,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAExE;;;;;;;;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"}
@@ -25,12 +25,28 @@ export type TokenPrice<TokenAddress extends Hex, Currency extends string> = {
25
25
  pricePercentChange200d: number;
26
26
  totalVolume: number;
27
27
  };
28
+ /**
29
+ * Represents an exchange rate.
30
+ */
31
+ export type ExchangeRate = {
32
+ name: string;
33
+ ticker: string;
34
+ value: number;
35
+ currencyType: string;
36
+ usd?: number;
37
+ };
28
38
  /**
29
39
  * A map of token address to its price.
30
40
  */
31
41
  export type TokenPricesByTokenAddress<TokenAddress extends Hex, Currency extends string> = {
32
42
  [A in TokenAddress]: TokenPrice<A, Currency>;
33
43
  };
44
+ /**
45
+ * A map of currency to its exchange rate.
46
+ */
47
+ export type ExchangeRatesByCurrency<Currency extends string> = {
48
+ [C in Currency]: ExchangeRate;
49
+ };
34
50
  /**
35
51
  * An ideal token prices service. All implementations must confirm to this
36
52
  * interface.
@@ -60,6 +76,20 @@ export type AbstractTokenPricesService<ChainId extends Hex = Hex, TokenAddress e
60
76
  tokenAddresses: TokenAddress[];
61
77
  currency: Currency;
62
78
  }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;
79
+ /**
80
+ * Retrieves exchange rates in the given currency.
81
+ *
82
+ * @param args - The arguments to this function.
83
+ * @param args.baseCurrency - The desired currency of the token prices.
84
+ * @param args.includeUsdRate - Whether to include the USD rate in the response.
85
+ * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.
86
+ * @returns The exchange rates in the requested base currency.
87
+ */
88
+ fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }: {
89
+ baseCurrency: Currency;
90
+ includeUsdRate: boolean;
91
+ cryptocurrencies: string[];
92
+ }): Promise<ExchangeRatesByCurrency<Currency>>;
63
93
  /**
64
94
  * Type guard for whether the API can return token prices for the given chain
65
95
  * ID.
@@ -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,GAAG,EAAE,wBAAwB;AAE3C;;GAEG;AACH,MAAM,MAAM,UAAU,CAAC,YAAY,SAAS,GAAG,EAAE,QAAQ,SAAS,MAAM,IAAI;IAC1E,YAAY,EAAE,YAAY,CAAC;IAC3B,QAAQ,EAAE,QAAQ,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,wBAAwB,EAAE,MAAM,CAAC;IACjC,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,oBAAoB,EAAE,MAAM,CAAC;IAC7B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,sBAAsB,EAAE,MAAM,CAAC;IAC/B,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,yBAAyB,CACnC,YAAY,SAAS,GAAG,EACxB,QAAQ,SAAS,MAAM,IACrB;KACD,CAAC,IAAI,YAAY,GAAG,UAAU,CAAC,CAAC,EAAE,QAAQ,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,0BAA0B,CACpC,OAAO,SAAS,GAAG,GAAG,GAAG,EACzB,YAAY,SAAS,GAAG,GAAG,GAAG,EAC9B,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG,YAAY,CAAC,CAAC,GAAG;IAC3D;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EACf,OAAO,EACP,cAAc,EACd,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,OAAO,CAAC;QACjB,cAAc,EAAE,YAAY,EAAE,CAAC;QAC/B,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,OAAO,CAAC,yBAAyB,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAExE;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,IAAI,OAAO,CAAC;IAE/D;;;;;;OAMG;IACH,yBAAyB,CAAC,QAAQ,EAAE,OAAO,GAAG,QAAQ,IAAI,QAAQ,CAAC;CACpE,CAAC"}
1
+ {"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,GAAG,EAAE,wBAAwB;AAE3C;;GAEG;AACH,MAAM,MAAM,UAAU,CAAC,YAAY,SAAS,GAAG,EAAE,QAAQ,SAAS,MAAM,IAAI;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AG,EACzB,YAAY,SAAS,GAAG,GAAG,GAAG,EAC9B,QAAQ,SAAS,MAAM,GAAG,MAAM,IAC9B,OAAO,CAAC,IAAI,CAAC,aAAa,EAAE,SAAS,GAAG,YAAY,CAAC,CAAC,GAAG;IAC3D;;;;;;;;;OASG;IACH,gBAAgB,CAAC,EACf,OAAO,EACP,cAAc,EACd,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,OAAO,CAAC;QACjB,cAAc,EAAE,YAAY,EAAE,CAAC;QAC/B,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,OAAO,CAAC,yBAAyB,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC;IAExE;;;;;;;;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 { Hex } from '@metamask/utils';\n\n/**\n * Represents the price of a token in a currency.\n */\nexport type TokenPrice<TokenAddress extends Hex, Currency extends string> = {\n tokenAddress: TokenAddress;\n currency: Currency;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\n\n/**\n * A map of token address to its price.\n */\nexport type TokenPricesByTokenAddress<\n TokenAddress extends Hex,\n Currency extends string,\n> = {\n [A in TokenAddress]: TokenPrice<A, Currency>;\n};\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template TokenAddress - A type union of all token addresses. The reason this\n * type parameter exists is so that we can guarantee that same addresses that\n * `fetchTokenPrices` receives are the same addresses that shown up in the\n * return value.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n TokenAddress extends Hex = Hex,\n Currency extends string = string,\n> = 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.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: ChainId;\n tokenAddresses: TokenAddress[];\n currency: Currency;\n }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is ChainId;\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is Currency;\n};\n"]}
1
+ {"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 { Hex } from '@metamask/utils';\n\n/**\n * Represents the price of a token in a currency.\n */\nexport type TokenPrice<TokenAddress extends Hex, Currency extends string> = {\n tokenAddress: TokenAddress;\n currency: Currency;\n allTimeHigh: number;\n allTimeLow: number;\n circulatingSupply: number;\n dilutedMarketCap: number;\n high1d: number;\n low1d: number;\n marketCap: number;\n marketCapPercentChange1d: number;\n price: number;\n priceChange1d: number;\n pricePercentChange1d: number;\n pricePercentChange1h: number;\n pricePercentChange1y: number;\n pricePercentChange7d: number;\n pricePercentChange14d: number;\n pricePercentChange30d: number;\n pricePercentChange200d: number;\n totalVolume: number;\n};\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 token address to its price.\n */\nexport type TokenPricesByTokenAddress<\n TokenAddress extends Hex,\n Currency extends string,\n> = {\n [A in TokenAddress]: TokenPrice<A, Currency>;\n};\n\n/**\n * A map of currency to its exchange rate.\n */\nexport type ExchangeRatesByCurrency<Currency extends string> = {\n [C in Currency]: ExchangeRate;\n};\n\n/**\n * An ideal token prices service. All implementations must confirm to this\n * interface.\n *\n * @template ChainId - A type union of valid arguments for the `chainId`\n * argument to `fetchTokenPrices`.\n * @template TokenAddress - A type union of all token addresses. The reason this\n * type parameter exists is so that we can guarantee that same addresses that\n * `fetchTokenPrices` receives are the same addresses that shown up in the\n * return value.\n * @template Currency - A type union of valid arguments for the `currency`\n * argument to `fetchTokenPrices`.\n */\nexport type AbstractTokenPricesService<\n ChainId extends Hex = Hex,\n TokenAddress extends Hex = Hex,\n Currency extends string = string,\n> = 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.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: ChainId;\n tokenAddresses: TokenAddress[];\n currency: Currency;\n }): Promise<Partial<TokenPricesByTokenAddress<TokenAddress, Currency>>>;\n\n /**\n * 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"]}
@@ -252,6 +252,7 @@ exports.SUPPORTED_CHAIN_IDS = [
252
252
  * All requests to V2 of the Price API start with this.
253
253
  */
254
254
  const BASE_URL = 'https://price.api.cx.metamask.io/v2';
255
+ const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
255
256
  /**
256
257
  * This version of the token prices service uses V2 of the Codefi Price API to
257
258
  * fetch token prices.
@@ -328,6 +329,80 @@ class CodefiTokenPricesServiceV2 {
328
329
  };
329
330
  }, {});
330
331
  }
332
+ /**
333
+ * Retrieves exchange rates in the given base currency.
334
+ *
335
+ * @param args - The arguments to this function.
336
+ * @param args.baseCurrency - The desired base currency of the exchange rates.
337
+ * @param args.includeUsdRate - Whether to include the USD rate in the response.
338
+ * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.
339
+ * @returns The exchange rates for the requested base currency.
340
+ */
341
+ async fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }) {
342
+ const url = new URL(`${BASE_URL_V1}/exchange-rates`);
343
+ url.searchParams.append('baseCurrency', baseCurrency);
344
+ const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);
345
+ urlUsd.searchParams.append('baseCurrency', 'usd');
346
+ const [exchangeRatesResult, exchangeRatesResultUsd] = await Promise.allSettled([
347
+ __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => (0, controller_utils_1.handleFetch)(url, { headers: { 'Cache-Control': 'no-cache' } })),
348
+ ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'
349
+ ? [
350
+ __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => (0, controller_utils_1.handleFetch)(urlUsd, {
351
+ headers: { 'Cache-Control': 'no-cache' },
352
+ })),
353
+ ]
354
+ : []),
355
+ ]);
356
+ // Handle resolved/rejected
357
+ const exchangeRates = exchangeRatesResult.status === 'fulfilled'
358
+ ? exchangeRatesResult.value
359
+ : {};
360
+ const exchangeRatesUsd = exchangeRatesResultUsd?.status === 'fulfilled'
361
+ ? exchangeRatesResultUsd.value
362
+ : {};
363
+ if (exchangeRatesResult.status === 'rejected') {
364
+ throw new Error('Failed to fetch');
365
+ }
366
+ const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {
367
+ if (exchangeRates[key.toLowerCase()]) {
368
+ acc[key.toLowerCase()] =
369
+ exchangeRates[key.toLowerCase()];
370
+ }
371
+ return acc;
372
+ }, {});
373
+ if (Object.keys(filteredExchangeRates).length === 0) {
374
+ throw new Error('None of the cryptocurrencies are supported by price api');
375
+ }
376
+ const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {
377
+ if (exchangeRatesUsd[key.toLowerCase()]) {
378
+ acc[key.toLowerCase()] =
379
+ exchangeRatesUsd[key.toLowerCase()];
380
+ }
381
+ return acc;
382
+ }, {});
383
+ if (baseCurrency.toLowerCase() === 'usd') {
384
+ Object.keys(filteredExchangeRates).forEach((key) => {
385
+ filteredExchangeRates[key] = {
386
+ ...filteredExchangeRates[key],
387
+ usd: filteredExchangeRates[key]?.value,
388
+ };
389
+ });
390
+ return filteredExchangeRates;
391
+ }
392
+ if (!includeUsdRate) {
393
+ return filteredExchangeRates;
394
+ }
395
+ const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {
396
+ acc[key] = {
397
+ ...filteredExchangeRates[key],
398
+ ...(filteredUsdExchangeRates[key]?.value
399
+ ? { usd: filteredUsdExchangeRates[key]?.value }
400
+ : {}),
401
+ };
402
+ return acc;
403
+ }, {});
404
+ return merged;
405
+ }
331
406
  /**
332
407
  * Type guard for whether the API can return token prices for the given chain
333
408
  * ID.
@@ -1 +1 @@
1
- {"version":3,"file":"codefi-v2.cjs","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,iEAOoC;AAGpC,2CAA8C;AAQ9C;;;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;I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sMC","sourcesContent":["import {\n createServicePolicy,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Mantle\n '0x1388',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n // Sei Mainnet\n '0x531',\n // Sonic Mainnet\n '0x92',\n // Monad Mainnet\n '0x8f',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [getNativeTokenAddress(chainId), ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [getNativeTokenAddress(chainId), ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (!marketData) {\n return obj;\n }\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * 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,2CAA8C;AAS9C;;;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,i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ACpE,CAAC,CAAC,EAAE,CAAC;aACR,CAAC;YACF,OAAO,GAAG,CAAC;QACb,CAAC,EAAE,EAAgD,CAAC,CAAC;QAErD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;;OAMG;IACH,wBAAwB,CAAC,OAAgB;QACvC,MAAM,iBAAiB,GAAsB,2BAAmB,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,4BAAoB,CAAC;QACpE,OAAO,CACL,OAAO,QAAQ,KAAK,QAAQ;YAC5B,mBAAmB,CAAC,QAAQ,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CACrD,CAAC;IACJ,CAAC;CACF;AA5SD,gEA4SC","sourcesContent":["import {\n createServicePolicy,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n handleFetch,\n} from '@metamask/controller-utils';\nimport type { ServicePolicy } from '@metamask/controller-utils';\nimport type { Hex } from '@metamask/utils';\nimport { hexToNumber } from '@metamask/utils';\n\nimport type {\n AbstractTokenPricesService,\n ExchangeRatesByCurrency,\n TokenPrice,\n TokenPricesByTokenAddress,\n} from './abstract-token-prices-service';\n\n/**\n * The list of currencies that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint, in lowercase form.\n */\nexport const SUPPORTED_CURRENCIES = [\n // Bitcoin\n 'btc',\n // Ether\n 'eth',\n // Litecoin\n 'ltc',\n // Bitcoin Cash\n 'bch',\n // Binance Coin\n 'bnb',\n // EOS\n 'eos',\n // XRP\n 'xrp',\n // Lumens\n 'xlm',\n // Chainlink\n 'link',\n // Polkadot\n 'dot',\n // Yearn.finance\n 'yfi',\n // US Dollar\n 'usd',\n // United Arab Emirates Dirham\n 'aed',\n // Argentine Peso\n 'ars',\n // Australian Dollar\n 'aud',\n // Bangladeshi Taka\n 'bdt',\n // Bahraini Dinar\n 'bhd',\n // Bermudian Dollar\n 'bmd',\n // Brazil Real\n 'brl',\n // Canadian Dollar\n 'cad',\n // Swiss Franc\n 'chf',\n // Chilean Peso\n 'clp',\n // Chinese Yuan\n 'cny',\n // Czech Koruna\n 'czk',\n // Danish Krone\n 'dkk',\n // Euro\n 'eur',\n // British Pound Sterling\n 'gbp',\n // Hong Kong Dollar\n 'hkd',\n // Hungarian Forint\n 'huf',\n // Indonesian Rupiah\n 'idr',\n // Israeli New Shekel\n 'ils',\n // Indian Rupee\n 'inr',\n // Japanese Yen\n 'jpy',\n // South Korean Won\n 'krw',\n // Kuwaiti Dinar\n 'kwd',\n // Sri Lankan Rupee\n 'lkr',\n // Burmese Kyat\n 'mmk',\n // Mexican Peso\n 'mxn',\n // Malaysian Ringgit\n 'myr',\n // Nigerian Naira\n 'ngn',\n // Norwegian Krone\n 'nok',\n // New Zealand Dollar\n 'nzd',\n // Philippine Peso\n 'php',\n // Pakistani Rupee\n 'pkr',\n // Polish Zloty\n 'pln',\n // Russian Ruble\n 'rub',\n // Saudi Riyal\n 'sar',\n // Swedish Krona\n 'sek',\n // Singapore Dollar\n 'sgd',\n // Thai Baht\n 'thb',\n // Turkish Lira\n 'try',\n // New Taiwan Dollar\n 'twd',\n // Ukrainian hryvnia\n 'uah',\n // Venezuelan bolívar fuerte\n 'vef',\n // Vietnamese đồng\n 'vnd',\n // South African Rand\n 'zar',\n // IMF Special Drawing Rights\n 'xdr',\n // Silver - Troy Ounce\n 'xag',\n // Gold - Troy Ounce\n 'xau',\n // Bits\n 'bits',\n // Satoshi\n 'sats',\n] as const;\n\n/**\n * Represents the zero address, commonly used as a placeholder in blockchain transactions.\n * In the context of fetching market data, the zero address is utilized to retrieve information\n * specifically for native currencies. This allows for a standardized approach to query market\n * data for blockchain-native assets without a specific contract address.\n */\nexport const ZERO_ADDRESS: Hex =\n '0x0000000000000000000000000000000000000000' as const;\n\n/**\n * A mapping from chain id to the address of the chain's native token.\n * Only for chains whose native tokens have a specific address.\n */\nconst chainIdToNativeTokenAddress: Record<Hex, Hex> = {\n '0x89': '0x0000000000000000000000000000000000001010',\n};\n\n/**\n * Returns the address that should be used to query the price api for the\n * chain's native token. On most chains, this is signified by the zero address.\n * But on some chains, the native token has a specific address.\n * @param chainId - The hexadecimal chain id.\n * @returns The address of the chain's native token.\n */\nexport const getNativeTokenAddress = (chainId: Hex): Hex =>\n chainIdToNativeTokenAddress[chainId] ?? ZERO_ADDRESS;\n\n/**\n * A currency that can be supplied as the `vsCurrency` parameter to\n * the `/spot-prices` endpoint. Covers both uppercase and lowercase versions.\n */\ntype SupportedCurrency =\n | (typeof SUPPORTED_CURRENCIES)[number]\n | Uppercase<(typeof SUPPORTED_CURRENCIES)[number]>;\n\n/**\n * The list of chain IDs that can be supplied in the URL for the `/spot-prices`\n * endpoint, but in hexadecimal form (for consistency with how we represent\n * chain IDs in other places).\n * @see Used by {@link CodefiTokenPricesServiceV2} to validate that a given chain ID is supported by V2 of the Codefi Price API.\n */\nexport const SUPPORTED_CHAIN_IDS = [\n // Ethereum Mainnet\n '0x1',\n // OP Mainnet\n '0xa',\n // Cronos Mainnet\n '0x19',\n // BNB Smart Chain Mainnet\n '0x38',\n // Syscoin Mainnet\n '0x39',\n // OKXChain Mainnet\n '0x42',\n // Hoo Smart Chain\n '0x46',\n // Meter Mainnet\n '0x52',\n // TomoChain\n '0x58',\n // Gnosis\n '0x64',\n // Velas EVM Mainnet\n '0x6a',\n // Fuse Mainnet\n '0x7a',\n // Huobi ECO Chain Mainnet\n '0x80',\n // Polygon Mainnet\n '0x89',\n // Fantom Opera\n '0xfa',\n // Boba Network\n '0x120',\n // KCC Mainnet\n '0x141',\n // zkSync Era Mainnet\n '0x144',\n // Theta Mainnet\n '0x169',\n // Metis Andromeda Mainnet\n '0x440',\n // Moonbeam\n '0x504',\n // Moonriver\n '0x505',\n // Mantle\n '0x1388',\n // Base\n '0x2105',\n // Shiden\n '0x150',\n // Smart Bitcoin Cash\n '0x2710',\n // Arbitrum One\n '0xa4b1',\n // Celo Mainnet\n '0xa4ec',\n // Oasis Emerald\n '0xa516',\n // Avalanche C-Chain\n '0xa86a',\n // Polis Mainnet\n '0x518af',\n // Aurora Mainnet\n '0x4e454152',\n // Harmony Mainnet Shard 0\n '0x63564c40',\n // Linea Mainnet\n '0xe708',\n // Sei Mainnet\n '0x531',\n // Sonic Mainnet\n '0x92',\n // Monad Mainnet\n '0x8f',\n] as const;\n\n/**\n * A chain ID that can be supplied in the URL for the `/spot-prices` endpoint,\n * but in hexadecimal form (for consistency with how we represent chain IDs in\n * other places).\n */\ntype SupportedChainId = (typeof SUPPORTED_CHAIN_IDS)[number];\n\n/**\n * All requests to V2 of the Price API start with this.\n */\nconst BASE_URL = 'https://price.api.cx.metamask.io/v2';\n\nconst BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';\n\n/**\n * The shape of the data that the /spot-prices endpoint returns.\n */\ntype MarketData = {\n /**\n * The all-time highest price of the token.\n */\n allTimeHigh: number;\n /**\n * The all-time lowest price of the token.\n */\n allTimeLow: number;\n /**\n * The number of tokens currently in circulation.\n */\n circulatingSupply: number;\n /**\n * The market cap calculated using the diluted supply.\n */\n dilutedMarketCap: number;\n /**\n * The highest price of the token in the last 24 hours.\n */\n high1d: number;\n /**\n * The lowest price of the token in the last 24 hours.\n */\n low1d: number;\n /**\n * The current market capitalization of the token.\n */\n marketCap: number;\n /**\n * The percentage change in market capitalization over the last 24 hours.\n */\n marketCapPercentChange1d: number;\n /**\n * The current price of the token.\n */\n price: number;\n /**\n * The absolute change in price over the last 24 hours.\n */\n priceChange1d: number;\n /**\n * The percentage change in price over the last 24 hours.\n */\n pricePercentChange1d: number;\n /**\n * The percentage change in price over the last hour.\n */\n pricePercentChange1h: number;\n /**\n * The percentage change in price over the last year.\n */\n pricePercentChange1y: number;\n /**\n * The percentage change in price over the last 7 days.\n */\n pricePercentChange7d: number;\n /**\n * The percentage change in price over the last 14 days.\n */\n pricePercentChange14d: number;\n /**\n * The percentage change in price over the last 30 days.\n */\n pricePercentChange30d: number;\n /**\n * The percentage change in price over the last 200 days.\n */\n pricePercentChange200d: number;\n /**\n * The total trading volume of the token in the last 24 hours.\n */\n totalVolume: number;\n};\n\ntype MarketDataByTokenAddress = { [address: Hex]: MarketData };\n/**\n * This version of the token prices service uses V2 of the Codefi Price API to\n * fetch token prices.\n */\nexport class CodefiTokenPricesServiceV2\n implements\n AbstractTokenPricesService<SupportedChainId, Hex, SupportedCurrency>\n{\n readonly #policy: ServicePolicy;\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n });\n\n /**\n * Construct a Codefi Token Price Service.\n *\n * @deprecated This signature is deprecated; please use the `onBreak` and\n * `onDegraded` methods instead.\n * @param args - The arguments.\n * @param args.degradedThreshold - The length of time (in milliseconds)\n * that governs when the service is regarded as degraded (affecting when\n * `onDegraded` is called). Defaults to 5 seconds.\n * @param args.retries - Number of retry attempts for each fetch request.\n * @param args.maximumConsecutiveFailures - The maximum number of consecutive\n * failures allowed before breaking the circuit and pausing further updates.\n * @param args.onBreak - Callback for when the circuit breaks, useful\n * for capturing metrics about network failures.\n * @param args.onDegraded - Callback for when the API responds successfully\n * but takes too long to respond (5 seconds or more).\n * @param args.circuitBreakDuration - The amount of time to wait when the\n * circuit breaks from too many consecutive failures.\n */\n // eslint-disable-next-line @typescript-eslint/unified-signatures\n constructor(args?: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n });\n\n constructor({\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n retries = DEFAULT_MAX_RETRIES,\n maximumConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak,\n onDegraded,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n }: {\n degradedThreshold?: number;\n retries?: number;\n maximumConsecutiveFailures?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n circuitBreakDuration?: number;\n } = {}) {\n this.#policy = createServicePolicy({\n maxRetries: retries,\n maxConsecutiveFailures: maximumConsecutiveFailures,\n circuitBreakDuration,\n degradedThreshold,\n });\n if (onBreak) {\n this.#policy.onBreak(onBreak);\n }\n if (onDegraded) {\n this.#policy.onDegraded(onDegraded);\n }\n }\n\n /**\n * Listens for when the request to the API fails too many times in a row.\n *\n * @param args - The same arguments that {@link ServicePolicy.onBreak}\n * takes.\n * @returns What {@link ServicePolicy.onBreak} returns.\n */\n onBreak(...args: Parameters<ServicePolicy['onBreak']>) {\n return this.#policy.onBreak(...args);\n }\n\n /**\n * Listens for when the API is degraded.\n *\n * @param args - The same arguments that {@link ServicePolicy.onDegraded}\n * takes.\n * @returns What {@link ServicePolicy.onDegraded} returns.\n */\n onDegraded(...args: Parameters<ServicePolicy['onDegraded']>) {\n return this.#policy.onDegraded(...args);\n }\n\n /**\n * Retrieves prices in the given currency for the tokens identified by the\n * given addresses which are expected to live on the given chain.\n *\n * @param args - The arguments to function.\n * @param args.chainId - An EIP-155 chain ID.\n * @param args.tokenAddresses - Addresses for tokens that live on the chain.\n * @param args.currency - The desired currency of the token prices.\n * @returns The prices for the requested tokens.\n */\n async fetchTokenPrices({\n chainId,\n tokenAddresses,\n currency,\n }: {\n chainId: SupportedChainId;\n tokenAddresses: Hex[];\n currency: SupportedCurrency;\n }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>> {\n const chainIdAsNumber = hexToNumber(chainId);\n\n const url = new URL(`${BASE_URL}/chains/${chainIdAsNumber}/spot-prices`);\n url.searchParams.append(\n 'tokenAddresses',\n [getNativeTokenAddress(chainId), ...tokenAddresses].join(','),\n );\n url.searchParams.append('vsCurrency', currency);\n url.searchParams.append('includeMarketData', 'true');\n\n const addressCryptoDataMap: MarketDataByTokenAddress =\n await this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n );\n\n return [getNativeTokenAddress(chainId), ...tokenAddresses].reduce(\n (\n obj: Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>,\n tokenAddress,\n ) => {\n // The Price API lowercases both currency and token addresses, so we have\n // to keep track of them and make sure we return the original versions.\n const lowercasedTokenAddress =\n tokenAddress.toLowerCase() as Lowercase<Hex>;\n\n const marketData = addressCryptoDataMap[lowercasedTokenAddress];\n\n if (!marketData) {\n return obj;\n }\n\n const token: TokenPrice<Hex, SupportedCurrency> = {\n tokenAddress,\n currency,\n ...marketData,\n };\n\n return {\n ...obj,\n [tokenAddress]: token,\n };\n },\n {},\n ) as Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>;\n }\n\n /**\n * Retrieves exchange rates in the given base currency.\n *\n * @param args - The arguments to this function.\n * @param args.baseCurrency - The desired base currency of the exchange rates.\n * @param args.includeUsdRate - Whether to include the USD rate in the response.\n * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.\n * @returns The exchange rates for the requested base currency.\n */\n async fetchExchangeRates({\n baseCurrency,\n includeUsdRate,\n cryptocurrencies,\n }: {\n baseCurrency: SupportedCurrency;\n includeUsdRate: boolean;\n cryptocurrencies: string[];\n }): Promise<ExchangeRatesByCurrency<SupportedCurrency>> {\n const url = new URL(`${BASE_URL_V1}/exchange-rates`);\n url.searchParams.append('baseCurrency', baseCurrency);\n\n const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);\n urlUsd.searchParams.append('baseCurrency', 'usd');\n\n const [exchangeRatesResult, exchangeRatesResultUsd] =\n await Promise.allSettled([\n this.#policy.execute(() =>\n handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } }),\n ),\n ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'\n ? [\n this.#policy.execute(() =>\n handleFetch(urlUsd, {\n headers: { 'Cache-Control': 'no-cache' },\n }),\n ),\n ]\n : []),\n ]);\n\n // Handle resolved/rejected\n const exchangeRates =\n exchangeRatesResult.status === 'fulfilled'\n ? exchangeRatesResult.value\n : {};\n const exchangeRatesUsd =\n exchangeRatesResultUsd?.status === 'fulfilled'\n ? exchangeRatesResultUsd.value\n : {};\n\n if (exchangeRatesResult.status === 'rejected') {\n throw new Error('Failed to fetch');\n }\n\n const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRates[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRates[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (Object.keys(filteredExchangeRates).length === 0) {\n throw new Error(\n 'None of the cryptocurrencies are supported by price api',\n );\n }\n\n const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {\n if (exchangeRatesUsd[key.toLowerCase() as SupportedCurrency]) {\n acc[key.toLowerCase() as SupportedCurrency] =\n exchangeRatesUsd[key.toLowerCase() as SupportedCurrency];\n }\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n if (baseCurrency.toLowerCase() === 'usd') {\n Object.keys(filteredExchangeRates).forEach((key) => {\n filteredExchangeRates[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n usd: filteredExchangeRates[key as SupportedCurrency]?.value,\n };\n });\n return filteredExchangeRates;\n }\n if (!includeUsdRate) {\n return filteredExchangeRates;\n }\n\n const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {\n acc[key as SupportedCurrency] = {\n ...filteredExchangeRates[key as SupportedCurrency],\n ...(filteredUsdExchangeRates[key as SupportedCurrency]?.value\n ? { usd: filteredUsdExchangeRates[key as SupportedCurrency]?.value }\n : {}),\n };\n return acc;\n }, {} as ExchangeRatesByCurrency<SupportedCurrency>);\n\n return merged;\n }\n\n /**\n * Type guard for whether the API can return token prices for the given chain\n * ID.\n *\n * @param chainId - The chain ID to check.\n * @returns True if the API supports the chain ID, false otherwise.\n */\n validateChainIdSupported(chainId: unknown): chainId is SupportedChainId {\n const supportedChainIds: readonly string[] = SUPPORTED_CHAIN_IDS;\n return typeof chainId === 'string' && supportedChainIds.includes(chainId);\n }\n\n /**\n * Type guard for whether the API can return token prices in the given\n * currency.\n *\n * @param currency - The currency to check. If a string, can be either\n * lowercase or uppercase.\n * @returns True if the API supports the currency, false otherwise.\n */\n validateCurrencySupported(currency: unknown): currency is SupportedCurrency {\n const supportedCurrencies: readonly string[] = SUPPORTED_CURRENCIES;\n return (\n typeof currency === 'string' &&\n supportedCurrencies.includes(currency.toLowerCase())\n );\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { ServicePolicy } from "@metamask/controller-utils";
2
2
  import type { Hex } from "@metamask/utils";
3
- import type { AbstractTokenPricesService, TokenPricesByTokenAddress } from "./abstract-token-prices-service.cjs";
3
+ import type { AbstractTokenPricesService, ExchangeRatesByCurrency, TokenPricesByTokenAddress } from "./abstract-token-prices-service.cjs";
4
4
  /**
5
5
  * The list of currencies that can be supplied as the `vsCurrency` parameter to
6
6
  * the `/spot-prices` endpoint, in lowercase form.
@@ -122,6 +122,20 @@ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesSe
122
122
  tokenAddresses: Hex[];
123
123
  currency: SupportedCurrency;
124
124
  }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>>;
125
+ /**
126
+ * Retrieves exchange rates in the given base currency.
127
+ *
128
+ * @param args - The arguments to this function.
129
+ * @param args.baseCurrency - The desired base currency of the exchange rates.
130
+ * @param args.includeUsdRate - Whether to include the USD rate in the response.
131
+ * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.
132
+ * @returns The exchange rates for the requested base currency.
133
+ */
134
+ fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }: {
135
+ baseCurrency: SupportedCurrency;
136
+ includeUsdRate: boolean;
137
+ cryptocurrencies: string[];
138
+ }): Promise<ExchangeRatesByCurrency<SupportedCurrency>>;
125
139
  /**
126
140
  * Type guard for whether the API can return token prices for the given chain
127
141
  * ID.
@@ -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,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EACV,0BAA0B,EAE1B,yBAAyB,EAC1B,4CAAwC;AAEzC;;;GAGG;AACH,eAAO,MAAM,oBAAoB,ybA2HvB,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,GAC4B,CAAC;AAUxD;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,YAAa,GAAG,KAAG,GACC,CAAC;AAEvD;;;GAGG;AACH,KAAK,iBAAiB,GAClB,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,GACrC,SAAS,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;AAErD;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,yVA2EtB,CAAC;AAEX;;;;GAIG;AACH,KAAK,gBAAgB,GAAG,CAAC,OAAO,mBAAmB,CAAC,CAAC,MAAM,CAAC,CAAC;AAsF7D;;;GAGG;AACH,qBAAa,0BACX,YACE,0BAA0B,CAAC,gBAAgB,EAAE,GAAG,EAAE,iBAA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AAE,MAAM,IAAI,CAAC;QACxB,oBAAoB,CAAC,EAAE,MAAM,CAAC;KAC/B;IA+BD;;;;;;OAMG;IACH,OAAO,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;IAIrD;;;;;;OAMG;IACH,UAAU,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC;IAI3D;;;;;;;;;OASG;IACG,gBAAgB,CAAC,EACrB,OAAO,EACP,cAAc,EACd,QAAQ,GACT,EAAE;QACD,OAAO,EAAE,gBAAgB,CAAC;QAC1B,cAAc,EAAE,GAAG,EAAE,CAAC;QACtB,QAAQ,EAAE,iBAAiB,CAAC;KAC7B,GAAG,OAAO,CAAC,OAAO,CAAC,yBAAyB,CAAC,GAAG,EAAE,iBAAiB,CAAC,CAAC,CAAC;IA+CvE;;;;;;;;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"}
@@ -1,6 +1,6 @@
1
1
  import type { ServicePolicy } from "@metamask/controller-utils";
2
2
  import type { Hex } from "@metamask/utils";
3
- import type { AbstractTokenPricesService, TokenPricesByTokenAddress } from "./abstract-token-prices-service.mjs";
3
+ import type { AbstractTokenPricesService, ExchangeRatesByCurrency, TokenPricesByTokenAddress } from "./abstract-token-prices-service.mjs";
4
4
  /**
5
5
  * The list of currencies that can be supplied as the `vsCurrency` parameter to
6
6
  * the `/spot-prices` endpoint, in lowercase form.
@@ -122,6 +122,20 @@ export declare class CodefiTokenPricesServiceV2 implements AbstractTokenPricesSe
122
122
  tokenAddresses: Hex[];
123
123
  currency: SupportedCurrency;
124
124
  }): Promise<Partial<TokenPricesByTokenAddress<Hex, SupportedCurrency>>>;
125
+ /**
126
+ * Retrieves exchange rates in the given base currency.
127
+ *
128
+ * @param args - The arguments to this function.
129
+ * @param args.baseCurrency - The desired base currency of the exchange rates.
130
+ * @param args.includeUsdRate - Whether to include the USD rate in the response.
131
+ * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.
132
+ * @returns The exchange rates for the requested base currency.
133
+ */
134
+ fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }: {
135
+ baseCurrency: SupportedCurrency;
136
+ includeUsdRate: boolean;
137
+ cryptocurrencies: string[];
138
+ }): Promise<ExchangeRatesByCurrency<SupportedCurrency>>;
125
139
  /**
126
140
  * Type guard for whether the API can return token prices for the given chain
127
141
  * ID.
@@ -1 +1 @@
1
- {"version":3,"file":"codefi-v2.d.mts","sourceRoot":"","sources":["../../src/token-prices-service/codefi-v2.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,mCAAmC;AAChE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAG3C,OAAO,KAAK,EACV,0BAA0B,EAE1B,yBAAyB,EAC1B,4CAAwC;AAEzC;;;GAGG;AACH,eAAO,MAAM,oBAAoB,ybA2HvB,CAAC;AAEX;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,GAC4B,CAAC;AAUxD;;;;;;GAMG;AACH,eAAO,MAAM,qBAAqB,YAAa,GAAG,KAAG,GACC,CAAC;AAEvD;;;GAGG;AACH,KAAK,iBAAiB,GAClB,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,GACrC,SAAS,CAAC,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,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7 @@ export const SUPPORTED_CHAIN_IDS = [
248
248
  * All requests to V2 of the Price API start with this.
249
249
  */
250
250
  const BASE_URL = 'https://price.api.cx.metamask.io/v2';
251
+ const BASE_URL_V1 = 'https://price.api.cx.metamask.io/v1';
251
252
  /**
252
253
  * This version of the token prices service uses V2 of the Codefi Price API to
253
254
  * fetch token prices.
@@ -324,6 +325,80 @@ export class CodefiTokenPricesServiceV2 {
324
325
  };
325
326
  }, {});
326
327
  }
328
+ /**
329
+ * Retrieves exchange rates in the given base currency.
330
+ *
331
+ * @param args - The arguments to this function.
332
+ * @param args.baseCurrency - The desired base currency of the exchange rates.
333
+ * @param args.includeUsdRate - Whether to include the USD rate in the response.
334
+ * @param args.cryptocurrencies - The cryptocurrencies to get exchange rates for.
335
+ * @returns The exchange rates for the requested base currency.
336
+ */
337
+ async fetchExchangeRates({ baseCurrency, includeUsdRate, cryptocurrencies, }) {
338
+ const url = new URL(`${BASE_URL_V1}/exchange-rates`);
339
+ url.searchParams.append('baseCurrency', baseCurrency);
340
+ const urlUsd = new URL(`${BASE_URL_V1}/exchange-rates`);
341
+ urlUsd.searchParams.append('baseCurrency', 'usd');
342
+ const [exchangeRatesResult, exchangeRatesResultUsd] = await Promise.allSettled([
343
+ __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(url, { headers: { 'Cache-Control': 'no-cache' } })),
344
+ ...(includeUsdRate && baseCurrency.toLowerCase() !== 'usd'
345
+ ? [
346
+ __classPrivateFieldGet(this, _CodefiTokenPricesServiceV2_policy, "f").execute(() => handleFetch(urlUsd, {
347
+ headers: { 'Cache-Control': 'no-cache' },
348
+ })),
349
+ ]
350
+ : []),
351
+ ]);
352
+ // Handle resolved/rejected
353
+ const exchangeRates = exchangeRatesResult.status === 'fulfilled'
354
+ ? exchangeRatesResult.value
355
+ : {};
356
+ const exchangeRatesUsd = exchangeRatesResultUsd?.status === 'fulfilled'
357
+ ? exchangeRatesResultUsd.value
358
+ : {};
359
+ if (exchangeRatesResult.status === 'rejected') {
360
+ throw new Error('Failed to fetch');
361
+ }
362
+ const filteredExchangeRates = cryptocurrencies.reduce((acc, key) => {
363
+ if (exchangeRates[key.toLowerCase()]) {
364
+ acc[key.toLowerCase()] =
365
+ exchangeRates[key.toLowerCase()];
366
+ }
367
+ return acc;
368
+ }, {});
369
+ if (Object.keys(filteredExchangeRates).length === 0) {
370
+ throw new Error('None of the cryptocurrencies are supported by price api');
371
+ }
372
+ const filteredUsdExchangeRates = cryptocurrencies.reduce((acc, key) => {
373
+ if (exchangeRatesUsd[key.toLowerCase()]) {
374
+ acc[key.toLowerCase()] =
375
+ exchangeRatesUsd[key.toLowerCase()];
376
+ }
377
+ return acc;
378
+ }, {});
379
+ if (baseCurrency.toLowerCase() === 'usd') {
380
+ Object.keys(filteredExchangeRates).forEach((key) => {
381
+ filteredExchangeRates[key] = {
382
+ ...filteredExchangeRates[key],
383
+ usd: filteredExchangeRates[key]?.value,
384
+ };
385
+ });
386
+ return filteredExchangeRates;
387
+ }
388
+ if (!includeUsdRate) {
389
+ return filteredExchangeRates;
390
+ }
391
+ const merged = Object.keys(filteredExchangeRates).reduce((acc, key) => {
392
+ acc[key] = {
393
+ ...filteredExchangeRates[key],
394
+ ...(filteredUsdExchangeRates[key]?.value
395
+ ? { usd: filteredUsdExchangeRates[key]?.value }
396
+ : {}),
397
+ };
398
+ return acc;
399
+ }, {});
400
+ return merged;
401
+ }
327
402
  /**
328
403
  * Type guard for whether the API can return token prices for the given chain
329
404
  * ID.