@subwallet/extension-base 1.0.1 → 1.0.2-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/background/KoniTypes.d.ts +10 -3
  2. package/background/KoniTypes.js +6 -0
  3. package/cjs/background/KoniTypes.js +8 -1
  4. package/cjs/constants/index.js +6 -3
  5. package/cjs/koni/api/dotsama/balance.js +11 -0
  6. package/cjs/koni/api/staking/bonding/amplitude.js +6 -2
  7. package/cjs/koni/api/staking/bonding/astar.js +40 -243
  8. package/cjs/koni/api/staking/bonding/index.js +4 -4
  9. package/cjs/koni/api/staking/bonding/paraChain.js +16 -10
  10. package/cjs/koni/api/staking/bonding/relayChain.js +62 -7
  11. package/cjs/koni/api/staking/bonding/utils.js +29 -3
  12. package/cjs/koni/api/xcm/index.js +0 -111
  13. package/cjs/koni/api/xcm/polkadotXcm.js +1 -1
  14. package/cjs/koni/api/xcm/xTokens.js +2 -4
  15. package/cjs/koni/background/cron.js +61 -62
  16. package/cjs/koni/background/handlers/Extension.js +143 -149
  17. package/cjs/koni/background/handlers/State.js +129 -91
  18. package/cjs/koni/background/handlers/Tabs.js +40 -38
  19. package/cjs/koni/background/subscription.js +48 -43
  20. package/cjs/packageInfo.js +1 -1
  21. package/cjs/page/index.js +5 -0
  22. package/cjs/services/chain-service/constants.js +1 -11
  23. package/cjs/services/chain-service/index.js +39 -5
  24. package/cjs/services/chain-service/utils.js +4 -0
  25. package/cjs/services/event-service/index.js +71 -0
  26. package/cjs/services/event-service/types.js +1 -0
  27. package/cjs/services/history-service/index.js +36 -17
  28. package/cjs/services/history-service/subsquid-multi-chain-history.js +7 -2
  29. package/cjs/services/keyring-service/index.js +101 -0
  30. package/cjs/services/migration-service/index.js +13 -10
  31. package/cjs/{koni/migration/scripts/RemoveWrongCrowdloan.js → services/migration-service/scripts/AutoEnableChainsTokens.js} +11 -6
  32. package/cjs/services/migration-service/scripts/MigrateNetworkSettings.js +39 -19
  33. package/cjs/services/migration-service/scripts/MigrateSettings.js +31 -0
  34. package/cjs/services/migration-service/scripts/MigrateTransactionHistory.js +72 -0
  35. package/cjs/services/migration-service/scripts/index.js +13 -4
  36. package/cjs/services/price-service/coingecko.js +16 -3
  37. package/cjs/services/price-service/index.js +15 -17
  38. package/cjs/services/request-service/constants.js +8 -2
  39. package/cjs/services/request-service/handler/AuthRequestHandler.js +39 -12
  40. package/cjs/services/request-service/index.js +3 -0
  41. package/cjs/services/storage-service/DatabaseService.js +1 -1
  42. package/cjs/services/storage-service/databases/index.js +1 -1
  43. package/cjs/services/storage-service/db-stores/BaseStoreWithAddressAndChain.js +2 -8
  44. package/cjs/services/storage-service/db-stores/Nft.js +4 -1
  45. package/cjs/services/storage-service/db-stores/Transaction.js +10 -7
  46. package/cjs/services/subscan-service/index.js +107 -0
  47. package/cjs/services/subscan-service/subscan-chain-map.js +74 -0
  48. package/cjs/services/subscan-service/types.js +1 -0
  49. package/cjs/services/transaction-service/index.js +45 -10
  50. package/cjs/services/transaction-service/utils.js +4 -6
  51. package/cjs/utils/address.js +9 -1
  52. package/cjs/utils/index.js +24 -13
  53. package/constants/index.d.ts +1 -0
  54. package/constants/index.js +1 -0
  55. package/koni/api/dotsama/balance.js +11 -0
  56. package/koni/api/staking/bonding/amplitude.d.ts +1 -1
  57. package/koni/api/staking/bonding/amplitude.js +8 -4
  58. package/koni/api/staking/bonding/astar.d.ts +2 -11
  59. package/koni/api/staking/bonding/astar.js +35 -229
  60. package/koni/api/staking/bonding/index.d.ts +1 -1
  61. package/koni/api/staking/bonding/index.js +4 -4
  62. package/koni/api/staking/bonding/paraChain.d.ts +1 -1
  63. package/koni/api/staking/bonding/paraChain.js +17 -11
  64. package/koni/api/staking/bonding/relayChain.d.ts +1 -1
  65. package/koni/api/staking/bonding/relayChain.js +63 -8
  66. package/koni/api/staking/bonding/utils.d.ts +13 -1
  67. package/koni/api/staking/bonding/utils.js +27 -3
  68. package/koni/api/xcm/index.js +1 -112
  69. package/koni/api/xcm/polkadotXcm.js +1 -1
  70. package/koni/api/xcm/xTokens.js +3 -5
  71. package/koni/background/cron.js +60 -60
  72. package/koni/background/handlers/Extension.js +71 -76
  73. package/koni/background/handlers/State.d.ts +16 -14
  74. package/koni/background/handlers/State.js +126 -91
  75. package/koni/background/handlers/Tabs.js +22 -19
  76. package/koni/background/subscription.d.ts +1 -1
  77. package/koni/background/subscription.js +49 -44
  78. package/package.json +56 -16
  79. package/packageInfo.js +1 -1
  80. package/page/index.d.ts +2 -0
  81. package/page/index.js +4 -0
  82. package/services/chain-service/constants.d.ts +0 -1
  83. package/services/chain-service/constants.js +0 -9
  84. package/services/chain-service/index.d.ts +6 -4
  85. package/services/chain-service/index.js +39 -7
  86. package/services/chain-service/utils.d.ts +1 -0
  87. package/services/chain-service/utils.js +3 -0
  88. package/services/event-service/index.d.ts +22 -0
  89. package/services/event-service/index.js +59 -0
  90. package/services/event-service/types.d.ts +32 -0
  91. package/services/event-service/types.js +1 -0
  92. package/services/history-service/index.d.ts +5 -3
  93. package/services/history-service/index.js +36 -17
  94. package/services/history-service/subsquid-multi-chain-history.js +7 -2
  95. package/services/keyring-service/index.d.ts +19 -0
  96. package/services/keyring-service/index.js +93 -0
  97. package/services/migration-service/index.js +11 -9
  98. package/services/migration-service/scripts/AutoEnableChainsTokens.d.ts +4 -0
  99. package/services/migration-service/scripts/AutoEnableChainsTokens.js +13 -0
  100. package/services/migration-service/scripts/MigrateNetworkSettings.js +37 -18
  101. package/services/migration-service/scripts/MigrateSettings.d.ts +4 -0
  102. package/services/migration-service/scripts/MigrateSettings.js +23 -0
  103. package/services/migration-service/scripts/MigrateTransactionHistory.d.ts +4 -0
  104. package/services/migration-service/scripts/MigrateTransactionHistory.js +64 -0
  105. package/services/migration-service/scripts/index.d.ts +1 -0
  106. package/services/migration-service/scripts/index.js +10 -3
  107. package/services/price-service/coingecko.js +16 -3
  108. package/services/price-service/index.d.ts +5 -3
  109. package/services/price-service/index.js +15 -17
  110. package/services/request-service/constants.d.ts +1 -0
  111. package/services/request-service/constants.js +6 -1
  112. package/services/request-service/handler/AuthRequestHandler.d.ts +8 -1
  113. package/services/request-service/handler/AuthRequestHandler.js +40 -13
  114. package/services/request-service/index.d.ts +7 -1
  115. package/services/request-service/index.js +3 -0
  116. package/services/storage-service/DatabaseService.js +1 -1
  117. package/services/storage-service/databases/index.js +1 -1
  118. package/services/storage-service/db-stores/BaseStoreWithAddressAndChain.d.ts +1 -1
  119. package/services/storage-service/db-stores/BaseStoreWithAddressAndChain.js +2 -8
  120. package/services/storage-service/db-stores/Nft.d.ts +2 -1
  121. package/services/storage-service/db-stores/Nft.js +4 -1
  122. package/services/storage-service/db-stores/Transaction.js +10 -7
  123. package/services/subscan-service/index.d.ts +20 -0
  124. package/services/subscan-service/index.js +99 -0
  125. package/services/subscan-service/subscan-chain-map.d.ts +5 -0
  126. package/services/subscan-service/subscan-chain-map.js +63 -0
  127. package/services/subscan-service/types.d.ts +27 -0
  128. package/services/subscan-service/types.js +1 -0
  129. package/services/transaction-service/event-parser/index.d.ts +2 -2
  130. package/services/transaction-service/index.d.ts +4 -2
  131. package/services/transaction-service/index.js +45 -10
  132. package/services/transaction-service/utils.js +5 -6
  133. package/utils/address.d.ts +1 -0
  134. package/utils/address.js +9 -2
  135. package/utils/index.d.ts +1 -0
  136. package/utils/index.js +21 -12
  137. package/cjs/background/errors/EvmRpcError.js +0 -21
  138. package/cjs/background/errors/SubWalletProviderError.js +0 -17
  139. package/cjs/constants/ethereum.js +0 -19
  140. package/cjs/errors/SubWalletProviderError.js +0 -17
  141. package/cjs/koni/api/xcm/astar.js +0 -160
  142. package/cjs/koni/api/xcm/moonbeamXcm.js +0 -80
  143. package/cjs/koni/api/xcm/statemintXcm.js +0 -197
  144. package/cjs/koni/api/xcm/substrateXcm.js +0 -213
  145. package/cjs/koni/migration/Base.js +0 -20
  146. package/cjs/koni/migration/index.js +0 -45
  147. package/cjs/koni/migration/scripts/ChangeRouteToHome.js +0 -22
  148. package/cjs/koni/migration/scripts/ClearOldStorage.js +0 -24
  149. package/cjs/koni/migration/scripts/RemoveWrongTransactionHistoriesFromStore.js +0 -36
  150. package/cjs/koni/migration/scripts/ResetTransactionHistoryEventIdx.js +0 -21
  151. package/cjs/koni/migration/scripts/index.js +0 -22
  152. package/cjs/koni/page/index.js +0 -16
  153. package/cjs/services/asset-service/index.js +0 -91
  154. package/cjs/services/storage-service/db-stores/ExtraDelegationInfo.js +0 -17
  155. package/cjs/stores/Balance.js +0 -18
  156. package/cjs/stores/Crowdloan.js +0 -18
  157. package/cjs/stores/CustomEvmToken.js +0 -18
  158. package/cjs/stores/NetworkMap.js +0 -18
  159. package/cjs/stores/Nft.js +0 -18
  160. package/cjs/stores/NftCollection.js +0 -18
  161. package/cjs/stores/Price.js +0 -18
  162. package/cjs/stores/Staking.js +0 -18
  163. package/cjs/stores/StakingReward.js +0 -18
  164. package/cjs/utils/eth/parseTransactionData.js +0 -284
  165. package/koni/page/index.d.ts +0 -2
  166. package/koni/page/index.js +0 -9
  167. /package/cjs/{koni/page → page}/SubWalleEvmProvider.js +0 -0
  168. /package/{koni/page → page}/SubWalleEvmProvider.d.ts +0 -0
  169. /package/{koni/page → page}/SubWalleEvmProvider.js +0 -0
@@ -11,15 +11,18 @@ import { BalanceService } from '@subwallet/extension-base/services/balance-servi
11
11
  import { ChainService } from '@subwallet/extension-base/services/chain-service';
12
12
  import { _PREDEFINED_SINGLE_MODES } from '@subwallet/extension-base/services/chain-service/constants';
13
13
  import { _getEvmChainId, _getSubstrateGenesisHash, _isAssetFungibleToken, _isChainEnabled, _isChainTestNet, _isSubstrateParachain, _parseMetadataForSmartContractAsset } from '@subwallet/extension-base/services/chain-service/utils';
14
+ import { EventService } from '@subwallet/extension-base/services/event-service';
14
15
  import { HistoryService } from '@subwallet/extension-base/services/history-service';
16
+ import { KeyringService } from '@subwallet/extension-base/services/keyring-service';
15
17
  import MigrationService from '@subwallet/extension-base/services/migration-service';
16
18
  import NotificationService from '@subwallet/extension-base/services/notification-service/NotificationService';
17
19
  import { PriceService } from '@subwallet/extension-base/services/price-service';
18
20
  import RequestService from '@subwallet/extension-base/services/request-service';
19
21
  import SettingService from '@subwallet/extension-base/services/setting-service/SettingService';
20
22
  import DatabaseService from '@subwallet/extension-base/services/storage-service/DatabaseService';
23
+ import { SubscanService } from '@subwallet/extension-base/services/subscan-service';
24
+ import { SUBSCAN_CHAIN_MAP_REVERSE } from '@subwallet/extension-base/services/subscan-service/subscan-chain-map';
21
25
  import TransactionService from '@subwallet/extension-base/services/transaction-service';
22
- import { CurrentAccountStore } from '@subwallet/extension-base/stores';
23
26
  import AccountRefStore from '@subwallet/extension-base/stores/AccountRef';
24
27
  import { isContractAddress, parseContractInput } from '@subwallet/extension-base/utils/eth/parseTransaction';
25
28
  import { decodePair } from '@subwallet/keyring/pair/decode';
@@ -54,15 +57,8 @@ const generateDefaultCrowdloanMap = () => {
54
57
  export default class KoniState {
55
58
  injectedProviders = new Map();
56
59
  unsubscriptionMap = {};
57
- currentAccountStore = new CurrentAccountStore();
58
60
  accountRefStore = new AccountRefStore();
59
- keyringStateSubject = new Subject();
60
61
  externalRequest = {};
61
- keyringState = {
62
- isReady: false,
63
- isLocked: true,
64
- hasMasterPassword: false
65
- };
66
62
  serviceInfoSubject = new Subject();
67
63
  balanceMap = {};
68
64
  balanceSubject = new Subject();
@@ -80,18 +76,20 @@ export default class KoniState {
80
76
  };
81
77
  lazyMap = {};
82
78
  ready = false;
83
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
84
79
  constructor(providers = {}) {
85
80
  this.providers = providers;
86
81
  this.dbService = new DatabaseService();
82
+ this.eventService = new EventService();
83
+ this.subscanService = new SubscanService();
84
+ this.keyringService = new KeyringService(this.eventService);
87
85
  this.notificationService = new NotificationService();
88
- this.chainService = new ChainService(this.dbService);
86
+ this.chainService = new ChainService(this.dbService, this.eventService);
89
87
  this.settingService = new SettingService();
90
88
  this.requestService = new RequestService(this.chainService, this.settingService);
91
- this.priceService = new PriceService(this.serviceInfoSubject, this.dbService, this.chainService);
89
+ this.priceService = new PriceService(this.dbService, this.eventService, this.chainService);
92
90
  this.balanceService = new BalanceService(this.chainService);
93
- this.historyService = new HistoryService(this.dbService, this.chainService);
94
- this.transactionService = new TransactionService(this.chainService, this.requestService, this.balanceService, this.historyService, this.notificationService, this.dbService);
91
+ this.historyService = new HistoryService(this.dbService, this.chainService, this.eventService);
92
+ this.transactionService = new TransactionService(this.chainService, this.eventService, this.requestService, this.balanceService, this.historyService, this.notificationService, this.dbService);
95
93
  this.migrationService = new MigrationService(this);
96
94
  this.subscription = new KoniSubscription(this, this.dbService);
97
95
  this.cron = new KoniCron(this, this.subscription, this.dbService);
@@ -198,8 +196,10 @@ export default class KoniState {
198
196
  await this.chainService.init();
199
197
  await this.migrationService.run();
200
198
  this.startSubscription();
201
- this.updateServiceInfo();
199
+ this.eventService.emit('chain.ready', true);
202
200
  this.onReady();
201
+ this.onAccountAdd();
202
+ this.onAccountRemove();
203
203
  this.logger.log('Done init state');
204
204
  }
205
205
  startSubscription() {
@@ -219,15 +219,8 @@ export default class KoniState {
219
219
  isReady() {
220
220
  return this.ready;
221
221
  }
222
- getKeyringState() {
223
- return this.keyringState;
224
- }
225
- subscribeKeyringState() {
226
- return this.keyringStateSubject;
227
- }
228
- setKeyringState(data, callback) {
229
- this.keyringStateSubject.next(data);
230
- this.keyringState = data;
222
+ updateKeyringState(isReady = true, callback) {
223
+ this.keyringService.updateKeyringState(isReady);
231
224
  callback && callback();
232
225
  }
233
226
  lazyNext = (key, callback) => {
@@ -285,7 +278,7 @@ export default class KoniState {
285
278
  return this.dbService.getNominatorMetadata();
286
279
  }
287
280
  async getStaking() {
288
- const addresses = await this.getDecodedAddresses();
281
+ const addresses = this.getDecodedAddresses();
289
282
  const stakings = await this.dbService.getStakings(addresses, this.activeChainSlugs);
290
283
  return {
291
284
  ready: true,
@@ -344,12 +337,12 @@ export default class KoniState {
344
337
  subscribeNftCollection() {
345
338
  return this.dbService.stores.nftCollection.subscribeNftCollection(this.activeChainSlugs);
346
339
  }
347
- async resetNft(newAddress) {
340
+ resetNft(newAddress) {
348
341
  this.getNft().then(data => this.nftSubject.next(data || {
349
342
  nftList: [],
350
343
  total: 0
351
344
  })).catch(e => this.logger.warn(e));
352
- const addresses = await this.getDecodedAddresses(newAddress);
345
+ const addresses = this.getDecodedAddresses(newAddress);
353
346
  this.dbService.subscribeNft(addresses, this.activeChainSlugs, nfts => {
354
347
  this.nftSubject.next({
355
348
  nftList: nfts,
@@ -368,7 +361,7 @@ export default class KoniState {
368
361
  return this.dbService.deleteNftCollection(chain, collectionId);
369
362
  }
370
363
  async getNft() {
371
- const addresses = await this.getDecodedAddresses();
364
+ const addresses = this.getDecodedAddresses();
372
365
  if (!addresses.length) {
373
366
  return;
374
367
  }
@@ -442,9 +435,6 @@ export default class KoniState {
442
435
  subscribeStakingReward() {
443
436
  return this.stakingRewardSubject;
444
437
  }
445
- getCurrentAccount(update) {
446
- this.currentAccountStore.get('CurrentAccountInfo', update);
447
- }
448
438
  setCurrentAccount(data, callback) {
449
439
  const {
450
440
  address,
@@ -454,7 +444,7 @@ export default class KoniState {
454
444
  ...data
455
445
  };
456
446
  if (address === ALL_ACCOUNT_KEY) {
457
- const pairs = keyring.getPairs();
447
+ const pairs = keyring.getAccounts();
458
448
  const pair = pairs[0];
459
449
  const pairGenesisHash = pair.meta.genesisHash;
460
450
  if (pairs.length > 1 || !pair) {
@@ -465,10 +455,8 @@ export default class KoniState {
465
455
  result.allGenesisHash = pairGenesisHash || undefined;
466
456
  }
467
457
  }
468
- this.currentAccountStore.set('CurrentAccountInfo', result, () => {
469
- this.updateServiceInfo();
470
- callback && callback();
471
- });
458
+ this.keyringService.setCurrentAccount(result);
459
+ callback && callback();
472
460
  }
473
461
  setAccountTie(address, genesisHash) {
474
462
  if (address !== ALL_ACCOUNT_KEY) {
@@ -479,12 +467,11 @@ export default class KoniState {
479
467
  genesisHash
480
468
  });
481
469
  }
482
- this.getCurrentAccount(accountInfo => {
483
- if (address === accountInfo.address) {
484
- accountInfo.currentGenesisHash = genesisHash || ALL_GENESIS_HASH;
485
- this.setCurrentAccount(accountInfo);
486
- }
487
- });
470
+ const accountInfo = this.keyringService.currentAccount;
471
+ if (address === accountInfo.address) {
472
+ accountInfo.currentGenesisHash = genesisHash || ALL_GENESIS_HASH;
473
+ this.setCurrentAccount(accountInfo);
474
+ }
488
475
  return true;
489
476
  }
490
477
  async switchEvmNetworkByUrl(shortenUrl, networkKey) {
@@ -507,9 +494,7 @@ export default class KoniState {
507
494
  const {
508
495
  address,
509
496
  currentGenesisHash
510
- } = await new Promise(resolve => {
511
- this.getCurrentAccount(resolve);
512
- });
497
+ } = this.keyringService.currentAccount;
513
498
  return this.requestService.addConfirmation(id, url, 'switchNetworkRequest', {
514
499
  networkKey,
515
500
  address: changeAddress
@@ -624,35 +609,28 @@ export default class KoniState {
624
609
  subscribeSettingsSubject() {
625
610
  return this.settingService.getSubject();
626
611
  }
627
- subscribeCurrentAccount() {
628
- return this.currentAccountStore.getSubject();
629
- }
630
612
  getAccountAddress() {
631
- return new Promise((resolve, reject) => {
632
- this.getCurrentAccount(account => {
633
- if (account) {
634
- resolve(account.address);
635
- } else {
636
- resolve(null);
637
- }
638
- });
639
- });
613
+ const address = this.keyringService.currentAccount.address;
614
+ if (address === '') {
615
+ return null;
616
+ }
617
+ return address;
640
618
  }
641
- async getDecodedAddresses(address) {
619
+ getDecodedAddresses(address) {
642
620
  let checkingAddress = address;
643
621
  if (!address) {
644
- checkingAddress = await this.getAccountAddress();
622
+ checkingAddress = this.getAccountAddress();
645
623
  }
646
624
  if (!checkingAddress) {
647
625
  return [];
648
626
  }
649
627
  if (checkingAddress === ALL_ACCOUNT_KEY) {
650
- return Object.keys(accounts.subject.value);
628
+ return this.getAllAddresses();
651
629
  }
652
630
  return [checkingAddress];
653
631
  }
654
632
  getAllAddresses() {
655
- return Object.keys(accounts.subject.value);
633
+ return keyring.getAccounts().map(account => account.address);
656
634
  }
657
635
  removeInactiveChainBalances(balanceMap) {
658
636
  const activeBalanceMap = {};
@@ -700,11 +678,11 @@ export default class KoniState {
700
678
  };
701
679
  this.publishCrowdloan(true);
702
680
  }
703
- async resetStaking(newAddress) {
681
+ resetStaking(newAddress) {
704
682
  this.getStaking().then(data => {
705
683
  this.stakingSubject.next(data);
706
684
  }).catch(e => this.logger.warn(e));
707
- const addresses = await this.getDecodedAddresses(newAddress);
685
+ const addresses = this.getDecodedAddresses(newAddress);
708
686
  this.dbService.subscribeStaking(addresses, this.activeChainSlugs, stakings => {
709
687
  this.stakingSubject.next({
710
688
  ready: true,
@@ -723,9 +701,8 @@ export default class KoniState {
723
701
  });
724
702
  }
725
703
  updateBalanceStore(item) {
726
- this.getCurrentAccount(currentAccountInfo => {
727
- this.dbService.updateBalanceStore(currentAccountInfo.address, item).catch(e => this.logger.warn(e));
728
- });
704
+ const currentAccountInfo = this.keyringService.currentAccount;
705
+ this.dbService.updateBalanceStore(currentAccountInfo.address, item).catch(e => this.logger.warn(e));
729
706
  }
730
707
  subscribeBalance() {
731
708
  return this.balanceSubject;
@@ -754,9 +731,8 @@ export default class KoniState {
754
731
  });
755
732
  }
756
733
  updateCrowdloanStore(networkKey, item) {
757
- this.getCurrentAccount(currentAccountInfo => {
758
- this.dbService.updateCrowdloanStore(networkKey, currentAccountInfo.address, item).catch(e => this.logger.warn(e));
759
- });
734
+ const currentAccountInfo = this.keyringService.currentAccount;
735
+ this.dbService.updateCrowdloanStore(networkKey, currentAccountInfo.address, item).catch(e => this.logger.warn(e));
760
736
  }
761
737
  subscribeCrowdloan() {
762
738
  return this.crowdloanSubject;
@@ -821,12 +797,11 @@ export default class KoniState {
821
797
  await this.chainService.updateAssetSetting(tokenSlug, {
822
798
  visible: true
823
799
  });
800
+ this.eventService.emit('asset.update', tokenSlug);
824
801
  }
825
- this.updateServiceInfo();
826
802
  }
827
803
  deleteCustomAssets(targetTokens) {
828
804
  this.chainService.deleteCustomAssets(targetTokens);
829
- this.updateServiceInfo();
830
805
  }
831
806
  async validateCustomChain(provider, existedChainSlug) {
832
807
  return await this.chainService.validateCustomChain(provider, existedChainSlug);
@@ -850,13 +825,10 @@ export default class KoniState {
850
825
  visible: true
851
826
  });
852
827
  }
853
- this.updateServiceInfo();
854
828
  return true;
855
829
  }
856
830
  removeCustomChain(networkKey) {
857
- const result = this.chainService.removeCustomChain(networkKey);
858
- this.updateServiceInfo();
859
- return result;
831
+ return this.chainService.removeCustomChain(networkKey);
860
832
  }
861
833
 
862
834
  // TODO: avoids turning off chains related to ledger account
@@ -882,17 +854,13 @@ export default class KoniState {
882
854
  async disableChain(chainSlug) {
883
855
  // const defaultChains = this.getDefaultNetworkKeys();
884
856
  await this.chainService.updateAssetSettingByChain(chainSlug, false);
885
- const result = this.chainService.disableChain(chainSlug);
886
- this.updateServiceInfo();
887
- return result;
857
+ return this.chainService.disableChain(chainSlug);
888
858
  }
889
859
  async enableChain(chainSlug, enableTokens = true) {
890
860
  if (enableTokens) {
891
861
  await this.chainService.updateAssetSettingByChain(chainSlug, true);
892
862
  }
893
- const result = this.chainService.enableChain(chainSlug);
894
- this.updateServiceInfo();
895
- return result;
863
+ return this.chainService.enableChain(chainSlug);
896
864
  }
897
865
  resetDefaultChains() {
898
866
  const defaultChains = this.getDefaultNetworkKeys();
@@ -933,17 +901,14 @@ export default class KoniState {
933
901
  subscribeServiceInfo() {
934
902
  return this.serviceInfoSubject;
935
903
  }
936
- updateServiceInfo() {
937
- this.logger.log('<---Update serviceInfo--->');
938
- this.getCurrentAccount(value => {
939
- this.serviceInfoSubject.next({
940
- chainInfoMap: this.chainService.getChainInfoMap(),
941
- chainApiMap: this.getApiMap(),
942
- currentAccountInfo: value,
943
- assetRegistry: this.chainService.getAssetRegistry(),
944
- chainStateMap: this.chainService.getChainStateMap()
945
- });
946
- });
904
+ getServiceInfo() {
905
+ return {
906
+ chainInfoMap: this.chainService.getChainInfoMap(),
907
+ chainApiMap: this.getApiMap(),
908
+ currentAccountInfo: this.keyringService.currentAccount,
909
+ assetRegistry: this.chainService.getAssetRegistry(),
910
+ chainStateMap: this.chainService.getChainStateMap()
911
+ };
947
912
  }
948
913
  getExternalRequestMap() {
949
914
  return this.externalRequest;
@@ -1374,4 +1339,74 @@ export default class KoniState {
1374
1339
  createUnsubscriptionHandle(id, unsubscribe) {
1375
1340
  this.unsubscriptionMap[id] = unsubscribe;
1376
1341
  }
1342
+ async autoEnableChains(addresses) {
1343
+ const assetMap = this.chainService.getAssetRegistry();
1344
+ const promiseList = addresses.map(address => {
1345
+ return this.subscanService.getMultiChainBalance(address).catch(e => {
1346
+ console.error(e);
1347
+ return null;
1348
+ });
1349
+ });
1350
+ const needEnableChains = [];
1351
+ const needActiveTokens = [];
1352
+ const currentAssetSettings = await this.chainService.getAssetSettings();
1353
+ const chainMap = this.chainService.getChainInfoMap();
1354
+ const balanceDataList = await Promise.all(promiseList);
1355
+ balanceDataList.forEach(balanceData => {
1356
+ balanceData && balanceData.forEach(({
1357
+ balance,
1358
+ bonded,
1359
+ category,
1360
+ locked,
1361
+ network,
1362
+ symbol
1363
+ }) => {
1364
+ var _currentAssetSettings;
1365
+ const chain = SUBSCAN_CHAIN_MAP_REVERSE[network];
1366
+ const chainInfo = chain ? chainMap[chain] : null;
1367
+ const balanceIsEmpty = (!balance || balance === '0') && !locked && locked === '0' && (!bonded || bonded === '0');
1368
+
1369
+ // Cancel if chain is not supported or is testnet or balance is 0
1370
+ if (!chainInfo || chainInfo.isTestnet || balanceIsEmpty) {
1371
+ return;
1372
+ }
1373
+ const tokenKey = `${chain}-${category === 'native' ? 'NATIVE' : 'LOCAL'}-${symbol.toUpperCase()}`;
1374
+ if (assetMap[tokenKey] && !((_currentAssetSettings = currentAssetSettings[tokenKey]) !== null && _currentAssetSettings !== void 0 && _currentAssetSettings.visible)) {
1375
+ needEnableChains.push(chain);
1376
+ needActiveTokens.push(tokenKey);
1377
+ currentAssetSettings[tokenKey] = {
1378
+ visible: true
1379
+ };
1380
+ }
1381
+ });
1382
+ });
1383
+ if (needActiveTokens.length) {
1384
+ this.chainService.enableChains(needEnableChains);
1385
+ this.chainService.setAssetSettings({
1386
+ ...currentAssetSettings
1387
+ });
1388
+ }
1389
+ }
1390
+ onAccountAdd() {
1391
+ this.eventService.on('account.add', address => {
1392
+ this.autoEnableChains([address]).catch(this.logger.error);
1393
+ });
1394
+ }
1395
+ onAccountRemove() {
1396
+ this.eventService.on('account.remove', address => {
1397
+ // Some separate service like historyService will listen to this event and remove inside that service
1398
+
1399
+ const stores = this.dbService.stores;
1400
+
1401
+ // Remove Balance
1402
+ stores.balance.removeAllByAddress(address).catch(console.error);
1403
+ stores.balance.removeAllByAddress(ALL_ACCOUNT_KEY).catch(console.error);
1404
+
1405
+ // Remove NFT
1406
+ stores.nft.deleteNftByAddress([address]).catch(console.error);
1407
+
1408
+ // Remove Staking Data
1409
+ stores.staking.removeAllByAddress(address).catch(console.error);
1410
+ });
1411
+ }
1377
1412
  }
@@ -216,31 +216,34 @@ export default class KoniTabs {
216
216
  const allAccounts = accountsObservable.subject.getValue();
217
217
  const accountList = transformAccountsV2(allAccounts, false, authInfo, 'evm').map(a => a.address);
218
218
  let accounts = [];
219
- this.#koniState.getCurrentAccount(({
220
- address
221
- }) => {
222
- if (address === ALL_ACCOUNT_KEY || !accountList.includes(address) || getAll) {
223
- accounts = accountList;
224
- } else if (address && accountList.includes(address)) {
225
- accounts = [address];
226
- }
227
- resolve(accounts);
228
- });
219
+ const address = this.#koniState.keyringService.currentAccount.address;
220
+ if (address === ALL_ACCOUNT_KEY || !accountList.includes(address) || getAll) {
221
+ accounts = accountList;
222
+ } else if (address && accountList.includes(address)) {
223
+ accounts = [address];
224
+ }
225
+ resolve(accounts);
229
226
  }).catch(console.error);
230
227
  });
231
228
  }
232
229
  async getEvmState(url) {
233
- let currentEvmNetworkKey;
230
+ let currentChain;
231
+ let autoActiveChain = false;
234
232
  if (url) {
235
233
  const authInfo = await this.getAuthInfo(url);
236
- currentEvmNetworkKey = authInfo === null || authInfo === void 0 ? void 0 : authInfo.currentEvmNetworkKey;
237
- }
238
- let currentEvmNetwork = currentEvmNetworkKey ? this.#koniState.getChainInfo(currentEvmNetworkKey) : undefined;
239
- if (currentEvmNetworkKey && !this.#koniState.getChainStateByKey(currentEvmNetworkKey).active) {
240
- currentEvmNetwork = Object.values(this.#koniState.getChainInfoMap()).find(network => {
241
- return network.evmInfo !== null && this.#koniState.getChainStateByKey(network.slug).active;
242
- });
234
+ if (authInfo !== null && authInfo !== void 0 && authInfo.currentEvmNetworkKey) {
235
+ currentChain = authInfo === null || authInfo === void 0 ? void 0 : authInfo.currentEvmNetworkKey;
236
+ }
237
+ if (authInfo !== null && authInfo !== void 0 && authInfo.isAllowed) {
238
+ autoActiveChain = true;
239
+ }
243
240
  }
241
+ const currentEvmNetwork = this.#koniState.requestService.getDAppChainInfo({
242
+ autoActive: autoActiveChain,
243
+ accessType: 'evm',
244
+ defaultChain: currentChain,
245
+ url
246
+ });
244
247
  if (currentEvmNetwork) {
245
248
  const {
246
249
  evmInfo,
@@ -437,7 +440,7 @@ export default class KoniTabs {
437
440
  currentAccountList = newAccountList;
438
441
  }
439
442
  };
440
- const accountListSubscription = this.#koniState.subscribeCurrentAccount().subscribe(() => {
443
+ const accountListSubscription = this.#koniState.keyringService.currentAccountSubject.subscribe(() => {
441
444
  onCurrentAccountChanged().catch(console.error);
442
445
  });
443
446
 
@@ -4,7 +4,7 @@ import DatabaseService from '@subwallet/extension-base/services/storage-service/
4
4
  import KoniState from './handlers/State';
5
5
  declare type SubscriptionName = 'balance' | 'crowdloan' | 'stakingOnChain';
6
6
  export declare class KoniSubscription {
7
- private serviceSubscription;
7
+ private eventHandler?;
8
8
  private subscriptionMap;
9
9
  dbService: DatabaseService;
10
10
  private state;
@@ -10,8 +10,9 @@ import { getRelayChainPoolMemberMetadata } from '@subwallet/extension-base/koni/
10
10
  import { getAmplitudeUnclaimedStakingReward } from '@subwallet/extension-base/koni/api/staking/paraChain';
11
11
  import { nftHandler } from '@subwallet/extension-base/koni/background/handlers';
12
12
  import { _STAKING_CHAIN_GROUP } from '@subwallet/extension-base/services/chain-service/constants';
13
- import { _isChainEnabled, _isChainSupportSubstrateStaking, _isSubstrateRelayChain } from '@subwallet/extension-base/services/chain-service/utils';
13
+ import { _isChainEnabled, _isChainEvmCompatible, _isChainSupportSubstrateStaking, _isSubstrateRelayChain } from '@subwallet/extension-base/services/chain-service/utils';
14
14
  import { logger as createLogger } from '@polkadot/util';
15
+ import { isEthereumAddress } from '@polkadot/util-crypto';
15
16
  export class KoniSubscription {
16
17
  subscriptionMap = {
17
18
  crowdloan: undefined,
@@ -50,19 +51,22 @@ export class KoniSubscription {
50
51
  }
51
52
  }
52
53
  start() {
54
+ var _this$state$keyringSe;
53
55
  this.logger.log('Starting subscription');
54
- this.state.getCurrentAccount(currentAccountInfo => {
55
- if (currentAccountInfo) {
56
- const {
57
- address
58
- } = currentAccountInfo;
59
- this.subscribeBalancesAndCrowdloans(address, this.state.getChainInfoMap(), this.state.getChainStateMap(), this.state.getSubstrateApiMap(), this.state.getEvmApiMap());
60
- this.subscribeStakingOnChain(address, this.state.getSubstrateApiMap());
61
- }
62
- });
63
- !this.serviceSubscription && (this.serviceSubscription = this.state.subscribeServiceInfo().subscribe({
64
- next: serviceInfo => {
56
+ const currentAddress = (_this$state$keyringSe = this.state.keyringService.currentAccount) === null || _this$state$keyringSe === void 0 ? void 0 : _this$state$keyringSe.address;
57
+ if (currentAddress) {
58
+ this.subscribeBalancesAndCrowdloans(currentAddress, this.state.getChainInfoMap(), this.state.getChainStateMap(), this.state.getSubstrateApiMap(), this.state.getEvmApiMap());
59
+ this.subscribeStakingOnChain(currentAddress, this.state.getSubstrateApiMap());
60
+ }
61
+ if (!this.eventHandler) {
62
+ const reloadEvents = ['account.add', 'account.remove', 'account.updateCurrent', 'chain.add', 'chain.update', 'chain.enable', 'asset.update', 'asset.enable', 'transaction.done', 'transaction.failed'];
63
+ this.eventHandler = (events, eventTypes) => {
65
64
  var _serviceInfo$currentA;
65
+ const serviceInfo = this.state.getServiceInfo();
66
+ const needReload = eventTypes.some(eT => reloadEvents.includes(eT));
67
+ if (!needReload) {
68
+ return;
69
+ }
66
70
  this.logger.log('ServiceInfo updated, restarting...');
67
71
  const address = (_serviceInfo$currentA = serviceInfo.currentAccountInfo) === null || _serviceInfo$currentA === void 0 ? void 0 : _serviceInfo$currentA.address;
68
72
  if (!address) {
@@ -70,14 +74,14 @@ export class KoniSubscription {
70
74
  }
71
75
  this.subscribeBalancesAndCrowdloans(address, serviceInfo.chainInfoMap, serviceInfo.chainStateMap, serviceInfo.chainApiMap.substrate, serviceInfo.chainApiMap.evm);
72
76
  this.subscribeStakingOnChain(address, serviceInfo.chainApiMap.substrate);
73
- }
74
- }));
77
+ };
78
+ this.state.eventService.onLazy(this.eventHandler);
79
+ }
75
80
  }
76
81
  stop() {
77
82
  this.logger.log('Stopping subscription');
78
- if (this.serviceSubscription) {
79
- this.serviceSubscription.unsubscribe();
80
- this.serviceSubscription = undefined;
83
+ if (this.eventHandler) {
84
+ this.state.eventService.offLazy(this.eventHandler);
81
85
  }
82
86
  this.stopAllSubscription();
83
87
  }
@@ -104,24 +108,21 @@ export class KoniSubscription {
104
108
  }
105
109
  subscribeBalancesAndCrowdloans(address, chainInfoMap, chainStateMap, substrateApiMap, web3ApiMap, onlyRunOnFirstTime) {
106
110
  this.state.switchAccount(address).then(() => {
107
- this.state.getDecodedAddresses(address).then(addresses => {
108
- if (!addresses.length) {
109
- return;
110
- }
111
- this.updateSubscription('balance', this.initBalanceSubscription(addresses, chainInfoMap, chainStateMap, substrateApiMap, web3ApiMap, onlyRunOnFirstTime));
112
- this.updateSubscription('crowdloan', this.initCrowdloanSubscription(addresses, substrateApiMap, onlyRunOnFirstTime));
113
- }).catch(this.logger.error);
111
+ const addresses = this.state.getDecodedAddresses(address);
112
+ if (!addresses.length) {
113
+ return;
114
+ }
115
+ this.updateSubscription('balance', this.initBalanceSubscription(addresses, chainInfoMap, chainStateMap, substrateApiMap, web3ApiMap, onlyRunOnFirstTime));
116
+ this.updateSubscription('crowdloan', this.initCrowdloanSubscription(addresses, substrateApiMap, onlyRunOnFirstTime));
114
117
  }).catch(err => this.logger.warn(err));
115
118
  }
116
119
  subscribeStakingOnChain(address, substrateApiMap, onlyRunOnFirstTime) {
117
- this.state.resetStaking(address).then(() => {
118
- this.state.getDecodedAddresses(address).then(addresses => {
119
- if (!addresses.length) {
120
- return;
121
- }
122
- this.updateSubscription('stakingOnChain', this.initStakingOnChainSubscription(addresses, substrateApiMap, onlyRunOnFirstTime));
123
- }).catch(this.logger.error);
124
- }).catch(err => this.logger.warn(err));
120
+ this.state.resetStaking(address);
121
+ const addresses = this.state.getDecodedAddresses(address);
122
+ if (!addresses.length) {
123
+ return;
124
+ }
125
+ this.updateSubscription('stakingOnChain', this.initStakingOnChainSubscription(addresses, substrateApiMap, onlyRunOnFirstTime));
125
126
  }
126
127
  initStakingOnChainSubscription(addresses, substrateApiMap, onlyRunOnFirstTime) {
127
128
  const unsub = stakingOnChainApi(addresses, substrateApiMap, (networkKey, rs) => {
@@ -137,9 +138,9 @@ export class KoniSubscription {
137
138
  }
138
139
  initBalanceSubscription(addresses, chainInfoMap, chainStateMap, substrateApiMap, evmApiMap, onlyRunOnFirstTime) {
139
140
  const filteredChainInfoMap = {};
140
- Object.values(chainInfoMap).forEach(chainInfo => {
141
- if (chainStateMap[chainInfo.slug].active) {
142
- filteredChainInfoMap[chainInfo.slug] = chainInfo;
141
+ Object.values(chainStateMap).forEach(chainState => {
142
+ if (chainState.active) {
143
+ filteredChainInfoMap[chainState.slug] = chainInfoMap[chainState.slug];
143
144
  }
144
145
  });
145
146
  const unsub = subscribeBalance(addresses, filteredChainInfoMap, substrateApiMap, evmApiMap, result => {
@@ -166,12 +167,11 @@ export class KoniSubscription {
166
167
  };
167
168
  }
168
169
  subscribeNft(address, substrateApiMap, evmApiMap, smartContractNfts, chainInfoMap) {
169
- this.state.getDecodedAddresses(address).then(addresses => {
170
- if (!addresses.length) {
171
- return;
172
- }
173
- this.initNftSubscription(addresses, substrateApiMap, evmApiMap, smartContractNfts, chainInfoMap);
174
- }).catch(this.logger.error);
170
+ const addresses = this.state.getDecodedAddresses(address);
171
+ if (!addresses.length) {
172
+ return;
173
+ }
174
+ this.initNftSubscription(addresses, substrateApiMap, evmApiMap, smartContractNfts, chainInfoMap);
175
175
  }
176
176
  initNftSubscription(addresses, substrateApiMap, evmApiMap, smartContractNfts, chainInfoMap) {
177
177
  nftHandler.setChainInfoMap(chainInfoMap);
@@ -183,7 +183,7 @@ export class KoniSubscription {
183
183
  }).catch(this.logger.log);
184
184
  }
185
185
  async subscribeStakingReward(address) {
186
- const addresses = await this.state.getDecodedAddresses(address);
186
+ const addresses = this.state.getDecodedAddresses(address);
187
187
  if (!addresses.length) {
188
188
  return;
189
189
  }
@@ -200,7 +200,7 @@ export class KoniSubscription {
200
200
  this.logger.log('Set staking reward state done', result);
201
201
  }
202
202
  async subscribeStakingRewardFastInterval(address) {
203
- const addresses = await this.state.getDecodedAddresses(address);
203
+ const addresses = this.state.getDecodedAddresses(address);
204
204
  if (!addresses.length) {
205
205
  return;
206
206
  }
@@ -249,8 +249,13 @@ export class KoniSubscription {
249
249
  if (currentAddress === ALL_ACCOUNT_KEY) {
250
250
  addresses = await this.state.getStakingOwnersByChains(Object.keys(filteredChainInfoMap));
251
251
  }
252
- await Promise.all(addresses.map(async address => {
252
+ const validAddresses = addresses.filter(address => !isEthereumAddress(address));
253
+ await Promise.all(validAddresses.map(async address => {
254
+ const isEvmAddress = isEthereumAddress(address);
253
255
  await Promise.all(Object.values(filteredChainInfoMap).map(async chainInfo => {
256
+ if (isEvmAddress && !_isChainEvmCompatible(chainInfo)) {
257
+ return;
258
+ }
254
259
  if (_isSubstrateRelayChain(chainInfo) && _STAKING_CHAIN_GROUP.nominationPool.includes(chainInfo.slug)) {
255
260
  const poolMemberMetadata = await getRelayChainPoolMemberMetadata(chainInfo, address, substrateApiMap[chainInfo.slug]);
256
261
  if (poolMemberMetadata) {