@metamask/assets-controllers 84.0.0 → 85.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 (48) hide show
  1. package/CHANGELOG.md +15 -1
  2. package/dist/CurrencyRateController.cjs +65 -12
  3. package/dist/CurrencyRateController.cjs.map +1 -1
  4. package/dist/CurrencyRateController.d.cts +14 -7
  5. package/dist/CurrencyRateController.d.cts.map +1 -1
  6. package/dist/CurrencyRateController.d.mts +14 -7
  7. package/dist/CurrencyRateController.d.mts.map +1 -1
  8. package/dist/CurrencyRateController.mjs +65 -12
  9. package/dist/CurrencyRateController.mjs.map +1 -1
  10. package/dist/MultichainAssetsController/MultichainAssetsController.cjs +42 -10
  11. package/dist/MultichainAssetsController/MultichainAssetsController.cjs.map +1 -1
  12. package/dist/MultichainAssetsController/MultichainAssetsController.d.cts +15 -1
  13. package/dist/MultichainAssetsController/MultichainAssetsController.d.cts.map +1 -1
  14. package/dist/MultichainAssetsController/MultichainAssetsController.d.mts +15 -1
  15. package/dist/MultichainAssetsController/MultichainAssetsController.d.mts.map +1 -1
  16. package/dist/MultichainAssetsController/MultichainAssetsController.mjs +42 -10
  17. package/dist/MultichainAssetsController/MultichainAssetsController.mjs.map +1 -1
  18. package/dist/balances.cjs +20 -12
  19. package/dist/balances.cjs.map +1 -1
  20. package/dist/balances.d.cts +7 -3
  21. package/dist/balances.d.cts.map +1 -1
  22. package/dist/balances.d.mts +7 -3
  23. package/dist/balances.d.mts.map +1 -1
  24. package/dist/balances.mjs +20 -12
  25. package/dist/balances.mjs.map +1 -1
  26. package/dist/selectors/token-selectors.cjs +5 -1
  27. package/dist/selectors/token-selectors.cjs.map +1 -1
  28. package/dist/selectors/token-selectors.d.cts +13 -6
  29. package/dist/selectors/token-selectors.d.cts.map +1 -1
  30. package/dist/selectors/token-selectors.d.mts +13 -6
  31. package/dist/selectors/token-selectors.d.mts.map +1 -1
  32. package/dist/selectors/token-selectors.mjs +5 -1
  33. package/dist/selectors/token-selectors.mjs.map +1 -1
  34. package/dist/token-prices-service/abstract-token-prices-service.cjs.map +1 -1
  35. package/dist/token-prices-service/abstract-token-prices-service.d.cts +30 -0
  36. package/dist/token-prices-service/abstract-token-prices-service.d.cts.map +1 -1
  37. package/dist/token-prices-service/abstract-token-prices-service.d.mts +30 -0
  38. package/dist/token-prices-service/abstract-token-prices-service.d.mts.map +1 -1
  39. package/dist/token-prices-service/abstract-token-prices-service.mjs.map +1 -1
  40. package/dist/token-prices-service/codefi-v2.cjs +75 -0
  41. package/dist/token-prices-service/codefi-v2.cjs.map +1 -1
  42. package/dist/token-prices-service/codefi-v2.d.cts +15 -1
  43. package/dist/token-prices-service/codefi-v2.d.cts.map +1 -1
  44. package/dist/token-prices-service/codefi-v2.d.mts +15 -1
  45. package/dist/token-prices-service/codefi-v2.d.mts.map +1 -1
  46. package/dist/token-prices-service/codefi-v2.mjs +75 -0
  47. package/dist/token-prices-service/codefi-v2.mjs.map +1 -1
  48. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [85.0.0]
11
+
12
+ ### Added
13
+
14
+ - **BREAKING:** Added constructor argument `tokenPricesService` in `currencyRateController` ([#6863](https://github.com/MetaMask/core/pull/6863))
15
+ - Added `fetchExchangeRates` function to fetch exchange rates from price-api ([#6863](https://github.com/MetaMask/core/pull/6863))
16
+ - Added `ignoreAssets` to allow ignoring assets for non-EVM chains ([#6981](https://github.com/MetaMask/core/pull/6981))
17
+
18
+ ### Changed
19
+
20
+ - Bump `@metamask/controller-utils` from `^11.14.1` to `^11.15.0` ([#7003](https://github.com/MetaMask/core/pull/7003))
21
+ - `CurrencyRateController` now fetches exchange rates from price-api and fallback to cryptoCompare ([#6863](https://github.com/MetaMask/core/pull/6863))
22
+
10
23
  ## [84.0.0]
11
24
 
12
25
  ### Added
@@ -2190,7 +2203,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2190
2203
 
2191
2204
  - Use Ethers for AssetsContractController ([#845](https://github.com/MetaMask/core/pull/845))
2192
2205
 
2193
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/assets-controllers@84.0.0...HEAD
2206
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/assets-controllers@85.0.0...HEAD
2207
+ [85.0.0]: https://github.com/MetaMask/core/compare/@metamask/assets-controllers@84.0.0...@metamask/assets-controllers@85.0.0
2194
2208
  [84.0.0]: https://github.com/MetaMask/core/compare/@metamask/assets-controllers@83.1.0...@metamask/assets-controllers@84.0.0
2195
2209
  [83.1.0]: https://github.com/MetaMask/core/compare/@metamask/assets-controllers@83.0.0...@metamask/assets-controllers@83.1.0
2196
2210
  [83.0.0]: https://github.com/MetaMask/core/compare/@metamask/assets-controllers@82.0.0...@metamask/assets-controllers@83.0.0
@@ -1,4 +1,16 @@
1
1
  "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var _CurrencyRateController_instances, _CurrencyRateController_tokenPricesService, _CurrencyRateController_fetchExchangeRatesWithFallback;
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
15
  exports.CurrencyRateController = void 0;
4
16
  const controller_utils_1 = require("@metamask/controller-utils");
@@ -45,19 +57,23 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
45
57
  * @param options.state - Initial state to set on this controller.
46
58
  * @param options.useExternalServices - Feature Switch for using external services (default: true)
47
59
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
60
+ * @param options.tokenPricesService - An object in charge of retrieving token prices
48
61
  */
49
- constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = crypto_compare_service_1.fetchMultiExchangeRate, }) {
62
+ constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = crypto_compare_service_1.fetchMultiExchangeRate, tokenPricesService, }) {
50
63
  super({
51
64
  name,
52
65
  metadata,
53
66
  messenger,
54
67
  state: { ...defaultState, ...state },
55
68
  });
69
+ _CurrencyRateController_instances.add(this);
56
70
  this.mutex = new async_mutex_1.Mutex();
71
+ _CurrencyRateController_tokenPricesService.set(this, void 0);
57
72
  this.includeUsdRate = includeUsdRate;
58
73
  this.useExternalServices = useExternalServices;
59
74
  this.setIntervalLength(interval);
60
75
  this.fetchMultiExchangeRate = fetchMultiExchangeRate;
76
+ __classPrivateFieldSet(this, _CurrencyRateController_tokenPricesService, tokenPricesService, "f");
61
77
  }
62
78
  /**
63
79
  * Sets a currency to track.
@@ -93,7 +109,6 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
93
109
  }
94
110
  const releaseLock = await this.mutex.acquire();
95
111
  try {
96
- const { currentCurrency } = this.state;
97
112
  // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.
98
113
  // Map each native currency to the symbol we want to fetch for it.
99
114
  const testnetSymbols = Object.values(controller_utils_1.TESTNET_TICKER_SYMBOLS);
@@ -106,16 +121,7 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
106
121
  : nativeCurrency;
107
122
  return acc;
108
123
  }, {});
109
- const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(currentCurrency, [...new Set(Object.values(nativeCurrenciesToFetch))], this.includeUsdRate);
110
- const rates = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
111
- const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];
112
- acc[nativeCurrency] = {
113
- conversionDate: rate !== undefined ? Date.now() / 1000 : null,
114
- conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,
115
- usdConversionRate: rate?.usd ?? null,
116
- };
117
- return acc;
118
- }, {});
124
+ const rates = await __classPrivateFieldGet(this, _CurrencyRateController_instances, "m", _CurrencyRateController_fetchExchangeRatesWithFallback).call(this, nativeCurrenciesToFetch);
119
125
  this.update((state) => {
120
126
  state.currencyRates = {
121
127
  ...state.currencyRates,
@@ -151,5 +157,52 @@ class CurrencyRateController extends (0, polling_controller_1.StaticIntervalPoll
151
157
  }
152
158
  }
153
159
  exports.CurrencyRateController = CurrencyRateController;
160
+ _CurrencyRateController_tokenPricesService = new WeakMap(), _CurrencyRateController_instances = new WeakSet(), _CurrencyRateController_fetchExchangeRatesWithFallback = async function _CurrencyRateController_fetchExchangeRatesWithFallback(nativeCurrenciesToFetch) {
161
+ const { currentCurrency } = this.state;
162
+ try {
163
+ const priceApiExchangeRatesResponse = await __classPrivateFieldGet(this, _CurrencyRateController_tokenPricesService, "f").fetchExchangeRates({
164
+ baseCurrency: currentCurrency,
165
+ includeUsdRate: this.includeUsdRate,
166
+ cryptocurrencies: [
167
+ ...new Set(Object.values(nativeCurrenciesToFetch)),
168
+ ],
169
+ });
170
+ const ratesPriceApi = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
171
+ const rate = priceApiExchangeRatesResponse[fetchedCurrency.toLowerCase()];
172
+ acc[nativeCurrency] = {
173
+ conversionDate: rate !== undefined ? Date.now() / 1000 : null,
174
+ conversionRate: rate?.value
175
+ ? Number((1 / rate?.value).toFixed(2))
176
+ : null,
177
+ usdConversionRate: rate?.usd
178
+ ? Number((1 / rate?.usd).toFixed(2))
179
+ : null,
180
+ };
181
+ return acc;
182
+ }, {});
183
+ return ratesPriceApi;
184
+ }
185
+ catch (error) {
186
+ console.error('Failed to fetch exchange rates.', error);
187
+ }
188
+ // fallback to crypto compare
189
+ try {
190
+ const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(currentCurrency, [...new Set(Object.values(nativeCurrenciesToFetch))], this.includeUsdRate);
191
+ const rates = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
192
+ const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];
193
+ acc[nativeCurrency] = {
194
+ conversionDate: rate !== undefined ? Date.now() / 1000 : null,
195
+ conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,
196
+ usdConversionRate: rate?.usd ?? null,
197
+ };
198
+ return acc;
199
+ }, {});
200
+ return rates;
201
+ }
202
+ catch (error) {
203
+ console.error('Failed to fetch exchange rates.', error);
204
+ throw error;
205
+ }
206
+ };
154
207
  exports.default = CurrencyRateController;
155
208
  //# sourceMappingURL=CurrencyRateController.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.cjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;AAKA,iEAGoC;AAGpC,qEAA+E;AAC/E,6CAAoC;AAEpC,+EAAmG;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAwBtC,MAAM,QAAQ,GAAqC;IACjD,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE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GAAG,CAAC,cAAc,CAAC,GAAG;oBACpB,cAAc,EAAE,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI;oBAC7D,cAAc,EAAE,IAAI,EAAE,CAAC,eAAe,CAAC,WAAW,EAAE,CAAC,IAAI,IAAI;oBAC7D,iBAAiB,EAAE,IAAI,EAAE,GAAG,IAAI,IAAI;iBACrC,CAAC;gBACF,OAAO,GAAG,CAAC;YACb,CAAC,EACD,EAAwC,CACzC,CAAC;YAEF,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;gBACpB,KAAK,CAAC,aAAa,GAAG;oBACpB,GAAG,KAAK,CAAC,aAAa;oBACtB,GAAG,KAAK;iBACT,CAAC;YACJ,CAAC,CAAC,CAAC;SACJ;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;YACxD,MAAM,KAAK,CAAC;SACb;gBAAS;YACR,WAAW,EAAE,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACM,OAAO;QACd,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,gBAAgB,GACS;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAClD,CAAC;CACF;AAjKD,wDAiKC;AAED,kBAAe,sBAAsB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\nexport type CurrencyRateMessenger = Messenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents\n>;\n\nconst metadata: StateMetadata<CurrencyRateState> = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.useExternalServices - Feature Switch for using external services (default: true)\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
1
+ {"version":3,"file":"CurrencyRateController.cjs","sourceRoot":"","sources":["../src/C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,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI;gBAC7D,cAAc,EAAE,IAAI,EAAE,CAAC,eAAe,CAAC,WAAW,EAAE,CAAC,IAAI,IAAI;gBAC7D,iBAAiB,EAAE,IAAI,EAAE,GAAG,IAAI,IAAI;aACrC,CAAC;YACF,OAAO,GAAG,CAAC;QACb,CAAC,EACD,EAAwC,CACzC,CAAC;QAEF,OAAO,KAAK,CAAC;KACd;IAAC,OAAO,KAAK,EAAE;QACd,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AA0EH,kBAAe,sBAAsB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\n\n/**\n * currencyRates - Object keyed by native currency\n *\n * currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n *\n * currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n *\n * currentCurrency - Currently-active ISO 4217 currency code\n *\n * usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\nexport type CurrencyRateMessenger = Messenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents\n>;\n\nconst metadata: StateMetadata<CurrencyRateState> = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\n\n readonly #tokenPricesService: AbstractTokenPricesService;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.useExternalServices - Feature Switch for using external services (default: true)\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n * @param options.tokenPricesService - An object in charge of retrieving token prices\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n tokenPricesService,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n tokenPricesService: AbstractTokenPricesService;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#tokenPricesService = tokenPricesService;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateExchangeRate(nativeCurrencies);\n }\n\n async #fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch: Record<string, string>,\n ): Promise<CurrencyRateState['currencyRates']> {\n const { currentCurrency } = this.state;\n\n try {\n const priceApiExchangeRatesResponse =\n await this.#tokenPricesService.fetchExchangeRates({\n baseCurrency: currentCurrency,\n includeUsdRate: this.includeUsdRate,\n cryptocurrencies: [\n ...new Set(Object.values(nativeCurrenciesToFetch)),\n ],\n });\n\n const ratesPriceApi = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate =\n priceApiExchangeRatesResponse[fetchedCurrency.toLowerCase()];\n\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.value\n ? Number((1 / rate?.value).toFixed(2))\n : null,\n usdConversionRate: rate?.usd\n ? Number((1 / rate?.usd).toFixed(2))\n : null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n return ratesPriceApi;\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n }\n\n // fallback to crypto compare\n\n try {\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n return rates;\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n }\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const rates = await this.#fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch,\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
@@ -2,13 +2,17 @@ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@meta
2
2
  import type { Messenger } from "@metamask/messenger";
3
3
  import type { NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
4
4
  import { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from "./crypto-compare-service/index.cjs";
5
+ import type { AbstractTokenPricesService } from "./token-prices-service/abstract-token-prices-service.cjs";
5
6
  /**
6
- * @type CurrencyRateState
7
- * @property currencyRates - Object keyed by native currency
8
- * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
9
- * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency
10
- * @property currentCurrency - Currently-active ISO 4217 currency code
11
- * @property usdConversionRate - Conversion rate from usd to the current currency
7
+ * currencyRates - Object keyed by native currency
8
+ *
9
+ * currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
10
+ *
11
+ * currencyRates.conversionRate - Conversion rate from current base asset to the current currency
12
+ *
13
+ * currentCurrency - Currently-active ISO 4217 currency code
14
+ *
15
+ * usdConversionRate - Conversion rate from usd to the current currency
12
16
  */
13
17
  export type CurrencyRateState = {
14
18
  currentCurrency: string;
@@ -49,6 +53,7 @@ declare const CurrencyRateController_base: (abstract new (...args: any[]) => {
49
53
  * asset to the user's preferred currency.
50
54
  */
51
55
  export declare class CurrencyRateController extends CurrencyRateController_base<typeof name, CurrencyRateState, CurrencyRateMessenger> {
56
+ #private;
52
57
  private readonly mutex;
53
58
  private readonly fetchMultiExchangeRate;
54
59
  private readonly includeUsdRate;
@@ -63,14 +68,16 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
63
68
  * @param options.state - Initial state to set on this controller.
64
69
  * @param options.useExternalServices - Feature Switch for using external services (default: true)
65
70
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
71
+ * @param options.tokenPricesService - An object in charge of retrieving token prices
66
72
  */
67
- constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, }: {
73
+ constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, tokenPricesService, }: {
68
74
  includeUsdRate?: boolean;
69
75
  interval?: number;
70
76
  messenger: CurrencyRateMessenger;
71
77
  state?: Partial<CurrencyRateState>;
72
78
  useExternalServices?: () => boolean;
73
79
  fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;
80
+ tokenPricesService: AbstractTokenPricesService;
74
81
  });
75
82
  /**
76
83
  * Sets a currency to track.
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.d.cts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,2CAA2C,EAAE,qCAAqC;AAIhG,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAEnG;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CACnB,MAAM,EACN;QACE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAA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;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
@@ -2,13 +2,17 @@ import type { ControllerGetStateAction, ControllerStateChangeEvent } from "@meta
2
2
  import type { Messenger } from "@metamask/messenger";
3
3
  import type { NetworkControllerGetNetworkClientByIdAction } from "@metamask/network-controller";
4
4
  import { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from "./crypto-compare-service/index.mjs";
5
+ import type { AbstractTokenPricesService } from "./token-prices-service/abstract-token-prices-service.mjs";
5
6
  /**
6
- * @type CurrencyRateState
7
- * @property currencyRates - Object keyed by native currency
8
- * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
9
- * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency
10
- * @property currentCurrency - Currently-active ISO 4217 currency code
11
- * @property usdConversionRate - Conversion rate from usd to the current currency
7
+ * currencyRates - Object keyed by native currency
8
+ *
9
+ * currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
10
+ *
11
+ * currencyRates.conversionRate - Conversion rate from current base asset to the current currency
12
+ *
13
+ * currentCurrency - Currently-active ISO 4217 currency code
14
+ *
15
+ * usdConversionRate - Conversion rate from usd to the current currency
12
16
  */
13
17
  export type CurrencyRateState = {
14
18
  currentCurrency: string;
@@ -49,6 +53,7 @@ declare const CurrencyRateController_base: (abstract new (...args: any[]) => {
49
53
  * asset to the user's preferred currency.
50
54
  */
51
55
  export declare class CurrencyRateController extends CurrencyRateController_base<typeof name, CurrencyRateState, CurrencyRateMessenger> {
56
+ #private;
52
57
  private readonly mutex;
53
58
  private readonly fetchMultiExchangeRate;
54
59
  private readonly includeUsdRate;
@@ -63,14 +68,16 @@ export declare class CurrencyRateController extends CurrencyRateController_base<
63
68
  * @param options.state - Initial state to set on this controller.
64
69
  * @param options.useExternalServices - Feature Switch for using external services (default: true)
65
70
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
71
+ * @param options.tokenPricesService - An object in charge of retrieving token prices
66
72
  */
67
- constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, }: {
73
+ constructor({ includeUsdRate, interval, useExternalServices, messenger, state, fetchMultiExchangeRate, tokenPricesService, }: {
68
74
  includeUsdRate?: boolean;
69
75
  interval?: number;
70
76
  messenger: CurrencyRateMessenger;
71
77
  state?: Partial<CurrencyRateState>;
72
78
  useExternalServices?: () => boolean;
73
79
  fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;
80
+ tokenPricesService: AbstractTokenPricesService;
74
81
  });
75
82
  /**
76
83
  * Sets a currency to track.
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.d.mts","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,wBAAwB,EACxB,0BAA0B,EAE3B,kCAAkC;AAKnC,OAAO,KAAK,EAAE,SAAS,EAAE,4BAA4B;AACrD,OAAO,KAAK,EAAE,2CAA2C,EAAE,qCAAqC;AAIhG,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAEnG;;;;;;;GAOG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,eAAe,EAAE,MAAM,CAAC;IACxB,aAAa,EAAE,MAAM,CACnB,MAAM,EACN;QACE,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;QAC9B,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;KAClC,CACF,CAAC;CACH,CAAC;AAEF,QAAA,MAAM,IAAI,2BAA2B,CAAC;AAEtC,MAAM,MAAM,uBAAuB,GAAG,0BAA0B,CAC9D,OAAO,IAAI,EACX,iBAAiB,CAClB,CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG,uBAAuB,CAAC;AAEnE,MAAM,MAAM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ACxE,KAAK,wBAAwB,GAAG;IAC9B,gBAAgB,EAAE,MAAM,EAAE,CAAC;CAC5B,CAAC;;;;;;;;;;;;;;;;AAEF;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,4BAC1C,OAAO,IAAI,EACX,iBAAiB,EACjB,qBAAqB,CACtB;;IACC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAe;IAErC,OAAO,CAAC,QAAQ,CAAC,sBAAsB,CAAC;IAExC,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAC;IAEhC,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAgB;IAIpD;;;;;;;;;;;OAWG;gBACS,EACV,cAAsB,EACtB,QAAiB,EACjB,mBAAgC,EAChC,SAAS,EACT,KAAK,EACL,sBAAsD,EACtD,kBAAkB,GACnB,EAAE;QACD,cAAc,CAAC,EAAE,OAAO,CAAC;QACzB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,EAAE,qBAAqB,CAAC;QACjC,KAAK,CAAC,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;QACnC,mBAAmB,CAAC,EAAE,MAAM,OAAO,CAAC;QACpC,sBAAsB,CAAC,EAAE,OAAO,6BAA6B,CAAC;QAC9D,kBAAkB,EAAE,0BAA0B,CAAC;KAChD;IAcD;;;;OAIG;IACG,kBAAkB,CAAC,eAAe,EAAE,MAAM;IAqFhD;;;;OAIG;IACG,kBAAkB,CACtB,gBAAgB,EAAE,CAAC,MAAM,GAAG,SAAS,CAAC,EAAE,GACvC,OAAO,CAAC,IAAI,CAAC;IA0ChB;;;;OAIG;IACM,OAAO;IAKhB;;;;;OAKG;IACG,YAAY,CAAC,EACjB,gBAAgB,GACjB,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC;CAG5C;AAED,eAAe,sBAAsB,CAAC"}
@@ -1,3 +1,15 @@
1
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
+ if (kind === "m") throw new TypeError("Private method is not writable");
3
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
+ };
7
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
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
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
+ };
12
+ var _CurrencyRateController_instances, _CurrencyRateController_tokenPricesService, _CurrencyRateController_fetchExchangeRatesWithFallback;
1
13
  import { TESTNET_TICKER_SYMBOLS, FALL_BACK_VS_CURRENCY } from "@metamask/controller-utils";
2
14
  import { StaticIntervalPollingController } from "@metamask/polling-controller";
3
15
  import { Mutex } from "async-mutex";
@@ -42,19 +54,23 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
42
54
  * @param options.state - Initial state to set on this controller.
43
55
  * @param options.useExternalServices - Feature Switch for using external services (default: true)
44
56
  * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.
57
+ * @param options.tokenPricesService - An object in charge of retrieving token prices
45
58
  */
46
- constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = defaultFetchMultiExchangeRate, }) {
59
+ constructor({ includeUsdRate = false, interval = 180000, useExternalServices = () => true, messenger, state, fetchMultiExchangeRate = defaultFetchMultiExchangeRate, tokenPricesService, }) {
47
60
  super({
48
61
  name,
49
62
  metadata,
50
63
  messenger,
51
64
  state: { ...defaultState, ...state },
52
65
  });
66
+ _CurrencyRateController_instances.add(this);
53
67
  this.mutex = new Mutex();
68
+ _CurrencyRateController_tokenPricesService.set(this, void 0);
54
69
  this.includeUsdRate = includeUsdRate;
55
70
  this.useExternalServices = useExternalServices;
56
71
  this.setIntervalLength(interval);
57
72
  this.fetchMultiExchangeRate = fetchMultiExchangeRate;
73
+ __classPrivateFieldSet(this, _CurrencyRateController_tokenPricesService, tokenPricesService, "f");
58
74
  }
59
75
  /**
60
76
  * Sets a currency to track.
@@ -90,7 +106,6 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
90
106
  }
91
107
  const releaseLock = await this.mutex.acquire();
92
108
  try {
93
- const { currentCurrency } = this.state;
94
109
  // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.
95
110
  // Map each native currency to the symbol we want to fetch for it.
96
111
  const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);
@@ -103,16 +118,7 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
103
118
  : nativeCurrency;
104
119
  return acc;
105
120
  }, {});
106
- const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(currentCurrency, [...new Set(Object.values(nativeCurrenciesToFetch))], this.includeUsdRate);
107
- const rates = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
108
- const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];
109
- acc[nativeCurrency] = {
110
- conversionDate: rate !== undefined ? Date.now() / 1000 : null,
111
- conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,
112
- usdConversionRate: rate?.usd ?? null,
113
- };
114
- return acc;
115
- }, {});
121
+ const rates = await __classPrivateFieldGet(this, _CurrencyRateController_instances, "m", _CurrencyRateController_fetchExchangeRatesWithFallback).call(this, nativeCurrenciesToFetch);
116
122
  this.update((state) => {
117
123
  state.currencyRates = {
118
124
  ...state.currencyRates,
@@ -147,5 +153,52 @@ export class CurrencyRateController extends StaticIntervalPollingController() {
147
153
  await this.updateExchangeRate(nativeCurrencies);
148
154
  }
149
155
  }
156
+ _CurrencyRateController_tokenPricesService = new WeakMap(), _CurrencyRateController_instances = new WeakSet(), _CurrencyRateController_fetchExchangeRatesWithFallback = async function _CurrencyRateController_fetchExchangeRatesWithFallback(nativeCurrenciesToFetch) {
157
+ const { currentCurrency } = this.state;
158
+ try {
159
+ const priceApiExchangeRatesResponse = await __classPrivateFieldGet(this, _CurrencyRateController_tokenPricesService, "f").fetchExchangeRates({
160
+ baseCurrency: currentCurrency,
161
+ includeUsdRate: this.includeUsdRate,
162
+ cryptocurrencies: [
163
+ ...new Set(Object.values(nativeCurrenciesToFetch)),
164
+ ],
165
+ });
166
+ const ratesPriceApi = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
167
+ const rate = priceApiExchangeRatesResponse[fetchedCurrency.toLowerCase()];
168
+ acc[nativeCurrency] = {
169
+ conversionDate: rate !== undefined ? Date.now() / 1000 : null,
170
+ conversionRate: rate?.value
171
+ ? Number((1 / rate?.value).toFixed(2))
172
+ : null,
173
+ usdConversionRate: rate?.usd
174
+ ? Number((1 / rate?.usd).toFixed(2))
175
+ : null,
176
+ };
177
+ return acc;
178
+ }, {});
179
+ return ratesPriceApi;
180
+ }
181
+ catch (error) {
182
+ console.error('Failed to fetch exchange rates.', error);
183
+ }
184
+ // fallback to crypto compare
185
+ try {
186
+ const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(currentCurrency, [...new Set(Object.values(nativeCurrenciesToFetch))], this.includeUsdRate);
187
+ const rates = Object.entries(nativeCurrenciesToFetch).reduce((acc, [nativeCurrency, fetchedCurrency]) => {
188
+ const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];
189
+ acc[nativeCurrency] = {
190
+ conversionDate: rate !== undefined ? Date.now() / 1000 : null,
191
+ conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,
192
+ usdConversionRate: rate?.usd ?? null,
193
+ };
194
+ return acc;
195
+ }, {});
196
+ return rates;
197
+ }
198
+ catch (error) {
199
+ console.error('Failed to fetch exchange rates.', error);
200
+ throw error;
201
+ }
202
+ };
150
203
  export default CurrencyRateController;
151
204
  //# sourceMappingURL=CurrencyRateController.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,mCAAmC;AAGpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AAsBnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAwBtC,MAAM,QAAQ,GAAqC;IACjD,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,EAAE;QACb,GAAG,EAAE;YACH,cAAc,EAAE,CAAC;YACjB,cAAc,EAAE,CAAC;YACjB,iBAAiB,EAAE,IAAI;SACxB;KACF;CACF,CAAC;AAOF;;;GAGG;AACH,MAAM,OAAO,sBAAuB,SAAQ,+BAA+B,EAI1E;IASC;;;;;;;;;;OAUG;IACH,YAAY,EACV,cAAc,GAAG,KAAK,EACtB,QAAQ,GAAG,MAAM,EACjB,mBAAmB,GAAG,GAAG,EAAE,CAAC,IAAI,EAChC,SAAS,EACT,KAAK,EACL,sBAAsB,GAAG,6BAA6B,GAQvD;QACC,KAAK,CAAC;YACJ,IAAI;YACJ,QAAQ;YACR,SAAS;YACT,KAAK,EAAE,EAAE,GAAG,YAAY,EAAE,GAAG,KAAK,EAAE;SACrC,CAAC,CAAC;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AAC,CAAC;YACxD,MAAM,KAAK,CAAC;SACb;gBAAS;YACR,WAAW,EAAE,CAAC;SACf;IACH,CAAC;IAED;;;;OAIG;IACM,OAAO;QACd,KAAK,CAAC,OAAO,EAAE,CAAC;QAChB,IAAI,CAAC,cAAc,EAAE,CAAC;IACxB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,YAAY,CAAC,EACjB,gBAAgB,GACS;QACzB,MAAM,IAAI,CAAC,kBAAkB,CAAC,gBAAgB,CAAC,CAAC;IAClD,CAAC;CACF;AAED,eAAe,sBAAsB,CAAC","sourcesContent":["import type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n StateMetadata,\n} from '@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\n\n/**\n * @type CurrencyRateState\n * @property currencyRates - Object keyed by native currency\n * @property currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n * @property currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n * @property currentCurrency - Currently-active ISO 4217 currency code\n * @property usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\nexport type CurrencyRateMessenger = Messenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents\n>;\n\nconst metadata: StateMetadata<CurrencyRateState> = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.useExternalServices - Feature Switch for using external services (default: true)\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateExchangeRate(nativeCurrencies);\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n const { currentCurrency } = this.state;\n\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}
1
+ {"version":3,"file":"CurrencyRateController.mjs","sourceRoot":"","sources":["../src/CurrencyRateController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAKA,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACtB,mCAAmC;AAGpC,OAAO,EAAE,+BAA+B,EAAE,qCAAqC;AAC/E,OAAO,EAAE,KAAK,EAAE,oBAAoB;AAEpC,OAAO,EAAE,sBAAsB,IAAI,6BAA6B,EAAE,2CAAiC;AA0BnG,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAwBtC,MAAM,QAAQ,GAAqC;IACjD,eAAe,EAAE;QACf,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;IACD,aAAa,EAAE;QACb,kBAAkB,EAAE,IAAI;QACxB,OAAO,EAAE,IAAI;QACb,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,IAAI;KACf;CACF,CAAC;AAEF,MAAM,YAAY,GAAG;IACnB,eAAe,EAAE,KAAK;IACtB,aAAa,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'@metamask/base-controller';\nimport {\n TESTNET_TICKER_SYMBOLS,\n FALL_BACK_VS_CURRENCY,\n} from '@metamask/controller-utils';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport { Mutex } from 'async-mutex';\n\nimport { fetchMultiExchangeRate as defaultFetchMultiExchangeRate } from './crypto-compare-service';\nimport type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';\n\n/**\n * currencyRates - Object keyed by native currency\n *\n * currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch\n *\n * currencyRates.conversionRate - Conversion rate from current base asset to the current currency\n *\n * currentCurrency - Currently-active ISO 4217 currency code\n *\n * usdConversionRate - Conversion rate from usd to the current currency\n */\nexport type CurrencyRateState = {\n currentCurrency: string;\n currencyRates: Record<\n string,\n {\n conversionDate: number | null;\n conversionRate: number | null;\n usdConversionRate: number | null;\n }\n >;\n};\n\nconst name = 'CurrencyRateController';\n\nexport type CurrencyRateStateChange = ControllerStateChangeEvent<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerEvents = CurrencyRateStateChange;\n\nexport type GetCurrencyRateState = ControllerGetStateAction<\n typeof name,\n CurrencyRateState\n>;\n\nexport type CurrencyRateControllerActions = GetCurrencyRateState;\n\ntype AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\nexport type CurrencyRateMessenger = Messenger<\n typeof name,\n CurrencyRateControllerActions | AllowedActions,\n CurrencyRateControllerEvents\n>;\n\nconst metadata: StateMetadata<CurrencyRateState> = {\n currentCurrency: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n currencyRates: {\n includeInStateLogs: true,\n persist: true,\n includeInDebugSnapshot: true,\n usedInUi: true,\n },\n};\n\nconst defaultState = {\n currentCurrency: 'usd',\n currencyRates: {\n ETH: {\n conversionDate: 0,\n conversionRate: 0,\n usdConversionRate: null,\n },\n },\n};\n\n/** The input to start polling for the {@link CurrencyRateController} */\ntype CurrencyRatePollingInput = {\n nativeCurrencies: string[];\n};\n\n/**\n * Controller that passively polls on a set interval for an exchange rate from the current network\n * asset to the user's preferred currency.\n */\nexport class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<\n typeof name,\n CurrencyRateState,\n CurrencyRateMessenger\n> {\n private readonly mutex = new Mutex();\n\n private readonly fetchMultiExchangeRate;\n\n private readonly includeUsdRate;\n\n private readonly useExternalServices: () => boolean;\n\n readonly #tokenPricesService: AbstractTokenPricesService;\n\n /**\n * Creates a CurrencyRateController instance.\n *\n * @param options - Constructor options.\n * @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.\n * @param options.interval - The polling interval, in milliseconds.\n * @param options.messenger - A reference to the messenger.\n * @param options.state - Initial state to set on this controller.\n * @param options.useExternalServices - Feature Switch for using external services (default: true)\n * @param options.fetchMultiExchangeRate - Fetches the exchange rate from an external API. This option is primarily meant for use in unit tests.\n * @param options.tokenPricesService - An object in charge of retrieving token prices\n */\n constructor({\n includeUsdRate = false,\n interval = 180000,\n useExternalServices = () => true,\n messenger,\n state,\n fetchMultiExchangeRate = defaultFetchMultiExchangeRate,\n tokenPricesService,\n }: {\n includeUsdRate?: boolean;\n interval?: number;\n messenger: CurrencyRateMessenger;\n state?: Partial<CurrencyRateState>;\n useExternalServices?: () => boolean;\n fetchMultiExchangeRate?: typeof defaultFetchMultiExchangeRate;\n tokenPricesService: AbstractTokenPricesService;\n }) {\n super({\n name,\n metadata,\n messenger,\n state: { ...defaultState, ...state },\n });\n this.includeUsdRate = includeUsdRate;\n this.useExternalServices = useExternalServices;\n this.setIntervalLength(interval);\n this.fetchMultiExchangeRate = fetchMultiExchangeRate;\n this.#tokenPricesService = tokenPricesService;\n }\n\n /**\n * Sets a currency to track.\n *\n * @param currentCurrency - ISO 4217 currency code.\n */\n async setCurrentCurrency(currentCurrency: string) {\n const releaseLock = await this.mutex.acquire();\n const nativeCurrencies = Object.keys(this.state.currencyRates);\n try {\n this.update(() => {\n return {\n ...defaultState,\n currentCurrency,\n };\n });\n } finally {\n releaseLock();\n }\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.updateExchangeRate(nativeCurrencies);\n }\n\n async #fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch: Record<string, string>,\n ): Promise<CurrencyRateState['currencyRates']> {\n const { currentCurrency } = this.state;\n\n try {\n const priceApiExchangeRatesResponse =\n await this.#tokenPricesService.fetchExchangeRates({\n baseCurrency: currentCurrency,\n includeUsdRate: this.includeUsdRate,\n cryptocurrencies: [\n ...new Set(Object.values(nativeCurrenciesToFetch)),\n ],\n });\n\n const ratesPriceApi = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate =\n priceApiExchangeRatesResponse[fetchedCurrency.toLowerCase()];\n\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.value\n ? Number((1 / rate?.value).toFixed(2))\n : null,\n usdConversionRate: rate?.usd\n ? Number((1 / rate?.usd).toFixed(2))\n : null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n return ratesPriceApi;\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n }\n\n // fallback to crypto compare\n\n try {\n const fetchExchangeRateResponse = await this.fetchMultiExchangeRate(\n currentCurrency,\n [...new Set(Object.values(nativeCurrenciesToFetch))],\n this.includeUsdRate,\n );\n\n const rates = Object.entries(nativeCurrenciesToFetch).reduce(\n (acc, [nativeCurrency, fetchedCurrency]) => {\n const rate = fetchExchangeRateResponse[fetchedCurrency.toLowerCase()];\n acc[nativeCurrency] = {\n conversionDate: rate !== undefined ? Date.now() / 1000 : null,\n conversionRate: rate?.[currentCurrency.toLowerCase()] ?? null,\n usdConversionRate: rate?.usd ?? null,\n };\n return acc;\n },\n {} as CurrencyRateState['currencyRates'],\n );\n\n return rates;\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n }\n }\n\n /**\n * Updates the exchange rate for the current currency and native currency pairs.\n *\n * @param nativeCurrencies - The native currency symbols to fetch exchange rates for.\n */\n async updateExchangeRate(\n nativeCurrencies: (string | undefined)[],\n ): Promise<void> {\n if (!this.useExternalServices()) {\n return;\n }\n\n const releaseLock = await this.mutex.acquire();\n try {\n // For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.\n // Map each native currency to the symbol we want to fetch for it.\n const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);\n const nativeCurrenciesToFetch = nativeCurrencies.reduce(\n (acc, nativeCurrency) => {\n if (!nativeCurrency) {\n return acc;\n }\n\n acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)\n ? FALL_BACK_VS_CURRENCY\n : nativeCurrency;\n return acc;\n },\n {} as Record<string, string>,\n );\n\n const rates = await this.#fetchExchangeRatesWithFallback(\n nativeCurrenciesToFetch,\n );\n\n this.update((state) => {\n state.currencyRates = {\n ...state.currencyRates,\n ...rates,\n };\n });\n } catch (error) {\n console.error('Failed to fetch exchange rates.', error);\n throw error;\n } finally {\n releaseLock();\n }\n }\n\n /**\n * Prepare to discard this controller.\n *\n * This stops any active polling.\n */\n override destroy() {\n super.destroy();\n this.stopAllPolling();\n }\n\n /**\n * Updates exchange rate for the current currency.\n *\n * @param input - The input for the poll.\n * @param input.nativeCurrencies - The native currency symbols to poll prices for.\n */\n async _executePoll({\n nativeCurrencies,\n }: CurrencyRatePollingInput): Promise<void> {\n await this.updateExchangeRate(nativeCurrencies);\n }\n}\n\nexport default CurrencyRateController;\n"]}