forked from MetaMask/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurrencyRateController.ts
More file actions
498 lines (446 loc) · 15.4 KB
/
CurrencyRateController.ts
File metadata and controls
498 lines (446 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import type {
ControllerGetStateAction,
ControllerStateChangeEvent,
StateMetadata,
} from '@metamask/base-controller';
import {
TESTNET_TICKER_SYMBOLS,
FALL_BACK_VS_CURRENCY,
} from '@metamask/controller-utils';
import type { Messenger } from '@metamask/messenger';
import type {
NetworkControllerGetNetworkClientByIdAction,
NetworkControllerGetStateAction,
NetworkConfiguration,
} from '@metamask/network-controller';
import { StaticIntervalPollingController } from '@metamask/polling-controller';
import type { Hex } from '@metamask/utils';
import { Mutex } from 'async-mutex';
import type { CurrencyRateControllerMethodActions } from './CurrencyRateController-method-action-types';
import type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';
import { getNativeTokenAddress } from './token-prices-service/codefi-v2';
/**
* currencyRates - Object keyed by native currency
*
* currencyRates.conversionDate - Timestamp of conversion rate expressed in ms since UNIX epoch
*
* currencyRates.conversionRate - Conversion rate from current base asset to the current currency
*
* currentCurrency - Currently-active ISO 4217 currency code
*
* usdConversionRate - Conversion rate from usd to the current currency
*/
export type CurrencyRateState = {
currentCurrency: string;
currencyRates: Record<
string,
{
conversionDate: number | null;
conversionRate: number | null;
usdConversionRate: number | null;
}
>;
};
const name = 'CurrencyRateController';
const MESSENGER_EXPOSED_METHODS = [
'setCurrentCurrency',
'updateExchangeRate',
] as const;
export type CurrencyRateStateChange = ControllerStateChangeEvent<
typeof name,
CurrencyRateState
>;
export type CurrencyRateControllerEvents = CurrencyRateStateChange;
export type CurrencyRateControllerGetStateAction = ControllerGetStateAction<
typeof name,
CurrencyRateState
>;
export type CurrencyRateControllerActions =
| CurrencyRateControllerGetStateAction
| CurrencyRateControllerMethodActions;
type AllowedActions =
| NetworkControllerGetNetworkClientByIdAction
| NetworkControllerGetStateAction;
export type CurrencyRateMessenger = Messenger<
typeof name,
CurrencyRateControllerActions | AllowedActions,
CurrencyRateControllerEvents
>;
const metadata: StateMetadata<CurrencyRateState> = {
currentCurrency: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: true,
},
currencyRates: {
includeInStateLogs: true,
persist: true,
includeInDebugSnapshot: true,
usedInUi: true,
},
};
const defaultState = {
currentCurrency: 'usd',
currencyRates: {
ETH: {
conversionDate: 0,
conversionRate: 0,
usdConversionRate: null,
},
},
};
/** The input to start polling for the {@link CurrencyRateController} */
type CurrencyRatePollingInput = {
nativeCurrencies: string[];
};
const boundedPrecisionNumber = (value: number, precision = 9): number =>
Number(value.toFixed(precision));
/**
* Controller that passively polls on a set interval for an exchange rate from the current network
* asset to the user's preferred currency.
*/
/** Result from attempting to fetch rates from an API */
type FetchRatesResult = {
/** Successfully fetched rates */
rates: CurrencyRateState['currencyRates'];
/** Currencies that failed and need fallback or null state */
failedCurrencies: Record<string, string>;
};
/**
* Controller that passively polls on a set interval for an exchange rate from the current network
* asset to the user's preferred currency.
*/
export class CurrencyRateController extends StaticIntervalPollingController<CurrencyRatePollingInput>()<
typeof name,
CurrencyRateState,
CurrencyRateMessenger
> {
readonly #mutex = new Mutex();
readonly #includeUsdRate: boolean;
readonly #useExternalServices: () => boolean;
readonly #tokenPricesService: AbstractTokenPricesService;
/**
* Creates a CurrencyRateController instance.
*
* @param options - Constructor options.
* @param options.includeUsdRate - Keep track of the USD rate in addition to the current currency rate.
* @param options.interval - The polling interval, in milliseconds.
* @param options.messenger - A reference to the messenger.
* @param options.state - Initial state to set on this controller.
* @param options.useExternalServices - Feature Switch for using external services (default: true)
* @param options.tokenPricesService - An object in charge of retrieving token prices
*/
constructor({
includeUsdRate = false,
interval = 180000,
useExternalServices = () => true,
messenger,
state,
tokenPricesService,
}: {
includeUsdRate?: boolean;
interval?: number;
messenger: CurrencyRateMessenger;
state?: Partial<CurrencyRateState>;
useExternalServices?: () => boolean;
tokenPricesService: AbstractTokenPricesService;
}) {
super({
name,
metadata,
messenger,
state: { ...defaultState, ...state },
});
this.#includeUsdRate = includeUsdRate;
this.#useExternalServices = useExternalServices;
this.setIntervalLength(interval);
this.#tokenPricesService = tokenPricesService;
this.messenger.registerMethodActionHandlers(
this,
MESSENGER_EXPOSED_METHODS,
);
}
/**
* Sets a currency to track.
*
* @param currentCurrency - ISO 4217 currency code.
*/
async setCurrentCurrency(currentCurrency: string): Promise<void> {
const releaseLock = await this.#mutex.acquire();
const nativeCurrencies = Object.keys(this.state.currencyRates);
try {
this.update(() => {
return {
...defaultState,
currentCurrency,
};
});
} finally {
releaseLock();
}
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.updateExchangeRate(nativeCurrencies);
}
/**
* Attempts to fetch exchange rates from the primary Price API.
*
* @param nativeCurrenciesToFetch - Map of native currency to the currency symbol to fetch.
* @param currentCurrency - The current fiat currency to get rates for.
* @returns Object containing successful rates and currencies that failed.
*/
async #fetchRatesFromPriceApi(
nativeCurrenciesToFetch: Record<string, string>,
currentCurrency: string,
): Promise<FetchRatesResult> {
const rates: CurrencyRateState['currencyRates'] = {};
let failedCurrencies: Record<string, string> = {};
try {
const response = await this.#tokenPricesService.fetchExchangeRates({
baseCurrency: currentCurrency,
includeUsdRate: this.#includeUsdRate,
cryptocurrencies: [...new Set(Object.values(nativeCurrenciesToFetch))],
});
Object.entries(nativeCurrenciesToFetch).forEach(
([nativeCurrency, fetchedCurrency]) => {
const rate = response[fetchedCurrency.toLowerCase()];
if (rate?.value) {
rates[nativeCurrency] = {
conversionDate: Date.now() / 1000,
conversionRate: boundedPrecisionNumber(1 / rate.value),
usdConversionRate: rate?.usd
? boundedPrecisionNumber(1 / rate.usd)
: null,
};
} else {
failedCurrencies[nativeCurrency] = fetchedCurrency;
}
},
);
} catch (error) {
console.error('Failed to fetch exchange rates.', error);
failedCurrencies = { ...nativeCurrenciesToFetch };
}
return { rates, failedCurrencies };
}
/**
* Fetches exchange rates from the token prices service as a fallback.
* This method is designed to never throw - all errors are handled internally
* and result in currencies being marked as failed.
*
* @param currenciesToFetch - Map of native currencies that need fallback fetching.
* @param currentCurrency - The current fiat currency to get rates for.
* @returns Object containing successful rates and currencies that failed.
*/
async #fetchRatesFromTokenPricesService(
currenciesToFetch: Record<string, string>,
currentCurrency: string,
): Promise<FetchRatesResult> {
try {
const rates: CurrencyRateState['currencyRates'] = {};
const failedCurrencies: Record<string, string> = {};
const networkControllerState = this.messenger.call(
'NetworkController:getState',
);
const networkConfigurations =
networkControllerState.networkConfigurationsByChainId;
// Build a map of nativeCurrency -> chainId for currencies to fetch
const currencyToChainIds = Object.entries(currenciesToFetch).reduce<
Record<string, { fetchedCurrency: string; chainId: Hex }>
>((acc, [nativeCurrency, fetchedCurrency]) => {
const matchingEntry = (
Object.entries(networkConfigurations) as [Hex, NetworkConfiguration][]
).find(
([, config]) =>
config.nativeCurrency.toUpperCase() ===
fetchedCurrency.toUpperCase(),
);
if (matchingEntry) {
acc[nativeCurrency] = { fetchedCurrency, chainId: matchingEntry[0] };
} else {
// No matching network configuration - mark as failed
failedCurrencies[nativeCurrency] = fetchedCurrency;
}
return acc;
}, {});
const currencyToChainIdsEntries = Object.entries(currencyToChainIds);
const ratesResults = await Promise.allSettled(
currencyToChainIdsEntries.map(async ([nativeCurrency, { chainId }]) => {
const nativeTokenAddress = getNativeTokenAddress(chainId);
const tokenPrices = await this.#tokenPricesService.fetchTokenPrices({
assets: [{ chainId, tokenAddress: nativeTokenAddress }],
currency: currentCurrency,
});
const tokenPrice = tokenPrices.find(
(item) =>
item.tokenAddress.toLowerCase() ===
nativeTokenAddress.toLowerCase(),
);
return {
nativeCurrency,
conversionDate: tokenPrice ? Date.now() / 1000 : null,
conversionRate: tokenPrice?.price
? boundedPrecisionNumber(tokenPrice.price)
: null,
usdConversionRate: null,
};
}),
);
ratesResults.forEach((result, index) => {
const [nativeCurrency, { fetchedCurrency, chainId }] =
currencyToChainIdsEntries[index];
if (result.status === 'fulfilled' && result.value.conversionRate) {
rates[nativeCurrency] = {
conversionDate: result.value.conversionDate,
conversionRate: result.value.conversionRate,
usdConversionRate: result.value.usdConversionRate,
};
} else {
if (result.status === 'rejected') {
console.error(
`Failed to fetch token price for ${nativeCurrency} on chain ${chainId}`,
result.reason,
);
}
failedCurrencies[nativeCurrency] = fetchedCurrency;
}
});
return { rates, failedCurrencies };
} catch (error) {
console.error(
'Failed to fetch exchange rates from token prices service.',
error,
);
// Return all currencies as failed
return { rates: {}, failedCurrencies: { ...currenciesToFetch } };
}
}
/**
* Creates null rate entries for currencies that couldn't be fetched.
*
* @param currencies - Array of currency symbols to create null entries for.
* @returns Null rate entries for all provided currencies.
*/
#createNullRatesForCurrencies(
currencies: string[],
): CurrencyRateState['currencyRates'] {
return currencies.reduce<CurrencyRateState['currencyRates']>(
(acc, nativeCurrency) => {
acc[nativeCurrency] = {
conversionDate: null,
conversionRate: null,
usdConversionRate: null,
};
return acc;
},
{},
);
}
/**
* Fetches exchange rates with fallback logic.
* First tries the Price API, then falls back to token prices service for any failed currencies.
*
* @param nativeCurrenciesToFetch - Map of native currency to the currency symbol to fetch.
* @returns Exchange rates for all requested currencies.
*/
async #fetchExchangeRatesWithFallback(
nativeCurrenciesToFetch: Record<string, string>,
): Promise<CurrencyRateState['currencyRates']> {
const { currentCurrency } = this.state;
// Step 1: Try the Price API exchange rates first
const {
rates: ratesPriceApi,
failedCurrencies: failedCurrenciesFromPriceApi,
} = await this.#fetchRatesFromPriceApi(
nativeCurrenciesToFetch,
currentCurrency,
);
// Step 2: If all currencies succeeded, return early
if (Object.keys(failedCurrenciesFromPriceApi).length === 0) {
return ratesPriceApi;
}
// Step 3: Fallback using token prices service for failed currencies
const {
rates: ratesFromFallback,
failedCurrencies: failedCurrenciesFromFallback,
} = await this.#fetchRatesFromTokenPricesService(
failedCurrenciesFromPriceApi,
currentCurrency,
);
// Step 4: Create null rates for currencies that failed both approaches
const nullRates = this.#createNullRatesForCurrencies(
Object.keys(failedCurrenciesFromFallback),
);
// Step 5: Merge all results - Price API rates take priority, then fallback, then null rates
return {
...nullRates,
...ratesFromFallback,
...ratesPriceApi,
};
}
/**
* Updates the exchange rate for the current currency and native currency pairs.
*
* @param nativeCurrencies - The native currency symbols to fetch exchange rates for.
*/
async updateExchangeRate(
nativeCurrencies: (string | undefined)[],
): Promise<void> {
if (!this.#useExternalServices()) {
return;
}
const releaseLock = await this.#mutex.acquire();
try {
// For preloaded testnets (Goerli, Sepolia) we want to fetch exchange rate for real ETH.
// Map each native currency to the symbol we want to fetch for it.
const testnetSymbols = Object.values(TESTNET_TICKER_SYMBOLS);
const nativeCurrenciesToFetch = nativeCurrencies.reduce<
Record<string, string>
>((acc, nativeCurrency) => {
if (!nativeCurrency) {
return acc;
}
acc[nativeCurrency] = testnetSymbols.includes(nativeCurrency)
? FALL_BACK_VS_CURRENCY
: nativeCurrency;
return acc;
}, {});
const rates = await this.#fetchExchangeRatesWithFallback(
nativeCurrenciesToFetch,
);
this.update((state) => {
state.currencyRates = {
...state.currencyRates,
...rates,
};
});
} catch (error) {
console.error('Failed to fetch exchange rates.', error);
throw error;
} finally {
releaseLock();
}
}
/**
* Prepare to discard this controller.
*
* This stops any active polling.
*/
override destroy(): void {
super.destroy();
this.stopAllPolling();
}
/**
* Updates exchange rate for the current currency.
*
* @param input - The input for the poll.
* @param input.nativeCurrencies - The native currency symbols to poll prices for.
*/
async _executePoll({
nativeCurrencies,
}: CurrencyRatePollingInput): Promise<void> {
await this.updateExchangeRate(nativeCurrencies);
}
}
export default CurrencyRateController;