@subwallet/extension-base 1.0.2-2 → 1.0.3-0

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 (151) hide show
  1. package/background/KoniTypes.d.ts +56 -40
  2. package/background/KoniTypes.js +11 -9
  3. package/background/errors/TransactionError.js +25 -1
  4. package/background/types.d.ts +10 -5
  5. package/cjs/background/KoniTypes.js +11 -9
  6. package/cjs/background/errors/TransactionError.js +24 -0
  7. package/cjs/constants/index.js +8 -26
  8. package/cjs/koni/api/dotsama/balance.js +49 -224
  9. package/cjs/koni/api/dotsama/transfer.js +34 -39
  10. package/cjs/koni/api/nft/acala_nft/index.js +7 -7
  11. package/cjs/koni/api/nft/bit.country/index.js +7 -6
  12. package/cjs/koni/api/nft/evm_nft/index.js +8 -3
  13. package/cjs/koni/api/nft/index.js +3 -6
  14. package/cjs/koni/api/nft/karura_nft/index.js +7 -6
  15. package/cjs/koni/api/nft/rmrk_nft/index.js +11 -1
  16. package/cjs/koni/api/nft/statemine_nft/index.js +7 -6
  17. package/cjs/koni/api/nft/unique_nft/index.js +5 -1
  18. package/cjs/koni/api/nft/wasm_nft/index.js +170 -111
  19. package/cjs/koni/api/nft/wasm_nft/utils.js +11 -7
  20. package/cjs/koni/api/staking/bonding/amplitude.js +13 -9
  21. package/cjs/koni/api/staking/bonding/astar.js +15 -13
  22. package/cjs/koni/api/staking/bonding/index.js +22 -10
  23. package/cjs/koni/api/staking/bonding/paraChain.js +85 -2
  24. package/cjs/koni/api/staking/bonding/relayChain.js +122 -16
  25. package/cjs/koni/api/staking/bonding/utils.js +27 -8
  26. package/cjs/koni/api/tokens/wasm/index.js +5 -4
  27. package/cjs/koni/api/tokens/wasm/utils.js +63 -0
  28. package/cjs/koni/api/xcm/polkadotXcm.js +1 -1
  29. package/cjs/koni/api/xcm/utils.js +18 -13
  30. package/cjs/koni/api/xcm/xTokens.js +1 -1
  31. package/cjs/koni/api/xcm/xcmPallet.js +9 -6
  32. package/cjs/koni/background/cron.js +171 -61
  33. package/cjs/koni/background/handlers/Extension.js +391 -207
  34. package/cjs/koni/background/handlers/State.js +49 -34
  35. package/cjs/koni/background/handlers/Tabs.js +50 -17
  36. package/cjs/koni/background/subscription.js +53 -28
  37. package/cjs/packageInfo.js +1 -1
  38. package/cjs/services/base/types.js +20 -0
  39. package/cjs/services/chain-service/handler/SubstrateChainHandler.js +13 -8
  40. package/cjs/services/chain-service/index.js +73 -49
  41. package/cjs/services/event-service/index.js +5 -1
  42. package/cjs/services/event-service/types.js +11 -1
  43. package/cjs/services/history-service/index.js +101 -50
  44. package/cjs/services/history-service/subsquid-multi-chain-history.js +13 -10
  45. package/cjs/services/keyring-service/index.js +11 -13
  46. package/cjs/services/migration-service/scripts/MigrateImportedToken.js +2 -1
  47. package/cjs/services/price-service/coingecko.js +0 -1
  48. package/cjs/services/price-service/index.js +71 -24
  49. package/cjs/services/request-service/handler/AuthRequestHandler.js +13 -7
  50. package/cjs/services/request-service/handler/EvmRequestHandler.js +8 -12
  51. package/cjs/services/request-service/index.js +14 -5
  52. package/cjs/services/storage-service/DatabaseService.js +66 -34
  53. package/cjs/services/storage-service/db-stores/Nft.js +7 -15
  54. package/cjs/services/storage-service/db-stores/Transaction.js +6 -10
  55. package/cjs/services/transaction-service/event-parser/index.js +20 -48
  56. package/cjs/services/transaction-service/index.js +104 -48
  57. package/cjs/services/transaction-service/utils.js +10 -8
  58. package/cjs/utils/address.js +10 -1
  59. package/cjs/utils/index.js +9 -15
  60. package/cjs/utils/promise.js +26 -0
  61. package/constants/index.d.ts +7 -13
  62. package/constants/index.js +7 -13
  63. package/koni/api/dotsama/balance.d.ts +0 -1
  64. package/koni/api/dotsama/balance.js +22 -197
  65. package/koni/api/dotsama/transfer.js +11 -16
  66. package/koni/api/nft/acala_nft/index.js +7 -7
  67. package/koni/api/nft/bit.country/index.js +7 -6
  68. package/koni/api/nft/evm_nft/index.js +7 -3
  69. package/koni/api/nft/index.d.ts +1 -2
  70. package/koni/api/nft/index.js +3 -6
  71. package/koni/api/nft/karura_nft/index.js +7 -6
  72. package/koni/api/nft/nft.d.ts +1 -0
  73. package/koni/api/nft/rmrk_nft/index.js +11 -1
  74. package/koni/api/nft/statemine_nft/index.js +7 -6
  75. package/koni/api/nft/unique_nft/index.js +5 -1
  76. package/koni/api/nft/wasm_nft/index.d.ts +0 -2
  77. package/koni/api/nft/wasm_nft/index.js +168 -109
  78. package/koni/api/nft/wasm_nft/utils.d.ts +7 -5
  79. package/koni/api/nft/wasm_nft/utils.js +7 -5
  80. package/koni/api/staking/bonding/amplitude.d.ts +0 -1
  81. package/koni/api/staking/bonding/amplitude.js +15 -10
  82. package/koni/api/staking/bonding/astar.js +8 -6
  83. package/koni/api/staking/bonding/index.d.ts +4 -1
  84. package/koni/api/staking/bonding/index.js +23 -13
  85. package/koni/api/staking/bonding/paraChain.d.ts +3 -0
  86. package/koni/api/staking/bonding/paraChain.js +86 -5
  87. package/koni/api/staking/bonding/relayChain.d.ts +5 -1
  88. package/koni/api/staking/bonding/relayChain.js +121 -18
  89. package/koni/api/staking/bonding/utils.d.ts +3 -2
  90. package/koni/api/staking/bonding/utils.js +27 -9
  91. package/koni/api/tokens/wasm/index.js +5 -4
  92. package/koni/api/tokens/wasm/utils.d.ts +6 -0
  93. package/koni/api/tokens/wasm/utils.js +54 -0
  94. package/koni/api/xcm/polkadotXcm.js +2 -2
  95. package/koni/api/xcm/utils.d.ts +5 -6
  96. package/koni/api/xcm/utils.js +15 -10
  97. package/koni/api/xcm/xTokens.js +2 -2
  98. package/koni/api/xcm/xcmPallet.js +10 -9
  99. package/koni/background/cron.d.ts +6 -1
  100. package/koni/background/cron.js +172 -62
  101. package/koni/background/handlers/Extension.d.ts +9 -3
  102. package/koni/background/handlers/Extension.js +306 -126
  103. package/koni/background/handlers/State.d.ts +5 -6
  104. package/koni/background/handlers/State.js +51 -34
  105. package/koni/background/handlers/Tabs.js +50 -17
  106. package/koni/background/subscription.d.ts +2 -0
  107. package/koni/background/subscription.js +51 -29
  108. package/package.json +29 -14
  109. package/packageInfo.js +1 -1
  110. package/services/base/types.d.ts +34 -0
  111. package/services/base/types.js +15 -0
  112. package/services/chain-service/handler/SubstrateChainHandler.js +14 -9
  113. package/services/chain-service/helper/psp22_abi.json +1041 -881
  114. package/services/chain-service/helper/psp34_abi.json +2963 -1807
  115. package/services/chain-service/index.d.ts +5 -2
  116. package/services/chain-service/index.js +68 -45
  117. package/services/chain-service/types.d.ts +1 -0
  118. package/services/event-service/index.js +5 -1
  119. package/services/event-service/types.d.ts +5 -9
  120. package/services/event-service/types.js +4 -1
  121. package/services/history-service/index.d.ts +28 -7
  122. package/services/history-service/index.js +101 -50
  123. package/services/history-service/subsquid-multi-chain-history.js +16 -12
  124. package/services/keyring-service/index.d.ts +4 -2
  125. package/services/keyring-service/index.js +11 -13
  126. package/services/migration-service/scripts/MigrateImportedToken.js +2 -1
  127. package/services/price-service/coingecko.js +0 -1
  128. package/services/price-service/index.d.ts +22 -1
  129. package/services/price-service/index.js +71 -24
  130. package/services/request-service/handler/AuthRequestHandler.d.ts +3 -1
  131. package/services/request-service/handler/AuthRequestHandler.js +13 -7
  132. package/services/request-service/handler/EvmRequestHandler.js +8 -12
  133. package/services/request-service/index.d.ts +3 -1
  134. package/services/request-service/index.js +14 -5
  135. package/services/storage-service/DatabaseService.d.ts +2 -0
  136. package/services/storage-service/DatabaseService.js +66 -34
  137. package/services/storage-service/db-stores/Nft.d.ts +2 -2
  138. package/services/storage-service/db-stores/Nft.js +7 -14
  139. package/services/storage-service/db-stores/Transaction.d.ts +2 -0
  140. package/services/storage-service/db-stores/Transaction.js +6 -10
  141. package/services/transaction-service/event-parser/index.js +21 -49
  142. package/services/transaction-service/index.d.ts +2 -0
  143. package/services/transaction-service/index.js +86 -32
  144. package/services/transaction-service/types.d.ts +2 -0
  145. package/services/transaction-service/utils.js +10 -8
  146. package/utils/address.d.ts +3 -0
  147. package/utils/address.js +8 -1
  148. package/utils/index.d.ts +2 -2
  149. package/utils/index.js +7 -13
  150. package/utils/promise.d.ts +6 -0
  151. package/utils/promise.js +20 -0
@@ -31,7 +31,6 @@ var _AccountRef = _interopRequireDefault(require("@subwallet/extension-base/stor
31
31
  var _parseTransaction = require("@subwallet/extension-base/utils/eth/parseTransaction");
32
32
  var _decode = require("@subwallet/keyring/pair/decode");
33
33
  var _uiKeyring = require("@subwallet/ui-keyring");
34
- var _accounts = require("@subwallet/ui-keyring/observable/accounts");
35
34
  var _ethSimpleKeyring = _interopRequireDefault(require("eth-simple-keyring"));
36
35
  var _rxjs = require("rxjs");
37
36
  var _util = require("@polkadot/util");
@@ -67,7 +66,6 @@ class KoniState {
67
66
  unsubscriptionMap = {};
68
67
  accountRefStore = new _AccountRef.default();
69
68
  externalRequest = {};
70
- serviceInfoSubject = new _rxjs.Subject();
71
69
  balanceMap = {};
72
70
  balanceSubject = new _rxjs.Subject();
73
71
  crowdloanMap = generateDefaultCrowdloanMap();
@@ -94,10 +92,10 @@ class KoniState {
94
92
  this.notificationService = new _NotificationService.default();
95
93
  this.chainService = new _chainService.ChainService(this.dbService, this.eventService);
96
94
  this.settingService = new _SettingService.default();
97
- this.requestService = new _requestService.default(this.chainService, this.settingService);
95
+ this.requestService = new _requestService.default(this.chainService, this.settingService, this.keyringService);
98
96
  this.priceService = new _priceService.PriceService(this.dbService, this.eventService, this.chainService);
99
97
  this.balanceService = new _balanceService.BalanceService(this.chainService);
100
- this.historyService = new _historyService.HistoryService(this.dbService, this.chainService, this.eventService);
98
+ this.historyService = new _historyService.HistoryService(this.dbService, this.chainService, this.eventService, this.keyringService);
101
99
  this.transactionService = new _transactionService.default(this.chainService, this.eventService, this.requestService, this.balanceService, this.historyService, this.notificationService, this.dbService);
102
100
  this.migrationService = new _migrationService.default(this);
103
101
  this.subscription = new _subscription.KoniSubscription(this, this.dbService);
@@ -223,6 +221,8 @@ class KoniState {
223
221
  onReady() {
224
222
  this.subscription.start();
225
223
  this.cron.start();
224
+ this.historyService.start().catch(console.error);
225
+ this.priceService.start().catch(console.error);
226
226
  this.ready = true;
227
227
  this.logger.log('State is ready');
228
228
  }
@@ -266,7 +266,7 @@ class KoniState {
266
266
  }
267
267
  getAddressList() {
268
268
  let value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
269
- const addressList = Object.keys(_accounts.accounts.subject.value);
269
+ const addressList = Object.keys(this.keyringService.accounts);
270
270
  return addressList.reduce((addressList, v) => ({
271
271
  ...addressList,
272
272
  [v]: value
@@ -309,7 +309,7 @@ class KoniState {
309
309
  return addresses;
310
310
  }
311
311
  async getPooledStakingRecordsByAddress(addresses) {
312
- return await this.dbService.getPooledStakings(addresses, this.activeChainSlugs);
312
+ return this.dbService.getPooledStakings(addresses, this.activeChainSlugs);
313
313
  }
314
314
 
315
315
  // TODO: delete later
@@ -367,12 +367,12 @@ class KoniState {
367
367
  this.dbService.addNft(address, nftData).catch(e => this.logger.warn(e));
368
368
  callback && callback(nftData);
369
369
  }
370
- removeNfts(chain, address, collectionId, nftIds) {
371
- return this.dbService.removeNfts(chain, address, collectionId, nftIds);
372
- }
373
370
  deleteNftCollection(chain, collectionId) {
374
371
  return this.dbService.deleteNftCollection(chain, collectionId);
375
372
  }
373
+ cleanUpNfts(chain, owner, collectionId, nftIds, ownNothing) {
374
+ this.dbService.cleanUpNft(chain, owner, collectionId, nftIds, ownNothing).catch(e => this.logger.warn(e));
375
+ }
376
376
  async getNft() {
377
377
  const addresses = this.getDecodedAddresses();
378
378
  if (!addresses.length) {
@@ -459,7 +459,7 @@ class KoniState {
459
459
  if (address === _constants.ALL_ACCOUNT_KEY) {
460
460
  const pairs = _uiKeyring.keyring.getAccounts();
461
461
  const pair = pairs[0];
462
- const pairGenesisHash = pair.meta.genesisHash;
462
+ const pairGenesisHash = (pair === null || pair === void 0 ? void 0 : pair.meta.genesisHash) || '';
463
463
  if (pairs.length > 1 || !pair) {
464
464
  result.allGenesisHash = currentGenesisHash || undefined;
465
465
  } else {
@@ -546,7 +546,11 @@ class KoniState {
546
546
  isApproved
547
547
  } = _ref4;
548
548
  if (isApproved) {
549
- await this.upsertChainInfo(networkData);
549
+ if (networkData.mode === 'insert') {
550
+ await this.upsertChainInfo(networkData);
551
+ } else {
552
+ // TODO: update existed network (need more discussion)
553
+ }
550
554
  return null;
551
555
  } else {
552
556
  throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.USER_REJECTED_REQUEST);
@@ -570,7 +574,8 @@ class KoniState {
570
574
  assetType: tokenInfo.type,
571
575
  metadata: (0, _utils._parseMetadataForSmartContractAsset)(tokenInfo.contractAddress),
572
576
  multiChainAsset: null,
573
- hasValue: (0, _utils._isChainTestNet)(this.chainService.getChainInfoByKey(tokenInfo.originChain))
577
+ hasValue: (0, _utils._isChainTestNet)(this.chainService.getChainInfoByKey(tokenInfo.originChain)),
578
+ icon: ''
574
579
  });
575
580
  return isApproved;
576
581
  } else {
@@ -673,7 +678,7 @@ class KoniState {
673
678
  const items = await this.dbService.stores.balance.getBalanceMapByAddress(address);
674
679
  return items || {};
675
680
  }
676
- async switchAccount(newAddress) {
681
+ async handleSwitchAccount(newAddress) {
677
682
  await Promise.all([this.resetBalanceMap(newAddress), this.resetCrowdloanMap(newAddress)]);
678
683
  }
679
684
  async resetBalanceMap(newAddress) {
@@ -754,9 +759,6 @@ class KoniState {
754
759
  subscribeCrowdloan() {
755
760
  return this.crowdloanSubject;
756
761
  }
757
- getAllPriceIds() {
758
- return this.chainService.getAllPriceIds();
759
- }
760
762
  getSmartContractNfts() {
761
763
  return this.chainService.getSmartContractNfts();
762
764
  }
@@ -814,7 +816,9 @@ class KoniState {
814
816
  await this.chainService.updateAssetSetting(tokenSlug, {
815
817
  visible: true
816
818
  });
817
- this.eventService.emit('asset.update', tokenSlug);
819
+ this.eventService.emit('asset.updateState', tokenSlug);
820
+ } else {
821
+ this.eventService.emit('asset.updateState', tokenSlug);
818
822
  }
819
823
  }
820
824
  deleteCustomAssets(targetTokens) {
@@ -841,6 +845,7 @@ class KoniState {
841
845
  await this.chainService.updateAssetSetting(newNativeTokenSlug, {
842
846
  visible: true
843
847
  });
848
+ this.eventService.emit('asset.updateState', newNativeTokenSlug);
844
849
  }
845
850
  return true;
846
851
  }
@@ -884,13 +889,6 @@ class KoniState {
884
889
  const defaultChains = this.getDefaultNetworkKeys();
885
890
  return this.chainService.resetChainInfoMap(defaultChains);
886
891
  }
887
- updateNetworkStatus(networkKey, status) {
888
- const chainState = this.chainService.getChainStateByKey(networkKey);
889
- if (chainState.connectionStatus === status) {
890
- return;
891
- }
892
- this.chainService.setChainConnectionStatus(networkKey, status);
893
- }
894
892
  getSubstrateApiMap() {
895
893
  return this.chainService.getSubstrateApiMap();
896
894
  }
@@ -916,9 +914,6 @@ class KoniState {
916
914
  refreshWeb3Api(key) {
917
915
  this.chainService.refreshEvmApi(key);
918
916
  }
919
- subscribeServiceInfo() {
920
- return this.serviceInfoSubject;
921
- }
922
917
  getServiceInfo() {
923
918
  return {
924
919
  chainInfoMap: this.chainService.getChainInfoMap(),
@@ -1020,8 +1015,9 @@ class KoniState {
1020
1015
  return [undefined, undefined];
1021
1016
  }
1022
1017
  const rs = Object.entries(this.chainService.getChainInfoMap()).find(_ref8 => {
1018
+ var _chainInfo$evmInfo;
1023
1019
  let [networkKey, chainInfo] = _ref8;
1024
- return (0, _utils._getEvmChainId)(chainInfo) === chainId;
1020
+ return (chainInfo === null || chainInfo === void 0 ? void 0 : (_chainInfo$evmInfo = chainInfo.evmInfo) === null || _chainInfo$evmInfo === void 0 ? void 0 : _chainInfo$evmInfo.evmChainId) === chainId;
1025
1021
  });
1026
1022
  if (rs) {
1027
1023
  return rs;
@@ -1259,17 +1255,23 @@ class KoniState {
1259
1255
  account: account,
1260
1256
  canSign: true
1261
1257
  };
1258
+ const eType = transaction.value ? _KoniTypes.ExtrinsicType.TRANSFER_BALANCE : _KoniTypes.ExtrinsicType.EVM_EXECUTE;
1259
+ const transactionData = {
1260
+ ...transaction
1261
+ };
1262
+ if (eType === _KoniTypes.ExtrinsicType.TRANSFER_BALANCE) {
1263
+ // @ts-ignore
1264
+ transactionData.tokenSlug = this.chainService.getNativeTokenInfo(networkKey).slug;
1265
+ }
1262
1266
 
1263
- // Todo: Convert this to handle transaction
1267
+ // Custom handle this instead of general handler transaction
1264
1268
  const transactionEmitter = await this.transactionService.addTransaction({
1265
1269
  transaction: requestPayload,
1266
1270
  address: requestPayload.from,
1267
1271
  chain: networkKey,
1268
1272
  url,
1269
- data: {
1270
- ...transaction
1271
- },
1272
- extrinsicType: transaction.value ? _KoniTypes.ExtrinsicType.TRANSFER_BALANCE : _KoniTypes.ExtrinsicType.EVM_EXECUTE,
1273
+ data: transactionData,
1274
+ extrinsicType: eType,
1273
1275
  chainType: _KoniTypes.ChainType.EVM
1274
1276
  });
1275
1277
 
@@ -1349,11 +1351,15 @@ class KoniState {
1349
1351
  this.cron.stop();
1350
1352
  this.subscription.stop();
1351
1353
  await this.pauseAllNetworks(undefined, 'IDLE mode');
1354
+ await this.historyService.stop();
1355
+ await this.priceService.stop();
1352
1356
  }
1353
1357
  async wakeup() {
1354
1358
  await this.resumeAllNetworks();
1355
1359
  this.cron.start();
1356
1360
  this.subscription.start();
1361
+ await this.historyService.start();
1362
+ await this.priceService.start();
1357
1363
  }
1358
1364
  cancelSubscription(id) {
1359
1365
  if ((0, _subscriptions.isSubscriptionRunning)(id)) {
@@ -1368,6 +1374,9 @@ class KoniState {
1368
1374
  createUnsubscriptionHandle(id, unsubscribe) {
1369
1375
  this.unsubscriptionMap[id] = unsubscribe;
1370
1376
  }
1377
+ updateChainConnectionStatus(chain, status) {
1378
+ this.chainService.setChainConnectionStatus(chain, status);
1379
+ }
1371
1380
  async autoEnableChains(addresses) {
1372
1381
  const assetMap = this.chainService.getAssetRegistry();
1373
1382
  const promiseList = addresses.map(address => {
@@ -1394,7 +1403,7 @@ class KoniState {
1394
1403
  } = _ref14;
1395
1404
  const chain = _subscanChainMap.SUBSCAN_CHAIN_MAP_REVERSE[network];
1396
1405
  const chainInfo = chain ? chainMap[chain] : null;
1397
- const balanceIsEmpty = (!balance || balance === '0') && !locked && locked === '0' && (!bonded || bonded === '0');
1406
+ const balanceIsEmpty = (!balance || balance === '0') && (!locked || locked === '0') && (!bonded || bonded === '0');
1398
1407
 
1399
1408
  // Cancel if chain is not supported or is testnet or balance is 0
1400
1409
  if (!chainInfo || chainInfo.isTestnet || balanceIsEmpty) {
@@ -1439,5 +1448,11 @@ class KoniState {
1439
1448
  stores.staking.removeAllByAddress(address).catch(console.error);
1440
1449
  });
1441
1450
  }
1451
+ async reloadNft() {
1452
+ return await this.cron.reloadNft();
1453
+ }
1454
+ async reloadStaking() {
1455
+ return await this.cron.reloadStaking();
1456
+ }
1442
1457
  }
1443
1458
  exports.default = KoniState;
@@ -17,7 +17,6 @@ var _defaults = require("@subwallet/extension-base/defaults");
17
17
  var _utils = require("@subwallet/extension-base/services/chain-service/utils");
18
18
  var _utils2 = require("@subwallet/extension-base/utils");
19
19
  var _uiKeyring = _interopRequireDefault(require("@subwallet/ui-keyring"));
20
- var _accounts = require("@subwallet/ui-keyring/observable/accounts");
21
20
  var _web = _interopRequireDefault(require("web3"));
22
21
  var _phishing = require("@polkadot/phishing");
23
22
  var _util = require("@polkadot/util");
@@ -220,14 +219,14 @@ class KoniTabs {
220
219
  anyType
221
220
  } = _ref10;
222
221
  const authInfo = await this.getAuthInfo(url);
223
- return transformAccountsV2(_accounts.accounts.subject.getValue(), anyType, authInfo, accountAuthType);
222
+ return transformAccountsV2(this.#koniState.keyringService.accounts, anyType, authInfo, accountAuthType);
224
223
  }
225
224
  accountsSubscribeV2(url, _ref11, id, port) {
226
225
  let {
227
226
  accountAuthType
228
227
  } = _ref11;
229
228
  const cb = (0, _subscriptions.createSubscription)(id, port);
230
- const subscription = _accounts.accounts.subject.subscribe(accounts => {
229
+ const subscription = this.#koniState.keyringService.accountSubject.subscribe(accounts => {
231
230
  this.getAuthInfo(url).then(authInfo => {
232
231
  cb(transformAccountsV2(accounts, false, authInfo, accountAuthType));
233
232
  }).catch(console.error);
@@ -253,7 +252,7 @@ class KoniTabs {
253
252
  let getAll = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
254
253
  return await new Promise(resolve => {
255
254
  this.getAuthInfo(url).then(authInfo => {
256
- const allAccounts = _accounts.accounts.subject.getValue();
255
+ const allAccounts = this.#koniState.keyringService.accounts;
257
256
  const accountList = transformAccountsV2(allAccounts, false, authInfo, 'evm').map(a => a.address);
258
257
  let accounts = [];
259
258
  const address = this.#koniState.keyringService.currentAccount.address;
@@ -290,18 +289,25 @@ class KoniTabs {
290
289
  slug
291
290
  } = currentEvmNetwork;
292
291
  const evmApi = this.#koniState.getEvmApi(slug);
293
- const web3 = evmApi.api;
294
- if (web3.currentProvider instanceof _web.default.providers.WebsocketProvider) {
292
+ const web3 = evmApi === null || evmApi === void 0 ? void 0 : evmApi.api;
293
+ if ((web3 === null || web3 === void 0 ? void 0 : web3.currentProvider) instanceof _web.default.providers.WebsocketProvider) {
295
294
  if (!web3.currentProvider.connected) {
296
295
  console.log(`[Web3] ${slug} is disconnected, trying to connect...`);
297
296
  this.#koniState.refreshWeb3Api(slug);
297
+ let checkingNum = 0;
298
298
  const poll = resolve => {
299
+ checkingNum += 1;
299
300
  if (web3.currentProvider.connected) {
300
301
  console.log(`Network [${slug}] is connected.`);
301
302
  resolve(true);
302
303
  } else {
303
304
  console.log(`Connecting to network [${slug}]`);
304
- setTimeout(() => poll(resolve), 400);
305
+ if (checkingNum < 10) {
306
+ setTimeout(() => poll(resolve), 900);
307
+ } else {
308
+ console.log(`Max retry, stop checking [${slug}]`);
309
+ resolve(false);
310
+ }
305
311
  }
306
312
  };
307
313
  await new Promise(poll);
@@ -371,12 +377,16 @@ class KoniTabs {
371
377
  contractAddress: input.options.address,
372
378
  originChain: chain
373
379
  });
374
- if (validate.isExist) {
375
- throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.INTERNAL_ERROR, 'Current token is existed');
376
- } else if (validate.contractError) {
380
+
381
+ // Below code is comment because we will handle exited token in the ui-view
382
+ // if (validate.isExist) {
383
+ // throw new EvmProviderError(EvmProviderErrorType.INTERNAL_ERROR, 'Current token is existed');
384
+ // } else
385
+ if (validate.contractError) {
377
386
  throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.INVALID_PARAMS, 'Contract address is invalid');
378
387
  }
379
388
  const tokenInfo = {
389
+ slug: validate === null || validate === void 0 ? void 0 : validate.existedSlug,
380
390
  type: tokenType,
381
391
  name: validate.name,
382
392
  contractAddress: input.options.address,
@@ -400,16 +410,38 @@ class KoniTabs {
400
410
  } = input[0];
401
411
  if (chainId) {
402
412
  const chainIdNum = parseInt(chainId, 16);
403
- const [networkKey] = this.#koniState.findNetworkKeyByChainId(chainIdNum);
404
- if (networkKey) {
413
+ const [existedNetworkSlug, existedChainInfo] = this.#koniState.findNetworkKeyByChainId(chainIdNum);
414
+ if (existedNetworkSlug && existedChainInfo && existedChainInfo !== null && existedChainInfo !== void 0 && existedChainInfo.evmInfo) {
415
+ const evmInfo = existedChainInfo.evmInfo;
416
+ const substrateInfo = existedChainInfo.substrateInfo;
417
+ const chainState = this.#koniState.getChainStateByKey(existedNetworkSlug);
418
+ await this.#koniState.addNetworkConfirm(id, url, {
419
+ mode: 'update',
420
+ chainSpec: {
421
+ evmChainId: evmInfo.evmChainId,
422
+ decimals: evmInfo.decimals,
423
+ existentialDeposit: evmInfo.existentialDeposit,
424
+ genesisHash: (substrateInfo === null || substrateInfo === void 0 ? void 0 : substrateInfo.genesisHash) || '',
425
+ paraId: (substrateInfo === null || substrateInfo === void 0 ? void 0 : substrateInfo.paraId) || null,
426
+ addressPrefix: (substrateInfo === null || substrateInfo === void 0 ? void 0 : substrateInfo.addressPrefix) || 0
427
+ },
428
+ chainEditInfo: {
429
+ blockExplorer: blockExplorerUrls === null || blockExplorerUrls === void 0 ? void 0 : blockExplorerUrls[0],
430
+ slug: existedNetworkSlug,
431
+ currentProvider: chainState.currentProvider,
432
+ providers: existedChainInfo.providers,
433
+ symbol: evmInfo.symbol,
434
+ chainType: 'EVM',
435
+ name: existedChainInfo.name
436
+ }
437
+ });
405
438
  return await this.switchEvmChain(id, url, {
406
439
  method: 'wallet_switchEthereumChain',
407
440
  params: [{
408
441
  chainId
409
442
  }]
410
443
  });
411
- }
412
- if (rpcUrls && chainName) {
444
+ } else if (rpcUrls && chainName) {
413
445
  const filteredUrls = rpcUrls.filter(targetString => {
414
446
  let url;
415
447
  try {
@@ -450,6 +482,8 @@ class KoniTabs {
450
482
  name: chainInfo.name
451
483
  }
452
484
  });
485
+ } else {
486
+ throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.INVALID_PARAMS, 'Invalid provider');
453
487
  }
454
488
  }
455
489
  }
@@ -710,9 +744,8 @@ class KoniTabs {
710
744
  if (e.code) {
711
745
  throw e;
712
746
  } else {
713
- // @ts-ignore
714
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
715
- throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.INTERNAL_ERROR, e.message);
747
+ console.error(e);
748
+ throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.INTERNAL_ERROR, e === null || e === void 0 ? void 0 : e.toString());
716
749
  }
717
750
  }
718
751
  }
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
3
4
  Object.defineProperty(exports, "__esModule", {
4
5
  value: true
5
6
  });
@@ -14,6 +15,8 @@ var _paraChain = require("@subwallet/extension-base/koni/api/staking/paraChain")
14
15
  var _handlers = require("@subwallet/extension-base/koni/background/handlers");
15
16
  var _constants2 = require("@subwallet/extension-base/services/chain-service/constants");
16
17
  var _utils = require("@subwallet/extension-base/services/chain-service/utils");
18
+ var _types = require("@subwallet/extension-base/services/event-service/types");
19
+ var _axios = _interopRequireDefault(require("axios"));
17
20
  var _util = require("@polkadot/util");
18
21
  var _utilCrypto = require("@polkadot/util-crypto");
19
22
  // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
@@ -64,30 +67,28 @@ class KoniSubscription {
64
67
  this.subscribeBalancesAndCrowdloans(currentAddress, this.state.getChainInfoMap(), this.state.getChainStateMap(), this.state.getSubstrateApiMap(), this.state.getEvmApiMap());
65
68
  this.subscribeStakingOnChain(currentAddress, this.state.getSubstrateApiMap());
66
69
  }
67
- if (!this.eventHandler) {
68
- const reloadEvents = ['account.add', 'account.remove', 'account.updateCurrent', 'chain.add', 'chain.update', 'chain.enable', 'asset.update', 'asset.enable', 'transaction.done', 'transaction.failed'];
69
- this.eventHandler = (events, eventTypes) => {
70
- var _serviceInfo$currentA;
71
- const serviceInfo = this.state.getServiceInfo();
72
- const needReload = eventTypes.some(eT => reloadEvents.includes(eT));
73
- if (!needReload) {
74
- return;
75
- }
76
- this.logger.log('ServiceInfo updated, restarting...');
77
- const address = (_serviceInfo$currentA = serviceInfo.currentAccountInfo) === null || _serviceInfo$currentA === void 0 ? void 0 : _serviceInfo$currentA.address;
78
- if (!address) {
79
- return;
80
- }
81
- this.subscribeBalancesAndCrowdloans(address, serviceInfo.chainInfoMap, serviceInfo.chainStateMap, serviceInfo.chainApiMap.substrate, serviceInfo.chainApiMap.evm);
82
- this.subscribeStakingOnChain(address, serviceInfo.chainApiMap.substrate);
83
- };
84
- this.state.eventService.onLazy(this.eventHandler);
85
- }
70
+ this.eventHandler = (events, eventTypes) => {
71
+ var _serviceInfo$currentA;
72
+ const serviceInfo = this.state.getServiceInfo();
73
+ const needReload = eventTypes.some(eventType => _types.COMMON_RELOAD_EVENTS.includes(eventType));
74
+ if (!needReload) {
75
+ return;
76
+ }
77
+ this.logger.log('ServiceInfo updated, restarting...');
78
+ const address = (_serviceInfo$currentA = serviceInfo.currentAccountInfo) === null || _serviceInfo$currentA === void 0 ? void 0 : _serviceInfo$currentA.address;
79
+ if (!address) {
80
+ return;
81
+ }
82
+ this.subscribeBalancesAndCrowdloans(address, serviceInfo.chainInfoMap, serviceInfo.chainStateMap, serviceInfo.chainApiMap.substrate, serviceInfo.chainApiMap.evm);
83
+ this.subscribeStakingOnChain(address, serviceInfo.chainApiMap.substrate);
84
+ };
85
+ this.state.eventService.onLazy(this.eventHandler);
86
86
  }
87
87
  stop() {
88
88
  this.logger.log('Stopping subscription');
89
89
  if (this.eventHandler) {
90
90
  this.state.eventService.offLazy(this.eventHandler);
91
+ this.eventHandler = undefined;
91
92
  }
92
93
  this.stopAllSubscription();
93
94
  }
@@ -113,7 +114,7 @@ class KoniSubscription {
113
114
  });
114
115
  }
115
116
  subscribeBalancesAndCrowdloans(address, chainInfoMap, chainStateMap, substrateApiMap, web3ApiMap, onlyRunOnFirstTime) {
116
- this.state.switchAccount(address).then(() => {
117
+ this.state.handleSwitchAccount(address).then(() => {
117
118
  const addresses = this.state.getDecodedAddresses(address);
118
119
  if (!addresses.length) {
119
120
  return;
@@ -189,8 +190,8 @@ class KoniSubscription {
189
190
  return _this.state.updateNftData(...arguments);
190
191
  }, function () {
191
192
  return _this.state.setNftCollection(...arguments);
192
- }).then(() => {
193
- this.logger.log('nft state updated');
193
+ }, function () {
194
+ return _this.state.cleanUpNfts(...arguments);
194
195
  }).catch(this.logger.log);
195
196
  }
196
197
  async subscribeStakingReward(address) {
@@ -209,7 +210,6 @@ class KoniSubscription {
209
210
  });
210
211
  const result = await (0, _staking.getNominationStakingRewardData)(addresses, targetNetworkMap);
211
212
  this.state.updateStakingReward(result, 'slowInterval');
212
- this.logger.log('Set staking reward state done', result);
213
213
  }
214
214
  async subscribeStakingRewardFastInterval(address) {
215
215
  const addresses = this.state.getDecodedAddresses(address);
@@ -239,13 +239,39 @@ class KoniSubscription {
239
239
  const [poolingStakingRewards, amplitudeUnclaimedStakingRewards] = await Promise.all([(0, _staking.getPoolingStakingRewardData)(pooledAddresses, targetChainMap, this.state.getSubstrateApiMap()), (0, _paraChain.getAmplitudeUnclaimedStakingReward)(this.state.getSubstrateApiMap(), addresses, chainInfoMap, activeNetworks)]);
240
240
  const result = [...poolingStakingRewards, ...amplitudeUnclaimedStakingRewards];
241
241
  this.state.updateStakingReward(result, 'fastInterval');
242
- this.logger.log('Set staking reward state with fast interval done', result);
242
+ }
243
+ async fetchingStakingFromApi() {
244
+ try {
245
+ const response = await _axios.default.get('https://staking-data.subwallet.app/api/staking/get');
246
+ if (response.status === 200) {
247
+ return response.data;
248
+ }
249
+ } catch (e) {
250
+ this.logger.error(e);
251
+ }
252
+ return {};
243
253
  }
244
254
  async fetchChainStakingMetadata(chainInfoMap, chainStateMap, substrateApiMap) {
245
- await Promise.all(Object.values(chainInfoMap).map(async chainInfo => {
255
+ const filteredChainInfoMap = {};
256
+ Object.values(chainInfoMap).forEach(chainInfo => {
246
257
  const chainState = chainStateMap[chainInfo.slug];
247
258
  if (chainState !== null && chainState !== void 0 && chainState.active && (0, _utils._isChainSupportSubstrateStaking)(chainInfo)) {
248
- const chainStakingMetadata = await (0, _bonding.getChainStakingMetadata)(chainInfo.slug, substrateApiMap[chainInfo.slug]);
259
+ filteredChainInfoMap[chainInfo.slug] = chainInfo;
260
+ }
261
+ });
262
+ if (Object.values(filteredChainInfoMap).length === 0) {
263
+ return;
264
+ }
265
+
266
+ // Fetch data from helper API
267
+ const dataFromApi = await this.fetchingStakingFromApi();
268
+ await Promise.all(Object.values(filteredChainInfoMap).map(async chainInfo => {
269
+ // Use fetch API data if available
270
+ if (dataFromApi[chainInfo.slug]) {
271
+ this.state.updateChainStakingMetadata(dataFromApi[chainInfo.slug]);
272
+ } else {
273
+ console.warn('Not found staking data from api', chainInfo.slug);
274
+ const chainStakingMetadata = await (0, _bonding.getChainStakingMetadata)(chainInfo, substrateApiMap[chainInfo.slug]);
249
275
  this.state.updateChainStakingMetadata(chainStakingMetadata);
250
276
  }
251
277
  }));
@@ -262,8 +288,7 @@ class KoniSubscription {
262
288
  if (currentAddress === _constants.ALL_ACCOUNT_KEY) {
263
289
  addresses = await this.state.getStakingOwnersByChains(Object.keys(filteredChainInfoMap));
264
290
  }
265
- const validAddresses = addresses.filter(address => !(0, _utilCrypto.isEthereumAddress)(address));
266
- await Promise.all(validAddresses.map(async address => {
291
+ await Promise.all(addresses.map(async address => {
267
292
  const isEvmAddress = (0, _utilCrypto.isEthereumAddress)(address);
268
293
  await Promise.all(Object.values(filteredChainInfoMap).map(async chainInfo => {
269
294
  if (isEvmAddress && !(0, _utils._isChainEvmCompatible)(chainInfo)) {
@@ -13,6 +13,6 @@ const packageInfo = {
13
13
  name: '@subwallet/extension-base',
14
14
  path: typeof __dirname === 'string' ? __dirname : 'auto',
15
15
  type: 'cjs',
16
- version: '1.0.2-2'
16
+ version: '1.0.3-0'
17
17
  };
18
18
  exports.packageInfo = packageInfo;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ServiceStatus = void 0;
7
+ // Copyright 2019-2022 @subwallet/extension-base
8
+ // SPDX-License-Identifier: Apache-2.0
9
+ // 'init' | 'started' | 'starting' | 'stopped' | 'stopping'
10
+ let ServiceStatus;
11
+ exports.ServiceStatus = ServiceStatus;
12
+ (function (ServiceStatus) {
13
+ ServiceStatus["NOT_INITIALIZED"] = "not_initialized";
14
+ ServiceStatus["INITIALIZING"] = "initializing";
15
+ ServiceStatus["INITIALIZED"] = "initialized";
16
+ ServiceStatus["STARTED"] = "started";
17
+ ServiceStatus["STARTING"] = "starting";
18
+ ServiceStatus["STOPPED"] = "stopped";
19
+ ServiceStatus["STOPPING"] = "stopping";
20
+ })(ServiceStatus || (exports.ServiceStatus = ServiceStatus = {}));
@@ -7,6 +7,7 @@ exports.SubstrateChainHandler = exports.DEFAULT_AUX = void 0;
7
7
  var _api = require("@acala-network/api");
8
8
  var _types = require("@oak-foundation/types");
9
9
  var _types2 = require("@subwallet/chain-list/types");
10
+ var _utils = require("@subwallet/extension-base/koni/api/tokens/wasm/utils");
10
11
  var _lightClient = require("@subwallet/extension-base/services/chain-service/handler/light-client");
11
12
  var _api2 = require("@polkadot/api");
12
13
  var _apiContract = require("@polkadot/api-contract");
@@ -94,13 +95,13 @@ class SubstrateChainHandler {
94
95
  if (tokenType === _types2._AssetType.PSP22) {
95
96
  tokenContract = new _apiContract.ContractPromise(substrateApi.api, _helper._PSP22_ABI, contractAddress);
96
97
  const [nameResp, symbolResp, decimalsResp] = await Promise.all([tokenContract.query['psp22Metadata::tokenName'](contractCaller || contractAddress, {
97
- gasLimit: -1
98
+ gasLimit: (0, _utils.getDefaultWeightV2)(substrateApi.api)
98
99
  }),
99
100
  // read-only operation so no gas limit
100
101
  tokenContract.query['psp22Metadata::tokenSymbol'](contractCaller || contractAddress, {
101
- gasLimit: -1
102
+ gasLimit: (0, _utils.getDefaultWeightV2)(substrateApi.api)
102
103
  }), tokenContract.query['psp22Metadata::tokenDecimals'](contractCaller || contractAddress, {
103
- gasLimit: -1
104
+ gasLimit: (0, _utils.getDefaultWeightV2)(substrateApi.api)
104
105
  })]);
105
106
  if (!(nameResp.result.isOk && symbolResp.result.isOk && decimalsResp.result.isOk) || !nameResp.output || !decimalsResp.output || !symbolResp.output) {
106
107
  this.logger.error('Error response while validating WASM contract');
@@ -111,18 +112,22 @@ class SubstrateChainHandler {
111
112
  contractError: true
112
113
  };
113
114
  } else {
114
- var _symbolResp$output, _decimalsResp$output, _symbolResp$output2;
115
- name = (_symbolResp$output = symbolResp.output) === null || _symbolResp$output === void 0 ? void 0 : _symbolResp$output.toHuman();
116
- decimals = parseInt((_decimalsResp$output = decimalsResp.output) === null || _decimalsResp$output === void 0 ? void 0 : _decimalsResp$output.toHuman());
117
- symbol = (_symbolResp$output2 = symbolResp.output) === null || _symbolResp$output2 === void 0 ? void 0 : _symbolResp$output2.toHuman();
115
+ var _symbolResp$output, _decimalsResp$output, _nameResp$output;
116
+ const symbolObj = (_symbolResp$output = symbolResp.output) === null || _symbolResp$output === void 0 ? void 0 : _symbolResp$output.toHuman();
117
+ const decimalsObj = (_decimalsResp$output = decimalsResp.output) === null || _decimalsResp$output === void 0 ? void 0 : _decimalsResp$output.toHuman();
118
+ const nameObj = (_nameResp$output = nameResp.output) === null || _nameResp$output === void 0 ? void 0 : _nameResp$output.toHuman();
119
+ name = nameResp.output ? nameObj.Ok || nameObj.ok : '';
120
+ decimals = decimalsResp.output ? new _util.BN(decimalsObj.Ok || decimalsObj.ok).toNumber() : 0;
121
+ symbol = decimalsResp.output ? symbolObj.Ok || symbolObj.ok : '';
118
122
  if (name === '' || symbol === '') {
119
123
  contractError = true;
120
124
  }
125
+ console.log('validate PSP22', name, symbol, decimals);
121
126
  }
122
127
  } else {
123
128
  tokenContract = new _apiContract.ContractPromise(substrateApi.api, _helper._PSP34_ABI, contractAddress);
124
129
  const collectionIdResp = await tokenContract.query['psp34::collectionId'](contractCaller || contractAddress, {
125
- gasLimit: -1
130
+ gasLimit: (0, _utils.getDefaultWeightV2)(substrateApi.api)
126
131
  }); // read-only operation so no gas limit
127
132
 
128
133
  if (!collectionIdResp.result.isOk || !collectionIdResp.output) {