@subwallet/extension-base 1.3.36-0 → 1.3.38-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 (40) hide show
  1. package/background/KoniTypes.d.ts +7 -0
  2. package/background/types.d.ts +2 -1
  3. package/cjs/core/logic-validation/request.js +62 -13
  4. package/cjs/koni/background/handlers/Extension.js +168 -108
  5. package/cjs/koni/background/handlers/State.js +18 -17
  6. package/cjs/koni/background/handlers/Tabs.js +38 -5
  7. package/cjs/packageInfo.js +1 -1
  8. package/cjs/page/cardano/cips/cip30.js +21 -1
  9. package/cjs/page/cardano/index.js +5 -5
  10. package/cjs/services/request-service/handler/AuthRequestHandler.js +4 -1
  11. package/cjs/services/request-service/handler/CardanoRequestHandler.js +4 -3
  12. package/cjs/services/request-service/helper/index.js +19 -17
  13. package/cjs/services/swap-service/handler/base-handler.js +4 -2
  14. package/cjs/services/swap-service/handler/uniswap-handler.js +122 -57
  15. package/cjs/services/swap-service/index.js +1 -1
  16. package/cjs/utils/cardano.js +10 -2
  17. package/core/logic-validation/request.d.ts +1 -0
  18. package/core/logic-validation/request.js +63 -15
  19. package/koni/background/handlers/Extension.d.ts +1 -0
  20. package/koni/background/handlers/Extension.js +61 -2
  21. package/koni/background/handlers/State.js +20 -19
  22. package/koni/background/handlers/Tabs.d.ts +1 -0
  23. package/koni/background/handlers/Tabs.js +38 -5
  24. package/package.json +11 -11
  25. package/packageInfo.js +1 -1
  26. package/page/cardano/cips/cip30.d.ts +31 -17
  27. package/page/cardano/cips/cip30.js +17 -1
  28. package/page/cardano/index.d.ts +20 -4
  29. package/page/cardano/index.js +5 -5
  30. package/services/chain-service/types.d.ts +1 -1
  31. package/services/request-service/handler/AuthRequestHandler.js +4 -1
  32. package/services/request-service/handler/CardanoRequestHandler.js +4 -3
  33. package/services/request-service/helper/index.js +19 -17
  34. package/services/swap-service/handler/base-handler.js +4 -2
  35. package/services/swap-service/handler/uniswap-handler.d.ts +1 -1
  36. package/services/swap-service/handler/uniswap-handler.js +99 -34
  37. package/services/swap-service/index.js +1 -1
  38. package/types/service-base.d.ts +1 -0
  39. package/utils/cardano.d.ts +2 -0
  40. package/utils/cardano.js +7 -0
@@ -11,12 +11,13 @@ var _logicValidation = require("@subwallet/extension-base/core/logic-validation"
11
11
  var _web = require("@subwallet/extension-base/koni/api/contract-handler/evm/web3");
12
12
  var _xcm = require("@subwallet/extension-base/services/balance-service/transfer/xcm");
13
13
  var _acrossBridge = require("@subwallet/extension-base/services/balance-service/transfer/xcm/acrossBridge");
14
+ var _utils = require("@subwallet/extension-base/services/swap-service/utils");
14
15
  var _types = require("@subwallet/extension-base/types");
15
- var _utils = require("@subwallet/extension-base/utils");
16
+ var _utils2 = require("@subwallet/extension-base/utils");
16
17
  var _getId = require("@subwallet/extension-base/utils/getId");
17
18
  var _bignumber = _interopRequireDefault(require("bignumber.js"));
18
- var _utils2 = require("../../chain-service/utils");
19
- var _utils3 = require("../../fee-service/utils");
19
+ var _utils3 = require("../../chain-service/utils");
20
+ var _utils4 = require("../../fee-service/utils");
20
21
  var _baseHandler = require("./base-handler");
21
22
  // Copyright 2019-2022 @subwallet/extension-base
22
23
  // SPDX-License-Identifier: Apache-2.0
@@ -101,7 +102,8 @@ class UniswapHandler {
101
102
  const stepFuncList = [];
102
103
  /**
103
104
  * approve - permit - swap or
104
- * approve - permit - swap - approve - bridge
105
+ * approve - permit - swap - approve - bridge or
106
+ * approve - bridge - approve - permit - swap
105
107
  */
106
108
 
107
109
  params.path.forEach(step => {
@@ -118,11 +120,26 @@ class UniswapHandler {
118
120
  return this.swapBaseHandler.generateOptimalProcessV2(params, stepFuncList);
119
121
  }
120
122
  async getApprovalStep(params, stepIndex) {
121
- if (stepIndex === 0) {
123
+ /**
124
+ * Explain: All processes will go through one of below processes. If a step do not have, it returns undefined and
125
+ * the stepIndex is still counted up
126
+ *
127
+ * Processes:
128
+ * approve - permit - swap or
129
+ * approve - permit - swap - approve - bridge or
130
+ * approve - bridge - approve - permit - swap
131
+ */
132
+ const actionList = JSON.stringify(params.path.map(step => step.action));
133
+ const swap = actionList === JSON.stringify([_types.DynamicSwapType.SWAP]);
134
+ const swapBridge = actionList === JSON.stringify([_types.DynamicSwapType.SWAP, _types.DynamicSwapType.BRIDGE]);
135
+ const bridgeSwap = actionList === JSON.stringify([_types.DynamicSwapType.BRIDGE, _types.DynamicSwapType.SWAP]);
136
+ const isApproveBridge = stepIndex === 3 && swapBridge || stepIndex === 0 && bridgeSwap;
137
+ const isApproveSwap = stepIndex === 0 && swap || stepIndex === 0 && swapBridge || stepIndex === 2 && bridgeSwap;
138
+ if (isApproveSwap) {
122
139
  return this.getApproveSwap(params);
123
140
  }
124
- if (stepIndex === 3) {
125
- return this.getApproveBridge(params);
141
+ if (isApproveBridge) {
142
+ return this.getApproveBridge(params, bridgeSwap);
126
143
  }
127
144
  return Promise.resolve(undefined);
128
145
  }
@@ -160,9 +177,9 @@ class UniswapHandler {
160
177
  return undefined;
161
178
  }
162
179
  const fromTokenInfo = this.chainService.getAssetBySlug(selectedQuote.pair.from);
163
- const fromChainInfo = this.chainService.getChainInfoByKey((0, _utils2._getAssetOriginChain)(fromTokenInfo));
180
+ const fromChainInfo = this.chainService.getChainInfoByKey((0, _utils3._getAssetOriginChain)(fromTokenInfo));
164
181
  const evmApi = this.chainService.getEvmApi(fromChainInfo.slug);
165
- const tokenContract = (0, _utils2._getContractAddressOfToken)(fromTokenInfo);
182
+ const tokenContract = (0, _utils3._getContractAddressOfToken)(fromTokenInfo);
166
183
  const approval = checkApprovalResponse.approval;
167
184
  if (!approval) {
168
185
  return Promise.resolve(undefined);
@@ -177,7 +194,7 @@ class UniswapHandler {
177
194
  const tx = await (0, _web.getERC20SpendingApprovalTx)(spender, sender, tokenContract, evmApi);
178
195
  const evmFeeInfo = await this.feeService.subscribeChainFee((0, _getId.getId)(), fromTokenInfo.originChain, 'evm');
179
196
  const estimatedFee = await (0, _web.estimateTxFee)(tx, evmApi, evmFeeInfo);
180
- const nativeTokenSlug = (0, _utils2._getChainNativeTokenSlug)(fromChainInfo);
197
+ const nativeTokenSlug = (0, _utils3._getChainNativeTokenSlug)(fromChainInfo);
181
198
  const feeInfo = {
182
199
  feeComponent: [{
183
200
  feeType: _types.SwapFeeType.NETWORK_FEE,
@@ -193,7 +210,7 @@ class UniswapHandler {
193
210
  // @ts-ignore
194
211
  metadata: {
195
212
  tokenApprove: fromTokenInfo.slug,
196
- contractAddress: (0, _utils2._getContractAddressOfToken)(fromTokenInfo) || approval.to,
213
+ contractAddress: (0, _utils3._getContractAddressOfToken)(fromTokenInfo) || approval.to,
197
214
  spenderAddress: spender,
198
215
  owner: sender,
199
216
  // todo: use approval.from?
@@ -203,22 +220,30 @@ class UniswapHandler {
203
220
  };
204
221
  return Promise.resolve([submitStep, feeInfo]);
205
222
  }
206
- async getApproveBridge(params) {
207
- const quote = params.selectedQuote;
208
- if (!quote) {
223
+ async getApproveBridge(params, isBridgeFirst) {
224
+ const {
225
+ path,
226
+ request,
227
+ selectedQuote
228
+ } = params;
229
+ if (!selectedQuote) {
209
230
  return Promise.resolve(undefined);
210
231
  }
211
- console.log('params', params);
212
- const sendingAmount = quote.toAmount;
213
- const senderAddress = params.request.address;
214
- const fromTokenInfo = this.chainService.getAssetBySlug(quote.pair.to);
215
- const fromChainInfo = this.chainService.getChainInfoByKey((0, _utils2._getAssetOriginChain)(fromTokenInfo));
216
- const fromChainId = (0, _utils2._getEvmChainId)(fromChainInfo);
232
+ const bridgePairInfo = path.find(action => action.action === _types.DynamicSwapType.BRIDGE);
233
+ if (!bridgePairInfo || !bridgePairInfo.pair) {
234
+ return Promise.resolve(undefined);
235
+ }
236
+ const _sendingAmount = isBridgeFirst ? request.fromAmount : selectedQuote.toAmount;
237
+ const sendingAmount = (0, _bignumber.default)(_sendingAmount).multipliedBy(2).toFixed(0, 1); // ensure approve enough amount
238
+ const senderAddress = request.address;
239
+ const fromTokenInfo = this.chainService.getAssetBySlug(bridgePairInfo.pair.from);
240
+ const fromChainInfo = this.chainService.getChainInfoByKey((0, _utils3._getAssetOriginChain)(fromTokenInfo));
241
+ const fromChainId = (0, _utils3._getEvmChainId)(fromChainInfo);
217
242
  const evmApi = this.chainService.getEvmApi(fromChainInfo.slug);
218
- const tokenContract = (0, _utils2._getContractAddressOfToken)(fromTokenInfo);
219
- const toTokenInfo = this.chainService.getAssetBySlug(params.request.pair.to);
220
- const toChainInfo = this.chainService.getChainInfoByKey((0, _utils2._getAssetOriginChain)(toTokenInfo));
221
- if ((0, _utils2._isNativeToken)(fromTokenInfo)) {
243
+ const tokenContract = (0, _utils3._getContractAddressOfToken)(fromTokenInfo);
244
+ const toTokenInfo = this.chainService.getAssetBySlug(bridgePairInfo.pair.to);
245
+ const toChainInfo = this.chainService.getChainInfoByKey((0, _utils3._getAssetOriginChain)(toTokenInfo));
246
+ if ((0, _utils3._isNativeToken)(fromTokenInfo)) {
222
247
  return Promise.resolve(undefined);
223
248
  }
224
249
  if (!fromChainId) {
@@ -227,9 +252,10 @@ class UniswapHandler {
227
252
  const inputData = {
228
253
  destinationTokenInfo: toTokenInfo,
229
254
  originTokenInfo: fromTokenInfo,
230
- sendingValue: sendingAmount,
255
+ sendingValue: _sendingAmount,
231
256
  sender: senderAddress,
232
257
  recipient: senderAddress,
258
+ // todo: there's a case swap - bridge to another address
233
259
  destinationChain: toChainInfo,
234
260
  originChain: fromChainInfo
235
261
  };
@@ -242,7 +268,7 @@ class UniswapHandler {
242
268
  const tx = await (0, _web.getERC20SpendingApprovalTx)(spokePoolAddress, senderAddress, tokenContract, evmApi);
243
269
  const evmFeeInfo = await this.feeService.subscribeChainFee((0, _getId.getId)(), fromTokenInfo.originChain, 'evm');
244
270
  const estimatedFee = await (0, _web.estimateTxFee)(tx, evmApi, evmFeeInfo);
245
- const nativeTokenSlug = (0, _utils2._getChainNativeTokenSlug)(fromChainInfo);
271
+ const nativeTokenSlug = (0, _utils3._getChainNativeTokenSlug)(fromChainInfo);
246
272
  const feeInfo = {
247
273
  feeComponent: [{
248
274
  feeType: _types.SwapFeeType.NETWORK_FEE,
@@ -302,6 +328,10 @@ class UniswapHandler {
302
328
  if (!selectedQuote) {
303
329
  return Promise.resolve(undefined);
304
330
  }
331
+ const actionList = JSON.stringify(path.map(step => step.action));
332
+ const swapXcm = actionList === JSON.stringify([_types.DynamicSwapType.SWAP, _types.DynamicSwapType.BRIDGE]);
333
+ const sendingValue = swapXcm ? (0, _bignumber.default)(request.fromAmount).multipliedBy(_utils.DEFAULT_EXCESS_AMOUNT_WEIGHT).toFixed(0, 1) : request.fromAmount;
334
+ const expectedReceive = swapXcm ? (0, _bignumber.default)(selectedQuote.toAmount).multipliedBy(_utils.DEFAULT_EXCESS_AMOUNT_WEIGHT).toFixed(0, 1) : selectedQuote.toAmount;
305
335
  const originTokenInfo = this.chainService.getAssetBySlug(selectedQuote.pair.from);
306
336
  const destinationTokenInfo = this.chainService.getAssetBySlug(selectedQuote.pair.to);
307
337
  const originChain = this.chainService.getChainInfoByKey(originTokenInfo.originChain);
@@ -311,12 +341,12 @@ class UniswapHandler {
311
341
  type: _types.SwapStepType.SWAP,
312
342
  // @ts-ignore
313
343
  metadata: {
314
- sendingValue: request.fromAmount.toString(),
315
- expectedReceive: selectedQuote.toAmount,
344
+ sendingValue,
345
+ expectedReceive,
316
346
  originTokenInfo,
317
347
  destinationTokenInfo,
318
- sender: (0, _utils._reformatAddressWithChain)(request.address, originChain),
319
- receiver: (0, _utils._reformatAddressWithChain)(request.recipient || request.address, destinationChain),
348
+ sender: (0, _utils2._reformatAddressWithChain)(request.address, originChain),
349
+ receiver: (0, _utils2._reformatAddressWithChain)(request.recipient || request.address, destinationChain),
320
350
  version: 2
321
351
  }
322
352
  };
@@ -328,6 +358,20 @@ class UniswapHandler {
328
358
  request,
329
359
  selectedQuote
330
360
  } = params;
361
+ /**
362
+ * Explain: All processes will go through one of below processes. If a step do not have, it returns undefined and
363
+ * the stepIndex is still counted up
364
+ *
365
+ * Processes:
366
+ * approve - permit - swap or
367
+ * approve - permit - swap - approve - bridge or
368
+ * approve - bridge - approve - permit - swap
369
+ */
370
+ const actionList = JSON.stringify(path.map(step => step.action));
371
+ const bridgeSwap = actionList === JSON.stringify([_types.DynamicSwapType.BRIDGE, _types.DynamicSwapType.SWAP]);
372
+ const swapBridge = actionList === JSON.stringify([_types.DynamicSwapType.SWAP, _types.DynamicSwapType.BRIDGE]);
373
+ const isBridgeFirst = stepIndex === 1 && bridgeSwap;
374
+ const isBridgeSecond = stepIndex === 4 && swapBridge;
331
375
 
332
376
  // stepIndex is not corresponding index in path, because uniswap include approval and permit step
333
377
  const bridgePairInfo = path.find(action => action.action === _types.DynamicSwapType.BRIDGE);
@@ -344,9 +388,18 @@ class UniswapHandler {
344
388
  if (!fromChainInfo || !toChainInfo || !fromChainInfo || !toChainInfo) {
345
389
  throw Error('Token or chain not found');
346
390
  }
347
- const senderAddress = (0, _utils._reformatAddressWithChain)(request.address, fromChainInfo);
348
- const receiverAddress = (0, _utils._reformatAddressWithChain)(request.recipient || request.address, toChainInfo);
349
- const sendingValue = (0, _bignumber.default)(selectedQuote.toAmount).div(1.02).toFixed(0, 1);
391
+ let receiverAddress;
392
+ let mockSendingValue;
393
+ const senderAddress = (0, _utils2._reformatAddressWithChain)(request.address, fromChainInfo);
394
+ if (isBridgeFirst) {
395
+ receiverAddress = (0, _utils2._reformatAddressWithChain)(request.address, toChainInfo);
396
+ mockSendingValue = (0, _bignumber.default)(selectedQuote.fromAmount).toFixed(0, 1);
397
+ } else if (isBridgeSecond) {
398
+ receiverAddress = (0, _utils2._reformatAddressWithChain)(request.recipient || request.address, toChainInfo);
399
+ mockSendingValue = (0, _bignumber.default)(selectedQuote.toAmount).toFixed(0, 1);
400
+ } else {
401
+ return undefined;
402
+ }
350
403
  try {
351
404
  const evmApi = await this.chainService.getEvmApi(fromChainInfo.slug).isReady;
352
405
  const feeInfo = await this.feeService.subscribeChainFee((0, _getId.getId)(), fromTokenInfo.originChain, 'evm');
@@ -358,33 +411,45 @@ class UniswapHandler {
358
411
  evmApi,
359
412
  feeInfo,
360
413
  // Mock sending value to get payment info
361
- sendingValue,
414
+ sendingValue: mockSendingValue,
362
415
  sender: senderAddress,
363
416
  recipient: receiverAddress
364
417
  });
365
-
366
- // // todo: wait until this ready to get destination fee. the real receiveAmount is deduce by this fee
367
- // const acrossQuote = await getAcrossQuote({
368
- // destinationChain: toChainInfo,
369
- // destinationTokenInfo: toTokenInfo,
370
- // originChain: fromChainInfo,
371
- // originTokenInfo: fromTokenInfo,
372
- // recipient: receiverAddress,
373
- // sender: senderAddress,
374
- // sendingValue,
375
- // feeInfo
376
- // });
377
-
418
+ const acrossQuote = await (0, _acrossBridge.getAcrossQuote)({
419
+ destinationChain: toChainInfo,
420
+ destinationTokenInfo: toTokenInfo,
421
+ originChain: fromChainInfo,
422
+ originTokenInfo: fromTokenInfo,
423
+ recipient: receiverAddress,
424
+ sender: senderAddress,
425
+ sendingValue: mockSendingValue,
426
+ feeInfo
427
+ });
428
+ const acrossQuoteMetadata = acrossQuote.metadata;
378
429
  const estimatedBridgeFee = await (0, _web.estimateTxFee)(tx, evmApi, feeInfo);
379
- const expectedReceive = (0, _bignumber.default)(sendingValue).minus(estimatedBridgeFee).toFixed(0, 1);
430
+ const estimatedDestinationFee = (0, _bignumber.default)(mockSendingValue).minus(acrossQuoteMetadata.outputAmount).toFixed(0, 1); // todo: should better handle on backend and return desFee metadata instead of minus like this
431
+
432
+ let sendingValue;
433
+ let expectedReceive;
434
+ if (isBridgeFirst) {
435
+ expectedReceive = selectedQuote.fromAmount;
436
+ sendingValue = (0, _bignumber.default)(estimatedDestinationFee).multipliedBy(_utils.FEE_RATE_MULTIPLIER.medium).plus(selectedQuote.fromAmount).toFixed(0, 1);
437
+ } else if (isBridgeSecond) {
438
+ expectedReceive = selectedQuote.toAmount;
439
+ sendingValue = (0, _bignumber.default)(selectedQuote.toAmount).multipliedBy(_utils.DEFAULT_EXCESS_AMOUNT_WEIGHT).toFixed(0, 1);
440
+ } else {
441
+ return undefined;
442
+ }
443
+ console.log('[i] estimatedBridgeFee', estimatedBridgeFee);
444
+ console.log('[i] estimatedDestinationFee', estimatedDestinationFee);
380
445
  const fee = {
381
446
  feeComponent: [{
382
447
  feeType: _types.SwapFeeType.NETWORK_FEE,
383
448
  amount: estimatedBridgeFee,
384
- tokenSlug: (0, _utils2._getChainNativeTokenSlug)(fromChainInfo)
449
+ tokenSlug: (0, _utils3._getChainNativeTokenSlug)(fromChainInfo)
385
450
  }],
386
- defaultFeeToken: (0, _utils2._getChainNativeTokenSlug)(fromChainInfo),
387
- feeOptions: [(0, _utils2._getChainNativeTokenSlug)(fromChainInfo)]
451
+ defaultFeeToken: (0, _utils3._getChainNativeTokenSlug)(fromChainInfo),
452
+ feeOptions: [(0, _utils3._getChainNativeTokenSlug)(fromChainInfo)]
388
453
  };
389
454
  const step = {
390
455
  // @ts-ignore
@@ -479,7 +544,7 @@ class UniswapHandler {
479
544
  if (approval) {
480
545
  var _priority$options, _priority$options$Fee, _priority$options2;
481
546
  const evmApi = this.chainService.getEvmApi(fromAsset.originChain);
482
- const priority = await (0, _utils3.calculateGasFeeParams)(evmApi, evmApi.chainSlug);
547
+ const priority = await (0, _utils4.calculateGasFeeParams)(evmApi, evmApi.chainSlug);
483
548
  transactionConfig = {
484
549
  from: approval.from,
485
550
  to: approval.to,
@@ -511,7 +576,7 @@ class UniswapHandler {
511
576
  }
512
577
  async approveSpendingBridge(approveStep) {
513
578
  const fromAsset = this.chainService.getAssetBySlug(approveStep.tokenApprove);
514
- const fromChain = (0, _utils2._getAssetOriginChain)(fromAsset);
579
+ const fromChain = (0, _utils3._getAssetOriginChain)(fromAsset);
515
580
  const evmApi = this.chainService.getEvmApi(fromAsset.originChain);
516
581
  const sender = approveStep.owner;
517
582
  const sendingValue = approveStep.amount;
@@ -652,7 +717,7 @@ class UniswapHandler {
652
717
  submitSwapOrder,
653
718
  cronCheckTxSuccess
654
719
  },
655
- transferNativeAmount: (0, _utils2._isNativeToken)(fromAsset) ? params.quote.fromAmount : '0',
720
+ transferNativeAmount: (0, _utils3._isNativeToken)(fromAsset) ? params.quote.fromAmount : '0',
656
721
  extrinsicType: _KoniTypes.ExtrinsicType.SWAP,
657
722
  chainType: _KoniTypes.ChainType.EVM,
658
723
  isDutch: true
@@ -670,7 +735,7 @@ class UniswapHandler {
670
735
  txChain: fromAsset.originChain,
671
736
  txData,
672
737
  extrinsic: extrinsic,
673
- transferNativeAmount: (0, _utils2._isNativeToken)(fromAsset) ? params.quote.fromAmount : '0',
738
+ transferNativeAmount: (0, _utils3._isNativeToken)(fromAsset) ? params.quote.fromAmount : '0',
674
739
  extrinsicType: _KoniTypes.ExtrinsicType.SWAP,
675
740
  chainType: _KoniTypes.ChainType.EVM
676
741
  };
@@ -745,7 +810,7 @@ class UniswapHandler {
745
810
  if (swapIndex <= -1) {
746
811
  return [new _TransactionError.TransactionError(_types.BasicTxErrorType.INTERNAL_ERROR)];
747
812
  }
748
- if (swapXcm && bridgeIndex <= -1) {
813
+ if ((swapXcm || xcmSwap) && bridgeIndex <= -1) {
749
814
  return [new _TransactionError.TransactionError(_types.BasicTxErrorType.INTERNAL_ERROR)];
750
815
  }
751
816
  if (swap) {
@@ -756,7 +821,7 @@ class UniswapHandler {
756
821
  return this.swapBaseHandler.validateSwapXcmProcess(params, swapIndex, bridgeIndex);
757
822
  }
758
823
  if (xcmSwap) {
759
- return [new _TransactionError.TransactionError(_types.BasicTxErrorType.INTERNAL_ERROR)];
824
+ return this.swapBaseHandler.validateXcmSwapProcess(params, swapIndex, bridgeIndex);
760
825
  }
761
826
  if (xcmSwapXcm) {
762
827
  return [new _TransactionError.TransactionError(_types.BasicTxErrorType.INTERNAL_ERROR)];
@@ -46,7 +46,7 @@ class SwapService {
46
46
  var _subwalletApiSdk$swap;
47
47
  const availableQuotes = [];
48
48
 
49
- // hotfix
49
+ // hotfix // todo: remove later
50
50
  const request = {
51
51
  ..._request,
52
52
  isSupportKyberVersion: true
@@ -3,8 +3,9 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.convertCardanoHexToBech32 = exports.convertCardanoAddressToHex = void 0;
6
+ exports.validateAddressNetwork = exports.convertCardanoHexToBech32 = exports.convertCardanoAddressToHex = void 0;
7
7
  var _cardanoSerializationLibNodejs = require("@emurgo/cardano-serialization-lib-nodejs");
8
+ var _keyring = require("@subwallet/keyring");
8
9
  // Copyright 2019-2022 @polkadot/extension authors & contributors
9
10
  // SPDX-License-Identifier: Apache-2.0
10
11
 
@@ -17,4 +18,11 @@ const convertCardanoHexToBech32 = hexAddress => {
17
18
  const addr = _cardanoSerializationLibNodejs.Address.from_hex(hexAddress);
18
19
  return addr.to_bech32();
19
20
  };
20
- exports.convertCardanoHexToBech32 = convertCardanoHexToBech32;
21
+ exports.convertCardanoHexToBech32 = convertCardanoHexToBech32;
22
+ const validateAddressNetwork = (address, chainInfo) => {
23
+ if (!(chainInfo !== null && chainInfo !== void 0 && chainInfo.cardanoInfo) || !chainInfo.isTestnet) {
24
+ return (0, _keyring.isCardanoMainnetAddress)(address);
25
+ }
26
+ return (0, _keyring.isCardanoTestnetAddress)(address);
27
+ };
28
+ exports.validateAddressNetwork = validateAddressNetwork;
@@ -43,6 +43,7 @@ export declare function validationConnectMiddleware(koni: KoniState, url: string
43
43
  export declare function validationEvmDataTransactionMiddleware(koni: KoniState, url: string, payload: PayloadValidated): Promise<PayloadValidated>;
44
44
  export declare function validationEvmSignMessageMiddleware(koni: KoniState, url: string, payload_: PayloadValidated): Promise<PayloadValidated>;
45
45
  export declare function validationAuthWCMiddleware(koni: KoniState, url: string, payload: PayloadValidated, topic?: string): Promise<PayloadValidated>;
46
+ export declare function validationAuthCardanoMiddleware(koni: KoniState, url: string, payload: PayloadValidated): Promise<PayloadValidated>;
46
47
  export declare function validationCardanoSignDataMiddleware(koni: KoniState, url: string, payload_: PayloadValidated): Promise<PayloadValidated>;
47
48
  export declare function convertErrorMessage(message_: string, name?: string): string[];
48
49
  export declare function convertErrorFormat(errors: Error[]): ErrorValidation[];
@@ -7,10 +7,11 @@ import { EvmProviderError } from '@subwallet/extension-base/background/errors/Ev
7
7
  import { TransactionError } from '@subwallet/extension-base/background/errors/TransactionError';
8
8
  import { CardanoProviderErrorType, EvmProviderErrorType } from '@subwallet/extension-base/background/KoniTypes';
9
9
  import { BasicTxErrorType } from '@subwallet/extension-base/types';
10
- import { BN_ZERO, combineEthFee, createPromiseHandler, isSameAddress, stripUrl, wait } from '@subwallet/extension-base/utils';
10
+ import { BN_ZERO, combineEthFee, createPromiseHandler, isSameAddress, reformatAddress, stripUrl, wait } from '@subwallet/extension-base/utils';
11
+ import { validateAddressNetwork } from '@subwallet/extension-base/utils/cardano';
11
12
  import { isContractAddress, parseContractInput } from '@subwallet/extension-base/utils/eth/parseTransaction';
12
13
  import { getId } from '@subwallet/extension-base/utils/getId';
13
- import { isCardanoAddress, isSubstrateAddress } from '@subwallet/keyring';
14
+ import { isCardanoAddress, isCardanoBaseAddress, isCardanoRewardAddress, isSubstrateAddress } from '@subwallet/keyring';
14
15
  import { keyring } from '@subwallet/ui-keyring';
15
16
  import { getSdkError } from '@walletconnect/utils';
16
17
  import BigN from 'bignumber.js';
@@ -127,36 +128,33 @@ export async function generateValidationProcess(koni, url, payloadValidate, vali
127
128
  }
128
129
  return resultValidated;
129
130
  }
131
+ function handleAuthError(payload, message, errorPosition, errors) {
132
+ payload.errorPosition = errorPosition;
133
+ errors.push(new Error(convertErrorMessage(message)[0]));
134
+ return payload;
135
+ }
130
136
  export async function validationAuthMiddleware(koni, url, payload) {
131
137
  const {
132
138
  address,
133
139
  errors
134
140
  } = payload;
135
141
  if (!address || !isString(address)) {
136
- payload.errorPosition = 'dApp';
137
- const [message] = convertErrorMessage('Not found address to sign');
138
- errors.push(new Error(message));
142
+ return handleAuthError(payload, 'Not found address to sign', 'dApp', errors);
139
143
  } else {
140
144
  try {
141
145
  payload.pair = keyring.getPair(address);
142
146
  if (!payload.pair) {
143
- payload.errorPosition = 'dApp';
144
- const [message] = convertErrorMessage('Unable to find account');
145
- errors.push(new Error(message));
147
+ return handleAuthError(payload, 'Unable to find account', 'dApp', errors);
146
148
  } else {
147
149
  const authList = await koni.getAuthList();
148
150
  const authInfo = authList[stripUrl(url)];
149
151
  if (!authInfo || !authInfo.isAllowed || !authInfo.isAllowedMap[payload.pair.address]) {
150
- payload.errorPosition = 'dApp';
151
- const [message] = convertErrorMessage('Account not in allowed list', '');
152
- errors.push(new Error(message));
152
+ return handleAuthError(payload, 'Account not in allowed list', 'dApp', errors);
153
153
  }
154
154
  payload.authInfo = authInfo;
155
155
  }
156
156
  } catch (e) {
157
- const [message] = convertErrorMessage(e.message);
158
- payload.errorPosition = 'dApp';
159
- errors.push(new Error(message));
157
+ return handleAuthError(payload, e.message, 'dApp', errors);
160
158
  }
161
159
  }
162
160
  return payload;
@@ -544,11 +542,51 @@ export function validationAuthWCMiddleware(koni, url, payload, topic) {
544
542
  });
545
543
  return promise;
546
544
  }
545
+ export async function validationAuthCardanoMiddleware(koni, url, payload) {
546
+ const authList = await koni.getAuthList();
547
+ const authInfo = authList[stripUrl(url)];
548
+ const {
549
+ address,
550
+ errors
551
+ } = payload;
552
+ if (!authInfo || !authInfo.isAllowed) {
553
+ return handleAuthError(payload, 'Account not in allowed list', 'dApp', errors);
554
+ }
555
+ const currentAddress = authInfo.currentAccount;
556
+ const currentNetwork = authInfo.currentNetworkMap.cardano || 'cardano';
557
+ const currentNetworkId = +(currentNetwork === 'cardano');
558
+ if (!currentAddress || !authInfo.isAllowedMap[currentAddress]) {
559
+ return handleAuthError(payload, 'Unable to find account', 'dApp', errors);
560
+ }
561
+ const pair = keyring.getPair(currentAddress);
562
+ if (!pair) {
563
+ return handleAuthError(payload, 'Unable to find account', 'dApp', errors);
564
+ }
565
+ payload.pair = pair;
566
+ if (isCardanoBaseAddress(address)) {
567
+ if (!authInfo.isAllowedMap[address]) {
568
+ return handleAuthError(payload, 'Account not in allowed list', 'dApp', errors);
569
+ }
570
+ const addressByChainFormat = reformatAddress(currentAddress, currentNetworkId);
571
+ if (!isSameAddress(addressByChainFormat, address)) {
572
+ return handleAuthError(payload, 'Current account is changed', 'dApp', errors);
573
+ }
574
+ } else if (isCardanoRewardAddress(address)) {
575
+ const rewardAddress = pair.cardano.rewardAddress;
576
+ const addressByChainFormat = reformatAddress(rewardAddress, currentNetworkId);
577
+ if (!isSameAddress(addressByChainFormat, address)) {
578
+ return handleAuthError(payload, 'Current account is changed', 'dApp', errors);
579
+ }
580
+ }
581
+ return payload;
582
+ }
547
583
  export async function validationCardanoSignDataMiddleware(koni, url, payload_) {
548
584
  const {
549
585
  address,
586
+ authInfo,
550
587
  errors,
551
- pair: pair_
588
+ pair: pair_,
589
+ type
552
590
  } = payload_;
553
591
  const payload = payload_.payloadAfterValidated;
554
592
  const {
@@ -570,6 +608,15 @@ export async function validationCardanoSignDataMiddleware(koni, url, payload_) {
570
608
  if (!isCardanoAddress(address)) {
571
609
  handleError('Not found cardano address');
572
610
  }
611
+ const currentCardanoNetwork = koni.requestService.getDAppChainInfo({
612
+ autoActive: true,
613
+ accessType: 'cardano',
614
+ defaultChain: authInfo === null || authInfo === void 0 ? void 0 : authInfo.currentNetworkMap[type],
615
+ url
616
+ });
617
+ if (!validateAddressNetwork(address, currentCardanoNetwork)) {
618
+ handleError('Invalid address network');
619
+ }
573
620
  const pair = pair_ || keyring.getPair(address);
574
621
  if (!(pair !== null && pair !== void 0 && pair.meta.isExtneral)) {
575
622
  canSign = true;
@@ -577,6 +624,7 @@ export async function validationCardanoSignDataMiddleware(koni, url, payload_) {
577
624
  const payloadAfterValidated = {
578
625
  address,
579
626
  payload: payload,
627
+ currentAddress: authInfo === null || authInfo === void 0 ? void 0 : authInfo.currentAccount,
580
628
  hashPayload: payload,
581
629
  canSign: canSign,
582
630
  id: ''
@@ -59,6 +59,7 @@ export default class KoniExtension {
59
59
  private changeAuthorizationAll;
60
60
  private _changeAuthorization;
61
61
  toggleAuthorization2(url: string): Promise<ResponseAuthorizeList>;
62
+ private switchCurrentNetworkAuthorization;
62
63
  private changeAuthorization;
63
64
  private _changeAuthorizationPerAcc;
64
65
  private _changeAuthorizationBlock;
@@ -36,7 +36,7 @@ import { _isPolygonChainBridge, getClaimPolygonBridge, isClaimedPolygonBridge }
36
36
  import { _isPosChainBridge, getClaimPosBridge } from '@subwallet/extension-base/services/balance-service/transfer/xcm/posBridge';
37
37
  import { _DEFAULT_MANTA_ZK_CHAIN, _MANTA_ZK_CHAIN_GROUP, _ZK_ASSET_PREFIX } from '@subwallet/extension-base/services/chain-service/constants';
38
38
  import { _ChainConnectionStatus } from '@subwallet/extension-base/services/chain-service/types';
39
- import { _getAssetDecimals, _getAssetSymbol, _getChainNativeTokenBasicInfo, _getContractAddressOfToken, _getEvmChainId, _isAssetSmartContractNft, _isChainEvmCompatible, _isChainSubstrateCompatible, _isCustomAsset, _isLocalToken, _isMantaZkAsset, _isNativeToken, _isNativeTokenBySlug, _isPureEvmChain, _isTokenEvmSmartContract, _isTokenTransferredByCardano, _isTokenTransferredByEvm, _isTokenTransferredByTon } from '@subwallet/extension-base/services/chain-service/utils';
39
+ import { _getAssetDecimals, _getAssetSymbol, _getChainNativeTokenBasicInfo, _getContractAddressOfToken, _getEvmChainId, _isAssetSmartContractNft, _isChainEnabled, _isChainEvmCompatible, _isChainSubstrateCompatible, _isCustomAsset, _isLocalToken, _isMantaZkAsset, _isNativeToken, _isNativeTokenBySlug, _isPureEvmChain, _isTokenEvmSmartContract, _isTokenTransferredByCardano, _isTokenTransferredByEvm, _isTokenTransferredByTon } from '@subwallet/extension-base/services/chain-service/utils';
40
40
  import { calculateToAmountByReservePool } from '@subwallet/extension-base/services/fee-service/utils';
41
41
  import { batchExtrinsicSetFeeHydration, getAssetHubTokensCanPayFee, getHydrationTokensCanPayFee } from '@subwallet/extension-base/services/fee-service/utils/tokenPayFee';
42
42
  import { EXTENSION_REQUEST_URL } from '@subwallet/extension-base/services/request-service/constants';
@@ -45,7 +45,7 @@ import { isProposalExpired, isSupportWalletConnectChain, isSupportWalletConnectN
45
45
  import { SWStorage } from '@subwallet/extension-base/storage';
46
46
  import { AccountsStore } from '@subwallet/extension-base/stores';
47
47
  import { AccountSignMode, BasicTxErrorType, BasicTxWarningCode, CommonStepType, EarningProcessType, ProcessType, StakingTxErrorType, StepStatus, SwapFeeType, YieldPoolType, YieldStepType } from '@subwallet/extension-base/types';
48
- import { _analyzeAddress, calculateMaxTransferable, combineAllAccountProxy, createTransactionFromRLP, detectTransferTxType, getAccountSignMode, isSameAddress, MODULE_SUPPORT, reformatAddress, signatureToHex, transformAccounts, transformAddresses, uniqueStringArray } from '@subwallet/extension-base/utils';
48
+ import { _analyzeAddress, calculateMaxTransferable, combineAllAccountProxy, createPromiseHandler, createTransactionFromRLP, detectTransferTxType, getAccountSignMode, isSameAddress, MODULE_SUPPORT, reformatAddress, signatureToHex, transformAccounts, transformAddresses, uniqueStringArray } from '@subwallet/extension-base/utils';
49
49
  import { parseContractInput, parseEvmRlp } from '@subwallet/extension-base/utils/eth/parseTransaction';
50
50
  import { getId } from '@subwallet/extension-base/utils/getId';
51
51
  import { getKeypairTypeByAddress, isAddress, isCardanoAddress, isSubstrateAddress, isTonAddress } from '@subwallet/keyring';
@@ -648,6 +648,63 @@ export default class KoniExtension {
648
648
  });
649
649
  });
650
650
  }
651
+ async switchCurrentNetworkAuthorization({
652
+ authSwitchNetworkType,
653
+ networkKey,
654
+ url
655
+ }) {
656
+ const authUrls = await this.#koniState.getAuthList();
657
+ const chainInfo = this.#koniState.chainService.getChainInfoByKey(networkKey);
658
+ const chainState = this.#koniState.getChainStateByKey(networkKey);
659
+ const {
660
+ promise,
661
+ resolve
662
+ } = createPromiseHandler();
663
+ const typeInfoMap = {
664
+ substrate: 'substrateInfo',
665
+ evm: 'evmInfo',
666
+ cardano: 'cardanoInfo',
667
+ ton: 'tonInfo'
668
+ };
669
+ const typeInfoKey = typeInfoMap[authSwitchNetworkType];
670
+ if (!typeInfoKey || !chainInfo[typeInfoKey]) {
671
+ throw new Error(t('Network {{networkKey}} is not {{authSwitchNetworkType}}', {
672
+ replace: {
673
+ networkKey,
674
+ authSwitchNetworkType
675
+ }
676
+ }));
677
+ }
678
+ const authUrl = authUrls[url];
679
+ if (!authUrl) {
680
+ throw new Error(t('Not found {{url}} in auth list', {
681
+ replace: {
682
+ url
683
+ }
684
+ }));
685
+ }
686
+ if (chainInfo && !_isChainEnabled(chainState)) {
687
+ await this.enableChainWithPriorityAssets({
688
+ chainSlug: networkKey,
689
+ enableTokens: true
690
+ });
691
+ }
692
+ if (!authUrl.accountAuthTypes.includes(authSwitchNetworkType)) {
693
+ throw new Error(t('Network {{networkKey}} is not supported by {{authSwitchNetworkType}}', {
694
+ replace: {
695
+ networkKey,
696
+ authSwitchNetworkType
697
+ }
698
+ }));
699
+ }
700
+ authUrl.currentNetworkMap[authSwitchNetworkType] = networkKey;
701
+ this.#koniState.setAuthorize(authUrls, () => {
702
+ resolve({
703
+ list: authUrls
704
+ });
705
+ });
706
+ return promise;
707
+ }
651
708
  changeAuthorization(data, id, port) {
652
709
  const cb = createSubscription(id, port);
653
710
  this._changeAuthorization(data.url, data.connectValue, items => {
@@ -4255,6 +4312,8 @@ export default class KoniExtension {
4255
4312
  return this.getAuthListV2();
4256
4313
  case 'pri(authorize.toggle)':
4257
4314
  return this.toggleAuthorization2(request);
4315
+ case 'pri(authorize.switchCurrentNetwork)':
4316
+ return this.switchCurrentNetworkAuthorization(request);
4258
4317
  case 'pri(settings.changeBalancesVisibility)':
4259
4318
  return await this.toggleBalancesVisibility();
4260
4319