@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
@@ -129,11 +129,19 @@ class SubscanService {
129
129
  }
130
130
  getExtrinsicsList(chain, address) {
131
131
  let page = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
132
+ let blockRange = arguments.length > 3 ? arguments[3] : undefined;
133
+ const _blockRange = (() => {
134
+ if (!blockRange || !blockRange.to) {
135
+ return null;
136
+ }
137
+ return `${blockRange.from || 0}-${blockRange.to}`;
138
+ })();
132
139
  return this.addRequest(async () => {
133
140
  const rs = await this.postRequest(this.getApiUrl(chain, 'api/scan/extrinsics'), {
134
141
  page,
135
142
  row: QUERY_ROW,
136
- address
143
+ address,
144
+ block_range: _blockRange
137
145
  });
138
146
  if (rs.status !== 200) {
139
147
  throw new _SWError.SWError('SubscanService.getExtrinsicsList', await rs.text());
@@ -143,22 +151,38 @@ class SubscanService {
143
151
  });
144
152
  }
145
153
  async fetchAllPossibleExtrinsicItems(chain, address, cbAfterEachRequest) {
146
- let count = 0;
154
+ let limit = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
155
+ page: 10,
156
+ record: 1000
157
+ };
158
+ let maxCount = 0;
159
+ let currentCount = 0;
160
+ const blockRange = {
161
+ from: null,
162
+ to: null
163
+ };
147
164
  const resultMap = {};
148
165
  const _getExtrinsicItems = async page => {
149
- const res = await this.getExtrinsicsList(chain, address, page);
166
+ const res = await this.getExtrinsicsList(chain, address, page, blockRange);
150
167
  if (!res || !res.count || !res.extrinsics || !res.extrinsics.length) {
151
168
  return;
152
169
  }
153
- if (res.count > count) {
154
- count = res.count;
170
+ if (res.count > maxCount) {
171
+ maxCount = res.count;
155
172
  }
156
173
  cbAfterEachRequest === null || cbAfterEachRequest === void 0 ? void 0 : cbAfterEachRequest(res.extrinsics);
157
174
  res.extrinsics.forEach(item => {
158
175
  resultMap[item.extrinsic_hash] = item;
159
176
  });
160
- if (Object.values(resultMap).length < count) {
177
+ currentCount += res.extrinsics.length;
178
+ if (page > limit.page || currentCount > limit.record) {
179
+ return;
180
+ }
181
+ if (currentCount < maxCount) {
161
182
  await (0, _utils.wait)(100);
183
+ if (page === 0) {
184
+ blockRange.to = res.extrinsics[0].block_num;
185
+ }
162
186
  await _getExtrinsicItems(++page);
163
187
  }
164
188
  };
@@ -168,16 +192,16 @@ class SubscanService {
168
192
  getTransfersList(chain, address) {
169
193
  let page = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
170
194
  let direction = arguments.length > 3 ? arguments[3] : undefined;
171
- const requestBody = {
172
- page,
173
- row: QUERY_ROW,
174
- address
175
- };
176
- if (direction) {
177
- requestBody.direction = direction;
178
- }
195
+ let blockRange = arguments.length > 4 ? arguments[4] : undefined;
179
196
  return this.addRequest(async () => {
180
- const rs = await this.postRequest(this.getApiUrl(chain, 'api/v2/scan/transfers'), requestBody);
197
+ const rs = await this.postRequest(this.getApiUrl(chain, 'api/v2/scan/transfers'), {
198
+ page,
199
+ row: QUERY_ROW,
200
+ address,
201
+ direction: direction || null,
202
+ from_block: (blockRange === null || blockRange === void 0 ? void 0 : blockRange.from) || null,
203
+ to_block: (blockRange === null || blockRange === void 0 ? void 0 : blockRange.to) || null
204
+ });
181
205
  if (rs.status !== 200) {
182
206
  throw new _SWError.SWError('SubscanService.getTransfersList', await rs.text());
183
207
  }
@@ -186,27 +210,47 @@ class SubscanService {
186
210
  });
187
211
  }
188
212
  async fetchAllPossibleTransferItems(chain, address, direction, cbAfterEachRequest) {
189
- let count = 0;
213
+ let limit = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {
214
+ page: 10,
215
+ record: 1000
216
+ };
217
+ let maxCount = 0;
218
+ let currentCount = 0;
219
+ const blockRange = {
220
+ from: null,
221
+ to: null
222
+ };
190
223
  const resultMap = {};
191
224
  const _getTransferItems = async page => {
192
- const res = await this.getTransfersList(chain, address, page, direction);
225
+ const res = await this.getTransfersList(chain, address, page, direction, blockRange);
193
226
  if (!res || !res.count || !res.transfers || !res.transfers.length) {
194
227
  return;
195
228
  }
196
- if (res.count > count) {
197
- count = res.count;
229
+ if (res.count > maxCount) {
230
+ maxCount = res.count;
198
231
  }
199
232
  cbAfterEachRequest === null || cbAfterEachRequest === void 0 ? void 0 : cbAfterEachRequest(res.transfers);
200
233
  res.transfers.forEach(item => {
201
- resultMap[item.hash] = item;
234
+ if (!resultMap[item.hash]) {
235
+ resultMap[item.hash] = [item];
236
+ } else {
237
+ resultMap[item.hash].push(item);
238
+ }
202
239
  });
203
- if (Object.values(resultMap).length < count) {
240
+ currentCount += res.transfers.length;
241
+ if (page > limit.page || currentCount > limit.record) {
242
+ return;
243
+ }
244
+ if (currentCount < maxCount) {
204
245
  await (0, _utils.wait)(100);
246
+ if (page === 0) {
247
+ blockRange.to = res.transfers[0].block_num;
248
+ }
205
249
  await _getTransferItems(++page);
206
250
  }
207
251
  };
208
252
  await _getTransferItems(0);
209
- return Object.values(resultMap);
253
+ return resultMap;
210
254
  }
211
255
  }
212
256
  exports.SubscanService = SubscanService;
@@ -121,7 +121,8 @@ class TransactionService {
121
121
  if (!web3) {
122
122
  validationResponse.errors.push(new _TransactionError.TransactionError(_KoniTypes.BasicTxErrorType.CHAIN_DISCONNECTED, undefined));
123
123
  } else {
124
- const gasPrice = await web3.api.eth.getGasPrice();
124
+ const _price = await web3.api.eth.getGasPrice();
125
+ const gasPrice = (0, _eth.recalculateGasPrice)(_price, chainInfo.slug);
125
126
  const gasLimit = await web3.api.eth.estimateGas(transaction);
126
127
  estimateFee.value = (gasLimit * parseInt(gasPrice)).toString();
127
128
  }
@@ -932,8 +933,8 @@ class TransactionService {
932
933
  }).forEach(_ref11 => {
933
934
  let {
934
935
  event: {
935
- method,
936
- data: [error]
936
+ data: [error],
937
+ method
937
938
  }
938
939
  } = _ref11;
939
940
  if (method === 'ExtrinsicFailed') {
@@ -0,0 +1 @@
1
+ "use strict";
@@ -3,6 +3,17 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+ var _balance = require("./balance");
7
+ Object.keys(_balance).forEach(function (key) {
8
+ if (key === "default" || key === "__esModule") return;
9
+ if (key in exports && exports[key] === _balance[key]) return;
10
+ Object.defineProperty(exports, key, {
11
+ enumerable: true,
12
+ get: function () {
13
+ return _balance[key];
14
+ }
15
+ });
16
+ });
6
17
  var _buy = require("./buy");
7
18
  Object.keys(_buy).forEach(function (key) {
8
19
  if (key === "default" || key === "__esModule") return;
@@ -1,12 +1,14 @@
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
  });
6
- exports.convertSubjectInfoToAddresses = void 0;
7
+ exports.getAccountJsonByAddress = exports.convertSubjectInfoToAddresses = void 0;
7
8
  exports.quickFormatAddressToCompare = quickFormatAddressToCompare;
8
9
  exports.simpleAddress = void 0;
9
10
  var _index = require("@subwallet/extension-base/utils/index");
11
+ var _uiKeyring = _interopRequireDefault(require("@subwallet/ui-keyring"));
10
12
  var _utilCrypto = require("@polkadot/util-crypto");
11
13
  // Copyright 2019-2022 @subwallet/extension-base authors & contributors
12
14
  // SPDX-License-Identifier: Apache-2.0
@@ -31,4 +33,32 @@ const convertSubjectInfoToAddresses = subjectInfo => {
31
33
  ...info.json.meta
32
34
  }));
33
35
  };
34
- exports.convertSubjectInfoToAddresses = convertSubjectInfoToAddresses;
36
+
37
+ /**
38
+ * @function getAccountJsonByAddress
39
+ * @desc Get account info by address
40
+ * <p>
41
+ * Note: Use on the background only
42
+ * </p>
43
+ * @param {string} address - Address
44
+ * @returns {AccountJson|null} - Account info or null if not found
45
+ */
46
+ exports.convertSubjectInfoToAddresses = convertSubjectInfoToAddresses;
47
+ const getAccountJsonByAddress = address => {
48
+ try {
49
+ const pair = _uiKeyring.default.getPair(address);
50
+ if (pair) {
51
+ return {
52
+ address: pair.address,
53
+ type: pair.type,
54
+ ...pair.meta
55
+ };
56
+ } else {
57
+ return null;
58
+ }
59
+ } catch (e) {
60
+ console.warn(e);
61
+ return null;
62
+ }
63
+ };
64
+ exports.getAccountJsonByAddress = getAccountJsonByAddress;
package/cjs/utils/eth.js CHANGED
@@ -4,7 +4,8 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.signatureToHex = exports.createTransactionFromRLP = exports.anyNumberToBN = exports.Transaction = void 0;
7
+ exports.signatureToHex = exports.recalculateGasPrice = exports.createTransactionFromRLP = exports.anyNumberToBN = exports.Transaction = void 0;
8
+ var _constants = require("@subwallet/extension-base/constants");
8
9
  var _bignumber = _interopRequireDefault(require("bignumber.js"));
9
10
  var _ethers = require("ethers");
10
11
  var _util = require("@polkadot/util");
@@ -69,4 +70,8 @@ const signatureToHex = sig => {
69
70
  const hexV = (0, _util.hexStripPrefix)((0, _util.numberToHex)(v));
70
71
  return hexR + hexS + hexV;
71
72
  };
72
- exports.signatureToHex = signatureToHex;
73
+ exports.signatureToHex = signatureToHex;
74
+ const recalculateGasPrice = (_price, chain) => {
75
+ return _constants.NETWORK_MULTI_GAS_FEE.includes(chain) ? new _bignumber.default(_price).multipliedBy(_constants.GAS_PRICE_RATIO).toFixed(0) : _price;
76
+ };
77
+ exports.recalculateGasPrice = recalculateGasPrice;
@@ -78,6 +78,18 @@ var _i18next = require("i18next");
78
78
  var _util = require("@polkadot/util");
79
79
  var _utilCrypto = require("@polkadot/util-crypto");
80
80
  var _canDerive = require("./canDerive");
81
+ var _account = require("./account");
82
+ Object.keys(_account).forEach(function (key) {
83
+ if (key === "default" || key === "__esModule") return;
84
+ if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
85
+ if (key in exports && exports[key] === _account[key]) return;
86
+ Object.defineProperty(exports, key, {
87
+ enumerable: true,
88
+ get: function () {
89
+ return _account[key];
90
+ }
91
+ });
92
+ });
81
93
  var _array = require("./array");
82
94
  Object.keys(_array).forEach(function (key) {
83
95
  if (key === "default" || key === "__esModule") return;
@@ -20,5 +20,7 @@ export declare const ALL_GENESIS_HASH: null;
20
20
  export declare const IGNORE_GET_SUBSTRATE_FEATURES_LIST: string[];
21
21
  export declare const IGNORE_QR_SIGNER: string[];
22
22
  export declare const XCM_MIN_AMOUNT_RATIO = 1.2;
23
+ export declare const GAS_PRICE_RATIO = 1.05;
24
+ export declare const NETWORK_MULTI_GAS_FEE: string[];
23
25
  export * from './staking';
24
26
  export * from './storage';
@@ -23,5 +23,7 @@ export const ALL_GENESIS_HASH = null;
23
23
  export const IGNORE_GET_SUBSTRATE_FEATURES_LIST = ['astarEvm', 'ethereum', 'ethereum_goerli', 'binance', 'binance_test', 'boba_rinkeby', 'boba', 'bobabase', 'bobabeam'];
24
24
  export const IGNORE_QR_SIGNER = [];
25
25
  export const XCM_MIN_AMOUNT_RATIO = 1.2;
26
+ export const GAS_PRICE_RATIO = 1.05;
27
+ export const NETWORK_MULTI_GAS_FEE = ['astarEvm'];
26
28
  export * from "./staking.js";
27
29
  export * from "./storage.js";
@@ -104,6 +104,7 @@ export async function getCancelWithdrawalExtrinsic(substrateApi, chain, selected
104
104
  export function subscribeEssentialChainStakingMetadata(substrateApiMap, chainInfoMap, callback) {
105
105
  const unsubList = [];
106
106
 
107
+ // TODO: replace with for of to improve performance
107
108
  // eslint-disable-next-line @typescript-eslint/no-misused-promises
108
109
  Object.values(chainInfoMap).forEach(async chainInfo => {
109
110
  if (!substrateApiMap[chainInfo.slug]) {
@@ -4,6 +4,10 @@
4
4
  export async function getEVMBalance(networkKey, addresses, evmApiMap) {
5
5
  const web3Api = evmApiMap[networkKey];
6
6
  return await Promise.all(addresses.map(async address => {
7
- return await web3Api.api.eth.getBalance(address);
7
+ try {
8
+ return await web3Api.api.eth.getBalance(address);
9
+ } catch (e) {
10
+ return '0';
11
+ }
8
12
  }));
9
13
  }
@@ -13,5 +13,5 @@ interface HandleTransferBalanceResultProps {
13
13
  export declare const handleTransferBalanceResult: ({ callback, changeValue, networkKey, receipt, response, updateState }: HandleTransferBalanceResultProps) => void;
14
14
  export declare function getEVMTransactionObject(chainInfo: _ChainInfo, from: string, to: string, value: string, transferAll: boolean, evmApiMap: Record<string, _EvmApi>): Promise<[TransactionConfig, string]>;
15
15
  export declare function getERC20TransactionObject(assetAddress: string, chainInfo: _ChainInfo, from: string, to: string, value: string, transferAll: boolean, evmApiMap: Record<string, _EvmApi>): Promise<[TransactionConfig, string]>;
16
- export declare function getERC721Transaction(web3Api: _EvmApi, contractAddress: string, senderAddress: string, recipientAddress: string, tokenId: string): Promise<TransactionConfig>;
16
+ export declare function getERC721Transaction(web3Api: _EvmApi, chain: string, contractAddress: string, senderAddress: string, recipientAddress: string, tokenId: string): Promise<TransactionConfig>;
17
17
  export {};
@@ -5,6 +5,7 @@ import { ExternalRequestPromiseStatus } from '@subwallet/extension-base/backgrou
5
5
  import { getERC20Contract } from '@subwallet/extension-base/koni/api/tokens/evm/web3';
6
6
  import { _BALANCE_PARSING_CHAIN_GROUP, EVM_REFORMAT_DECIMALS } from '@subwallet/extension-base/services/chain-service/constants';
7
7
  import { _ERC721_ABI } from '@subwallet/extension-base/services/chain-service/helper';
8
+ import { recalculateGasPrice } from '@subwallet/extension-base/utils/eth';
8
9
  import { BN, hexToBn } from '@polkadot/util';
9
10
  export const handleTransferBalanceResult = ({
10
11
  callback,
@@ -35,7 +36,8 @@ export const handleTransferBalanceResult = ({
35
36
  export async function getEVMTransactionObject(chainInfo, from, to, value, transferAll, evmApiMap) {
36
37
  const networkKey = chainInfo.slug;
37
38
  const web3Api = evmApiMap[networkKey];
38
- const gasPrice = await web3Api.api.eth.getGasPrice();
39
+ const _price = await web3Api.api.eth.getGasPrice();
40
+ const gasPrice = recalculateGasPrice(_price, chainInfo.slug);
39
41
  const transactionObject = {
40
42
  gasPrice: gasPrice,
41
43
  to: to,
@@ -69,11 +71,12 @@ export async function getERC20TransactionObject(assetAddress, chainInfo, from, t
69
71
  return erc20Contract.methods.transfer(to, transferValue).encodeABI();
70
72
  }
71
73
  const transferData = generateTransferData(to, transferValue);
72
- const [gasLimit, gasPrice] = await Promise.all([
74
+ const [gasLimit, _price] = await Promise.all([
73
75
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
74
76
  erc20Contract.methods.transfer(to, transferValue).estimateGas({
75
77
  from
76
78
  }), evmApi.api.eth.getGasPrice()]);
79
+ const gasPrice = recalculateGasPrice(_price, chainInfo.slug);
77
80
  const transactionObject = {
78
81
  gasPrice: gasPrice,
79
82
  gas: gasLimit,
@@ -87,14 +90,15 @@ export async function getERC20TransactionObject(assetAddress, chainInfo, from, t
87
90
  }
88
91
  return [transactionObject, transferValue];
89
92
  }
90
- export async function getERC721Transaction(web3Api, contractAddress, senderAddress, recipientAddress, tokenId) {
93
+ export async function getERC721Transaction(web3Api, chain, contractAddress, senderAddress, recipientAddress, tokenId) {
91
94
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
92
95
  const contract = new web3Api.api.eth.Contract(_ERC721_ABI, contractAddress);
93
- const [gasLimit, gasPrice] = await Promise.all([
96
+ const [gasLimit, _price] = await Promise.all([
94
97
  // eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
95
98
  contract.methods.safeTransferFrom(senderAddress, recipientAddress, tokenId).estimateGas({
96
99
  from: senderAddress
97
100
  }), web3Api.api.eth.getGasPrice()]);
101
+ const gasPrice = recalculateGasPrice(_price, chain);
98
102
  return {
99
103
  from: senderAddress,
100
104
  gasPrice,
@@ -1,7 +1,7 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { CRON_REFRESH_NFT_INTERVAL, CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL, CRON_REFRESH_STAKING_REWARD_INTERVAL, CRON_SYNC_MANTA_PAY } from '@subwallet/extension-base/constants';
4
+ import { CRON_REFRESH_NFT_INTERVAL, CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL, CRON_SYNC_MANTA_PAY } from '@subwallet/extension-base/constants';
5
5
  import { _isChainSupportEvmNft, _isChainSupportNativeNft, _isChainSupportWasmNft } from '@subwallet/extension-base/services/chain-service/utils';
6
6
  import { waitTimeout } from '@subwallet/extension-base/utils';
7
7
  import { Subject } from 'rxjs';
@@ -104,8 +104,8 @@ export class KoniCron {
104
104
  if (Object.keys(this.state.getSubstrateApiMap()).length !== 0 || Object.keys(this.state.getEvmApiMap()).length !== 0) {
105
105
  this.resetNft(currentAccountInfo.address);
106
106
  this.addCron('refreshNft', this.refreshNft(currentAccountInfo.address, this.state.getApiMap(), this.state.getSmartContractNfts(), this.state.getActiveChainInfoMap()), CRON_REFRESH_NFT_INTERVAL);
107
- this.addCron('refreshStakingReward', this.refreshStakingReward(currentAccountInfo.address), CRON_REFRESH_STAKING_REWARD_INTERVAL);
108
- this.addCron('refreshPoolingSta kingReward', this.refreshStakingRewardFastInterval(currentAccountInfo.address), CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL);
107
+ // this.addCron('refreshStakingReward', this.refreshStakingReward(currentAccountInfo.address), CRON_REFRESH_STAKING_REWARD_INTERVAL);
108
+ this.addCron('refreshPoolingStakingReward', this.refreshStakingRewardFastInterval(currentAccountInfo.address), CRON_REFRESH_STAKING_REWARD_FAST_INTERVAL);
109
109
  this.addCron('syncMantaPay', this.syncMantaPay, CRON_SYNC_MANTA_PAY);
110
110
  } else {
111
111
  this.setStakingRewardReady();
@@ -28,9 +28,8 @@ import { EXTENSION_REQUEST_URL } from '@subwallet/extension-base/services/reques
28
28
  import { DEFAULT_AUTO_LOCK_TIME } from '@subwallet/extension-base/services/setting-service/constants';
29
29
  import { WALLET_CONNECT_EIP155_NAMESPACE } from '@subwallet/extension-base/services/wallet-connect-service/constants';
30
30
  import { isProposalExpired, isSupportWalletConnectChain, isSupportWalletConnectNamespace } from '@subwallet/extension-base/services/wallet-connect-service/helpers';
31
- import { isSameAddress, reformatAddress, uniqueStringArray } from '@subwallet/extension-base/utils';
32
- import { convertSubjectInfoToAddresses } from '@subwallet/extension-base/utils/address';
33
- import { createTransactionFromRLP, signatureToHex } from '@subwallet/extension-base/utils/eth';
31
+ import { convertSubjectInfoToAddresses, isSameAddress, reformatAddress, uniqueStringArray } from '@subwallet/extension-base/utils';
32
+ import { createTransactionFromRLP, recalculateGasPrice, signatureToHex } from '@subwallet/extension-base/utils/eth';
34
33
  import { parseContractInput, parseEvmRlp } from '@subwallet/extension-base/utils/eth/parseTransaction';
35
34
  import { balanceFormatter, formatNumber } from '@subwallet/extension-base/utils/number';
36
35
  import { createPair } from '@subwallet/keyring';
@@ -1725,7 +1724,7 @@ export default class KoniExtension {
1725
1724
  } = inputData;
1726
1725
  const contractAddress = params.contractAddress;
1727
1726
  const tokenId = params.tokenId;
1728
- const transaction = await getERC721Transaction(this.#koniState.getEvmApi(networkKey), contractAddress, senderAddress, recipientAddress, tokenId);
1727
+ const transaction = await getERC721Transaction(this.#koniState.getEvmApi(networkKey), networkKey, contractAddress, senderAddress, recipientAddress, tokenId);
1729
1728
 
1730
1729
  // this.addContact(recipientAddress);
1731
1730
 
@@ -1872,7 +1871,8 @@ export default class KoniExtension {
1872
1871
  // null address
1873
1872
  from: address
1874
1873
  };
1875
- const gasPrice = await web3.api.eth.getGasPrice();
1874
+ const _price = await web3.api.eth.getGasPrice();
1875
+ const gasPrice = recalculateGasPrice(_price, networkKey);
1876
1876
  const gasLimit = await web3.api.eth.estimateGas(transaction);
1877
1877
  estimatedFee = (gasLimit * parseInt(gasPrice)).toString();
1878
1878
  } else {
@@ -4062,6 +4062,15 @@ export default class KoniExtension {
4062
4062
  case 'pri(buyService.services.subscribe)':
4063
4063
  return this.subscribeBuyServices(id, port);
4064
4064
  /* Buy service */
4065
+
4066
+ /* Database */
4067
+ case 'pri(database.export)':
4068
+ return this.#koniState.dbService.exportDB();
4069
+ case 'pri(database.import)':
4070
+ return this.#koniState.dbService.importDB(request);
4071
+ case 'pri(database.checkMetadata)':
4072
+ return this.#koniState.dbService.checkImportMetadata(request);
4073
+ /* Database */
4065
4074
  // Default
4066
4075
  default:
4067
4076
  throw new Error(`Unable to handle message of type ${type}`);
@@ -1,9 +1,10 @@
1
1
  /// <reference types="chrome" />
2
- import { ActiveCronAndSubscriptionMap, CronServiceType, RequestCronAndSubscriptionAction, RequestInitCronAndSubscription, SubscriptionServiceType } from '@subwallet/extension-base/background/KoniTypes';
2
+ import { ActiveCronAndSubscriptionMap, CronServiceType, MobileData, RequestCronAndSubscriptionAction, RequestInitCronAndSubscription, SubscriptionServiceType } from '@subwallet/extension-base/background/KoniTypes';
3
3
  import { MessageTypes, RequestTypes, ResponseType } from '@subwallet/extension-base/background/types';
4
4
  import KoniState from '@subwallet/extension-base/koni/background/handlers/State';
5
5
  export default class Mobile {
6
6
  private state;
7
+ private restoreHandler;
7
8
  constructor(state: KoniState);
8
9
  ping(): string;
9
10
  initCronAndSubscription({ cron: { activeServices, intervalMap }, subscription: { activeServices } }: RequestInitCronAndSubscription): ActiveCronAndSubscriptionMap;
@@ -17,5 +18,8 @@ export default class Mobile {
17
18
  startSubscriptionServices(services: SubscriptionServiceType[]): void;
18
19
  stopSubscriptionServices(services: SubscriptionServiceType[]): void;
19
20
  restartSubscriptionServices(services: SubscriptionServiceType[]): void;
21
+ mobileBackup(): Promise<MobileData>;
22
+ mobileRestore({ indexedDB, storage }: Partial<MobileData>): Promise<void>;
23
+ waitRestore(): Promise<void>;
20
24
  handle<TMessageType extends MessageTypes>(id: string, type: TMessageType, request: RequestTypes[TMessageType], port: chrome.runtime.Port): Promise<ResponseType<TMessageType>>;
21
25
  }
@@ -1,6 +1,7 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
+ import { createPromiseHandler } from '@subwallet/extension-base/utils/promise';
4
5
  const DEFAULT_SERVICE_MAP = {
5
6
  subscription: {
6
7
  chainRegistry: true,
@@ -20,6 +21,7 @@ const DEFAULT_SERVICE_MAP = {
20
21
  export default class Mobile {
21
22
  // @ts-ignore
22
23
 
24
+ restoreHandler = createPromiseHandler();
23
25
  constructor(state) {
24
26
  this.state = state;
25
27
  }
@@ -92,6 +94,31 @@ export default class Mobile {
92
94
  restartSubscriptionServices(services) {
93
95
  console.log('restartSubscriptionServices');
94
96
  }
97
+ async mobileBackup() {
98
+ const indexedDB = await this.state.dbService.exportDB();
99
+ return {
100
+ storage: JSON.stringify(localStorage),
101
+ indexedDB
102
+ };
103
+ }
104
+ async mobileRestore({
105
+ indexedDB,
106
+ storage
107
+ }) {
108
+ if (storage) {
109
+ const storageData = JSON.parse(storage);
110
+ for (const key in storageData) {
111
+ localStorage.setItem(key, storageData[key]);
112
+ }
113
+ }
114
+ if (indexedDB) {
115
+ await this.state.dbService.importDB(indexedDB);
116
+ }
117
+ this.restoreHandler.resolve();
118
+ }
119
+ waitRestore() {
120
+ return this.restoreHandler.promise;
121
+ }
95
122
 
96
123
  // eslint-disable-next-line @typescript-eslint/require-await
97
124
  async handle(id, type, request, port) {
@@ -120,6 +147,10 @@ export default class Mobile {
120
147
  return this.stopSubscriptionServices(request);
121
148
  case 'mobile(subscription.restart)':
122
149
  return this.restartSubscriptionServices(request);
150
+ case 'mobile(storage.restore)':
151
+ return this.mobileRestore(request);
152
+ case 'mobile(storage.backup)':
153
+ return this.mobileBackup();
123
154
  default:
124
155
  throw new Error(`Unable to handle message of type ${type}`);
125
156
  }
@@ -1,6 +1,6 @@
1
1
  /// <reference types="chrome" />
2
2
  import { _AssetRef, _AssetType, _ChainAsset, _ChainInfo, _MultiChainAsset } from '@subwallet/chain-list/types';
3
- import { AddTokenRequestExternal, AmountData, ApiMap, AuthRequestV2, BalanceItem, BalanceJson, ChainStakingMetadata, ConfirmationsQueue, CrowdloanItem, CrowdloanJson, CurrentAccountInfo, EvmSendTransactionParams, ExternalRequestPromise, MantaPayConfig, MantaPaySyncState, NftCollection, NftItem, NftJson, NominatorMetadata, RequestAccountExportPrivateKey, RequestCheckPublicAndSecretKey, RequestConfirmationComplete, RequestSettingsType, ResponseAccountExportPrivateKey, ResponseCheckPublicAndSecretKey, ServiceInfo, SingleModeJson, StakingItem, StakingJson, StakingRewardItem, StakingRewardJson, StakingType, UiSettings } from '@subwallet/extension-base/background/KoniTypes';
3
+ import { AddTokenRequestExternal, AmountData, ApiMap, AuthRequestV2, ChainStakingMetadata, ConfirmationsQueue, CrowdloanItem, CrowdloanJson, CurrentAccountInfo, EvmSendTransactionParams, ExternalRequestPromise, MantaPayConfig, MantaPaySyncState, NftCollection, NftItem, NftJson, NominatorMetadata, RequestAccountExportPrivateKey, RequestCheckPublicAndSecretKey, RequestConfirmationComplete, RequestSettingsType, ResponseAccountExportPrivateKey, ResponseCheckPublicAndSecretKey, ServiceInfo, SingleModeJson, StakingItem, StakingJson, StakingRewardItem, StakingRewardJson, StakingType, UiSettings } from '@subwallet/extension-base/background/KoniTypes';
4
4
  import { AccountJson, RequestAuthorizeTab, RequestRpcSend, RequestRpcSubscribe, RequestRpcUnsubscribe, RequestSign, ResponseRpcListProviders, ResponseSigning } from '@subwallet/extension-base/background/types';
5
5
  import { BalanceService } from '@subwallet/extension-base/services/balance-service';
6
6
  import BuyService from '@subwallet/extension-base/services/buy-service';
@@ -20,6 +20,7 @@ import DatabaseService from '@subwallet/extension-base/services/storage-service/
20
20
  import { SubscanService } from '@subwallet/extension-base/services/subscan-service';
21
21
  import TransactionService from '@subwallet/extension-base/services/transaction-service';
22
22
  import WalletConnectService from '@subwallet/extension-base/services/wallet-connect-service';
23
+ import { BalanceItem, BalanceJson, BalanceMap } from '@subwallet/extension-base/types';
23
24
  import { MetadataDef, ProviderMeta } from '@subwallet/extension-inject/types';
24
25
  import SimpleKeyring from 'eth-simple-keyring';
25
26
  import { BehaviorSubject, Subject } from 'rxjs';
@@ -83,7 +84,7 @@ export default class KoniState {
83
84
  saveMetadata(meta: MetadataDef): void;
84
85
  sign(url: string, request: RequestSign, account: AccountJson): Promise<ResponseSigning>;
85
86
  get authSubjectV2(): BehaviorSubject<import("@subwallet/extension-base/background/types").AuthorizeRequest[]>;
86
- generateDefaultBalanceMap(): Record<string, BalanceItem>;
87
+ generateDefaultBalanceMap(): BalanceMap;
87
88
  private afterChainServiceInit;
88
89
  init(): Promise<void>;
89
90
  initMantaPay(password: string): Promise<void>;
@@ -151,12 +152,13 @@ export default class KoniState {
151
152
  getAllAddresses(): string[];
152
153
  private removeInactiveChainBalances;
153
154
  getBalance(reset?: boolean): BalanceJson;
154
- getStoredBalance(address: string): Promise<Record<string, BalanceItem>>;
155
+ getStoredBalance(address: string): Promise<BalanceMap>;
155
156
  handleSwitchAccount(newAddress: string): Promise<void>;
156
157
  resetBalanceMap(newAddress: string): Promise<void>;
157
158
  resetCrowdloanMap(newAddress: string): Promise<void>;
158
159
  resetStaking(newAddress: string): void;
159
- setBalanceItem(tokenSlug: string, item: BalanceItem): void;
160
+ /** Note: items must be same tokenSlug */
161
+ setBalanceItem(items: BalanceItem[]): void;
160
162
  private updateBalanceStore;
161
163
  subscribeBalance(): Subject<BalanceJson>;
162
164
  getCrowdloan(reset?: boolean): CrowdloanJson;