@subwallet/extension-base 1.1.23-0 → 1.1.24-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 (82) hide show
  1. package/background/KoniTypes.d.ts +12 -26
  2. package/cjs/constants/index.js +9 -3
  3. package/cjs/koni/api/staking/bonding/index.js +1 -0
  4. package/cjs/koni/api/tokens/evm/balance.js +5 -1
  5. package/cjs/koni/api/tokens/evm/transfer.js +8 -4
  6. package/cjs/koni/background/cron.js +2 -2
  7. package/cjs/koni/background/handlers/Extension.js +14 -5
  8. package/cjs/koni/background/handlers/Mobile.js +32 -0
  9. package/cjs/koni/background/handlers/State.js +126 -45
  10. package/cjs/koni/background/subscription.js +2 -2
  11. package/cjs/packageInfo.js +1 -1
  12. package/cjs/services/balance-service/helpers/group.js +53 -0
  13. package/cjs/services/balance-service/helpers/subscribe/balance.js +111 -0
  14. package/cjs/services/balance-service/helpers/subscribe/evm.js +95 -0
  15. package/cjs/services/balance-service/helpers/subscribe/substrate/equilibrium.js +113 -0
  16. package/cjs/services/balance-service/helpers/subscribe/substrate/index.js +324 -0
  17. package/cjs/services/balance-service/index.js +41 -16
  18. package/cjs/services/history-service/helpers/subscan-extrinsic-parser-helper.js +7 -1
  19. package/cjs/services/history-service/index.js +12 -8
  20. package/cjs/services/migration-service/scripts/MigrateProvider.js +1 -1
  21. package/cjs/services/storage-service/DatabaseService.js +47 -2
  22. package/cjs/services/storage-service/db-stores/Balance.js +9 -9
  23. package/cjs/services/subscan-service/index.js +66 -22
  24. package/cjs/services/transaction-service/index.js +4 -3
  25. package/cjs/types/balance.js +1 -0
  26. package/cjs/types/index.js +11 -0
  27. package/cjs/utils/{address.js → account.js} +32 -2
  28. package/cjs/utils/eth.js +7 -2
  29. package/cjs/utils/index.js +12 -0
  30. package/constants/index.d.ts +2 -0
  31. package/constants/index.js +2 -0
  32. package/koni/api/staking/bonding/index.js +1 -0
  33. package/koni/api/tokens/evm/balance.js +5 -1
  34. package/koni/api/tokens/evm/transfer.d.ts +1 -1
  35. package/koni/api/tokens/evm/transfer.js +8 -4
  36. package/koni/background/cron.js +3 -3
  37. package/koni/background/handlers/Extension.js +14 -5
  38. package/koni/background/handlers/Mobile.d.ts +5 -1
  39. package/koni/background/handlers/Mobile.js +31 -0
  40. package/koni/background/handlers/State.d.ts +6 -4
  41. package/koni/background/handlers/State.js +114 -34
  42. package/koni/background/subscription.js +2 -2
  43. package/package.json +40 -14
  44. package/packageInfo.js +1 -1
  45. package/services/balance-service/helpers/group.d.ts +9 -0
  46. package/services/balance-service/helpers/group.js +46 -0
  47. package/services/balance-service/helpers/subscribe/balance.d.ts +4 -0
  48. package/services/balance-service/helpers/subscribe/balance.js +103 -0
  49. package/services/balance-service/helpers/subscribe/evm.d.ts +5 -0
  50. package/services/balance-service/helpers/subscribe/evm.js +87 -0
  51. package/services/balance-service/helpers/subscribe/substrate/equilibrium.d.ts +4 -0
  52. package/services/balance-service/helpers/subscribe/substrate/equilibrium.js +105 -0
  53. package/services/balance-service/helpers/subscribe/substrate/index.d.ts +4 -0
  54. package/services/balance-service/helpers/subscribe/substrate/index.js +316 -0
  55. package/services/balance-service/index.d.ts +24 -5
  56. package/services/balance-service/index.js +40 -14
  57. package/services/history-service/helpers/subscan-extrinsic-parser-helper.js +7 -1
  58. package/services/history-service/index.js +12 -8
  59. package/services/migration-service/scripts/MigrateProvider.js +1 -1
  60. package/services/storage-service/DatabaseService.d.ts +7 -2
  61. package/services/storage-service/DatabaseService.js +47 -2
  62. package/services/storage-service/databases/index.d.ts +2 -1
  63. package/services/storage-service/db-stores/Balance.d.ts +2 -2
  64. package/services/storage-service/db-stores/Balance.js +9 -9
  65. package/services/subscan-service/index.d.ts +11 -5
  66. package/services/subscan-service/index.js +66 -26
  67. package/services/subscan-service/types.d.ts +4 -0
  68. package/services/transaction-service/index.js +5 -4
  69. package/types/balance.d.ts +40 -0
  70. package/types/balance.js +1 -0
  71. package/types/index.d.ts +1 -0
  72. package/types/index.js +1 -0
  73. package/utils/account.d.ts +15 -0
  74. package/utils/{address.js → account.js} +28 -0
  75. package/utils/eth.d.ts +1 -0
  76. package/utils/eth.js +4 -0
  77. package/utils/index.d.ts +1 -0
  78. package/utils/index.js +1 -0
  79. package/cjs/koni/api/dotsama/balance.js +0 -464
  80. package/koni/api/dotsama/balance.d.ts +0 -6
  81. package/koni/api/dotsama/balance.js +0 -451
  82. package/utils/address.d.ts +0 -5
@@ -1,4 +1,3 @@
1
- /// <reference types="bn.js" />
2
1
  import { _AssetRef, _AssetType, _ChainAsset, _ChainInfo, _FundStatus, _MultiChainAsset } from '@subwallet/chain-list/types';
3
2
  import { TransactionError } from '@subwallet/extension-base/background/errors/TransactionError';
4
3
  import { AuthUrls, Resolver } from '@subwallet/extension-base/background/handlers/State';
@@ -7,17 +6,17 @@ import { _CHAIN_VALIDATION_ERROR } from '@subwallet/extension-base/services/chai
7
6
  import { _ChainState, _EvmApi, _NetworkUpsertParams, _SubstrateApi, _ValidateCustomAssetRequest, _ValidateCustomAssetResponse, EnableChainParams, EnableMultiChainParams } from '@subwallet/extension-base/services/chain-service/types';
8
7
  import { SWTransactionResponse, SWTransactionResult } from '@subwallet/extension-base/services/transaction-service/types';
9
8
  import { WalletConnectNotSupportRequest, WalletConnectSessionRequest } from '@subwallet/extension-base/services/wallet-connect-service/types';
10
- import { BuyServiceInfo, BuyTokenInfo } from '@subwallet/extension-base/types';
9
+ import { BalanceJson, BuyServiceInfo, BuyTokenInfo } from '@subwallet/extension-base/types';
11
10
  import { InjectedAccount, InjectedAccountWithMeta, MetadataDefBase } from '@subwallet/extension-inject/types';
12
11
  import { KeyringPair$Json, KeyringPair$Meta } from '@subwallet/keyring/types';
13
12
  import { KeyringOptions } from '@subwallet/ui-keyring/options/types';
14
13
  import { KeyringAddress, KeyringPairs$Json } from '@subwallet/ui-keyring/types';
15
14
  import { SessionTypes } from '@walletconnect/types/dist/types/sign-client/session';
15
+ import { DexieExportJsonMeta } from 'dexie-export-import';
16
16
  import Web3 from 'web3';
17
17
  import { RequestArguments, TransactionConfig } from 'web3-core';
18
18
  import { JsonRpcPayload, JsonRpcResponse } from 'web3-core-helpers';
19
19
  import { SignerResult } from '@polkadot/types/types/extrinsic';
20
- import { BN } from '@polkadot/util';
21
20
  import { HexString } from '@polkadot/util/types';
22
21
  import { KeypairType } from '@polkadot/util-crypto/types';
23
22
  import { TransactionWarning } from './warnings/TransactionWarning';
@@ -36,7 +35,7 @@ export interface RuntimeEnvironmentInfo {
36
35
  host?: string;
37
36
  protocol?: string;
38
37
  }
39
- export declare type TargetEnvironment = 'extension' | 'webapp' | 'web-runner';
38
+ export declare type TargetEnvironment = 'extension' | 'webapp' | 'mobile';
40
39
  export interface EnvironmentSupport {
41
40
  MANTA_ZK: boolean;
42
41
  }
@@ -195,28 +194,6 @@ export interface MetadataItem {
195
194
  specVersion: string;
196
195
  hexValue: HexString;
197
196
  }
198
- export interface TokenBalanceRaw {
199
- reserved: BN;
200
- frozen: BN;
201
- free: BN;
202
- }
203
- export interface SubstrateBalance {
204
- reserved?: string;
205
- miscFrozen?: string;
206
- feeFrozen?: string;
207
- }
208
- export interface BalanceItem {
209
- tokenSlug: string;
210
- state: APIItemState;
211
- timestamp?: number;
212
- free: string;
213
- locked: string;
214
- substrateInfo?: SubstrateBalance;
215
- }
216
- export interface BalanceJson {
217
- reset?: boolean;
218
- details: Record<string, BalanceItem>;
219
- }
220
197
  export interface CrowdloanItem {
221
198
  state: APIItemState;
222
199
  paraState?: CrowdloanParaState;
@@ -1419,6 +1396,10 @@ export interface RequestGetTransaction {
1419
1396
  id: string;
1420
1397
  }
1421
1398
  export declare type SubscriptionServiceType = 'chainRegistry' | 'balance' | 'crowdloan' | 'staking';
1399
+ export interface MobileData {
1400
+ storage: string;
1401
+ indexedDB: string;
1402
+ }
1422
1403
  export declare type CronServiceType = 'price' | 'nft' | 'staking' | 'history' | 'recoverApi' | 'checkApiStatus';
1423
1404
  export declare type CronType = 'recoverApiMap' | 'checkApiMapStatus' | 'refreshHistory' | 'refreshNft' | 'refreshPrice' | 'refreshStakeUnlockingInfo' | 'refreshStakingReward' | 'refreshPoolingStakingReward';
1424
1405
  export interface RequestInitCronAndSubscription {
@@ -1782,6 +1763,8 @@ export interface KoniRequestSignatures {
1782
1763
  'mobile(subscription.start)': [SubscriptionServiceType[], void];
1783
1764
  'mobile(subscription.stop)': [SubscriptionServiceType[], void];
1784
1765
  'mobile(subscription.restart)': [SubscriptionServiceType[], void];
1766
+ 'mobile(storage.backup)': [null, MobileData];
1767
+ 'mobile(storage.restore)': [Partial<MobileData>, null];
1785
1768
  'pub(token.add)': [RequestAddPspToken, boolean];
1786
1769
  'pri(walletConnect.connect)': [RequestConnectWalletConnect, boolean];
1787
1770
  'pri(walletConnect.requests.connect.subscribe)': [null, WalletConnectSessionRequest[], WalletConnectSessionRequest[]];
@@ -1798,6 +1781,9 @@ export interface KoniRequestSignatures {
1798
1781
  'pri(campaign.banner.complete)': [RequestCampaignBannerComplete, boolean];
1799
1782
  'pri(buyService.tokens.subscribe)': [null, Record<string, BuyTokenInfo>, Record<string, BuyTokenInfo>];
1800
1783
  'pri(buyService.services.subscribe)': [null, Record<string, BuyServiceInfo>, Record<string, BuyServiceInfo>];
1784
+ 'pri(database.export)': [null, string];
1785
+ 'pri(database.import)': [string, boolean];
1786
+ 'pri(database.checkMetadata)': [string, DexieExportJsonMeta];
1801
1787
  }
1802
1788
  export interface ApplicationMetadataType {
1803
1789
  version: string;
@@ -25,9 +25,11 @@ var _exportNames = {
25
25
  ALL_GENESIS_HASH: true,
26
26
  IGNORE_GET_SUBSTRATE_FEATURES_LIST: true,
27
27
  IGNORE_QR_SIGNER: true,
28
- XCM_MIN_AMOUNT_RATIO: true
28
+ XCM_MIN_AMOUNT_RATIO: true,
29
+ GAS_PRICE_RATIO: true,
30
+ NETWORK_MULTI_GAS_FEE: true
29
31
  };
30
- exports.XCM_MIN_AMOUNT_RATIO = exports.SUB_TOKEN_REFRESH_BALANCE_INTERVAL = exports.MANTA_PAY_BALANCE_INTERVAL = exports.IGNORE_QR_SIGNER = exports.IGNORE_GET_SUBSTRATE_FEATURES_LIST = exports.CRON_SYNC_MANTA_PAY = exports.CRON_REFRESH_STAKING_REWARD_INTERVAL = exports.CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL = exports.CRON_REFRESH_PRICE_INTERVAL = exports.CRON_REFRESH_NFT_INTERVAL = exports.CRON_REFRESH_HISTORY_INTERVAL = exports.CRON_REFRESH_CHAIN_STAKING_METADATA = exports.CRON_REFRESH_CHAIN_NOMINATOR_METADATA = exports.CRON_RECOVER_HISTORY_INTERVAL = exports.CRON_GET_API_MAP_STATUS = exports.CRON_AUTO_RECOVER_WEB3_INTERVAL = exports.CRON_AUTO_RECOVER_DOTSAMA_INTERVAL = exports.ASTAR_REFRESH_BALANCE_INTERVAL = exports.ALL_NETWORK_KEY = exports.ALL_GENESIS_HASH = exports.ALL_ACCOUNT_KEY = exports.ACALA_REFRESH_CROWDLOAN_INTERVAL = void 0;
32
+ exports.XCM_MIN_AMOUNT_RATIO = exports.SUB_TOKEN_REFRESH_BALANCE_INTERVAL = exports.NETWORK_MULTI_GAS_FEE = exports.MANTA_PAY_BALANCE_INTERVAL = exports.IGNORE_QR_SIGNER = exports.IGNORE_GET_SUBSTRATE_FEATURES_LIST = exports.GAS_PRICE_RATIO = exports.CRON_SYNC_MANTA_PAY = exports.CRON_REFRESH_STAKING_REWARD_INTERVAL = exports.CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL = exports.CRON_REFRESH_PRICE_INTERVAL = exports.CRON_REFRESH_NFT_INTERVAL = exports.CRON_REFRESH_HISTORY_INTERVAL = exports.CRON_REFRESH_CHAIN_STAKING_METADATA = exports.CRON_REFRESH_CHAIN_NOMINATOR_METADATA = exports.CRON_RECOVER_HISTORY_INTERVAL = exports.CRON_GET_API_MAP_STATUS = exports.CRON_AUTO_RECOVER_WEB3_INTERVAL = exports.CRON_AUTO_RECOVER_DOTSAMA_INTERVAL = exports.ASTAR_REFRESH_BALANCE_INTERVAL = exports.ALL_NETWORK_KEY = exports.ALL_GENESIS_HASH = exports.ALL_ACCOUNT_KEY = exports.ACALA_REFRESH_CROWDLOAN_INTERVAL = void 0;
31
33
  var _staking = require("./staking");
32
34
  Object.keys(_staking).forEach(function (key) {
33
35
  if (key === "default" || key === "__esModule") return;
@@ -98,4 +100,8 @@ exports.IGNORE_GET_SUBSTRATE_FEATURES_LIST = IGNORE_GET_SUBSTRATE_FEATURES_LIST;
98
100
  const IGNORE_QR_SIGNER = [];
99
101
  exports.IGNORE_QR_SIGNER = IGNORE_QR_SIGNER;
100
102
  const XCM_MIN_AMOUNT_RATIO = 1.2;
101
- exports.XCM_MIN_AMOUNT_RATIO = XCM_MIN_AMOUNT_RATIO;
103
+ exports.XCM_MIN_AMOUNT_RATIO = XCM_MIN_AMOUNT_RATIO;
104
+ const GAS_PRICE_RATIO = 1.05;
105
+ exports.GAS_PRICE_RATIO = GAS_PRICE_RATIO;
106
+ const NETWORK_MULTI_GAS_FEE = ['astarEvm'];
107
+ exports.NETWORK_MULTI_GAS_FEE = NETWORK_MULTI_GAS_FEE;
@@ -122,6 +122,7 @@ async function getCancelWithdrawalExtrinsic(substrateApi, chain, selectedUnstaki
122
122
  function subscribeEssentialChainStakingMetadata(substrateApiMap, chainInfoMap, callback) {
123
123
  const unsubList = [];
124
124
 
125
+ // TODO: replace with for of to improve performance
125
126
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
126
127
  Object.values(chainInfoMap).forEach(async chainInfo => {
127
128
  if (!substrateApiMap[chainInfo.slug]) {
@@ -10,6 +10,10 @@ exports.getEVMBalance = getEVMBalance;
10
10
  async function getEVMBalance(networkKey, addresses, evmApiMap) {
11
11
  const web3Api = evmApiMap[networkKey];
12
12
  return await Promise.all(addresses.map(async address => {
13
- return await web3Api.api.eth.getBalance(address);
13
+ try {
14
+ return await web3Api.api.eth.getBalance(address);
15
+ } catch (e) {
16
+ return '0';
17
+ }
14
18
  }));
15
19
  }
@@ -11,6 +11,7 @@ var _KoniTypes = require("@subwallet/extension-base/background/KoniTypes");
11
11
  var _web = require("@subwallet/extension-base/koni/api/tokens/evm/web3");
12
12
  var _constants = require("@subwallet/extension-base/services/chain-service/constants");
13
13
  var _helper = require("@subwallet/extension-base/services/chain-service/helper");
14
+ var _eth = require("@subwallet/extension-base/utils/eth");
14
15
  var _util = require("@polkadot/util");
15
16
  // Copyright 2019-2022 @subwallet/extension-base
16
17
  // SPDX-License-Identifier: Apache-2.0
@@ -46,7 +47,8 @@ exports.handleTransferBalanceResult = handleTransferBalanceResult;
46
47
  async function getEVMTransactionObject(chainInfo, from, to, value, transferAll, evmApiMap) {
47
48
  const networkKey = chainInfo.slug;
48
49
  const web3Api = evmApiMap[networkKey];
49
- const gasPrice = await web3Api.api.eth.getGasPrice();
50
+ const _price = await web3Api.api.eth.getGasPrice();
51
+ const gasPrice = (0, _eth.recalculateGasPrice)(_price, chainInfo.slug);
50
52
  const transactionObject = {
51
53
  gasPrice: gasPrice,
52
54
  to: to,
@@ -80,11 +82,12 @@ async function getERC20TransactionObject(assetAddress, chainInfo, from, to, valu
80
82
  return erc20Contract.methods.transfer(to, transferValue).encodeABI();
81
83
  }
82
84
  const transferData = generateTransferData(to, transferValue);
83
- const [gasLimit, gasPrice] = await Promise.all([
85
+ const [gasLimit, _price] = await Promise.all([
84
86
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
85
87
  erc20Contract.methods.transfer(to, transferValue).estimateGas({
86
88
  from
87
89
  }), evmApi.api.eth.getGasPrice()]);
90
+ const gasPrice = (0, _eth.recalculateGasPrice)(_price, chainInfo.slug);
88
91
  const transactionObject = {
89
92
  gasPrice: gasPrice,
90
93
  gas: gasLimit,
@@ -98,14 +101,15 @@ async function getERC20TransactionObject(assetAddress, chainInfo, from, to, valu
98
101
  }
99
102
  return [transactionObject, transferValue];
100
103
  }
101
- async function getERC721Transaction(web3Api, contractAddress, senderAddress, recipientAddress, tokenId) {
104
+ async function getERC721Transaction(web3Api, chain, contractAddress, senderAddress, recipientAddress, tokenId) {
102
105
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
103
106
  const contract = new web3Api.api.eth.Contract(_helper._ERC721_ABI, contractAddress);
104
- const [gasLimit, gasPrice] = await Promise.all([
107
+ const [gasLimit, _price] = await Promise.all([
105
108
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
106
109
  contract.methods.safeTransferFrom(senderAddress, recipientAddress, tokenId).estimateGas({
107
110
  from: senderAddress
108
111
  }), web3Api.api.eth.getGasPrice()]);
112
+ const gasPrice = (0, _eth.recalculateGasPrice)(_price, chain);
109
113
  return {
110
114
  from: senderAddress,
111
115
  gasPrice,
@@ -115,8 +115,8 @@ class KoniCron {
115
115
  if (Object.keys(this.state.getSubstrateApiMap()).length !== 0 || Object.keys(this.state.getEvmApiMap()).length !== 0) {
116
116
  this.resetNft(currentAccountInfo.address);
117
117
  this.addCron('refreshNft', this.refreshNft(currentAccountInfo.address, this.state.getApiMap(), this.state.getSmartContractNfts(), this.state.getActiveChainInfoMap()), _constants.CRON_REFRESH_NFT_INTERVAL);
118
- this.addCron('refreshStakingReward', this.refreshStakingReward(currentAccountInfo.address), _constants.CRON_REFRESH_STAKING_REWARD_INTERVAL);
119
- this.addCron('refreshPoolingSta kingReward', this.refreshStakingRewardFastInterval(currentAccountInfo.address), _constants.CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL);
118
+ // this.addCron('refreshStakingReward', this.refreshStakingReward(currentAccountInfo.address), CRON_REFRESH_STAKING_REWARD_INTERVAL);
119
+ this.addCron('refreshPoolingStakingReward', this.refreshStakingRewardFastInterval(currentAccountInfo.address), _constants.CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL);
120
120
  this.addCron('syncMantaPay', this.syncMantaPay, _constants.CRON_SYNC_MANTA_PAY);
121
121
  } else {
122
122
  this.setStakingRewardReady();
@@ -33,7 +33,6 @@ var _constants4 = require("@subwallet/extension-base/services/setting-service/co
33
33
  var _constants5 = require("@subwallet/extension-base/services/wallet-connect-service/constants");
34
34
  var _helpers2 = require("@subwallet/extension-base/services/wallet-connect-service/helpers");
35
35
  var _utils2 = require("@subwallet/extension-base/utils");
36
- var _address2 = require("@subwallet/extension-base/utils/address");
37
36
  var _eth = require("@subwallet/extension-base/utils/eth");
38
37
  var _parseTransaction2 = require("@subwallet/extension-base/utils/eth/parseTransaction");
39
38
  var _number = require("@subwallet/extension-base/utils/number");
@@ -546,7 +545,7 @@ class KoniExtension {
546
545
  subscribeAddresses(id, port) {
547
546
  const _cb = (0, _subscriptions.createSubscription)(id, port);
548
547
  const subscription = this.#koniState.keyringService.addressesSubject.subscribe(subjectInfo => {
549
- const addresses = (0, _address2.convertSubjectInfoToAddresses)(subjectInfo);
548
+ const addresses = (0, _utils2.convertSubjectInfoToAddresses)(subjectInfo);
550
549
  _cb({
551
550
  addresses: addresses
552
551
  });
@@ -557,7 +556,7 @@ class KoniExtension {
557
556
  });
558
557
  const subjectInfo = this.#koniState.keyringService.addresses;
559
558
  return {
560
- addresses: (0, _address2.convertSubjectInfoToAddresses)(subjectInfo)
559
+ addresses: (0, _utils2.convertSubjectInfoToAddresses)(subjectInfo)
561
560
  };
562
561
  }
563
562
  saveRecentAccount(_ref22) {
@@ -1779,7 +1778,7 @@ class KoniExtension {
1779
1778
  } = inputData;
1780
1779
  const contractAddress = params.contractAddress;
1781
1780
  const tokenId = params.tokenId;
1782
- const transaction = await (0, _transfer3.getERC721Transaction)(this.#koniState.getEvmApi(networkKey), contractAddress, senderAddress, recipientAddress, tokenId);
1781
+ const transaction = await (0, _transfer3.getERC721Transaction)(this.#koniState.getEvmApi(networkKey), networkKey, contractAddress, senderAddress, recipientAddress, tokenId);
1783
1782
 
1784
1783
  // this.addContact(recipientAddress);
1785
1784
 
@@ -1930,7 +1929,8 @@ class KoniExtension {
1930
1929
  // null address
1931
1930
  from: address
1932
1931
  };
1933
- const gasPrice = await web3.api.eth.getGasPrice();
1932
+ const _price = await web3.api.eth.getGasPrice();
1933
+ const gasPrice = (0, _eth.recalculateGasPrice)(_price, networkKey);
1934
1934
  const gasLimit = await web3.api.eth.estimateGas(transaction);
1935
1935
  estimatedFee = (gasLimit * parseInt(gasPrice)).toString();
1936
1936
  } else {
@@ -4164,6 +4164,15 @@ class KoniExtension {
4164
4164
  case 'pri(buyService.services.subscribe)':
4165
4165
  return this.subscribeBuyServices(id, port);
4166
4166
  /* Buy service */
4167
+
4168
+ /* Database */
4169
+ case 'pri(database.export)':
4170
+ return this.#koniState.dbService.exportDB();
4171
+ case 'pri(database.import)':
4172
+ return this.#koniState.dbService.importDB(request);
4173
+ case 'pri(database.checkMetadata)':
4174
+ return this.#koniState.dbService.checkImportMetadata(request);
4175
+ /* Database */
4167
4176
  // Default
4168
4177
  default:
4169
4178
  throw new Error(`Unable to handle message of type ${type}`);
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.default = void 0;
7
+ var _promise = require("@subwallet/extension-base/utils/promise");
7
8
  // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
8
9
  // SPDX-License-Identifier: Apache-2.0
9
10
 
@@ -26,6 +27,7 @@ const DEFAULT_SERVICE_MAP = {
26
27
  class Mobile {
27
28
  // @ts-ignore
28
29
 
30
+ restoreHandler = (0, _promise.createPromiseHandler)();
29
31
  constructor(state) {
30
32
  this.state = state;
31
33
  }
@@ -102,6 +104,32 @@ class Mobile {
102
104
  restartSubscriptionServices(services) {
103
105
  console.log('restartSubscriptionServices');
104
106
  }
107
+ async mobileBackup() {
108
+ const indexedDB = await this.state.dbService.exportDB();
109
+ return {
110
+ storage: JSON.stringify(localStorage),
111
+ indexedDB
112
+ };
113
+ }
114
+ async mobileRestore(_ref5) {
115
+ let {
116
+ indexedDB,
117
+ storage
118
+ } = _ref5;
119
+ if (storage) {
120
+ const storageData = JSON.parse(storage);
121
+ for (const key in storageData) {
122
+ localStorage.setItem(key, storageData[key]);
123
+ }
124
+ }
125
+ if (indexedDB) {
126
+ await this.state.dbService.importDB(indexedDB);
127
+ }
128
+ this.restoreHandler.resolve();
129
+ }
130
+ waitRestore() {
131
+ return this.restoreHandler.promise;
132
+ }
105
133
 
106
134
  // eslint-disable-next-line @typescript-eslint/require-await
107
135
  async handle(id, type, request, port) {
@@ -130,6 +158,10 @@ class Mobile {
130
158
  return this.stopSubscriptionServices(request);
131
159
  case 'mobile(subscription.restart)':
132
160
  return this.restartSubscriptionServices(request);
161
+ case 'mobile(storage.restore)':
162
+ return this.mobileRestore(request);
163
+ case 'mobile(storage.backup)':
164
+ return this.mobileBackup();
133
165
  default:
134
166
  throw new Error(`Unable to handle message of type ${type}`);
135
167
  }
@@ -11,6 +11,7 @@ var _subscriptions = require("@subwallet/extension-base/background/handlers/subs
11
11
  var _KoniTypes = require("@subwallet/extension-base/background/KoniTypes");
12
12
  var _constants = require("@subwallet/extension-base/constants");
13
13
  var _balanceService = require("@subwallet/extension-base/services/balance-service");
14
+ var _group = require("@subwallet/extension-base/services/balance-service/helpers/group");
14
15
  var _types = require("@subwallet/extension-base/services/base/types");
15
16
  var _buyService = _interopRequireDefault(require("@subwallet/extension-base/services/buy-service"));
16
17
  var _campaignService = _interopRequireDefault(require("@subwallet/extension-base/services/campaign-service"));
@@ -32,6 +33,7 @@ var _transactionService = _interopRequireDefault(require("@subwallet/extension-b
32
33
  var _walletConnectService = _interopRequireDefault(require("@subwallet/extension-base/services/wallet-connect-service"));
33
34
  var _AccountRef = _interopRequireDefault(require("@subwallet/extension-base/stores/AccountRef"));
34
35
  var _utils2 = require("@subwallet/extension-base/utils");
36
+ var _eth = require("@subwallet/extension-base/utils/eth");
35
37
  var _parseTransaction = require("@subwallet/extension-base/utils/eth/parseTransaction");
36
38
  var _promise = require("@subwallet/extension-base/utils/promise");
37
39
  var _decode = require("@subwallet/keyring/pair/decode");
@@ -97,7 +99,7 @@ class KoniState {
97
99
  this.settingService = new _SettingService.default();
98
100
  this.requestService = new _requestService.default(this.chainService, this.settingService, this.keyringService);
99
101
  this.priceService = new _priceService.PriceService(this.dbService, this.eventService, this.chainService);
100
- this.balanceService = new _balanceService.BalanceService(this.chainService);
102
+ this.balanceService = new _balanceService.BalanceService(this);
101
103
  this.historyService = new _historyService.HistoryService(this.dbService, this.chainService, this.eventService, this.keyringService, this.subscanService);
102
104
  this.transactionService = new _transactionService.default(this.chainService, this.eventService, this.requestService, this.balanceService, this.historyService, this.notificationService, this.dbService);
103
105
  this.walletConnectService = new _walletConnectService.default(this, this.requestService);
@@ -109,7 +111,9 @@ class KoniState {
109
111
  this.logger = (0, _util.logger)('State');
110
112
 
111
113
  // Init state
112
- this.init().catch(console.error);
114
+ if (_utils2.TARGET_ENV !== 'mobile') {
115
+ this.init().catch(console.error);
116
+ }
113
117
  }
114
118
 
115
119
  // Clone from polkadot.js
@@ -193,16 +197,23 @@ class KoniState {
193
197
  generateDefaultBalanceMap() {
194
198
  const balanceMap = {};
195
199
  const activeChains = this.chainService.getActiveChainInfoMap();
196
- Object.values(activeChains).forEach(chainInfo => {
197
- const chainAssetMap = this.chainService.getFungibleTokensByChain(chainInfo.slug);
198
- Object.keys(chainAssetMap).forEach(assetSlug => {
199
- balanceMap[assetSlug] = {
200
- tokenSlug: assetSlug,
201
- free: '',
202
- locked: '',
203
- state: _KoniTypes.APIItemState.PENDING
204
- };
200
+ const isAllAccount = (0, _utils2.isAccountAll)(this.keyringService.currentAccount.address);
201
+ const addresses = isAllAccount ? Object.keys(this.keyringService.accounts) : [this.keyringService.currentAccount.address];
202
+ addresses.forEach(address => {
203
+ const temp = {};
204
+ Object.values(activeChains).forEach(chainInfo => {
205
+ const chainAssetMap = this.chainService.getFungibleTokensByChain(chainInfo.slug);
206
+ Object.keys(chainAssetMap).forEach(assetSlug => {
207
+ temp[assetSlug] = {
208
+ address,
209
+ tokenSlug: assetSlug,
210
+ free: '',
211
+ locked: '',
212
+ state: _KoniTypes.APIItemState.PENDING
213
+ };
214
+ });
205
215
  });
216
+ balanceMap[address] = temp;
206
217
  });
207
218
  return balanceMap;
208
219
  }
@@ -679,14 +690,18 @@ class KoniState {
679
690
  removeInactiveChainBalances(balanceMap) {
680
691
  const activeBalanceMap = {};
681
692
  Object.entries(balanceMap).forEach(_ref5 => {
682
- let [tokenSlug, balanceItem] = _ref5;
683
- const tokenInfo = this.chainService.getAssetBySlug(tokenSlug);
684
- if (tokenInfo) {
685
- const chainInfo = this.chainService.getChainInfoByKey(tokenInfo.originChain);
686
- if (chainInfo && this.getChainStateByKey(chainInfo.slug).active) {
687
- activeBalanceMap[tokenSlug] = balanceItem;
693
+ let [address, balances] = _ref5;
694
+ activeBalanceMap[address] = {};
695
+ Object.entries(balances).forEach(_ref6 => {
696
+ let [tokenSlug, item] = _ref6;
697
+ const tokenInfo = this.chainService.getAssetBySlug(tokenSlug);
698
+ if (tokenInfo) {
699
+ const chainInfo = this.chainService.getChainInfoByKey(tokenInfo.originChain);
700
+ if (chainInfo && this.getChainStateByKey(chainInfo.slug).active) {
701
+ activeBalanceMap[address][tokenSlug] = item;
702
+ }
688
703
  }
689
- }
704
+ });
690
705
  });
691
706
  return activeBalanceMap;
692
707
  }
@@ -698,7 +713,7 @@ class KoniState {
698
713
  };
699
714
  }
700
715
  async getStoredBalance(address) {
701
- const items = await this.dbService.stores.balance.getBalanceMapByAddress(address);
716
+ const items = await this.dbService.stores.balance.getBalanceMapByAddresses(address);
702
717
  return items || {};
703
718
  }
704
719
  async handleSwitchAccount(newAddress) {
@@ -708,6 +723,31 @@ class KoniState {
708
723
  const defaultData = this.generateDefaultBalanceMap();
709
724
  let storedData = await this.getStoredBalance(newAddress);
710
725
  storedData = this.removeInactiveChainBalances(storedData);
726
+ const result = {};
727
+ for (const [address, balanceInfo] of Object.entries(defaultData)) {
728
+ result[address] = {
729
+ ...balanceInfo
730
+ };
731
+ }
732
+ for (const [address, balanceInfo] of Object.entries(storedData)) {
733
+ if (!result[address]) {
734
+ result[address] = {
735
+ ...balanceInfo
736
+ };
737
+ } else {
738
+ const temp = {
739
+ ...result[address]
740
+ };
741
+ for (const [slug, item] of Object.entries(balanceInfo)) {
742
+ temp[slug] = {
743
+ ...item
744
+ };
745
+ }
746
+ result[address] = {
747
+ ...temp
748
+ };
749
+ }
750
+ }
711
751
  this.balanceMap = {
712
752
  ...defaultData,
713
753
  ...storedData
@@ -735,19 +775,59 @@ class KoniState {
735
775
  });
736
776
  });
737
777
  }
738
- setBalanceItem(tokenSlug, item) {
739
- this.balanceMap[tokenSlug] = {
740
- timestamp: +new Date(),
741
- ...item
742
- };
743
- this.updateBalanceStore(item);
744
- this.lazyNext('setBalanceItem', () => {
745
- this.publishBalance();
746
- });
778
+
779
+ /** Note: items must be same tokenSlug */
780
+ setBalanceItem(items) {
781
+ if (items.length) {
782
+ const tokens = [];
783
+ const updates = [];
784
+ for (const item of items) {
785
+ const address = item.address;
786
+ const tokenSlug = item.tokenSlug;
787
+ if (!tokens.includes(tokenSlug)) {
788
+ tokens.push(tokenSlug);
789
+ }
790
+ if (!this.balanceMap[address]) {
791
+ this.balanceMap[address] = {};
792
+ }
793
+ const data = {
794
+ timestamp: +new Date(),
795
+ ...item
796
+ };
797
+ this.balanceMap[address][tokenSlug] = data;
798
+ updates.push(data);
799
+ }
800
+ const isAllAccount = (0, _utils2.isAccountAll)(this.keyringService.currentAccount.address);
801
+ if (isAllAccount) {
802
+ const address = _constants.ALL_ACCOUNT_KEY;
803
+ for (const token of tokens) {
804
+ const items = [];
805
+ for (const [_adr, balanceInfo] of Object.entries(this.balanceMap)) {
806
+ if (!(0, _utils2.isSameAddress)(_adr, address)) {
807
+ const item = balanceInfo[token];
808
+ item && items.push(item);
809
+ }
810
+ }
811
+ const _balance = (0, _group.groupBalance)(items, address, token);
812
+ const balance = {
813
+ timestamp: +new Date(),
814
+ ..._balance
815
+ };
816
+ if (!this.balanceMap[address]) {
817
+ this.balanceMap[address] = {};
818
+ }
819
+ this.balanceMap[address][token] = balance;
820
+ updates.push(balance);
821
+ }
822
+ }
823
+ this.updateBalanceStore(updates);
824
+ this.lazyNext('setBalanceItem', () => {
825
+ this.publishBalance();
826
+ });
827
+ }
747
828
  }
748
- updateBalanceStore(item) {
749
- const currentAccountInfo = this.keyringService.currentAccount;
750
- this.dbService.updateBalanceStore(currentAccountInfo.address, item).catch(e => this.logger.warn(e));
829
+ updateBalanceStore(items) {
830
+ this.dbService.updateBulkBalanceStore(items).catch(e => this.logger.warn(e));
751
831
  }
752
832
  subscribeBalance() {
753
833
  return this.balanceSubject;
@@ -1028,8 +1108,8 @@ class KoniState {
1028
1108
  if (!genesisHash) {
1029
1109
  return [undefined, undefined];
1030
1110
  }
1031
- const rs = Object.entries(this.chainService.getChainInfoMap()).find(_ref6 => {
1032
- let [networkKey, chainInfo] = _ref6;
1111
+ const rs = Object.entries(this.chainService.getChainInfoMap()).find(_ref7 => {
1112
+ let [networkKey, chainInfo] = _ref7;
1033
1113
  return (0, _utils._getSubstrateGenesisHash)(chainInfo) === genesisHash;
1034
1114
  });
1035
1115
  if (rs) {
@@ -1046,9 +1126,9 @@ class KoniState {
1046
1126
  if (!chainId) {
1047
1127
  return [undefined, undefined];
1048
1128
  }
1049
- const rs = Object.entries(this.chainService.getChainInfoMap()).find(_ref7 => {
1129
+ const rs = Object.entries(this.chainService.getChainInfoMap()).find(_ref8 => {
1050
1130
  var _chainInfo$evmInfo;
1051
- let [networkKey, chainInfo] = _ref7;
1131
+ let [networkKey, chainInfo] = _ref8;
1052
1132
  return (chainInfo === null || chainInfo === void 0 ? void 0 : (_chainInfo$evmInfo = chainInfo.evmInfo) === null || _chainInfo$evmInfo === void 0 ? void 0 : _chainInfo$evmInfo.evmChainId) === chainId;
1053
1133
  });
1054
1134
  if (rs) {
@@ -1064,11 +1144,11 @@ class KoniState {
1064
1144
  }
1065
1145
  return Object.values(_constants2._PREDEFINED_SINGLE_MODES).find(item => item.networkKeys.includes(networkKey));
1066
1146
  }
1067
- accountExportPrivateKey(_ref8) {
1147
+ accountExportPrivateKey(_ref9) {
1068
1148
  let {
1069
1149
  address,
1070
1150
  password
1071
- } = _ref8;
1151
+ } = _ref9;
1072
1152
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1073
1153
  const exportedJson = _uiKeyring.keyring.backupAccount(_uiKeyring.keyring.getPair(address), password);
1074
1154
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
@@ -1078,11 +1158,11 @@ class KoniState {
1078
1158
  publicKey: (0, _util.u8aToHex)(decoded.publicKey)
1079
1159
  };
1080
1160
  }
1081
- checkPublicAndSecretKey(_ref9) {
1161
+ checkPublicAndSecretKey(_ref10) {
1082
1162
  let {
1083
1163
  publicKey,
1084
1164
  secretKey
1085
- } = _ref9;
1165
+ } = _ref10;
1086
1166
  try {
1087
1167
  const _secret = (0, _util.hexStripPrefix)(secretKey);
1088
1168
  if (_secret.length === 64) {
@@ -1200,11 +1280,11 @@ class KoniState {
1200
1280
  return this.requestService.addConfirmation(id, url, 'evmSignatureRequest', signPayload, {
1201
1281
  requiredPassword: false,
1202
1282
  address
1203
- }).then(_ref10 => {
1283
+ }).then(_ref11 => {
1204
1284
  let {
1205
1285
  isApproved,
1206
1286
  payload
1207
- } = _ref10;
1287
+ } = _ref11;
1208
1288
  if (isApproved) {
1209
1289
  if (payload) {
1210
1290
  return payload;
@@ -1251,7 +1331,8 @@ class KoniState {
1251
1331
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
1252
1332
  throw new _EvmProviderError.EvmProviderError(_KoniTypes.EvmProviderErrorType.INVALID_PARAMS, e === null || e === void 0 ? void 0 : e.message);
1253
1333
  }
1254
- const gasPrice = await web3.eth.getGasPrice();
1334
+ const _price = await web3.eth.getGasPrice();
1335
+ const gasPrice = (0, _eth.recalculateGasPrice)(_price, networkKey);
1255
1336
  transaction.gasPrice = gasPrice;
1256
1337
  const estimateGas = new _util.BN(gasPrice.toString()).mul(new _util.BN(transaction.gas)).toString();
1257
1338
 
@@ -1488,7 +1569,7 @@ class KoniState {
1488
1569
  const chainMap = this.chainService.getChainInfoMap();
1489
1570
  const balanceDataList = await Promise.all(promiseList);
1490
1571
  balanceDataList.forEach(balanceData => {
1491
- balanceData && balanceData.forEach(_ref11 => {
1572
+ balanceData && balanceData.forEach(_ref12 => {
1492
1573
  var _currentAssetSettings;
1493
1574
  let {
1494
1575
  balance,
@@ -1497,7 +1578,7 @@ class KoniState {
1497
1578
  locked,
1498
1579
  network,
1499
1580
  symbol
1500
- } = _ref11;
1581
+ } = _ref12;
1501
1582
  const chain = _subscanChainMap.SUBSCAN_BALANCE_CHAIN_MAP_REVERSE[network];
1502
1583
  const chainInfo = chain ? chainMap[chain] : null;
1503
1584
  const balanceIsEmpty = (!balance || balance === '0') && (!locked || locked === '0') && (!bonded || bonded === '0');
@@ -1686,7 +1767,7 @@ class KoniState {
1686
1767
  };
1687
1768
  balanceItem.free = ((_zkBalances$i = zkBalances[i]) === null || _zkBalances$i === void 0 ? void 0 : _zkBalances$i.toString()) || '0';
1688
1769
  balanceItem.state = _KoniTypes.APIItemState.READY;
1689
- this.setBalanceItem(balanceItem.tokenSlug, balanceItem);
1770
+ this.setBalanceItem([balanceItem]);
1690
1771
  }
1691
1772
  }).catch(console.warn);
1692
1773
  }
@@ -4,12 +4,12 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.KoniSubscription = void 0;
7
- var _balance = require("@subwallet/extension-base/koni/api/dotsama/balance");
8
7
  var _crowdloan = require("@subwallet/extension-base/koni/api/dotsama/crowdloan");
9
8
  var _staking = require("@subwallet/extension-base/koni/api/staking");
10
9
  var _bonding = require("@subwallet/extension-base/koni/api/staking/bonding");
11
10
  var _paraChain = require("@subwallet/extension-base/koni/api/staking/paraChain");
12
11
  var _handlers = require("@subwallet/extension-base/koni/background/handlers");
12
+ var _balance = require("@subwallet/extension-base/services/balance-service/helpers/subscribe/balance");
13
13
  var _utils = require("@subwallet/extension-base/services/chain-service/utils");
14
14
  var _types = require("@subwallet/extension-base/services/event-service/types");
15
15
  var _utils2 = require("@subwallet/extension-base/utils");
@@ -153,7 +153,7 @@ class KoniSubscription {
153
153
  }
154
154
  });
155
155
  const unsub = (0, _balance.subscribeBalance)(addresses, filteredChainInfoMap, substrateApiMap, evmApiMap, result => {
156
- this.state.setBalanceItem(result.tokenSlug, result);
156
+ this.state.setBalanceItem(result);
157
157
  });
158
158
  const unsub2 = this.state.subscribeMantaPayBalance();
159
159
  if (onlyRunOnFirstTime) {
@@ -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.1.23-0'
16
+ version: '1.1.24-1'
17
17
  };
18
18
  exports.packageInfo = packageInfo;