-
-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathTokenRatesController.ts
More file actions
622 lines (557 loc) · 17.6 KB
/
TokenRatesController.ts
File metadata and controls
622 lines (557 loc) · 17.6 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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import type {
ControllerGetStateAction,
ControllerStateChangeEvent,
StateMetadata,
} from '@metamask/base-controller';
import { toChecksumHexAddress } from '@metamask/controller-utils';
import type { Messenger } from '@metamask/messenger';
import type {
NetworkControllerGetStateAction,
NetworkControllerStateChangeEvent,
} from '@metamask/network-controller';
import type { NetworkEnablementControllerGetStateAction } from '@metamask/network-enablement-controller';
import { StaticIntervalPollingController } from '@metamask/polling-controller';
import type { Hex } from '@metamask/utils';
import { isEqual } from 'lodash';
import { reduceInBatchesSerially, TOKEN_PRICES_BATCH_SIZE } from './assetsUtil';
import type { AbstractTokenPricesService } from './token-prices-service/abstract-token-prices-service';
import { getNativeTokenAddress } from './token-prices-service/codefi-v2';
import { TokenRwaData } from './token-service';
import type {
TokensControllerGetStateAction,
TokensControllerStateChangeEvent,
TokensControllerState,
} from './TokensController';
/**
* @type Token
*
* Token representation
*
* @property address - Hex address of the token contract
* @property decimals - Number of decimals the token uses
* @property symbol - Symbol of the token
* @property aggregators - An array containing the token's aggregators
* @property image - Image of the token, url or bit32 image
* @property hasBalanceError - 'true' if there is an error while updating the token balance
* @property isERC721 - 'true' if the token is a ERC721 token
* @property name - Name of the token
*/
export type Token = {
address: string;
decimals: number;
symbol: string;
aggregators?: string[];
image?: string;
hasBalanceError?: boolean;
isERC721?: boolean;
name?: string;
rwaData?: TokenRwaData;
};
const DEFAULT_INTERVAL = 180000;
export type ContractExchangeRates = {
[address: string]: number | undefined;
};
export type MarketDataDetails = {
tokenAddress: `0x${string}`;
currency: string;
allTimeHigh: number;
allTimeLow: number;
circulatingSupply: number;
dilutedMarketCap: number;
high1d: number;
low1d: number;
marketCap: number;
marketCapPercentChange1d: number;
price: number;
priceChange1d: number;
pricePercentChange1d: number;
pricePercentChange1h: number;
pricePercentChange1y: number;
pricePercentChange7d: number;
pricePercentChange14d: number;
pricePercentChange30d: number;
pricePercentChange200d: number;
totalVolume: number;
};
/**
* Represents a mapping of token contract addresses to their market data.
*/
export type ContractMarketData = Record<Hex, MarketDataDetails>;
type ChainIdAndNativeCurrency = {
chainId: Hex;
nativeCurrency: string;
};
/**
* The external actions available to the {@link TokenRatesController}.
*/
export type AllowedActions =
| TokensControllerGetStateAction
| NetworkControllerGetStateAction
| NetworkEnablementControllerGetStateAction;
/**
* The external events available to the {@link TokenRatesController}.
*/
export type AllowedEvents =
| TokensControllerStateChangeEvent
| NetworkControllerStateChangeEvent;
/**
* The name of the {@link TokenRatesController}.
*/
export const controllerName = 'TokenRatesController';
/**
* @type TokenRatesState
*
* Token rates controller state
*
* @property marketData - Market data for tokens, keyed by chain ID and then token contract address.
*/
export type TokenRatesControllerState = {
marketData: Record<Hex, Record<Hex, MarketDataDetails>>;
};
/**
* The action that can be performed to get the state of the {@link TokenRatesController}.
*/
export type TokenRatesControllerGetStateAction = ControllerGetStateAction<
typeof controllerName,
TokenRatesControllerState
>;
/**
* The actions that can be performed using the {@link TokenRatesController}.
*/
export type TokenRatesControllerActions = TokenRatesControllerGetStateAction;
/**
* The event that {@link TokenRatesController} can emit.
*/
export type TokenRatesControllerStateChangeEvent = ControllerStateChangeEvent<
typeof controllerName,
TokenRatesControllerState
>;
/**
* The events that {@link TokenRatesController} can emit.
*/
export type TokenRatesControllerEvents = TokenRatesControllerStateChangeEvent;
/**
* The messenger of the {@link TokenRatesController} for communication.
*/
export type TokenRatesControllerMessenger = Messenger<
typeof controllerName,
TokenRatesControllerActions | AllowedActions,
TokenRatesControllerEvents | AllowedEvents
>;
const tokenRatesControllerMetadata: StateMetadata<TokenRatesControllerState> = {
marketData: {
includeInStateLogs: false,
persist: true,
includeInDebugSnapshot: false,
usedInUi: true,
},
};
/**
* Get the default {@link TokenRatesController} state.
*
* @returns The default {@link TokenRatesController} state.
*/
export const getDefaultTokenRatesControllerState =
(): TokenRatesControllerState => {
return {
marketData: {},
};
};
/** The input to start polling for the {@link TokenRatesController} */
export type TokenRatesPollingInput = {
chainIds: Hex[];
};
/**
* Controller that passively polls on a set interval for token-to-fiat exchange rates
* for tokens stored in the TokensController
*/
export class TokenRatesController extends StaticIntervalPollingController<TokenRatesPollingInput>()<
typeof controllerName,
TokenRatesControllerState,
TokenRatesControllerMessenger
> {
readonly #tokenPricesService: AbstractTokenPricesService;
#disabled: boolean;
#allTokens: TokensControllerState['allTokens'];
#allDetectedTokens: TokensControllerState['allDetectedTokens'];
/**
* Creates a TokenRatesController instance.
*
* @param options - The controller options.
* @param options.interval - The polling interval in ms
* @param options.disabled - Boolean to track if network requests are blocked
* @param options.tokenPricesService - An object in charge of retrieving token price
* @param options.messenger - The messenger instance for communication
* @param options.state - Initial state to set on this controller
*/
constructor({
interval = DEFAULT_INTERVAL,
disabled = false,
tokenPricesService,
messenger,
state,
}: {
interval?: number;
disabled?: boolean;
tokenPricesService: AbstractTokenPricesService;
messenger: TokenRatesControllerMessenger;
state?: Partial<TokenRatesControllerState>;
}) {
super({
name: controllerName,
messenger,
state: { ...getDefaultTokenRatesControllerState(), ...state },
metadata: tokenRatesControllerMetadata,
});
this.setIntervalLength(interval);
this.#tokenPricesService = tokenPricesService;
this.#disabled = disabled;
const { allTokens, allDetectedTokens } = this.#getTokensControllerState();
this.#allTokens = allTokens;
this.#allDetectedTokens = allDetectedTokens;
// Set native asset identifiers from NetworkEnablementController for CAIP-19 native token lookups
this.#initNativeAssetIdentifiers();
this.#subscribeToTokensStateChange();
this.#subscribeToNetworkStateChange();
}
#subscribeToTokensStateChange() {
this.messenger.subscribe(
'TokensController:stateChange',
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
// eslint-disable-next-line @typescript-eslint/no-misused-promises
async ({ allTokens, allDetectedTokens }) => {
if (this.#disabled) {
return;
}
const { networkConfigurationsByChainId } = this.messenger.call(
'NetworkController:getState',
);
const chainIds = [
...new Set([
...Object.keys(allTokens),
...Object.keys(allDetectedTokens),
]),
] as Hex[];
const chainIdsToUpdate = chainIds.filter(
(chainId) =>
!isEqual(this.#allTokens[chainId], allTokens[chainId]) ||
!isEqual(
this.#allDetectedTokens[chainId],
allDetectedTokens[chainId],
),
);
this.#allTokens = allTokens;
this.#allDetectedTokens = allDetectedTokens;
const chainIdAndNativeCurrency = chainIdsToUpdate.reduce<
{ chainId: Hex; nativeCurrency: string }[]
>((acc, chainId) => {
const networkConfiguration = networkConfigurationsByChainId[chainId];
if (!networkConfiguration) {
console.error(
`TokenRatesController: No network configuration found for chainId ${chainId}`,
);
return acc;
}
acc.push({
chainId,
nativeCurrency: networkConfiguration.nativeCurrency,
});
return acc;
}, []);
await this.updateExchangeRates(chainIdAndNativeCurrency);
},
({ allTokens, allDetectedTokens }) => {
return { allTokens, allDetectedTokens };
},
);
}
#subscribeToNetworkStateChange() {
this.messenger.subscribe(
'NetworkController:stateChange',
(_state, patches) => {
// Remove state for deleted networks
for (const patch of patches) {
if (
patch.op === 'remove' &&
patch.path[0] === 'networkConfigurationsByChainId'
) {
const removedChainId = patch.path[1] as Hex;
this.update((state) => {
delete state.marketData[removedChainId];
});
}
}
},
);
}
/**
* Initialize the native asset identifiers from NetworkEnablementController.
* This provides CAIP-19 native asset IDs for the token prices service.
*/
#initNativeAssetIdentifiers(): void {
if (this.#tokenPricesService.setNativeAssetIdentifiers) {
const { nativeAssetIdentifiers } = this.messenger.call(
'NetworkEnablementController:getState',
);
this.#tokenPricesService.setNativeAssetIdentifiers(
nativeAssetIdentifiers,
);
}
}
/**
* Get the tokens for the given chain.
*
* @param chainId - The chain ID.
* @returns The list of tokens addresses for the current chain
*/
#getTokenAddresses(chainId: Hex): Hex[] {
const getTokens = (allTokens: Record<Hex, { address: string }[]>) =>
Object.values(allTokens ?? {}).flatMap((tokens) =>
tokens.map(({ address }) => toChecksumHexAddress(address) as Hex),
);
const tokenAddresses = getTokens(this.#allTokens[chainId]);
const detectedTokenAddresses = getTokens(this.#allDetectedTokens[chainId]);
return [
...new Set([
...tokenAddresses,
...detectedTokenAddresses,
getNativeTokenAddress(chainId),
]),
].sort();
}
/**
* Allows controller to make active and passive polling requests
*/
enable(): void {
this.#disabled = false;
}
/**
* Blocks controller from making network calls
*/
disable(): void {
this.#disabled = true;
}
#getTokensControllerState(): {
allTokens: TokensControllerState['allTokens'];
allDetectedTokens: TokensControllerState['allDetectedTokens'];
} {
const { allTokens, allDetectedTokens } = this.messenger.call(
'TokensController:getState',
);
return {
allTokens,
allDetectedTokens,
};
}
/**
* Updates exchange rates for all tokens.
*
* @param chainIdAndNativeCurrency - The chain ID and native currency.
*/
async updateExchangeRates(
chainIdAndNativeCurrency: ChainIdAndNativeCurrency[],
): Promise<void> {
if (this.#disabled) {
return;
}
const marketData: Record<Hex, Record<Hex, MarketDataDetails>> = {};
const assetsByNativeCurrency: Record<
string,
{
chainId: Hex;
tokenAddress: Hex;
}[]
> = {};
const unsupportedAssetsByNativeCurrency: Record<
string,
{
chainId: Hex;
tokenAddress: Hex;
}[]
> = {};
for (const { chainId, nativeCurrency } of chainIdAndNativeCurrency) {
if (this.#tokenPricesService.validateChainIdSupported(chainId)) {
for (const tokenAddress of this.#getTokenAddresses(chainId)) {
if (
this.#tokenPricesService.validateCurrencySupported(nativeCurrency)
) {
(assetsByNativeCurrency[nativeCurrency] ??= []).push({
chainId,
tokenAddress,
});
} else {
(unsupportedAssetsByNativeCurrency[nativeCurrency] ??= []).push({
chainId,
tokenAddress,
});
}
}
}
}
const promises = [
...Object.entries(assetsByNativeCurrency).map(
([nativeCurrency, assets]) =>
this.#fetchAndMapExchangeRatesForSupportedNativeCurrency(
assets,
nativeCurrency,
marketData,
),
),
...Object.entries(unsupportedAssetsByNativeCurrency).map(
([nativeCurrency, assets]) =>
this.#fetchAndMapExchangeRatesForUnsupportedNativeCurrency(
assets,
nativeCurrency,
marketData,
),
),
];
await Promise.allSettled(promises);
const chainIds = new Set(
Object.values(chainIdAndNativeCurrency).map((chain) => chain.chainId),
);
for (const chainId of chainIds) {
if (!marketData[chainId]) {
marketData[chainId] = {};
}
}
if (Object.keys(marketData).length > 0) {
this.update((state) => {
state.marketData = {
...state.marketData,
...marketData,
};
});
}
}
async #fetchAndMapExchangeRatesForSupportedNativeCurrency(
assets: {
chainId: Hex;
tokenAddress: Hex;
}[],
currency: string,
marketData: Record<Hex, Record<Hex, MarketDataDetails>> = {},
) {
return await reduceInBatchesSerially<
{ chainId: Hex; tokenAddress: Hex },
Record<Hex, Record<Hex, MarketDataDetails>>
>({
values: assets,
batchSize: TOKEN_PRICES_BATCH_SIZE,
eachBatch: async (partialMarketData, assetsBatch) => {
const batchMarketData = await this.#tokenPricesService.fetchTokenPrices(
{
assets: assetsBatch,
currency,
},
);
for (const tokenPrice of batchMarketData) {
(partialMarketData[tokenPrice.chainId] ??= {})[
tokenPrice.tokenAddress
] = tokenPrice;
}
return partialMarketData;
},
initialResult: marketData,
});
}
async #fetchAndMapExchangeRatesForUnsupportedNativeCurrency(
assets: {
chainId: Hex;
tokenAddress: Hex;
}[],
currency: string,
marketData: Record<Hex, Record<Hex, MarketDataDetails>>,
) {
// Step -1: Then fetch all tracked tokens priced in USD
const marketDataInUSD =
await this.#fetchAndMapExchangeRatesForSupportedNativeCurrency(
assets,
'usd', // Fallback currency when the native currency is not supported
);
// Formula: price_in_native = token_usd / native_usd
const convertUSDToNative = (
valueInUSD: number,
nativeTokenPriceInUSD: number,
) => valueInUSD / nativeTokenPriceInUSD;
// Step -2: Convert USD prices to native currency
for (const [chainId, marketDataByTokenAddress] of Object.entries(
marketDataInUSD,
) as [Hex, Record<Hex, MarketDataDetails>][]) {
const nativeTokenPriceInUSD =
marketDataByTokenAddress[getNativeTokenAddress(chainId)]?.price;
// Return here if it's null, undefined or 0
if (!nativeTokenPriceInUSD) {
continue;
}
for (const [tokenAddress, tokenData] of Object.entries(
marketDataByTokenAddress,
) as [Hex, MarketDataDetails][]) {
(marketData[chainId] ??= {})[tokenAddress] = {
...tokenData,
currency,
price: convertUSDToNative(tokenData.price, nativeTokenPriceInUSD),
marketCap: convertUSDToNative(
tokenData.marketCap,
nativeTokenPriceInUSD,
),
allTimeHigh: convertUSDToNative(
tokenData.allTimeHigh,
nativeTokenPriceInUSD,
),
allTimeLow: convertUSDToNative(
tokenData.allTimeLow,
nativeTokenPriceInUSD,
),
totalVolume: convertUSDToNative(
tokenData.totalVolume,
nativeTokenPriceInUSD,
),
high1d: convertUSDToNative(tokenData.high1d, nativeTokenPriceInUSD),
low1d: convertUSDToNative(tokenData.low1d, nativeTokenPriceInUSD),
dilutedMarketCap: convertUSDToNative(
tokenData.dilutedMarketCap,
nativeTokenPriceInUSD,
),
};
}
}
}
/**
* Updates token rates for the given networkClientId
*
* @param input - The input for the poll.
* @param input.chainIds - The chain ids to poll token rates on.
*/
async _executePoll({ chainIds }: TokenRatesPollingInput): Promise<void> {
const { networkConfigurationsByChainId } = this.messenger.call(
'NetworkController:getState',
);
const chainIdAndNativeCurrency = chainIds.reduce<
{ chainId: Hex; nativeCurrency: string }[]
>((acc, chainId) => {
const networkConfiguration = networkConfigurationsByChainId[chainId];
if (!networkConfiguration) {
console.error(
`TokenRatesController: No network configuration found for chainId ${chainId}`,
);
return acc;
}
acc.push({
chainId,
nativeCurrency: networkConfiguration.nativeCurrency,
});
return acc;
}, []);
await this.updateExchangeRates(chainIdAndNativeCurrency);
}
/**
* Reset the controller state to the default state.
*/
resetState() {
this.update(() => {
return getDefaultTokenRatesControllerState();
});
}
}
export default TokenRatesController;