@subwallet/extension-base 1.3.16-0 → 1.3.18-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 (137) hide show
  1. package/background/KoniTypes.d.ts +12 -2
  2. package/cjs/constants/index.js +6 -3
  3. package/cjs/core/logic-validation/request.js +26 -19
  4. package/cjs/core/logic-validation/transfer.js +18 -17
  5. package/cjs/koni/api/contract-handler/evm/web3.js +3 -3
  6. package/cjs/koni/api/staking/bonding/utils.js +1 -1
  7. package/cjs/koni/background/handlers/Extension.js +289 -124
  8. package/cjs/koni/background/handlers/State.js +1 -8
  9. package/cjs/packageInfo.js +1 -1
  10. package/cjs/services/balance-service/helpers/subscribe/substrate/index.js +14 -2
  11. package/cjs/services/balance-service/index.js +13 -0
  12. package/cjs/services/balance-service/transfer/smart-contract.js +47 -33
  13. package/cjs/services/balance-service/transfer/token.js +5 -4
  14. package/cjs/services/balance-service/transfer/xcm/availBridge.js +14 -18
  15. package/cjs/services/balance-service/transfer/xcm/index.js +30 -61
  16. package/cjs/services/balance-service/transfer/xcm/polygonBridge.js +13 -17
  17. package/cjs/services/balance-service/transfer/xcm/posBridge.js +20 -21
  18. package/cjs/services/balance-service/transfer/xcm/snowBridge.js +7 -7
  19. package/cjs/services/balance-service/transfer/xcm/utils.js +2 -2
  20. package/cjs/services/chain-service/constants.js +3 -3
  21. package/cjs/services/chain-service/index.js +22 -0
  22. package/cjs/services/earning-service/handlers/liquid-staking/stella-swap.js +7 -12
  23. package/cjs/services/earning-service/handlers/native-staking/tao.js +121 -30
  24. package/cjs/services/earning-service/handlers/nomination-pool/index.js +1 -1
  25. package/cjs/services/earning-service/handlers/special.js +34 -14
  26. package/cjs/services/fee-service/interfaces.js +1 -0
  27. package/cjs/services/fee-service/service.js +111 -0
  28. package/cjs/services/fee-service/utils/index.js +99 -113
  29. package/cjs/services/storage-service/db-stores/Balance.js +3 -0
  30. package/cjs/services/swap-service/handler/asset-hub/handler.js +21 -6
  31. package/cjs/services/swap-service/handler/asset-hub/router.js +1 -1
  32. package/cjs/services/swap-service/handler/asset-hub/utils.js +4 -4
  33. package/cjs/services/swap-service/handler/base-handler.js +2 -0
  34. package/cjs/services/swap-service/handler/chainflip-handler.js +25 -4
  35. package/cjs/services/swap-service/handler/hydradx-handler.js +20 -6
  36. package/cjs/services/swap-service/handler/simpleswap-handler.js +23 -3
  37. package/cjs/services/swap-service/index.js +8 -8
  38. package/cjs/services/transaction-service/index.js +23 -3
  39. package/cjs/types/balance/transfer.js +1 -0
  40. package/cjs/types/fee/base.js +1 -0
  41. package/cjs/types/fee/evm.js +16 -1
  42. package/cjs/types/fee/index.js +37 -4
  43. package/cjs/types/fee/option.js +1 -0
  44. package/cjs/types/fee/subscription.js +1 -0
  45. package/cjs/types/fee/substrate.js +1 -0
  46. package/cjs/types/fee/ton.js +1 -0
  47. package/cjs/utils/fee/combine.js +50 -0
  48. package/cjs/utils/fee/index.js +27 -0
  49. package/cjs/utils/fee/transfer.js +374 -0
  50. package/cjs/utils/index.js +12 -0
  51. package/constants/index.d.ts +1 -0
  52. package/constants/index.js +1 -0
  53. package/core/logic-validation/request.js +17 -10
  54. package/core/logic-validation/transfer.d.ts +5 -5
  55. package/core/logic-validation/transfer.js +20 -19
  56. package/core/substrate/xcm-parser.d.ts +1 -1
  57. package/koni/api/contract-handler/evm/web3.js +3 -3
  58. package/koni/api/staking/bonding/utils.js +1 -1
  59. package/koni/background/handlers/Extension.d.ts +4 -3
  60. package/koni/background/handlers/Extension.js +273 -108
  61. package/koni/background/handlers/State.js +1 -8
  62. package/package.json +55 -5
  63. package/packageInfo.js +1 -1
  64. package/services/balance-service/helpers/subscribe/substrate/index.js +14 -2
  65. package/services/balance-service/index.d.ts +1 -0
  66. package/services/balance-service/index.js +13 -0
  67. package/services/balance-service/transfer/smart-contract.d.ts +24 -4
  68. package/services/balance-service/transfer/smart-contract.js +45 -33
  69. package/services/balance-service/transfer/token.js +6 -5
  70. package/services/balance-service/transfer/xcm/availBridge.d.ts +3 -2
  71. package/services/balance-service/transfer/xcm/availBridge.js +11 -15
  72. package/services/balance-service/transfer/xcm/index.d.ts +12 -11
  73. package/services/balance-service/transfer/xcm/index.js +29 -58
  74. package/services/balance-service/transfer/xcm/polygonBridge.d.ts +4 -3
  75. package/services/balance-service/transfer/xcm/polygonBridge.js +13 -17
  76. package/services/balance-service/transfer/xcm/posBridge.d.ts +4 -3
  77. package/services/balance-service/transfer/xcm/posBridge.js +18 -19
  78. package/services/balance-service/transfer/xcm/snowBridge.d.ts +2 -1
  79. package/services/balance-service/transfer/xcm/snowBridge.js +7 -7
  80. package/services/balance-service/transfer/xcm/utils.js +2 -2
  81. package/services/chain-service/constants.js +3 -3
  82. package/services/chain-service/index.d.ts +6 -1
  83. package/services/chain-service/index.js +22 -0
  84. package/services/earning-service/handlers/liquid-staking/stella-swap.js +7 -12
  85. package/services/earning-service/handlers/native-staking/tao.d.ts +7 -2
  86. package/services/earning-service/handlers/native-staking/tao.js +119 -29
  87. package/services/earning-service/handlers/nomination-pool/index.js +1 -1
  88. package/services/earning-service/handlers/special.js +36 -16
  89. package/services/fee-service/interfaces.d.ts +5 -0
  90. package/services/fee-service/interfaces.js +1 -0
  91. package/services/fee-service/service.d.ts +4 -1
  92. package/services/fee-service/service.js +111 -0
  93. package/services/fee-service/utils/index.d.ts +8 -2
  94. package/services/fee-service/utils/index.js +92 -108
  95. package/services/storage-service/db-stores/Balance.d.ts +1 -0
  96. package/services/storage-service/db-stores/Balance.js +3 -0
  97. package/services/swap-service/handler/asset-hub/handler.d.ts +2 -1
  98. package/services/swap-service/handler/asset-hub/handler.js +21 -6
  99. package/services/swap-service/handler/asset-hub/router.js +2 -2
  100. package/services/swap-service/handler/asset-hub/utils.d.ts +1 -1
  101. package/services/swap-service/handler/asset-hub/utils.js +2 -2
  102. package/services/swap-service/handler/base-handler.d.ts +4 -1
  103. package/services/swap-service/handler/base-handler.js +2 -0
  104. package/services/swap-service/handler/chainflip-handler.d.ts +2 -1
  105. package/services/swap-service/handler/chainflip-handler.js +24 -3
  106. package/services/swap-service/handler/hydradx-handler.d.ts +2 -1
  107. package/services/swap-service/handler/hydradx-handler.js +19 -5
  108. package/services/swap-service/handler/simpleswap-handler.d.ts +2 -1
  109. package/services/swap-service/handler/simpleswap-handler.js +23 -3
  110. package/services/swap-service/index.js +8 -8
  111. package/services/transaction-service/index.js +23 -3
  112. package/services/transaction-service/types.d.ts +5 -4
  113. package/types/balance/transfer.d.ts +25 -0
  114. package/types/balance/transfer.js +1 -0
  115. package/types/fee/base.d.ts +8 -0
  116. package/types/fee/base.js +1 -0
  117. package/types/fee/evm.d.ts +46 -16
  118. package/types/fee/evm.js +10 -1
  119. package/types/fee/index.d.ts +4 -1
  120. package/types/fee/index.js +4 -1
  121. package/types/fee/option.d.ts +8 -0
  122. package/types/fee/option.js +1 -0
  123. package/types/fee/subscription.d.ts +12 -0
  124. package/types/fee/subscription.js +1 -0
  125. package/types/fee/substrate.d.ts +15 -0
  126. package/types/fee/substrate.js +1 -0
  127. package/types/fee/ton.d.ts +18 -0
  128. package/types/fee/ton.js +1 -0
  129. package/types/transaction/request.d.ts +13 -3
  130. package/utils/fee/combine.d.ts +12 -0
  131. package/utils/fee/combine.js +42 -0
  132. package/utils/fee/index.d.ts +2 -0
  133. package/utils/fee/index.js +5 -0
  134. package/utils/fee/transfer.d.ts +22 -0
  135. package/utils/fee/transfer.js +363 -0
  136. package/utils/index.d.ts +1 -0
  137. package/utils/index.js +1 -0
@@ -13,6 +13,7 @@ var _xcm = require("@subwallet/extension-base/services/balance-service/transfer/
13
13
  var _utils2 = require("@subwallet/extension-base/services/chain-service/utils");
14
14
  var _types = require("@subwallet/extension-base/types");
15
15
  var _utils3 = require("@subwallet/extension-base/utils");
16
+ var _getId = require("@subwallet/extension-base/utils/getId");
16
17
  var _i18next = require("i18next");
17
18
  var _util = require("@polkadot/util");
18
19
  var _base = _interopRequireDefault(require("./base"));
@@ -80,17 +81,27 @@ class BaseSpecialStakingPoolHandler extends _base.default {
80
81
  value: '0'
81
82
  }), this.state.balanceService.getTransferableBalance(request.address, feeAssetInfo.originChain, feeAssetInfo.slug)]);
82
83
  const bnInputAssetBalance = new _util.BN(inputAssetBalance.value);
83
- const bnAltInputAssetBalance = new _util.BN(altInputAssetBalance.value);
84
84
  const bnMinJoinPool = new _util.BN(poolInfo.statistic.earningThreshold.join);
85
85
  const inputTokenInfo = this.state.chainService.getAssetBySlug(this.inputAsset);
86
86
  const altInputTokenInfo = this.state.chainService.getAssetBySlug(this.altInputAsset);
87
+ const existentialDeposit = new _util.BN((0, _utils2._getAssetExistentialDeposit)(altInputTokenInfo));
88
+ const bnAltInputAssetBalance = new _util.BN(altInputAssetBalance.value);
87
89
  if (bnInputAssetBalance.add(bnAltInputAssetBalance).lt(bnMinJoinPool)) {
90
+ const missingAmount = bnMinJoinPool.sub(bnInputAssetBalance).sub(bnAltInputAssetBalance);
91
+ const isTheSame = missingAmount.toString() === bnMinJoinPool.toString();
88
92
  const originChain = this.state.getChainInfo(inputTokenInfo.originChain);
89
93
  const altChain = this.state.getChainInfo(altInputTokenInfo.originChain);
90
- const parsedMinJoinPool = (0, _utils3.formatNumber)(bnMinJoinPool.toString(), inputAssetInfo.decimals || 0);
94
+ const originSymbol = (0, _utils2._getAssetSymbol)(inputTokenInfo);
95
+ const altSymbol = (0, _utils2._getAssetSymbol)(altInputTokenInfo);
96
+ const originName = originChain.name;
97
+ const altName = altChain.name;
98
+ const parsedMinJoinPool = (0, _utils3.formatNumber)(missingAmount.toString(), inputAssetInfo.decimals || 0);
99
+ const formatparsedMinJoinPool = isTheSame ? parsedMinJoinPool : Number(parsedMinJoinPool) + 0.01;
100
+ const parsedMinAltJoinPool = (0, _utils3.formatNumber)(missingAmount.add(existentialDeposit).toString(), inputAssetInfo.decimals || 0);
101
+ const formatParsedMinAltJoinPool = isTheSame ? parsedMinAltJoinPool : Number(parsedMinAltJoinPool) + 0.01;
91
102
  return {
92
103
  passed: false,
93
- errorMessage: `You need at least ${parsedMinJoinPool} ${inputTokenInfo.symbol} (${originChain.name}) or ${altInputTokenInfo.symbol} (${altChain.name}) to start earning`
104
+ errorMessage: `You need to deposit an additional ${formatparsedMinJoinPool} ${originSymbol} (${originName}) or ${formatParsedMinAltJoinPool} ${altSymbol} (${altName}) to start earning`
94
105
  };
95
106
  }
96
107
  if (this.feeAssets.length === 1) {
@@ -222,13 +233,18 @@ class BaseSpecialStakingPoolHandler extends _base.default {
222
233
  type: _types.YieldStepType.XCM
223
234
  };
224
235
  const xcmOriginSubstrateApi = await this.state.getSubstrateApi(altInputTokenInfo.originChain).isReady;
236
+ const id = (0, _getId.getId)();
237
+ const feeInfo = await this.state.feeService.subscribeChainFee(id, altChainInfo.slug, 'substrate');
225
238
  const xcmTransfer = await (0, _xcm.createXcmExtrinsic)({
239
+ sender: address,
226
240
  originTokenInfo: altInputTokenInfo,
227
241
  destinationTokenInfo: inputTokenInfo,
228
242
  sendingValue: bnAmount.toString(),
229
243
  recipient: address,
230
- chainInfoMap: this.state.getChainInfoMap(),
231
- substrateApi: xcmOriginSubstrateApi
244
+ destinationChain: this.chainInfo,
245
+ originChain: altChainInfo,
246
+ substrateApi: xcmOriginSubstrateApi,
247
+ feeInfo
232
248
  });
233
249
  const _xcmFeeInfo = await xcmTransfer.paymentInfo(address);
234
250
  const xcmFeeInfo = _xcmFeeInfo.toPrimitive();
@@ -288,16 +304,15 @@ class BaseSpecialStakingPoolHandler extends _base.default {
288
304
  processValidation.failedStep = path.steps[1];
289
305
  processValidation.ok = false;
290
306
  processValidation.status = _types.YieldValidationStatus.NOT_ENOUGH_BALANCE;
307
+ const bnMaxXCM = new _util.BN(altInputTokenBalance.value).sub(xcmFee.mul(new _util.BN(_constants.XCM_FEE_RATIO)));
308
+ const inputTokenDecimal = (0, _utils2._getAssetDecimals)(inputTokenInfo);
291
309
  const maxBn = bnInputTokenBalance.add(new _util.BN(altInputTokenBalance.value)).sub(xcmFee).sub(xcmFee);
292
310
  const maxValue = (0, _utils3.formatNumber)(maxBn.toString(), inputTokenInfo.decimals || 0);
293
- const altInputTokenInfo = this.state.getAssetBySlug(altInputTokenSlug);
294
- const symbol = altInputTokenInfo.symbol;
295
- const altNetwork = this.state.getChainInfo(altInputTokenInfo.originChain);
311
+ const maxXCMValue = (0, _utils3.formatNumber)(bnMaxXCM.toString(), inputTokenDecimal);
312
+ const symbol = (0, _utils2._getAssetSymbol)(altInputTokenInfo);
296
313
  const inputNetworkName = this.chainInfo.name;
297
- const altNetworkName = altNetwork.name;
298
- const currentValue = (0, _utils3.formatNumber)(bnInputTokenBalance.toString(), inputTokenInfo.decimals || 0);
299
- const bnMaxXCM = new _util.BN(altInputTokenBalance.value).sub(xcmFee).sub(xcmFee);
300
- const maxXCMValue = (0, _utils3.formatNumber)(bnMaxXCM.toString(), inputTokenInfo.decimals || 0);
314
+ const altNetworkName = (0, _utils2._getAssetName)(altInputTokenInfo);
315
+ const currentValue = (0, _utils3.formatNumber)(bnInputTokenBalance.toString(), inputTokenDecimal);
301
316
  processValidation.message = (0, _i18next.t)('You can only enter a maximum of {{maxValue}} {{symbol}}, which is {{currentValue}} {{symbol}} ({{inputNetworkName}}) and {{maxXCMValue}} {{symbol}} ({{altNetworkName}}). Lower your amount and try again.', {
302
317
  replace: {
303
318
  symbol,
@@ -426,13 +441,18 @@ class BaseSpecialStakingPoolHandler extends _base.default {
426
441
  const bnXcmFee = new _util.BN(xcmFee);
427
442
  const bnAmount = new _util.BN(amount);
428
443
  const bnTotalAmount = bnAmount.sub(bnInputTokenBalance).add(bnXcmFee);
444
+ const id = (0, _getId.getId)();
445
+ const feeInfo = await this.state.feeService.subscribeChainFee(id, originChainInfo.slug, 'substrate');
429
446
  const extrinsic = await (0, _xcm.createXcmExtrinsic)({
430
- chainInfoMap: this.state.getChainInfoMap(),
431
447
  destinationTokenInfo,
432
448
  originTokenInfo,
433
449
  recipient: address,
434
450
  sendingValue: bnTotalAmount.toString(),
435
- substrateApi
451
+ substrateApi,
452
+ sender: address,
453
+ originChain: originChainInfo,
454
+ destinationChain: this.chainInfo,
455
+ feeInfo
436
456
  });
437
457
  const xcmData = {
438
458
  originNetworkKey: originChainInfo.slug,
@@ -0,0 +1 @@
1
+ "use strict";
@@ -12,6 +12,11 @@ var _rxjs = require("rxjs");
12
12
 
13
13
  class FeeService {
14
14
  evmFeeSubject = new _rxjs.BehaviorSubject({});
15
+ chainFeeSubscriptionMap = {
16
+ evm: {},
17
+ substrate: {},
18
+ ton: {}
19
+ };
15
20
  constructor(state) {
16
21
  this.state = state;
17
22
  this.useInfura = true;
@@ -66,5 +71,111 @@ class FeeService {
66
71
  clearInterval(interval);
67
72
  };
68
73
  }
74
+ subscribeChainFee(id, chain, type, callback) {
75
+ return new Promise(resolve => {
76
+ const _callback = value => {
77
+ if (value) {
78
+ callback === null || callback === void 0 ? void 0 : callback(value);
79
+ resolve(value);
80
+ }
81
+ };
82
+ const feeSubscription = this.chainFeeSubscriptionMap[type][chain];
83
+ if (feeSubscription) {
84
+ const observer = feeSubscription.observer;
85
+ _callback(observer.getValue());
86
+
87
+ // If have callback, just subscribe
88
+ if (callback) {
89
+ const subscription = observer.subscribe({
90
+ next: _callback
91
+ });
92
+ this.chainFeeSubscriptionMap[type][chain].subscription[id] = () => {
93
+ if (!subscription.closed) {
94
+ subscription.unsubscribe();
95
+ }
96
+ };
97
+ }
98
+ } else {
99
+ const observer = new _rxjs.BehaviorSubject(undefined);
100
+ const subscription = observer.subscribe({
101
+ next: _callback
102
+ });
103
+ let cancel = false;
104
+ let interval;
105
+ const update = () => {
106
+ if (cancel) {
107
+ clearInterval(interval);
108
+ } else {
109
+ const api = this.state.getEvmApi(chain);
110
+ if (api) {
111
+ (0, _utils2.calculateGasFeeParams)(api, chain).then(info => {
112
+ observer.next(info);
113
+ }).catch(e => {
114
+ console.warn(`Cannot get fee param for ${chain}`, e);
115
+ observer.next({
116
+ type: 'evm',
117
+ gasPrice: '0',
118
+ baseGasFee: undefined,
119
+ options: undefined
120
+ });
121
+ });
122
+ } else {
123
+ observer.next({
124
+ type: type,
125
+ busyNetwork: false,
126
+ options: {
127
+ slow: {
128
+ tip: '0'
129
+ },
130
+ average: {
131
+ tip: '0'
132
+ },
133
+ fast: {
134
+ tip: '0'
135
+ },
136
+ default: 'slow'
137
+ }
138
+ });
139
+ clearInterval(interval);
140
+ }
141
+ }
142
+ };
143
+ update();
144
+
145
+ // If have callback, just subscribe
146
+ if (callback) {
147
+ interval = setInterval(update, 15 * 1000);
148
+ const unsub = () => {
149
+ cancel = true;
150
+ observer.complete();
151
+ clearInterval(interval);
152
+ };
153
+ this.chainFeeSubscriptionMap[type][chain] = {
154
+ observer,
155
+ subscription: {
156
+ [id]: () => {
157
+ if (!subscription.closed) {
158
+ subscription.unsubscribe();
159
+ }
160
+ }
161
+ },
162
+ unsubscribe: unsub
163
+ };
164
+ }
165
+ }
166
+ });
167
+ }
168
+ unsubscribeChainFee(id, chain, type) {
169
+ const subscription = this.chainFeeSubscriptionMap[type][chain];
170
+ if (subscription) {
171
+ const unsub = subscription.subscription[id];
172
+ unsub && unsub();
173
+ delete subscription.subscription[id];
174
+ if (Object.keys(subscription.subscription).length === 0) {
175
+ subscription.unsubscribe();
176
+ delete this.chainFeeSubscriptionMap[type][chain];
177
+ }
178
+ }
179
+ }
69
180
  }
70
181
  exports.default = FeeService;
@@ -4,9 +4,10 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.recalculateGasPrice = exports.parseInfuraFee = exports.fetchSubWalletFeeData = exports.fetchOnlineFeeData = exports.fetchInfuraFeeData = exports.calculateGasFeeParams = void 0;
7
+ exports.recalculateGasPrice = exports.parseInfuraFee = exports.getEIP1559GasFee = exports.fetchSubWalletFeeData = exports.fetchOnlineFeeData = exports.fetchInfuraFeeData = exports.calculateToAmountByReservePool = exports.calculateGasFeeParams = exports.FEE_COVERAGE_PERCENTAGE_SPECIAL_CASE = void 0;
8
8
  var _constants = require("@subwallet/extension-base/constants");
9
- var _utils = require("@subwallet/extension-base/utils");
9
+ var _utils = require("@subwallet/extension-base/services/swap-service/handler/asset-hub/utils");
10
+ var _utils2 = require("@subwallet/extension-base/utils");
10
11
  var _bignumber = _interopRequireDefault(require("bignumber.js"));
11
12
  var _polygonBridge = require("../../balance-service/transfer/xcm/polygonBridge");
12
13
  // Copyright 2019-2022 @subwallet/extension-base
@@ -15,60 +16,79 @@ var _polygonBridge = require("../../balance-service/transfer/xcm/polygonBridge")
15
16
  const INFURA_API_KEY = process.env.INFURA_API_KEY || '';
16
17
  const INFURA_API_KEY_SECRET = process.env.INFURA_API_KEY_SECRET || '';
17
18
  const INFURA_AUTH = 'Basic ' + Buffer.from(INFURA_API_KEY + ':' + INFURA_API_KEY_SECRET).toString('base64');
18
- const parseInfuraFee = info => {
19
- const base = new _bignumber.default(info.estimatedBaseFee).multipliedBy(_utils.BN_WEI);
20
- const low = new _bignumber.default(info.low.suggestedMaxPriorityFeePerGas).multipliedBy(_utils.BN_WEI);
21
- const busyNetwork = base.gt(_utils.BN_ZERO) ? low.dividedBy(base).gte(0.3) : false;
22
- const data = !busyNetwork ? info.low : info.medium;
19
+ const FEE_COVERAGE_PERCENTAGE_SPECIAL_CASE = 105; // percentage
20
+ exports.FEE_COVERAGE_PERCENTAGE_SPECIAL_CASE = FEE_COVERAGE_PERCENTAGE_SPECIAL_CASE;
21
+ const parseInfuraFee = (info, threshold) => {
22
+ const base = new _bignumber.default(info.estimatedBaseFee).multipliedBy(_utils2.BN_WEI);
23
+ const thresholdBN = new _bignumber.default(threshold.busyThreshold).multipliedBy(_utils2.BN_WEI);
24
+ const busyNetwork = thresholdBN.gte(_utils2.BN_ZERO) ? base.gt(thresholdBN) : false;
23
25
  return {
24
26
  busyNetwork,
25
27
  gasPrice: undefined,
26
- baseGasFee: base,
27
- maxFeePerGas: new _bignumber.default(data.suggestedMaxFeePerGas).multipliedBy(_utils.BN_WEI).integerValue(_bignumber.default.ROUND_UP),
28
- maxPriorityFeePerGas: new _bignumber.default(data.suggestedMaxPriorityFeePerGas).multipliedBy(_utils.BN_WEI).integerValue(_bignumber.default.ROUND_UP)
28
+ baseGasFee: base.toFixed(0),
29
+ type: 'evm',
30
+ options: {
31
+ slow: {
32
+ maxFeePerGas: new _bignumber.default(info.low.suggestedMaxFeePerGas).multipliedBy(_utils2.BN_WEI).integerValue(_bignumber.default.ROUND_UP).toFixed(0),
33
+ maxPriorityFeePerGas: new _bignumber.default(info.low.suggestedMaxPriorityFeePerGas).multipliedBy(_utils2.BN_WEI).integerValue(_bignumber.default.ROUND_UP).toFixed(0),
34
+ maxWaitTimeEstimate: info.low.maxWaitTimeEstimate || 0,
35
+ minWaitTimeEstimate: info.low.minWaitTimeEstimate || 0
36
+ },
37
+ average: {
38
+ maxFeePerGas: new _bignumber.default(info.medium.suggestedMaxFeePerGas).multipliedBy(_utils2.BN_WEI).integerValue(_bignumber.default.ROUND_UP).toFixed(0),
39
+ maxPriorityFeePerGas: new _bignumber.default(info.medium.suggestedMaxPriorityFeePerGas).multipliedBy(_utils2.BN_WEI).integerValue(_bignumber.default.ROUND_UP).toFixed(0),
40
+ maxWaitTimeEstimate: info.medium.maxWaitTimeEstimate || 0,
41
+ minWaitTimeEstimate: info.medium.minWaitTimeEstimate || 0
42
+ },
43
+ fast: {
44
+ maxFeePerGas: new _bignumber.default(info.high.suggestedMaxFeePerGas).multipliedBy(_utils2.BN_WEI).integerValue(_bignumber.default.ROUND_UP).toFixed(0),
45
+ maxPriorityFeePerGas: new _bignumber.default(info.high.suggestedMaxPriorityFeePerGas).multipliedBy(_utils2.BN_WEI).integerValue(_bignumber.default.ROUND_UP).toFixed(0),
46
+ maxWaitTimeEstimate: info.high.maxWaitTimeEstimate || 0,
47
+ minWaitTimeEstimate: info.high.minWaitTimeEstimate || 0
48
+ },
49
+ default: busyNetwork ? 'average' : 'slow'
50
+ }
29
51
  };
30
52
  };
31
53
  exports.parseInfuraFee = parseInfuraFee;
32
54
  const fetchInfuraFeeData = async (chainId, infuraAuth) => {
33
- return await new Promise(resolve => {
34
- const baseUrl = 'https://gas.api.infura.io/networks/{{chainId}}/suggestedGasFees';
35
- const url = baseUrl.replaceAll('{{chainId}}', chainId.toString());
36
- fetch(url, {
37
- method: 'GET',
38
- headers: {
39
- Authorization: infuraAuth || INFURA_AUTH
40
- }
41
- }).then(rs => {
42
- return rs.json();
43
- }).then(info => {
44
- resolve(parseInfuraFee(info));
45
- }).catch(e => {
46
- console.warn(e);
47
- resolve(null);
48
- });
49
- });
55
+ const baseUrl = 'https://gas.api.infura.io/networks/{{chainId}}/suggestedGasFees';
56
+ const baseThressholdUrl = 'https://gas.api.infura.io/networks/{{chainId}}/busyThreshold';
57
+ // const baseFeeHistoryUrl = 'https://gas.api.infura.io/networks/{{chainId}}/baseFeeHistory';
58
+ // const baseFeePercentileUrl = 'https://gas.api.infura.io/networks/{{chainId}}/baseFeePercentile';
59
+ const feeUrl = baseUrl.replaceAll('{{chainId}}', chainId.toString());
60
+ const thressholdUrl = baseThressholdUrl.replaceAll('{{chainId}}', chainId.toString());
61
+ try {
62
+ const [feeResp, thressholdResp] = await Promise.all([feeUrl, thressholdUrl].map(url => {
63
+ return fetch(url, {
64
+ method: 'GET',
65
+ headers: {
66
+ Authorization: INFURA_AUTH
67
+ }
68
+ });
69
+ }));
70
+
71
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
72
+ const [feeInfo, thresholdInfo] = await Promise.all([feeResp.json(), thressholdResp.json()]);
73
+ return parseInfuraFee(feeInfo, thresholdInfo);
74
+ } catch (e) {
75
+ console.warn(e);
76
+ return null;
77
+ }
50
78
  };
51
79
  exports.fetchInfuraFeeData = fetchInfuraFeeData;
52
80
  const fetchSubWalletFeeData = async (chainId, networkKey) => {
53
81
  return await new Promise(resolve => {
54
82
  const baseUrl = 'https://api-cache.subwallet.app/sw-evm-gas/{{chain}}';
55
83
  const url = baseUrl.replaceAll('{{chain}}', networkKey);
84
+
85
+ // TODO: Update the logo to follow the new estimateFee format or move the logic to the backend
56
86
  fetch(url, {
57
87
  method: 'GET'
58
88
  }).then(rs => {
59
89
  return rs.json();
60
90
  }).then(info => {
61
- if (info.gasPrice !== undefined) {
62
- resolve(info);
63
- } else {
64
- resolve({
65
- busyNetwork: info.busyNetwork,
66
- gasPrice: info.gasPrice,
67
- baseGasFee: new _bignumber.default(info.baseGasFee),
68
- maxFeePerGas: new _bignumber.default(info.maxFeePerGas),
69
- maxPriorityFeePerGas: new _bignumber.default(info.maxPriorityFeePerGas)
70
- });
71
- }
91
+ resolve(info);
72
92
  }).catch(e => {
73
93
  console.warn(e);
74
94
  resolve(null);
@@ -94,9 +114,20 @@ const recalculateGasPrice = (_price, chain) => {
94
114
  return needMulti ? new _bignumber.default(_price).multipliedBy(_constants.GAS_PRICE_RATIO).toFixed(0) : _price;
95
115
  };
96
116
  exports.recalculateGasPrice = recalculateGasPrice;
117
+ const getEIP1559GasFee = (baseFee, maxPriorityFee, blockNumber, blockTime) => {
118
+ // https://www.blocknative.com/blog/eip-1559-fees
119
+ const maxFee = baseFee.multipliedBy(1.2).plus(maxPriorityFee);
120
+ return {
121
+ maxFeePerGas: maxFee.toFixed(0),
122
+ maxPriorityFeePerGas: maxPriorityFee.toFixed(0),
123
+ minWaitTimeEstimate: blockTime * (blockNumber - 2),
124
+ maxWaitTimeEstimate: blockTime * blockNumber
125
+ };
126
+ };
127
+ exports.getEIP1559GasFee = getEIP1559GasFee;
97
128
  const calculateGasFeeParams = async function (web3, networkKey) {
98
129
  let useOnline = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
99
- let useInfura = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
130
+ let useInfura = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
100
131
  if (useOnline) {
101
132
  try {
102
133
  const chainId = await web3.api.eth.getChainId();
@@ -113,19 +144,19 @@ const calculateGasFeeParams = async function (web3, networkKey) {
113
144
  const gasResponse = await fetch(`${gasDomain}`).then(res => res.json());
114
145
  const gasPriceInWei = gasResponse.standard * 1e9 + 200000;
115
146
  return {
147
+ type: 'evm',
116
148
  gasPrice: gasPriceInWei.toString(),
117
- maxFeePerGas: undefined,
118
- maxPriorityFeePerGas: undefined,
119
149
  baseGasFee: undefined,
120
- busyNetwork: false
150
+ busyNetwork: false,
151
+ options: undefined
121
152
  };
122
153
  }
123
154
  const numBlock = 20;
124
- const rewardPercent = [];
125
- for (let i = 0; i <= 100; i = i + 5) {
126
- rewardPercent.push(i);
127
- }
155
+ const rewardPercent = [25, 50, 75];
128
156
  const history = await web3.api.eth.getFeeHistory(numBlock, 'latest', rewardPercent);
157
+ const currentBlock = history.oldestBlock - 1;
158
+ const [newBlock, oldBlock] = await Promise.all([web3.api.eth.getBlock(currentBlock), web3.api.eth.getBlock(currentBlock - numBlock)]);
159
+ const blockTime = Number((BigInt(newBlock.timestamp || 0) - BigInt(oldBlock.timestamp || 0)) / BigInt(numBlock) * BigInt(1000));
129
160
  const baseGasFee = new _bignumber.default(history.baseFeePerGas[history.baseFeePerGas.length - 1]); // Last element is latest
130
161
 
131
162
  const blocksBusy = history.reward.reduce((previous, rewards, currentIndex) => {
@@ -137,87 +168,42 @@ const calculateGasFeeParams = async function (web3, networkKey) {
137
168
  /*
138
169
  * True if priority >= 0.3 * base
139
170
  * */
140
- const blockIsBusy = baseBN.gt(_utils.BN_ZERO) ? priorityBN.dividedBy(baseBN).gte(0.3) ? 1 : 0 : 0; // Special for bsc, base fee = 0
171
+ const blockIsBusy = baseBN.gt(_utils2.BN_ZERO) ? priorityBN.dividedBy(baseBN).gte(0.3) ? 1 : 0 : 0; // Special for bsc, base fee = 0
141
172
 
142
173
  return previous + blockIsBusy;
143
174
  }, 0);
144
175
  const busyNetwork = blocksBusy >= numBlock / 2; // True, if half of block is busy
145
176
 
146
- const maxPriorityFeePerGas = history.reward.reduce((previous, rewards) => {
147
- let firstBN = _utils.BN_ZERO;
148
- let firstIndex = 0;
149
-
150
- /* Get first priority which greater than 0 */
151
- for (let i = 0; i < rewards.length; i++) {
152
- firstIndex = i;
153
- const current = rewards[i];
154
- const currentBN = new _bignumber.default(current);
155
- if (currentBN.gt(_utils.BN_ZERO)) {
156
- firstBN = currentBN;
157
- break;
158
- }
159
- }
160
- let secondBN = firstBN;
161
-
162
- /* Get second priority which greater than first priority */
163
- for (let i = firstIndex; i < rewards.length; i++) {
164
- const current = rewards[i];
165
- const currentBN = new _bignumber.default(current);
166
- if (currentBN.gt(firstBN)) {
167
- secondBN = currentBN;
168
- break;
169
- }
170
- }
171
- let current;
172
- if (busyNetwork) {
173
- current = secondBN.dividedBy(2).gte(firstBN) ? firstBN : secondBN; // second too larger than first (> 2 times), use first else use second
174
- } else {
175
- current = firstBN;
176
- }
177
- if (busyNetwork) {
178
- /* Get max value */
179
- return current.gte(previous) ? current : previous; // get max priority
180
- } else {
181
- /* Get min value which greater than 0 */
182
- if (previous.eq(_utils.BN_ZERO)) {
183
- return current; // get min priority
184
- } else if (current.eq(_utils.BN_ZERO)) {
185
- return previous;
186
- }
187
- return current.lte(previous) ? current : previous; // get min priority
188
- }
189
- }, _utils.BN_ZERO);
190
- if (maxPriorityFeePerGas.eq(_utils.BN_ZERO)) {
191
- const _price = await web3.api.eth.getGasPrice();
192
- const gasPrice = recalculateGasPrice(_price, networkKey);
193
- return {
194
- gasPrice,
195
- maxFeePerGas: undefined,
196
- maxPriorityFeePerGas: undefined,
197
- baseGasFee: undefined,
198
- busyNetwork: false
199
- };
200
- }
201
-
202
- /* Max gas = (base + priority) * 1.5 (if not busy or 2 when busy); */
203
- const maxFeePerGas = baseGasFee.plus(maxPriorityFeePerGas).multipliedBy(busyNetwork ? 2 : 1.5).decimalPlaces(0);
177
+ const slowPriorityFee = history.reward.reduce((previous, rewards) => previous.plus(rewards[0]), _utils2.BN_ZERO).dividedBy(numBlock).decimalPlaces(0);
178
+ const averagePriorityFee = history.reward.reduce((previous, rewards) => previous.plus(rewards[1]), _utils2.BN_ZERO).dividedBy(numBlock).decimalPlaces(0);
179
+ const fastPriorityFee = history.reward.reduce((previous, rewards) => previous.plus(rewards[2]), _utils2.BN_ZERO).dividedBy(numBlock).decimalPlaces(0);
204
180
  return {
181
+ type: 'evm',
205
182
  gasPrice: undefined,
206
- maxFeePerGas,
207
- maxPriorityFeePerGas,
208
- baseGasFee,
209
- busyNetwork
183
+ baseGasFee: baseGasFee.toString(),
184
+ busyNetwork,
185
+ options: {
186
+ slow: getEIP1559GasFee(baseGasFee, slowPriorityFee, 10, blockTime),
187
+ average: getEIP1559GasFee(baseGasFee, averagePriorityFee, 5, blockTime),
188
+ fast: getEIP1559GasFee(baseGasFee, fastPriorityFee, 3, blockTime),
189
+ default: busyNetwork ? 'average' : 'slow'
190
+ }
210
191
  };
211
192
  } catch (e) {
212
193
  const _price = await web3.api.eth.getGasPrice();
213
194
  const gasPrice = recalculateGasPrice(_price, networkKey);
214
195
  return {
196
+ type: 'evm',
197
+ busyNetwork: false,
215
198
  gasPrice,
216
- maxFeePerGas: undefined,
217
- maxPriorityFeePerGas: undefined,
218
199
  baseGasFee: undefined,
219
- busyNetwork: false
200
+ options: undefined
220
201
  };
221
202
  }
222
203
  };
223
- exports.calculateGasFeeParams = calculateGasFeeParams;
204
+ exports.calculateGasFeeParams = calculateGasFeeParams;
205
+ const calculateToAmountByReservePool = async (api, fromToken, toToken, fromAmount) => {
206
+ const reserve = await (0, _utils.getReserveForPool)(api, fromToken, toToken);
207
+ return (0, _utils.estimateTokensForPool)(fromAmount, reserve);
208
+ };
209
+ exports.calculateToAmountByReservePool = calculateToAmountByReservePool;
@@ -13,6 +13,9 @@ class BalanceStore extends _BaseStoreWithAddress.default {
13
13
  async getBalanceMapByAddresses(addresses) {
14
14
  return this.table.where('address').anyOf(addresses).toArray();
15
15
  }
16
+ async getBalanceHasAmount(address, chain) {
17
+ return this.table.filter(item => item.address === address && item.free !== '0' && item.tokenSlug.startsWith(chain)).toArray();
18
+ }
16
19
  async removeBySlugs(tokenSlugs) {
17
20
  return this.table.where('tokenSlug').anyOfIgnoreCase(tokenSlugs).delete();
18
21
  }
@@ -15,6 +15,7 @@ var _utils2 = require("@subwallet/extension-base/services/swap-service/utils");
15
15
  var _types = require("@subwallet/extension-base/types");
16
16
  var _serviceBase = require("@subwallet/extension-base/types/service-base");
17
17
  var _swap2 = require("@subwallet/extension-base/types/swap");
18
+ var _getId = require("@subwallet/extension-base/utils/getId");
18
19
  var _bignumber = _interopRequireDefault(require("bignumber.js"));
19
20
  var _baseHandler = require("../base-handler");
20
21
  var _router = require("./router");
@@ -24,14 +25,15 @@ var _router = require("./router");
24
25
  const PAH_LOW_LIQUIDITY_THRESHOLD = 0.15;
25
26
  class AssetHubSwapHandler {
26
27
  isReady = false;
27
- constructor(chainService, balanceService, chain) {
28
+ constructor(chainService, balanceService, feeService, chain) {
28
29
  const chainInfo = chainService.getChainInfoByKey(chain);
29
30
  const providerSlug = chain === 'statemint' ? _swap2.SwapProviderId.POLKADOT_ASSET_HUB : chain === 'statemine' ? _swap2.SwapProviderId.KUSAMA_ASSET_HUB : _swap2.SwapProviderId.ROCOCO_ASSET_HUB;
30
31
  this.swapBaseHandler = new _baseHandler.SwapBaseHandler({
31
32
  balanceService,
32
33
  chainService,
33
34
  providerName: chainInfo.name,
34
- providerSlug
35
+ providerSlug,
36
+ feeService
35
37
  });
36
38
  this.providerSlug = providerSlug;
37
39
  this.chain = chain;
@@ -82,6 +84,7 @@ class AssetHubSwapHandler {
82
84
  }
83
85
  try {
84
86
  const alternativeChainInfo = this.chainService.getChainInfoByKey(alternativeAsset.originChain);
87
+ const originalChainInfo = this.chainService.getChainInfoByKey(this.chain);
85
88
  const step = {
86
89
  metadata: {
87
90
  sendingValue: bnAmount.toString(),
@@ -92,13 +95,18 @@ class AssetHubSwapHandler {
92
95
  type: _serviceBase.CommonStepType.XCM
93
96
  };
94
97
  const xcmOriginSubstrateApi = await this.chainService.getSubstrateApi(alternativeAsset.originChain).isReady;
98
+ const id = (0, _getId.getId)();
99
+ const feeInfo = await this.swapBaseHandler.feeService.subscribeChainFee(id, alternativeChainInfo.slug, 'substrate');
95
100
  const xcmTransfer = await (0, _xcm.createXcmExtrinsic)({
96
101
  originTokenInfo: alternativeAsset,
97
102
  destinationTokenInfo: fromAsset,
98
103
  sendingValue: bnAmount.toString(),
99
104
  recipient: params.request.address,
100
- chainInfoMap: this.chainService.getChainInfoMap(),
101
- substrateApi: xcmOriginSubstrateApi
105
+ sender: params.request.address,
106
+ feeInfo: feeInfo,
107
+ substrateApi: xcmOriginSubstrateApi,
108
+ destinationChain: originalChainInfo,
109
+ originChain: alternativeChainInfo
102
110
  });
103
111
  const _xcmFeeInfo = await xcmTransfer.paymentInfo(params.request.address);
104
112
  const xcmFeeInfo = _xcmFeeInfo.toPrimitive();
@@ -185,12 +193,16 @@ class AssetHubSwapHandler {
185
193
  const alternativeAssetSlug = (0, _utils2.getSwapAlternativeAsset)(pair);
186
194
  const originAsset = this.chainService.getAssetBySlug(alternativeAssetSlug);
187
195
  const destinationAsset = this.chainService.getAssetBySlug(pair.from);
196
+ const originChain = this.chainService.getChainInfoByKey(originAsset.originChain);
197
+ const destinationChain = this.chainService.getChainInfoByKey(destinationAsset.originChain);
188
198
  const substrateApi = this.chainService.getSubstrateApi(originAsset.originChain);
189
199
  const chainApi = await substrateApi.isReady;
190
200
  const destinationAssetBalance = await this.balanceService.getTransferableBalance(params.address, destinationAsset.originChain, destinationAsset.slug);
191
201
  const xcmFee = params.process.totalFee[params.currentStep];
192
202
  const bnAmount = new _bignumber.default(params.quote.fromAmount);
193
203
  const bnDestinationAssetBalance = new _bignumber.default(destinationAssetBalance.value);
204
+ const id = (0, _getId.getId)();
205
+ const feeInfo = await this.swapBaseHandler.feeService.subscribeChainFee(id, originChain.slug, 'substrate');
194
206
  let bnTotalAmount = bnAmount.minus(bnDestinationAssetBalance);
195
207
  if ((0, _utils._isNativeToken)(originAsset)) {
196
208
  const bnXcmFee = new _bignumber.default(xcmFee.feeComponent[0].amount); // xcm fee is paid in native token but swap token is not always native token
@@ -202,8 +214,11 @@ class AssetHubSwapHandler {
202
214
  destinationTokenInfo: destinationAsset,
203
215
  sendingValue: bnTotalAmount.toString(),
204
216
  recipient: params.address,
205
- chainInfoMap: this.chainService.getChainInfoMap(),
206
- substrateApi: chainApi
217
+ substrateApi: chainApi,
218
+ sender: params.address,
219
+ originChain: originChain,
220
+ destinationChain: destinationChain,
221
+ feeInfo
207
222
  });
208
223
  const xcmData = {
209
224
  originNetworkKey: originAsset.originChain,
@@ -45,7 +45,7 @@ class AssetHubRouter {
45
45
  const reserves = await (0, _utils2.getReserveForPath)(api, paths);
46
46
  const amounts = (0, _utils2.estimateTokensForPath)(amount, reserves);
47
47
  const marketRate = (0, _utils2.estimateRateForPath)(reserves);
48
- const marketRateAfter = (0, _utils2.estimateRateAfter)(amount, reserves);
48
+ const marketRateAfter = (0, _utils2.estimateRateAfterForPath)(amount, reserves);
49
49
  const priceImpactPct = (0, _utils2.estimatePriceImpactPct)(marketRate, marketRateAfter);
50
50
  const errors = [];
51
51
 
@@ -4,7 +4,7 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
4
4
  Object.defineProperty(exports, "__esModule", {
5
5
  value: true
6
6
  });
7
- exports.getReserveForPool = exports.getReserveForPath = exports.estimateTokensForPool = exports.estimateTokensForPath = exports.estimateRateForPath = exports.estimateRateAfter = exports.estimatePriceImpactPct = exports.estimateActualRate = exports.checkMinAmountForPool = exports.checkMinAmountForPath = exports.checkLiquidityForPool = exports.checkLiquidityForPath = exports.buildSwapExtrinsic = exports._getPoolInfo = void 0;
7
+ exports.getReserveForPool = exports.getReserveForPath = exports.estimateTokensForPool = exports.estimateTokensForPath = exports.estimateRateForPath = exports.estimateRateAfterForPath = exports.estimatePriceImpactPct = exports.estimateActualRate = exports.checkMinAmountForPool = exports.checkMinAmountForPath = exports.checkLiquidityForPool = exports.checkLiquidityForPath = exports.buildSwapExtrinsic = exports._getPoolInfo = void 0;
8
8
  var _utils = require("@subwallet/extension-base/services/chain-service/utils");
9
9
  var _swap = require("@subwallet/extension-base/types/swap");
10
10
  var _bignumber = _interopRequireDefault(require("bignumber.js"));
@@ -47,7 +47,7 @@ const getReserveForPath = async (api, paths) => {
47
47
  };
48
48
  exports.getReserveForPath = getReserveForPath;
49
49
  const estimateTokensForPool = (amount, reserves) => {
50
- if (amount === '0') {
50
+ if (!amount || amount === '0') {
51
51
  return '0';
52
52
  }
53
53
  return new _bignumber.default(amount).times(reserves[1]).div(reserves[0]).integerValue(_bignumber.default.ROUND_DOWN).toString();
@@ -85,7 +85,7 @@ const estimateActualRate = (amount, reserves) => {
85
85
  return result.toString();
86
86
  };
87
87
  exports.estimateActualRate = estimateActualRate;
88
- const estimateRateAfter = (amount, reserves) => {
88
+ const estimateRateAfterForPath = (amount, reserves) => {
89
89
  const m = new _bignumber.default(amount);
90
90
  const reserve = reserves[0];
91
91
  const x = new _bignumber.default(reserve[0]);
@@ -94,7 +94,7 @@ const estimateRateAfter = (amount, reserves) => {
94
94
  const result = x.plus(m).div(y.minus(n));
95
95
  return result.toString();
96
96
  };
97
- exports.estimateRateAfter = estimateRateAfter;
97
+ exports.estimateRateAfterForPath = estimateRateAfterForPath;
98
98
  const estimatePriceImpactPct = (marketRate, marketRateAfter) => {
99
99
  const bnMarketRate = new _bignumber.default(marketRate);
100
100
  const bnActualRate = new _bignumber.default(marketRateAfter);