-
-
Notifications
You must be signed in to change notification settings - Fork 278
Expand file tree
/
Copy pathRpcDataSource.ts
More file actions
1469 lines (1286 loc) · 44.7 KB
/
RpcDataSource.ts
File metadata and controls
1469 lines (1286 loc) · 44.7 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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Web3Provider } from '@ethersproject/providers';
import type { GetTokenListState } from '@metamask/assets-controllers';
import { toHex } from '@metamask/controller-utils';
import type { InternalAccount } from '@metamask/keyring-internal-api';
import type {
NetworkControllerGetNetworkClientByIdAction,
NetworkControllerGetStateAction,
NetworkControllerStateChangeEvent,
NetworkState,
NetworkStatus,
} from '@metamask/network-controller';
import type { NetworkEnablementControllerGetStateAction } from '@metamask/network-enablement-controller';
import type {
TransactionControllerIncomingTransactionsReceivedEvent,
TransactionControllerTransactionConfirmedEvent,
TransactionMeta,
} from '@metamask/transaction-controller';
import {
isStrictHexString,
isCaipChainId,
numberToHex,
parseCaipAssetType,
parseCaipChainId,
} from '@metamask/utils';
import type { Hex } from '@metamask/utils';
import BigNumberJS from 'bignumber.js';
import { AbstractDataSource } from './AbstractDataSource';
import type {
DataSourceState,
SubscriptionRequest,
} from './AbstractDataSource';
import {
BalanceFetcher,
MulticallClient,
TokenDetector,
} from './evm-rpc-services';
import type {
BalancePollingInput,
DetectionPollingInput,
} from './evm-rpc-services';
import type {
Address,
AssetFetchEntry,
Provider as RpcProvider,
TokenListState,
BalanceFetchResult,
TokenDetectionResult,
} from './evm-rpc-services/types';
import type {
AssetsControllerGetStateAction,
AssetsControllerMessenger,
} from '../AssetsController';
import { projectLogger, createModuleLogger } from '../logger';
import type {
ChainId,
Caip19AssetId,
AssetBalance,
AssetMetadata,
DataRequest,
DataResponse,
Middleware,
} from '../types';
import { normalizeAssetId } from '../utils';
import { ZERO_ADDRESS } from '../utils/constants';
const CONTROLLER_NAME = 'RpcDataSource';
const DEFAULT_BALANCE_INTERVAL = 30_000; // 30 seconds
const DEFAULT_DETECTION_INTERVAL = 180_000; // 3 minutes
const log = createModuleLogger(projectLogger, CONTROLLER_NAME);
// Allowed actions that RpcDataSource can call
export type RpcDataSourceAllowedActions =
| NetworkControllerGetStateAction
| NetworkControllerGetNetworkClientByIdAction
| AssetsControllerGetStateAction
| GetTokenListState
| NetworkEnablementControllerGetStateAction;
// Allowed events that RpcDataSource can subscribe to
export type RpcDataSourceAllowedEvents =
| NetworkControllerStateChangeEvent
| TransactionControllerTransactionConfirmedEvent
| TransactionControllerIncomingTransactionsReceivedEvent;
/** Network status for each chain */
export type ChainStatus = {
chainId: ChainId;
status: NetworkStatus;
name: string;
nativeCurrency: string;
/** Network client ID for getting the provider */
networkClientId: string;
};
/** RpcDataSource is stateless */
export type RpcDataSourceState = Record<never, never>;
/** Optional configuration for RpcDataSource when the controller instantiates it. */
export type RpcDataSourceConfig = {
balanceInterval?: number;
detectionInterval?: number;
/** Function returning whether token detection is enabled (avoids stale value) */
tokenDetectionEnabled?: () => boolean;
/** Function returning whether external services are allowed (avoids stale value; default: () => true) */
useExternalService?: () => boolean;
timeout?: number;
};
export type RpcDataSourceOptions = {
/** The AssetsController messenger (shared by all data sources). */
messenger: AssetsControllerMessenger;
/** Called when active chains are updated. Pass dataSourceName so the controller knows the source. */
onActiveChainsUpdated: (
dataSourceName: string,
chains: ChainId[],
previousChains: ChainId[],
) => void;
/** Request timeout in ms */
timeout?: number;
/** Balance polling interval in ms (default: 30s) */
balanceInterval?: number;
/** Token detection polling interval in ms (default: 180s / 3 min) */
detectionInterval?: number;
/** Function returning whether token detection is enabled (avoids stale value) */
tokenDetectionEnabled?: () => boolean;
/** Function returning whether external services are allowed (avoids stale value; default: () => true) */
useExternalService?: () => boolean;
};
/**
* Subscription data stored for each active subscription.
*/
type SubscriptionData = {
/** Polling tokens from BalanceFetcher */
balancePollingTokens: string[];
/** Polling tokens from TokenDetector */
detectionPollingTokens: string[];
/** Chain IDs being polled */
chains: ChainId[];
/** Accounts being polled */
accounts: InternalAccount[];
/** Callback to report asset updates to the controller */
onAssetsUpdate: (
response: DataResponse,
request?: DataRequest,
) => void | Promise<void>;
};
/**
* Convert CAIP chain ID or hex chain ID to hex chain ID.
*
* @param chainId - CAIP chain ID or hex chain ID.
* @returns Hex chain ID.
*/
export const caipChainIdToHex = (chainId: string): Hex => {
if (isStrictHexString(chainId)) {
return chainId;
}
if (isCaipChainId(chainId)) {
return toHex(parseCaipChainId(chainId).reference);
}
throw new Error('caipChainIdToHex - Failed to provide CAIP-2 or Hex chainId');
};
/**
* Data source for fetching balances via RPC calls.
*
* Orchestrates polling through BalanceFetcher and TokenDetector,
* each of which handle their own polling intervals.
*
* Communicates with AssetsController via Messenger:
*
* Actions:
* - RpcDataSource:getActiveChains
* - RpcDataSource:fetch
* - RpcDataSource:subscribe
* - RpcDataSource:unsubscribe
*
* Events:
* - RpcDataSource:activeChainsUpdated
* - RpcDataSource:assetsUpdated
*/
export class RpcDataSource extends AbstractDataSource<
typeof CONTROLLER_NAME,
DataSourceState
> {
readonly #messenger: AssetsControllerMessenger;
readonly #onActiveChainsUpdated: (
dataSourceName: string,
chains: ChainId[],
previousChains: ChainId[],
) => void;
readonly #timeout: number;
readonly #tokenDetectionEnabled: () => boolean;
readonly #useExternalService: () => boolean;
/** Currently active chains */
#activeChains: ChainId[] = [];
/** Network status for each active chain */
#chainStatuses: Record<ChainId, ChainStatus> = {};
/** Cache of Web3Provider instances by chainId */
readonly #providerCache: Map<ChainId, Web3Provider> = new Map();
/** Active subscriptions by ID */
readonly #activeSubscriptions: Map<string, SubscriptionData> = new Map();
#unsubscribeTransactionConfirmed: (() => void) | undefined = undefined;
#unsubscribeIncomingTransactions: (() => void) | undefined = undefined;
// Rpc-datasource components
readonly #multicallClient: MulticallClient;
readonly #balanceFetcher: BalanceFetcher;
readonly #tokenDetector: TokenDetector;
constructor(options: RpcDataSourceOptions) {
super(CONTROLLER_NAME, { activeChains: [] });
this.#messenger = options.messenger;
this.#onActiveChainsUpdated = options.onActiveChainsUpdated;
this.#timeout = options.timeout ?? 10_000;
this.#tokenDetectionEnabled =
options.tokenDetectionEnabled ?? ((): boolean => true);
this.#useExternalService =
options.useExternalService ?? ((): boolean => true);
const balanceInterval = options.balanceInterval ?? DEFAULT_BALANCE_INTERVAL;
const detectionInterval =
options.detectionInterval ?? DEFAULT_DETECTION_INTERVAL;
log('Initializing RpcDataSource', {
timeout: this.#timeout,
balanceInterval,
detectionInterval,
tokenDetectionEnabled: this.#tokenDetectionEnabled(),
useExternalService: this.#useExternalService(),
});
// Initialize MulticallClient with a provider getter
this.#multicallClient = new MulticallClient((hexChainId: string) => {
return this.#getMulticallProvider(hexChainId);
});
// Create messenger adapters for BalanceFetcher and TokenDetector
const balanceFetcherMessenger = {
call: (
_action: 'AssetsController:getState',
): {
assetsBalance: Record<string, Record<string, { amount: string }>>;
} => {
const state = this.#messenger.call('AssetsController:getState');
return {
assetsBalance: (state.assetsBalance ?? {}) as Record<
string,
Record<string, { amount: string }>
>,
};
},
};
const tokenDetectorMessenger = {
call: (_action: 'TokenListController:getState'): TokenListState => {
return this.#messenger.call('TokenListController:getState');
},
};
// Initialize BalanceFetcher with polling interval
this.#balanceFetcher = new BalanceFetcher(
this.#multicallClient,
balanceFetcherMessenger,
{ pollingInterval: balanceInterval },
);
// Polling controller awaits this callback; rejections must not become unhandled.
this.#balanceFetcher.setOnBalanceUpdate(async (result) => {
try {
await this.#handleBalanceUpdate(result);
} catch (error) {
log('Balance update handler failed', { error });
}
});
// Initialize TokenDetector with polling interval
this.#tokenDetector = new TokenDetector(
this.#multicallClient,
tokenDetectorMessenger,
{
pollingInterval: detectionInterval,
tokenDetectionEnabled: this.#tokenDetectionEnabled,
useExternalService: this.#useExternalService,
},
);
// Sync throw in the detector would reject the poll tick if uncaught.
this.#tokenDetector.setOnDetectionUpdate((result) => {
try {
this.#handleDetectionUpdate(result);
} catch (error) {
log('Detection update handler failed', { error });
}
});
this.#subscribeToNetworkController();
this.#subscribeToTransactionEvents();
this.#initializeFromNetworkController();
}
/**
* Convert a raw balance to human-readable format using decimals.
*
* @param rawBalance - The raw balance string.
* @param decimals - The number of decimals for the token.
* @returns The human-readable balance string.
*/
#convertToHumanReadable(rawBalance: string, decimals: number): string {
const rawAmount = new BigNumberJS(rawBalance);
const divisor = new BigNumberJS(10).pow(decimals);
return rawAmount.dividedBy(divisor).toFixed();
}
/**
* Collect metadata for a list of balance entries.
* For native tokens, generates metadata from chain status.
* For ERC20 tokens, looks up from existing state or token list.
*
* @param balances - Array of balance entries with assetId.
* @param chainId - The CAIP-2 chain ID.
* @returns Record of asset metadata keyed by asset ID.
*/
#collectMetadataForBalances(
balances: { assetId: Caip19AssetId }[],
chainId: ChainId,
): Record<Caip19AssetId, AssetMetadata> {
const assetsInfo: Record<Caip19AssetId, AssetMetadata> = {};
const existingMetadata = this.#getExistingAssetsMetadata();
for (const balance of balances) {
const isNative = balance.assetId.includes('/slip44:');
if (isNative) {
const chainStatus = this.#chainStatuses[chainId];
if (chainStatus) {
assetsInfo[balance.assetId] = {
type: 'native',
symbol: chainStatus.nativeCurrency,
name: chainStatus.nativeCurrency,
decimals: 18,
};
}
} else {
// For ERC20 tokens, try existing metadata from state first
const existingMeta = existingMetadata[balance.assetId];
if (existingMeta) {
assetsInfo[balance.assetId] = existingMeta;
} else {
// Fallback to token list if not in state
const tokenListMeta = this.#getTokenMetadataFromTokenList(
balance.assetId,
);
if (tokenListMeta) {
assetsInfo[balance.assetId] = tokenListMeta;
}
// Unknown ERC-20: omit from assetsInfo until decimals are known.
// #handleBalanceUpdate resolves decimals via RPC or omits the balance.
}
}
}
return assetsInfo;
}
/**
* Handle balance update from BalanceFetcher.
*
* @param result - The balance fetch result.
*/
async #handleBalanceUpdate(result: BalanceFetchResult): Promise<void> {
const newBalances: Record<string, { amount: string }> = {};
// Convert hex chain ID to CAIP-2 format
const chainIdDecimal = parseInt(result.chainId, 16);
const caipChainId = `eip155:${chainIdDecimal}` as ChainId;
// Normalize asset IDs from BalanceFetcher (lowercase) to checksummed form
const normalizedBalances = result.balances.map((b) => ({
...b,
assetId: normalizeAssetId(b.assetId),
}));
// Collect metadata for all balances
const assetsInfo = this.#collectMetadataForBalances(
normalizedBalances,
caipChainId,
);
// Convert balances to human-readable format.
// Resolution: state metadata → pipeline metadata; skip if decimals unknown.
const existingMetadata = this.#getExistingAssetsMetadata();
for (const balance of normalizedBalances) {
const stateMetadata = existingMetadata[balance.assetId];
const pipelineMetadata = assetsInfo[balance.assetId];
const decimals = stateMetadata?.decimals ?? pipelineMetadata?.decimals;
if (decimals === undefined) {
continue;
}
const humanReadableAmount = this.#convertToHumanReadable(
balance.balance,
decimals,
);
newBalances[balance.assetId] = {
amount: humanReadableAmount,
};
}
// Only send new data to AssetsController - it handles merging atomically
// to avoid race conditions when concurrent updates occur for the same account
const response: DataResponse = {
assetsBalance: {
[result.accountId]: newBalances,
},
assetsInfo,
updateMode: 'merge',
};
const request: DataRequest = {
accountsWithSupportedChains: [],
chainIds: [caipChainId],
dataTypes: ['balance'],
};
log('Balance update response', {
accountId: result.accountId,
newBalanceCount: Object.keys(newBalances).length,
});
for (const subscription of this.#activeSubscriptions.values()) {
subscription.onAssetsUpdate(response, request)?.catch((error) => {
log('Failed to update assets', { error });
});
}
}
/**
* Handle detection update from TokenDetector.
*
* @param result - The token detection result.
*/
#handleDetectionUpdate(result: TokenDetectionResult): void {
log('Detected new tokens', {
count: result.detectedAssets.length,
});
// Build new metadata from detected assets
const newMetadata: Record<Caip19AssetId, AssetMetadata> = {};
if (result.detectedAssets.length > 0) {
for (const asset of result.detectedAssets) {
// Only include if we have metadata (symbol and decimals at minimum)
if (asset.symbol && asset.decimals !== undefined) {
newMetadata[asset.assetId] = {
type: 'erc20',
symbol: asset.symbol,
name: asset.name ?? asset.symbol,
decimals: asset.decimals,
image: asset.image,
};
}
}
}
// Build new balances from detected tokens
const newBalances: Record<string, { amount: string }> = {};
if (result.detectedBalances.length > 0) {
for (const balance of result.detectedBalances) {
// Get decimals from the detected asset metadata
const detectedAsset = result.detectedAssets.find(
(asset) => asset.assetId === balance.assetId,
);
if (detectedAsset?.decimals === undefined) {
continue;
}
const humanReadableAmount = this.#convertToHumanReadable(
balance.balance,
detectedAsset.decimals,
);
newBalances[balance.assetId] = {
amount: humanReadableAmount,
};
}
}
// Only send new data to AssetsController - it handles merging atomically
// to avoid race conditions when concurrent updates occur for the same account
const response: DataResponse = {
detectedAssets: {
[result.accountId]: result.detectedAssets.map((asset) => asset.assetId),
},
assetsInfo: newMetadata,
assetsBalance: {
[result.accountId]: newBalances,
},
updateMode: 'merge',
};
const chainIdDecimal = parseInt(result.chainId, 16);
const caipChainId = `eip155:${chainIdDecimal}` as ChainId;
const request: DataRequest = {
accountsWithSupportedChains: [],
chainIds: [caipChainId],
dataTypes: ['balance', 'metadata', 'price'],
};
for (const subscription of this.#activeSubscriptions.values()) {
subscription.onAssetsUpdate(response, request)?.catch((error) => {
log('Failed to update detected assets', { error });
});
}
}
#subscribeToNetworkController(): void {
this.#messenger.subscribe(
'NetworkController:stateChange',
(networkState: NetworkState) => {
log('NetworkController state changed');
this.#clearProviderCache();
this.#updateFromNetworkState(networkState);
},
);
}
#subscribeToTransactionEvents(): void {
const unsubConfirmed = this.#messenger.subscribe(
'TransactionController:transactionConfirmed',
this.#onTransactionConfirmed.bind(this),
);
this.#unsubscribeTransactionConfirmed =
typeof unsubConfirmed === 'function' ? unsubConfirmed : undefined;
const unsubIncoming = this.#messenger.subscribe(
'TransactionController:incomingTransactionsReceived',
this.#onIncomingTransactions.bind(this),
);
this.#unsubscribeIncomingTransactions =
typeof unsubIncoming === 'function' ? unsubIncoming : undefined;
}
#onTransactionConfirmed(payload: TransactionMeta): void {
const hexChainId = payload?.chainId;
if (!hexChainId) {
return;
}
const caipChainId = `eip155:${parseInt(hexChainId, 16)}` as ChainId;
this.#refreshBalanceForChains([caipChainId]).catch((error) => {
log('Failed to refresh balance after transaction confirmed', { error });
});
}
#onIncomingTransactions(payload: TransactionMeta[]): void {
const chainIds = Array.from(
new Set(
(payload ?? [])
.map((item) => item?.chainId)
.filter((id): id is Hex => Boolean(id)),
),
);
const caipChainIds = chainIds.map(
(hexChainId) => `eip155:${parseInt(hexChainId, 16)}` as ChainId,
);
const toRefresh =
caipChainIds.length > 0 ? caipChainIds : [...this.#activeChains];
this.#refreshBalanceForChains(toRefresh).catch((error) => {
log('Failed to refresh balance after incoming transactions', { error });
});
}
/**
* Fetch balances for the given chains across all active subscriptions and
* push updates to the controller.
*
* @param chainIds - CAIP-2 chain IDs to refresh.
*/
async #refreshBalanceForChains(chainIds: ChainId[]): Promise<void> {
const chainIdsSet = new Set(chainIds);
const chainsToFetch = chainIds.filter((chainId) =>
this.#activeChains.includes(chainId),
);
if (chainsToFetch.length === 0) {
return;
}
for (const subscription of this.#activeSubscriptions.values()) {
const subscriptionChains = subscription.chains.filter((chainId) =>
chainIdsSet.has(chainId),
);
if (subscriptionChains.length === 0) {
continue;
}
const request: DataRequest = {
accountsWithSupportedChains: subscription.accounts.map((account) => ({
account,
supportedChains: subscriptionChains,
})),
chainIds: subscriptionChains,
dataTypes: ['balance'],
};
try {
const response = await this.fetch(request);
if (
response.assetsBalance &&
Object.keys(response.assetsBalance).length > 0
) {
subscription.onAssetsUpdate(response)?.catch((error) => {
log('Failed to report balance update after transaction', {
error,
});
});
}
} catch (error) {
log('Failed to fetch balance after transaction', {
chains: subscriptionChains,
error,
});
}
}
}
#initializeFromNetworkController(): void {
log('Initializing from NetworkController');
try {
const networkState = this.#messenger.call('NetworkController:getState');
this.#updateFromNetworkState(networkState);
} catch (error) {
log('Failed to initialize from NetworkController', error);
}
}
#updateFromNetworkState(networkState: NetworkState): void {
const { networkConfigurationsByChainId, networksMetadata } = networkState;
const chainStatuses: Record<ChainId, ChainStatus> = {};
const activeChains: ChainId[] = [];
for (const [hexChainId, config] of Object.entries(
networkConfigurationsByChainId,
)) {
const decimalChainId = parseInt(hexChainId, 16);
const caip2ChainId = `eip155:${decimalChainId}` as ChainId;
const defaultRpcEndpoint =
config.rpcEndpoints[config.defaultRpcEndpointIndex];
if (!defaultRpcEndpoint) {
continue;
}
const { networkClientId } = defaultRpcEndpoint;
const metadata = networksMetadata[networkClientId];
const status: NetworkStatus =
metadata?.status ?? ('unknown' as NetworkStatus);
chainStatuses[caip2ChainId] = {
chainId: caip2ChainId,
status,
name: config.name,
nativeCurrency: config.nativeCurrency,
networkClientId,
};
if (status === 'available' || status === 'unknown') {
activeChains.push(caip2ChainId);
}
}
log('Network state updated', {
configuredChains: Object.keys(chainStatuses),
activeChains,
});
// Check if chains changed
const previousChains = [...this.#activeChains];
const previousSet = new Set(previousChains);
const hasChanges =
previousChains.length !== activeChains.length ||
activeChains.some((chain) => !previousSet.has(chain));
// Update internal state and data source state before notifying, so that
// when the controller handles the callback and calls getActiveChainsSync(),
// it receives the updated chains (same order as AbstractDataSource.updateActiveChains).
this.#chainStatuses = chainStatuses;
this.#activeChains = activeChains;
this.state.activeChains = activeChains;
if (hasChanges) {
this.#onActiveChainsUpdated(this.getName(), activeChains, previousChains);
}
}
#getProvider(chainId: ChainId): Web3Provider | undefined {
const cached = this.#providerCache.get(chainId);
if (cached) {
return cached;
}
const chainStatus = this.#chainStatuses[chainId];
if (!chainStatus) {
return undefined;
}
try {
const networkClient = this.#messenger.call(
'NetworkController:getNetworkClientById',
chainStatus.networkClientId,
);
if (!networkClient?.provider) {
return undefined;
}
const web3Provider = new Web3Provider(networkClient.provider);
this.#providerCache.set(chainId, web3Provider);
return web3Provider;
} catch (error) {
log('Failed to get provider for chain', { chainId, error });
return undefined;
}
}
/**
* Get provider for MulticallClient using a hex chainId.
*
* @param hexChainId - The hex string representation of the chain id.
* @returns An RpcProvider instance for the specified chain.
*/
#getMulticallProvider(hexChainId: string): RpcProvider {
const decimalChainId = parseInt(hexChainId, 16);
const caip2ChainId = `eip155:${decimalChainId}` as ChainId;
const web3Provider = this.#getProvider(caip2ChainId);
if (!web3Provider) {
throw new Error(`No provider available for chain ${hexChainId}`);
}
return {
call: async (params: { to: string; data: string }): Promise<string> => {
return web3Provider.call({
to: params.to,
data: params.data,
});
},
getBalance: async (address: string): Promise<{ toString(): string }> => {
const balance = await web3Provider.getBalance(address);
return balance;
},
};
}
#clearProviderCache(): void {
this.#providerCache.clear();
}
/**
* Fetch the `decimals()` value from an ERC20 contract via RPC.
*
* @param chainId - CAIP-2 chain ID.
* @param tokenAddress - The token contract address.
* @returns The decimals value, or undefined if the call fails.
*/
async #fetchDecimalsViaRpc(
chainId: ChainId,
tokenAddress: string,
): Promise<number | undefined> {
try {
const provider = this.#getProvider(chainId);
if (!provider) {
return undefined;
}
// ERC20 decimals() selector: keccak256("decimals()") = 0x313ce567
const result = await provider.call({
to: tokenAddress,
data: '0x313ce567',
});
if (!result || result === '0x') {
return undefined;
}
const parsed = parseInt(result, 16);
if (Number.isNaN(parsed) || parsed < 0 || parsed > 255) {
return undefined;
}
return parsed;
} catch {
return undefined;
}
}
/**
* Get the data source name.
*
* @returns The name of this data source.
*/
/**
* Get the status of all configured chains.
*
* @returns Record of chain statuses keyed by chain ID.
*/
getChainStatuses(): Record<ChainId, ChainStatus> {
return { ...this.#chainStatuses };
}
/**
* Get the status of a specific chain.
*
* @param chainId - The chain ID to get status for.
* @returns The chain status or undefined if not found.
*/
getChainStatus(chainId: ChainId): ChainStatus | undefined {
return this.#chainStatuses[chainId];
}
/**
* Set the balance polling interval.
*
* @param interval - The polling interval in milliseconds.
*/
setBalancePollingInterval(interval: number): void {
log('Setting balance polling interval', { interval });
this.#balanceFetcher.setIntervalLength(interval);
}
/**
* Get the current balance polling interval.
*
* @returns The polling interval in milliseconds, or undefined if not set.
*/
getBalancePollingInterval(): number | undefined {
return this.#balanceFetcher.getIntervalLength();
}
/**
* Set the token detection polling interval.
*
* @param interval - The polling interval in milliseconds.
*/
setDetectionPollingInterval(interval: number): void {
log('Setting detection polling interval', { interval });
this.#tokenDetector.setIntervalLength(interval);
}
/**
* Get the current token detection polling interval.
*
* @returns The polling interval in milliseconds, or undefined if not set.
*/
getDetectionPollingInterval(): number | undefined {
return this.#tokenDetector.getIntervalLength();
}
async fetch(request: DataRequest): Promise<DataResponse> {
const response: DataResponse = {};
const chainsToFetch = request.chainIds.filter((chainId) =>
this.#activeChains.includes(chainId),
);
log('Fetch requested', {
accounts: request.accountsWithSupportedChains.map((a) => a.account.id),
requestedChains: request.chainIds,
chainsToFetch,
});
if (chainsToFetch.length === 0) {
log('No active chains to fetch');
return response;
}
const assetsBalance: Record<
string,
Record<Caip19AssetId, AssetBalance>
> = {};
const assetsInfo: Record<Caip19AssetId, AssetMetadata> = {};
const failedChains: ChainId[] = [];
// Fetch balances for each account and its supported chains (pre-computed in request)
for (const {
account,
supportedChains,
} of request.accountsWithSupportedChains) {
const chainsForAccount = chainsToFetch.filter((chain) =>
supportedChains.includes(chain),
);
if (chainsForAccount.length === 0) {
continue;
}
const { address, id: accountId } = account;
for (const chainId of chainsForAccount) {
const hexChainId = caipChainIdToHex(chainId);
// Build a single AssetFetchEntry[] for native + custom ERC-20s
const nativeAssetId = this.#buildNativeAssetId(chainId);
const assetsToFetch: AssetFetchEntry[] = [
{ assetId: nativeAssetId, address: ZERO_ADDRESS },
];
if (request.customAssets) {
const existingMetadata = this.#getExistingAssetsMetadata();
for (const assetId of request.customAssets) {
try {
const parsed = parseCaipAssetType(assetId);
const assetChainId = `${parsed.chain.namespace}:${parsed.chain.reference}`;
if (
assetChainId === chainId &&
parsed.assetNamespace === 'erc20'
) {
const tokenAddress =
parsed.assetReference.toLowerCase() as Address;
const normalizedId = normalizeAssetId(assetId);
const decimals =
existingMetadata[normalizedId]?.decimals ??
this.#getTokenMetadataFromTokenList(normalizedId)?.decimals;
assetsToFetch.push({
assetId,
address: tokenAddress,
decimals,
});
}
} catch {
// Skip unparseable asset IDs
}
}
}
try {
const result = await this.#balanceFetcher.fetchBalancesForAssets(
hexChainId,
accountId,
address as Address,
assetsToFetch,
);
if (!assetsBalance[accountId]) {
assetsBalance[accountId] = {};
}
// Normalize asset IDs from BalanceFetcher (which uses lowercase
// addresses) to checksummed form so they match assetsInfo state keys.
const normalizedBalances = result.balances.map((b) => ({
...b,
assetId: normalizeAssetId(b.assetId),
}));
// Collect metadata for all balances
const balanceMetadata = this.#collectMetadataForBalances(
normalizedBalances,
chainId,
);
Object.assign(assetsInfo, balanceMetadata);
// Convert balances to human-readable format using decimals from
// assetsInfo state (which includes pendingMetadata from addCustomAsset).
// Resolution: state → pipeline metadata → RPC `decimals()`; omit balance if still unknown.
const existingMetadata = this.#getExistingAssetsMetadata();
for (const balance of normalizedBalances) {
const stateMetadata = existingMetadata[balance.assetId];
const pipelineMetadata = assetsInfo[balance.assetId];
let decimals: number | undefined =
stateMetadata?.decimals ?? pipelineMetadata?.decimals;
if (decimals === undefined) {
const parsed = parseCaipAssetType(balance.assetId);
if (parsed.assetNamespace === 'erc20') {
decimals = await this.#fetchDecimalsViaRpc(
chainId,
parsed.assetReference,
);
}
}
if (decimals === undefined) {
continue;
}
const humanReadableAmount = this.#convertToHumanReadable(