forked from Koniverse/SubWallet-Extension
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
1997 lines (1577 loc) · 64.3 KB
/
index.ts
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
// Copyright 2019-2022 @subwallet/extension-base authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { AssetLogoMap, AssetRefMap, ChainAssetMap, ChainInfoMap, ChainLogoMap, MultiChainAssetMap } from '@subwallet/chain-list';
import { _AssetRef, _AssetRefPath, _AssetType, _ChainAsset, _ChainInfo, _ChainStatus, _EvmInfo, _MultiChainAsset, _SubstrateChainType, _SubstrateInfo } from '@subwallet/chain-list/types';
import { AssetSetting, ValidateNetworkResponse } from '@subwallet/extension-base/background/KoniTypes';
import { _DEFAULT_ACTIVE_CHAINS, _MANTA_ZK_CHAIN_GROUP, _ZK_ASSET_PREFIX, LATEST_CHAIN_DATA_FETCHING_INTERVAL } from '@subwallet/extension-base/services/chain-service/constants';
import { EvmChainHandler } from '@subwallet/extension-base/services/chain-service/handler/EvmChainHandler';
import { MantaPrivateHandler } from '@subwallet/extension-base/services/chain-service/handler/manta/MantaPrivateHandler';
import { SubstrateChainHandler } from '@subwallet/extension-base/services/chain-service/handler/SubstrateChainHandler';
import { _CHAIN_VALIDATION_ERROR } from '@subwallet/extension-base/services/chain-service/handler/types';
import { _ChainApiStatus, _ChainConnectionStatus, _ChainState, _CUSTOM_PREFIX, _DataMap, _EvmApi, _NetworkUpsertParams, _NFT_CONTRACT_STANDARDS, _SMART_CONTRACT_STANDARDS, _SmartContractTokenInfo, _SubstrateApi, _ValidateCustomAssetRequest, _ValidateCustomAssetResponse } from '@subwallet/extension-base/services/chain-service/types';
import { _isAssetAutoEnable, _isAssetCanPayTxFee, _isAssetFungibleToken, _isChainEnabled, _isCustomAsset, _isCustomChain, _isCustomProvider, _isEqualContractAddress, _isEqualSmartContractAsset, _isMantaZkAsset, _isPureEvmChain, _isPureSubstrateChain, _parseAssetRefKey, fetchPatchData, randomizeProvider, updateLatestChainInfo } from '@subwallet/extension-base/services/chain-service/utils';
import { EventService } from '@subwallet/extension-base/services/event-service';
import { IChain, IMetadataItem } from '@subwallet/extension-base/services/storage-service/databases';
import DatabaseService from '@subwallet/extension-base/services/storage-service/DatabaseService';
import AssetSettingStore from '@subwallet/extension-base/stores/AssetSetting';
import { addLazy, fetchStaticData, filterAssetsByChainAndType, MODULE_SUPPORT } from '@subwallet/extension-base/utils';
import { BehaviorSubject, Subject } from 'rxjs';
import Web3 from 'web3';
import { logger as createLogger } from '@polkadot/util/logger';
import { Logger } from '@polkadot/util/types';
const availChainInfoMap = (() => {
const enableList = [
'avail_mainnet',
'availTuringTest',
'goldberg_testnet',
'ethereum',
'binance',
'polygon',
'arbitrum_one',
'optimism',
'avalanche_c',
'base_mainnet',
'fantom',
'tomochain',
'manta_network_evm',
'ethereum_goerli',
'binance_test',
'fantom_testnet',
'okxTest'
];
return Object.fromEntries(enableList.map((slug) => {
return [slug, ChainInfoMap[slug]];
}));
})();
export class ChainService {
private dataMap: _DataMap = {
chainInfoMap: {},
chainStateMap: {},
assetRegistry: {},
assetRefMap: {}
};
private dbService: DatabaseService; // to save chain, token settings from user
private eventService: EventService;
private lockChainInfoMap = false; // prevent unwanted changes (edit, enable, disable) to chainInfoMap
private substrateChainHandler: SubstrateChainHandler;
private evmChainHandler: EvmChainHandler;
private mantaChainHandler: MantaPrivateHandler | undefined;
refreshLatestChainDataTimeOut: NodeJS.Timer | undefined;
public get mantaPay () {
return this.mantaChainHandler;
}
// TODO: consider BehaviorSubject
private chainInfoMapSubject = new Subject<Record<string, _ChainInfo>>();
private chainStateMapSubject = new Subject<Record<string, _ChainState>>();
private chainStatusMapSubject = new BehaviorSubject<Record<string, _ChainApiStatus>>({});
private assetRegistrySubject = new Subject<Record<string, _ChainAsset>>();
private multiChainAssetMapSubject = new Subject<Record<string, _MultiChainAsset>>();
private xcmRefMapSubject = new Subject<Record<string, _AssetRef>>();
private swapRefMapSubject = new Subject<Record<string, _AssetRef>>();
private assetLogoMapSubject = new BehaviorSubject<Record<string, string>>(AssetLogoMap);
private chainLogoMapSubject = new BehaviorSubject<Record<string, string>>(ChainLogoMap);
private assetMapPatch: string = JSON.stringify({});
private assetLogoPatch: string = JSON.stringify({});
// Todo: Update to new store indexed DB
private store: AssetSettingStore = new AssetSettingStore();
private assetSettingSubject = new BehaviorSubject({} as Record<string, AssetSetting>);
private logger: Logger;
constructor (dbService: DatabaseService, eventService: EventService) {
this.dbService = dbService;
this.eventService = eventService;
this.chainInfoMapSubject.next(this.dataMap.chainInfoMap);
this.chainStateMapSubject.next(this.dataMap.chainStateMap);
this.assetRegistrySubject.next(this.dataMap.assetRegistry);
this.xcmRefMapSubject.next(this.xcmRefMap);
this.swapRefMapSubject.next(this.swapRefMap);
if (MODULE_SUPPORT.MANTA_ZK) {
console.log('Init Manta ZK');
this.mantaChainHandler = new MantaPrivateHandler(dbService);
}
this.substrateChainHandler = new SubstrateChainHandler(this);
this.evmChainHandler = new EvmChainHandler(this);
this.logger = createLogger('chain-service');
}
public subscribeSwapRefMap () {
return this.swapRefMapSubject;
}
// Getter
get xcmRefMap () {
const result: Record<string, _AssetRef> = {};
Object.entries(this.dataMap.assetRefMap).forEach(([key, assetRef]) => {
if (assetRef.path === _AssetRefPath.XCM) {
result[key] = assetRef;
}
});
return result;
}
get swapRefMap () {
const result: Record<string, _AssetRef> = {};
Object.entries(this.dataMap.assetRefMap).forEach(([key, assetRef]) => {
if (assetRef.path === _AssetRefPath.SWAP) {
result[key] = assetRef;
}
});
return result;
}
public getEvmApi (slug: string) {
return this.evmChainHandler.getEvmApiByChain(slug);
}
public getEvmApiMap () {
return this.evmChainHandler.getEvmApiMap();
}
public getSubstrateApiMap () {
return this.substrateChainHandler.getSubstrateApiMap();
}
public getSubstrateApi (slug: string) {
return this.substrateChainHandler.getSubstrateApiByChain(slug);
}
public getChainCurrentProviderByKey (slug: string) {
const providerName = this.getChainStateByKey(slug).currentProvider;
const providerMap = this.getChainInfoByKey(slug).providers;
const endpoint = providerMap[providerName];
return {
endpoint,
providerName
};
}
public subscribeChainInfoMap () {
return this.chainInfoMapSubject;
}
public subscribeAssetRegistry () {
return this.assetRegistrySubject;
}
public subscribeMultiChainAssetMap () {
return this.multiChainAssetMapSubject;
}
public subscribeXcmRefMap () {
return this.xcmRefMapSubject;
}
public subscribeChainStateMap () {
return this.chainStateMapSubject;
}
public subscribeChainStatusMap () {
return this.chainStatusMapSubject;
}
public getAssetRegistry () {
return this.dataMap.assetRegistry;
}
public getMultiChainAssetMap () {
return MultiChainAssetMap;
}
public getSmartContractTokens () {
const filteredAssetRegistry: Record<string, _ChainAsset> = {};
Object.values(this.getAssetRegistry()).forEach((asset) => {
if (_SMART_CONTRACT_STANDARDS.includes(asset.assetType)) {
filteredAssetRegistry[asset.slug] = asset;
}
});
return filteredAssetRegistry;
}
public getChainInfoMap (): Record<string, _ChainInfo> {
return this.dataMap.chainInfoMap;
}
public getEvmChainInfoMap (): Record<string, _ChainInfo> {
const result: Record<string, _ChainInfo> = {};
Object.values(this.getChainInfoMap()).forEach((chainInfo) => {
if (_isPureEvmChain(chainInfo)) {
result[chainInfo.slug] = chainInfo;
}
});
return result;
}
public getSubstrateChainInfoMap (): Record<string, _ChainInfo> {
const result: Record<string, _ChainInfo> = {};
Object.values(this.getChainInfoMap()).forEach((chainInfo) => {
if (_isPureSubstrateChain(chainInfo)) {
result[chainInfo.slug] = chainInfo;
}
});
return result;
}
public getAllPriceIds () {
const result: string[] = [];
Object.values(this.getAssetRegistry()).forEach((assetInfo) => {
if (assetInfo.priceId !== null) {
result.push(assetInfo.priceId);
}
});
return result;
}
public getNativeTokenInfo (chainSlug: string) {
let nativeTokenInfo: _ChainAsset = {
assetType: _AssetType.NATIVE,
decimals: 0,
metadata: null,
minAmount: '',
multiChainAsset: '',
name: '',
originChain: '',
priceId: '',
slug: '',
symbol: '',
hasValue: true,
icon: ''
};
for (const assetInfo of Object.values(this.getAssetRegistry())) {
if (assetInfo.assetType === _AssetType.NATIVE && assetInfo.originChain === chainSlug) {
nativeTokenInfo = assetInfo;
break;
}
}
return nativeTokenInfo;
}
public getAssetRefMap () {
return this.dataMap.assetRefMap;
}
public getChainStateMap () {
return this.dataMap.chainStateMap;
}
public getChainStateByKey (key: string) {
return this.dataMap.chainStateMap[key];
}
public getChainStatusMap () {
return this.chainStatusMapSubject.getValue();
}
public getChainStatusByKey (key: string) {
return this.getChainStatusMap()[key];
}
public getActiveChains () {
return Object.entries(this.dataMap.chainStateMap)
.filter(([, chainState]) => _isChainEnabled(chainState))
.map(([key]) => key);
}
public getSupportedSmartContractTypes () {
return [_AssetType.ERC20, _AssetType.ERC721, _AssetType.PSP22, _AssetType.PSP34];
}
public getActiveChainInfoMap () {
const result: Record<string, _ChainInfo> = {};
Object.values(this.getChainInfoMap()).forEach((chainInfo) => {
const chainState = this.getChainStateByKey(chainInfo.slug);
if (_isChainEnabled(chainState)) {
result[chainInfo.slug] = chainInfo;
}
});
return result;
}
public getActiveChainSlugs () {
const result: string[] = [];
Object.values(this.getChainInfoMap()).forEach((chainInfo) => {
const chainState = this.getChainStateByKey(chainInfo.slug);
if (_isChainEnabled(chainState)) {
result.push(chainInfo.slug);
}
});
return result;
}
public getChainInfoByKey (key: string): _ChainInfo {
return this.dataMap.chainInfoMap[key];
}
public getActiveChainInfos () {
const result: Record<string, _ChainInfo> = {};
Object.values(this.getChainStateMap()).forEach((chainState) => {
const chainInfo = this.getChainInfoByKey(chainState.slug);
if (chainState.active && chainInfo && chainInfo.chainStatus === _ChainStatus.ACTIVE) {
result[chainState.slug] = chainInfo;
}
});
return result;
}
public getAssetBySlug (slug: string): _ChainAsset {
return this.getAssetRegistry()[slug];
}
public getMantaZkAssets (chain: string): Record<string, _ChainAsset> {
const result: Record<string, _ChainAsset> = {};
Object.values(this.getAssetRegistry()).forEach((chainAsset) => {
if (chainAsset.originChain === chain && _isAssetFungibleToken(chainAsset) && chainAsset.symbol.startsWith(_ZK_ASSET_PREFIX)) {
result[chainAsset.slug] = chainAsset;
}
});
return result;
}
public getFungibleTokensByChain (chainSlug: string, checkActive = false): Record<string, _ChainAsset> {
const result: Record<string, _ChainAsset> = {};
const assetSettings = this.assetSettingSubject.value;
Object.values(this.getAssetRegistry()).forEach((chainAsset) => {
const _filterActive = !checkActive || assetSettings[chainAsset.slug]?.visible;
if (chainAsset.originChain === chainSlug && _isAssetFungibleToken(chainAsset) && _filterActive) {
result[chainAsset.slug] = chainAsset;
}
});
return result;
}
public getXcmEqualAssetByChain (destinationChainSlug: string, originTokenSlug: string) {
let destinationTokenInfo: _ChainAsset | undefined;
for (const asset of Object.values(this.getAssetRegistry())) {
if (asset.originChain === destinationChainSlug) { // check
const assetRefKey = _parseAssetRefKey(originTokenSlug, asset.slug);
const assetRef = this.xcmRefMap[assetRefKey];
if (assetRef && assetRef.path === _AssetRefPath.XCM) { // there's only 1 corresponding token on 1 chain
destinationTokenInfo = asset;
break;
}
}
}
return destinationTokenInfo;
}
public getAssetByChainAndType (chainSlug: string, assetTypes: _AssetType[]) {
return filterAssetsByChainAndType(this.getAssetRegistry(), chainSlug, assetTypes);
}
public getSmartContractNfts () {
const result: _ChainAsset[] = [];
Object.values(this.getAssetRegistry()).forEach((assetInfo) => {
if (_NFT_CONTRACT_STANDARDS.includes(assetInfo.assetType)) {
result.push(assetInfo);
}
});
return result;
}
// Setter
public forceRemoveChain (slug: string) {
if (this.lockChainInfoMap) {
return false;
}
const chainInfoMap = this.getChainInfoMap();
const chainStateMap = this.getChainStateMap();
if (!(slug in chainInfoMap)) {
return false;
}
this.lockChainInfoMap = true;
delete chainStateMap[slug];
delete chainInfoMap[slug];
this.deleteAssetsByChain(slug);
this.dbService.removeFromChainStore([slug]).catch(console.error);
this.updateChainSubscription();
this.lockChainInfoMap = false;
this.eventService.emit('chain.updateState', slug);
return true;
}
public removeCustomChain (slug: string) {
if (this.lockChainInfoMap) {
return false;
}
const chainInfoMap = this.getChainInfoMap();
const chainStateMap = this.getChainStateMap();
if (!(slug in chainInfoMap)) {
return false;
}
if (!_isCustomChain(slug)) {
return false;
}
if (chainStateMap[slug].active) {
return false;
}
this.lockChainInfoMap = true;
delete chainStateMap[slug];
delete chainInfoMap[slug];
this.deleteAssetsByChain(slug);
this.dbService.removeFromChainStore([slug]).catch(console.error);
this.updateChainSubscription();
this.lockChainInfoMap = false;
this.eventService.emit('chain.updateState', slug);
return true;
}
public resetChainInfoMap (excludedChains?: string[]) {
if (this.lockChainInfoMap) {
return false;
}
this.lockChainInfoMap = true;
const chainStateMap = this.getChainStateMap();
for (const [slug, chainState] of Object.entries(chainStateMap)) {
if (!_DEFAULT_ACTIVE_CHAINS.includes(slug) && !excludedChains?.includes(slug)) {
chainState.active = false;
}
}
this.updateChainStateMapSubscription();
this.lockChainInfoMap = false;
return true;
}
private connectionStatusQueueMap = {} as Record<string, _ChainConnectionStatus>;
public updateChainConnectionStatus (slug: string, connectionStatus: _ChainConnectionStatus) {
this.connectionStatusQueueMap[slug] = connectionStatus;
addLazy('updateChainConnectionStatus', () => {
const chainStatusMap = this.getChainStatusMap();
let update = false;
Object.entries(this.connectionStatusQueueMap).forEach(([slug, status]) => {
if (chainStatusMap[slug]) {
if (chainStatusMap[slug].connectionStatus !== status) {
chainStatusMap[slug].connectionStatus = status;
chainStatusMap[slug].lastUpdated = Date.now();
update = true;
}
} else {
chainStatusMap[slug] = {
slug,
connectionStatus: status,
lastUpdated: Date.now()
};
update = true;
}
});
this.connectionStatusQueueMap = {};
update && this.chainStatusMapSubject.next(chainStatusMap);
});
}
public upsertCustomToken (token: _ChainAsset) {
const chainInfo = this.getChainInfoByKey(token.originChain);
if (token.slug.length === 0) { // new token
if (token.assetType === _AssetType.NATIVE) {
const defaultSlug = this.generateSlugForNativeToken(token.originChain, token.assetType, token.symbol);
token.slug = `${_CUSTOM_PREFIX}${defaultSlug}`;
} else {
const defaultSlug = this.generateSlugForSmartContractAsset(token.originChain, token.assetType, token.symbol, token.metadata?.contractAddress as string);
token.slug = `${_CUSTOM_PREFIX}${defaultSlug}`;
}
}
if (token.originChain && _isAssetFungibleToken(token)) {
token.hasValue = !chainInfo?.isTestnet;
}
const assetRegistry = this.getAssetRegistry();
assetRegistry[token.slug] = token;
this.dbService.updateAssetStore(token).catch((e) => this.logger.error(e));
this.assetRegistrySubject.next(assetRegistry);
return token.slug;
}
public deleteAssetsByChain (chainSlug: string) {
if (!_isCustomChain(chainSlug)) {
return;
}
const targetAssets: string[] = [];
const assetRegistry = this.getAssetRegistry();
Object.values(assetRegistry).forEach((targetToken) => {
if (targetToken.originChain === chainSlug) {
targetAssets.push(targetToken.slug);
}
});
this.deleteCustomAssets(targetAssets);
}
public deleteCustomAssets (targetAssets: string[]) {
const assetRegistry = this.getAssetRegistry();
targetAssets.forEach((targetToken) => {
delete assetRegistry[targetToken];
});
this.dbService.removeFromBalanceStore(targetAssets).catch((e) => this.logger.error(e));
this.dbService.removeFromAssetStore(targetAssets).catch((e) => this.logger.error(e));
this.assetRegistrySubject.next(assetRegistry);
targetAssets.forEach((assetSlug) => {
this.eventService.emit('asset.updateState', assetSlug);
});
}
// Business logic
public async init () {
await this.eventService.waitDatabaseReady;
// TODO: reconsider the flow of initiation
this.multiChainAssetMapSubject.next(MultiChainAssetMap);
// const storedAssetRefMap = await this.dbService.getAssetRefMap();
//
// this.dataMap.assetRefMap = storedAssetRefMap && Object.values(storedAssetRefMap).length > 0 ? storedAssetRefMap : AssetRefMap;
await this.initChains();
this.chainInfoMapSubject.next(this.getChainInfoMap());
this.assetRegistrySubject.next(this.getAssetRegistry());
this.xcmRefMapSubject.next(this.xcmRefMap);
await this.initApis();
await this.initAssetSettings();
this.initAssetRefMap();
await this.autoEnableTokens();
this.checkLatestData();
}
initAssetRefMap () {
this.dataMap.assetRefMap = AssetRefMap;
}
checkLatestData () {
clearInterval(this.refreshLatestChainDataTimeOut);
this.handleLatestData();
this.refreshLatestChainDataTimeOut = setInterval(this.handleLatestData.bind(this), LATEST_CHAIN_DATA_FETCHING_INTERVAL);
}
stopCheckLatestChainData () {
clearInterval(this.refreshLatestChainDataTimeOut);
}
handleLatestChainData (latestChainInfo: _ChainInfo[]) {
try {
if (latestChainInfo && latestChainInfo.length > 0) {
const { needUpdateChainApiList, storedChainInfoList } = updateLatestChainInfo(this.dataMap, latestChainInfo);
this.dbService.bulkUpdateChainStore(storedChainInfoList).catch(console.error);
this.updateChainSubscription();
needUpdateChainApiList.forEach((chainInfo) => {
console.log('Updating chain API for', chainInfo.slug);
this.initApiForChain(chainInfo).catch(console.error);
});
this.logger.log('Finished updating latest RPC providers');
}
} catch (e) {
console.error('Error fetching latest chain data');
}
}
handleLatestAssetRef (latestBlockedAssetRefList: string[], latestAssetRefMap: Record<string, _AssetRef> | null) {
const updatedAssetRefMap: Record<string, _AssetRef> = { ...AssetRefMap };
if (latestAssetRefMap) {
for (const [assetRefKey, assetRef] of Object.entries(latestAssetRefMap)) {
updatedAssetRefMap[assetRefKey] = assetRef;
}
}
latestBlockedAssetRefList.forEach((blockedAssetRef) => {
delete updatedAssetRefMap[blockedAssetRef];
});
this.dataMap.assetRefMap = updatedAssetRefMap;
this.xcmRefMapSubject.next(this.xcmRefMap);
this.swapRefMapSubject.next(this.swapRefMap);
this.logger.log('Finished updating latest asset ref');
}
handleLatestPriceId (latestPriceIds: Record<string, string | null>) {
let isUpdated = false;
Object.entries(latestPriceIds).forEach(([slug, priceId]) => {
if (this.dataMap.assetRegistry[slug] && this.dataMap.assetRegistry[slug].priceId !== priceId) {
isUpdated = true;
this.dataMap.assetRegistry[slug].priceId = priceId;
}
});
if (isUpdated) {
this.assetRegistrySubject.next(this.dataMap.assetRegistry);
this.eventService.emit('asset.updateState', '');
}
this.logger.log('Finished updating latest price IDs');
}
handleLatestAssetData (latestAssetInfo: Record<string, _ChainAsset> | null, latestAssetLogoMap: Record<string, string> | null) {
try {
if (latestAssetInfo) {
const latestAssetPatch = JSON.stringify(latestAssetInfo);
if (this.assetMapPatch !== latestAssetPatch) {
const assetRegistry = { ...ChainAssetMap, ...latestAssetInfo };
this.assetMapPatch = latestAssetPatch;
this.dataMap.assetRegistry = assetRegistry;
this.assetRegistrySubject.next(assetRegistry);
this.autoEnableTokens()
.then(() => {
this.eventService.emit('asset.updateState', '');
})
.catch(console.error);
}
}
if (latestAssetLogoMap) {
const latestAssetLogoPatch = JSON.stringify(latestAssetLogoMap);
if (this.assetLogoPatch !== latestAssetLogoPatch) {
const logoMap = { ...AssetLogoMap, ...latestAssetLogoMap };
this.assetLogoPatch = latestAssetLogoPatch;
this.assetLogoMapSubject.next(logoMap);
}
}
if (latestAssetLogoMap) {
const latestAssetLogoPatch = JSON.stringify(latestAssetLogoMap);
if (this.assetLogoPatch !== latestAssetLogoPatch) {
const logoMap = { ...AssetLogoMap, ...latestAssetLogoMap };
this.assetLogoPatch = latestAssetLogoPatch;
this.assetLogoMapSubject.next(logoMap);
}
}
} catch (e) {
console.error('Error fetching latest asset data');
}
this.eventService.emit('asset.online.ready', true);
this.logger.log('Finished updating latest asset');
}
async autoEnableTokens () {
const autoEnableTokens = Object.values(this.dataMap.assetRegistry).filter((asset) => _isAssetAutoEnable(asset));
const assetSettings = this.assetSettingSubject.value;
const chainStateMap = this.getChainStateMap();
for (const asset of autoEnableTokens) {
const { originChain, slug: assetSlug } = asset;
const assetState = assetSettings[assetSlug];
const chainState = chainStateMap[originChain];
if (!assetState) { // If this asset not has asset setting, this token is not enabled before (not turned off before)
if (!chainState || !chainState.manualTurnOff) {
await this.updateAssetSetting(assetSlug, { visible: true });
}
}
}
}
handleLatestData () {
this.fetchLatestAssetData().then(([latestAssetInfo, latestAssetLogoMap]) => {
this.eventService.waitAssetReady
.then(() => {
this.handleLatestAssetData(latestAssetInfo, latestAssetLogoMap);
})
.catch(console.error);
}).catch(console.error);
this.fetchLatestChainData().then((latestChainInfo) => {
this.handleLatestChainData(latestChainInfo);
}).catch(console.error);
this.fetchLatestAssetRef().then(([latestAssetRef, latestAssetRefMap]) => {
this.handleLatestAssetRef(latestAssetRef, latestAssetRefMap);
}).catch(console.error);
this.fetchLatestPriceIdsData().then((latestPriceIds) => {
this.handleLatestPriceId(latestPriceIds);
}).catch(console.error);
}
private async initApis () {
const chainInfoMap = this.getChainInfoMap();
const chainStateMap = this.getChainStateMap();
await Promise.all(Object.entries(chainInfoMap)
.filter(([slug]) => chainStateMap[slug]?.active)
.map(([, chainInfo]) => {
try {
return this.initApiForChain(chainInfo);
} catch (e) {
console.error(e);
return Promise.resolve();
}
}));
}
public async initSingleApi (slug: string) {
const chainInfoMap = this.getChainInfoMap();
const chainStateMap = this.getChainStateMap();
if (!chainStateMap[slug].active) {
return false;
}
await this.initApiForChain(chainInfoMap[slug]);
return true;
}
private async initApiForChain (chainInfo: _ChainInfo) {
const { endpoint, providerName } = this.getChainCurrentProviderByKey(chainInfo.slug);
/**
* Disable chain if not found provider
* */
if (!endpoint && !providerName) {
this.disableChain(chainInfo.slug);
return;
}
const onUpdateStatus = (status: _ChainConnectionStatus) => {
const slug = chainInfo.slug;
this.updateChainConnectionStatus(slug, status);
};
if (chainInfo.substrateInfo !== null && chainInfo.substrateInfo !== undefined) {
if (_MANTA_ZK_CHAIN_GROUP.includes(chainInfo.slug) && MODULE_SUPPORT.MANTA_ZK && this.mantaChainHandler) {
const apiPromise = await this.mantaChainHandler?.initMantaPay(endpoint, chainInfo.slug);
const chainApi = await this.substrateChainHandler.initApi(chainInfo.slug, endpoint, { providerName, externalApiPromise: apiPromise, onUpdateStatus });
this.substrateChainHandler.setSubstrateApi(chainInfo.slug, chainApi);
} else {
const chainApi = await this.substrateChainHandler.initApi(chainInfo.slug, endpoint, { providerName, onUpdateStatus });
this.substrateChainHandler.setSubstrateApi(chainInfo.slug, chainApi);
}
}
/**
* To check if the chain is EVM chain, we need to check if the chain has evmInfo and evmChainId is not -1
* (fake evm chain to connect to substrate chain)
* */
if (chainInfo.evmInfo !== null && chainInfo.evmInfo !== undefined && chainInfo.evmInfo.evmChainId !== -1) {
const chainApi = await this.evmChainHandler.initApi(chainInfo.slug, endpoint, { providerName, onUpdateStatus });
this.evmChainHandler.setEvmApi(chainInfo.slug, chainApi);
}
}
private destroyApiForChain (chainInfo: _ChainInfo) {
if (chainInfo.substrateInfo !== null) {
this.substrateChainHandler.destroySubstrateApi(chainInfo.slug);
}
if (chainInfo.evmInfo !== null) {
this.evmChainHandler.destroyEvmApi(chainInfo.slug);
}
}
public async enableChain (chainSlug: string) {
const chainInfo = this.getChainInfoByKey(chainSlug);
const chainStateMap = this.getChainStateMap();
if (chainStateMap[chainSlug].active || this.lockChainInfoMap) {
return false;
}
this.lockChainInfoMap = true;
this.dbService.updateChainStore({
...chainInfo,
active: true,
currentProvider: chainStateMap[chainSlug].currentProvider,
manualTurnOff: !!chainStateMap[chainSlug].manualTurnOff
}).catch(console.error);
chainStateMap[chainSlug].active = true;
await this.initApiForChain(chainInfo);
this.lockChainInfoMap = false;
this.eventService.emit('chain.updateState', chainSlug);
this.updateChainStateMapSubscription();
return true;
}
public async enableChains (chainSlugs: string[]): Promise<boolean> {
const chainInfoMap = this.getChainInfoMap();
const chainStateMap = this.getChainStateMap();
let needUpdate = false;
if (this.lockChainInfoMap) {
return false;
}
this.lockChainInfoMap = true;
const initPromises = chainSlugs.map(async (chainSlug) => {
// Add try catch to prevent one chain error stop the whole process
try {
const chainInfo = chainInfoMap[chainSlug];
const currentState = chainStateMap[chainSlug]?.active;
if (!currentState) {
// Enable chain success then update chain state
await this.initApiForChain(chainInfo);
this.dbService.updateChainStore({
...chainInfo,
active: true,
currentProvider: chainStateMap[chainSlug].currentProvider,
manualTurnOff: !!chainStateMap[chainSlug].manualTurnOff
}).catch(console.error);
chainStateMap[chainSlug].active = true;
this.eventService.emit('chain.updateState', chainSlug);
needUpdate = true;
}
} catch (e) {}
});
await Promise.all(initPromises);
this.lockChainInfoMap = false;
needUpdate && this.updateChainStateMapSubscription();
return needUpdate;
}
public async reconnectChain (chain: string) {
await this.getSubstrateApi(chain)?.recoverConnect();
await this.getEvmApi(chain)?.recoverConnect();
return true;
}
public disableChain (chainSlug: string): boolean {
const chainInfo = this.getChainInfoByKey(chainSlug);
const chainStateMap = this.getChainStateMap();
if (!chainStateMap[chainSlug].active || this.lockChainInfoMap) {
return false;
}
this.lockChainInfoMap = true;
chainStateMap[chainSlug].active = false;
chainStateMap[chainSlug].manualTurnOff = true;
// Set disconnect state for inactive chain
this.updateChainConnectionStatus(chainSlug, _ChainConnectionStatus.DISCONNECTED);
this.destroyApiForChain(chainInfo);
this.dbService.updateChainStore({
...chainInfo,
active: false,
currentProvider: chainStateMap[chainSlug].currentProvider,
manualTurnOff: true
}).catch(console.error);
this.updateChainStateMapSubscription();
this.lockChainInfoMap = false;
this.eventService.emit('chain.updateState', chainSlug);
return true;
}
private checkExistedPredefinedChain (latestChainInfoMap: Record<string, _ChainInfo>, genesisHash?: string, evmChainId?: number) {
let duplicatedSlug = '';
if (genesisHash) {
Object.values(latestChainInfoMap).forEach((chainInfo) => {
if (chainInfo.substrateInfo && chainInfo.substrateInfo.genesisHash === genesisHash) {
duplicatedSlug = chainInfo.slug;
}
});
} else if (evmChainId) {
Object.values(latestChainInfoMap).forEach((chainInfo) => {
if (chainInfo.evmInfo && chainInfo.evmInfo.evmChainId === evmChainId) {
duplicatedSlug = chainInfo.slug;
}
});
}
return duplicatedSlug;
}