@subwallet/extension-base 1.3.78-0 → 1.3.79-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 (41) hide show
  1. package/background/KoniTypes.d.ts +3 -3
  2. package/cjs/core/logic-validation/index.js +0 -12
  3. package/cjs/koni/background/handlers/Extension.js +7 -2
  4. package/cjs/packageInfo.js +1 -1
  5. package/cjs/services/balance-service/transfer/xcm/utils.js +9 -9
  6. package/cjs/services/earning-service/handlers/native-staking/dtao.js +13 -13
  7. package/cjs/services/earning-service/handlers/native-staking/tao.js +16 -10
  8. package/cjs/services/earning-service/handlers/special.js +9 -2
  9. package/cjs/services/swap-service/handler/asset-hub/handler.js +7 -4
  10. package/cjs/services/swap-service/handler/asset-hub/router.js +2 -66
  11. package/cjs/services/swap-service/handler/base-handler.js +4 -3
  12. package/cjs/services/swap-service/handler/hydradx-handler.js +9 -5
  13. package/cjs/services/swap-service/index.js +5 -4
  14. package/cjs/types/swap/index.js +4 -9
  15. package/cjs/utils/account/common.js +44 -8
  16. package/core/logic-validation/index.d.ts +0 -1
  17. package/core/logic-validation/index.js +0 -1
  18. package/koni/background/handlers/Extension.d.ts +3 -0
  19. package/koni/background/handlers/Extension.js +7 -2
  20. package/package.json +5 -10
  21. package/packageInfo.js +1 -1
  22. package/services/balance-service/transfer/xcm/utils.js +9 -9
  23. package/services/earning-service/handlers/native-staking/dtao.js +12 -13
  24. package/services/earning-service/handlers/native-staking/tao.d.ts +2 -1
  25. package/services/earning-service/handlers/native-staking/tao.js +15 -10
  26. package/services/earning-service/handlers/special.js +9 -2
  27. package/services/swap-service/handler/asset-hub/handler.js +7 -4
  28. package/services/swap-service/handler/asset-hub/router.d.ts +0 -4
  29. package/services/swap-service/handler/asset-hub/router.js +1 -64
  30. package/services/swap-service/handler/base-handler.js +4 -3
  31. package/services/swap-service/handler/hydradx-handler.js +9 -5
  32. package/services/swap-service/index.js +5 -4
  33. package/types/swap/index.d.ts +7 -35
  34. package/types/swap/index.js +3 -8
  35. package/types/yield/actions/join/step.d.ts +1 -0
  36. package/types/yield/actions/join/submit.d.ts +2 -1
  37. package/utils/account/common.d.ts +22 -1
  38. package/utils/account/common.js +44 -8
  39. package/cjs/core/logic-validation/swap.js +0 -235
  40. package/core/logic-validation/swap.d.ts +0 -26
  41. package/core/logic-validation/swap.js +0 -219
@@ -962,7 +962,7 @@ export default class KoniExtension {
962
962
  this.#koniState.eventService.emit('asset.updateState', params.tokenSlug);
963
963
  return true;
964
964
  } catch (e) {
965
- console.error(e);
965
+ console.error('[updateAssetSetting] Error:', e);
966
966
  return false;
967
967
  }
968
968
  }
@@ -4540,7 +4540,8 @@ export default class KoniExtension {
4540
4540
  ...this.createPassConfirmationParams(isPassConfirmation),
4541
4541
  eventsHandler,
4542
4542
  step,
4543
- xcmFeeDryRun: extrinsicType === ExtrinsicType.TRANSFER_XCM ? submitData.xcmStepFee : undefined
4543
+ xcmFeeDryRun: extrinsicType === ExtrinsicType.TRANSFER_XCM ? submitData.xcmStepFee : undefined,
4544
+ xcmDestinationFee: submitData.xcmDestinationFee
4544
4545
  });
4545
4546
  }
4546
4547
  async handleYieldLeave(params) {
@@ -4920,6 +4921,10 @@ export default class KoniExtension {
4920
4921
  ready = true;
4921
4922
  return this.#koniState.swapService.getSwapPairs();
4922
4923
  }
4924
+
4925
+ /**
4926
+ * @deprecated Use function `handleSwapRequestV2` instead.
4927
+ */
4923
4928
  async handleSwapRequest(request) {
4924
4929
  // @ts-ignore
4925
4930
  return Promise.resolve(null);
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "./cjs/detectPackage.js"
18
18
  ],
19
19
  "type": "module",
20
- "version": "1.3.78-0",
20
+ "version": "1.3.79-1",
21
21
  "main": "./cjs/index.js",
22
22
  "module": "./index.js",
23
23
  "types": "./index.d.ts",
@@ -194,11 +194,6 @@
194
194
  "require": "./cjs/core/logic-validation/request.js",
195
195
  "default": "./core/logic-validation/request.js"
196
196
  },
197
- "./core/logic-validation/swap": {
198
- "types": "./core/logic-validation/swap.d.ts",
199
- "require": "./cjs/core/logic-validation/swap.js",
200
- "default": "./core/logic-validation/swap.js"
201
- },
202
197
  "./core/logic-validation/transfer": {
203
198
  "types": "./core/logic-validation/transfer.d.ts",
204
199
  "require": "./cjs/core/logic-validation/transfer.js",
@@ -3029,10 +3024,10 @@
3029
3024
  "@substrate/connect": "^0.8.9",
3030
3025
  "@subwallet-monorepos/subwallet-services-sdk": "0.1.16",
3031
3026
  "@subwallet/chain-list": "0.2.127",
3032
- "@subwallet/extension-base": "^1.3.78-0",
3033
- "@subwallet/extension-chains": "^1.3.78-0",
3034
- "@subwallet/extension-dapp": "^1.3.78-0",
3035
- "@subwallet/extension-inject": "^1.3.78-0",
3027
+ "@subwallet/extension-base": "^1.3.79-1",
3028
+ "@subwallet/extension-chains": "^1.3.79-1",
3029
+ "@subwallet/extension-dapp": "^1.3.79-1",
3030
+ "@subwallet/extension-inject": "^1.3.79-1",
3036
3031
  "@subwallet/keyring": "^0.1.14",
3037
3032
  "@subwallet/ui-keyring": "^0.1.14",
3038
3033
  "@ton/core": "^0.56.3",
package/packageInfo.js CHANGED
@@ -7,5 +7,5 @@ export const packageInfo = {
7
7
  name: '@subwallet/extension-base',
8
8
  path: (import.meta && import.meta.url) ? new URL(import.meta.url).pathname.substring(0, new URL(import.meta.url).pathname.lastIndexOf('/') + 1) : 'auto',
9
9
  type: 'esm',
10
- version: '1.3.78-0'
10
+ version: '1.3.79-1'
11
11
  };
@@ -13,7 +13,7 @@ import { fetchFromProxyService } from '@subwallet/extension-base/utils';
13
13
  import BigNumber from 'bignumber.js';
14
14
  import { assert, compactToU8a, isHex, u8aConcat, u8aEq } from '@polkadot/util';
15
15
  import { _isBittensorToSubtensorBridge, _isSubtensorToBittensorBridge } from "./bittensorBridge/index.js";
16
- const version = '/v5';
16
+ const version = '/v1';
17
17
  const paraSpellApi = {
18
18
  buildXcm: `${version}/x-transfer`,
19
19
  feeXcm: `${version}/xcm-fee`,
@@ -93,8 +93,8 @@ export async function buildXcm(request) {
93
93
  }
94
94
  const paraSpellChainMap = await fetchParaSpellChainMap();
95
95
  const bodyData = {
96
- senderAddress: sender,
97
- address: recipient,
96
+ sender,
97
+ recipient,
98
98
  from: paraSpellChainMap[originChain.slug],
99
99
  to: paraSpellChainMap[destinationChain.slug],
100
100
  currency: createParaSpellCurrency(paraSpellIdentifyV4, sendingValue),
@@ -134,8 +134,8 @@ export async function dryRunXcm(request) {
134
134
  throw new Error('Token is not support XCM at this time');
135
135
  }
136
136
  const bodyData = {
137
- senderAddress: sender,
138
- address: recipient,
137
+ sender,
138
+ recipient,
139
139
  from: paraSpellChainMap[originChain.slug],
140
140
  to: paraSpellChainMap[destinationChain.slug],
141
141
  currency: createParaSpellCurrency(paraSpellIdentifyV4, sendingValue),
@@ -178,8 +178,8 @@ export async function dryRunPreviewXcm(request) {
178
178
  throw new Error('Token is not support XCM at this time');
179
179
  }
180
180
  const bodyData = {
181
- senderAddress: sender,
182
- address: recipient,
181
+ sender,
182
+ recipient,
183
183
  from: paraSpellChainMap[originChain.slug],
184
184
  to: paraSpellChainMap[destinationChain.slug],
185
185
  currency: createParaSpellCurrency(paraSpellIdentifyV4, sendingValue),
@@ -226,8 +226,8 @@ export async function estimateXcmFee(request) {
226
226
  return undefined;
227
227
  }
228
228
  const bodyData = {
229
- senderAddress: sender,
230
- address: recipient,
229
+ sender,
230
+ recipient,
231
231
  from: paraSpellChainMap[fromChainInfo.slug],
232
232
  to: paraSpellChainMap[toChainInfo.slug],
233
233
  currency: createParaSpellCurrency(paraSpellIdentifyV4, requestValue),
@@ -9,20 +9,19 @@ import { reformatAddress } from '@subwallet/extension-base/utils';
9
9
  import BigN from 'bignumber.js';
10
10
  import { BN_ZERO } from '@polkadot/util';
11
11
  import TaoNativeStakingPoolHandler, { DEFAULT_DTAO_MINBOND } from "./tao.js";
12
- const getAlphaToTaoRateMap = async substrateApi => {
13
- const allSubnets = (await substrateApi.api.call.subnetInfoRuntimeApi.getAllDynamicInfo()).toJSON();
14
- if (!allSubnets || allSubnets.length === 0) {
15
- return {};
16
- }
12
+ const getAlphaToTaoRateMap = async (substrateApi, priceScaleDecimals = 9) => {
17
13
  const result = Object.create(null);
18
- for (const subnet of allSubnets) {
19
- const netuid = subnet === null || subnet === void 0 ? void 0 : subnet.netuid;
20
- if (netuid === undefined) {
21
- continue;
14
+ const PRICE_SCALE = new BigN(10).pow(priceScaleDecimals);
15
+ const allSubnetPrices = (await substrateApi.api.call.swapRuntimeApi.currentAlphaPriceAll()).toJSON();
16
+ if (allSubnetPrices && allSubnetPrices.length > 0) {
17
+ for (const subnetPrice of allSubnetPrices) {
18
+ const netuid = subnetPrice === null || subnetPrice === void 0 ? void 0 : subnetPrice.netuid;
19
+ if (netuid === undefined) {
20
+ continue;
21
+ }
22
+ const rawPrice = subnetPrice !== null && subnetPrice !== void 0 && subnetPrice.price ? new BigN(subnetPrice.price) : new BigN(0);
23
+ result[netuid] = netuid === 0 ? '1' : rawPrice.dividedBy(PRICE_SCALE).toFixed();
22
24
  }
23
- const taoIn = subnet !== null && subnet !== void 0 && subnet.taoIn ? new BigN(subnet.taoIn) : new BigN(0);
24
- const alphaIn = subnet !== null && subnet !== void 0 && subnet.alphaIn ? new BigN(subnet.alphaIn) : new BigN(0);
25
- result[netuid] = netuid === 0 || alphaIn.lte(0) ? '1' : taoIn.dividedBy(alphaIn).toString();
26
25
  }
27
26
  return result;
28
27
  };
@@ -204,7 +203,7 @@ export default class SubnetTaoStakingPoolHandler extends TaoNativeStakingPoolHan
204
203
  const getPoolPosition = async () => {
205
204
  const rawDelegateStateInfos = await substrateApi.api.call.stakeInfoRuntimeApi.getStakeInfoForColdkeys(useAddresses);
206
205
  const delegateStateInfos = rawDelegateStateInfos.toPrimitive();
207
- const alphaToTaoRateMap = await getAlphaToTaoRateMap(this.substrateApi);
206
+ const alphaToTaoRateMap = await getAlphaToTaoRateMap(this.substrateApi, this.getAlphaPriceScaleDecimals());
208
207
  if (!delegateStateInfos || delegateStateInfos.length === 0) {
209
208
  return;
210
209
  }
@@ -82,10 +82,11 @@ export declare class BittensorCache {
82
82
  fetchApr(netuid: number): Promise<ValidatorAprResponse>;
83
83
  fetchSubnetFeeRate(netuid: number): Promise<string>;
84
84
  }
85
- export declare const getAlphaToTaoRate: (substrateApi: _SubstrateApi, netuid: number) => Promise<string>;
85
+ export declare const getAlphaToTaoRate: (substrateApi: _SubstrateApi, netuid: number, priceScaleDecimals?: number) => Promise<string>;
86
86
  export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHandler {
87
87
  readonly availableMethod: YieldPoolMethodInfo;
88
88
  protected bittensorCache: BittensorCache;
89
+ protected getAlphaPriceScaleDecimals(): number;
89
90
  protected getMinBond(netuid?: number): Promise<BigN>;
90
91
  constructor(state: KoniState, chain: string);
91
92
  get maintainBalance(): string;
@@ -113,14 +113,16 @@ export class BittensorCache {
113
113
  }
114
114
  }
115
115
  }
116
- export const getAlphaToTaoRate = async (substrateApi, netuid) => {
117
- const subnetInfo = (await substrateApi.api.call.subnetInfoRuntimeApi.getDynamicInfo(netuid)).toJSON();
118
- if (!subnetInfo) {
116
+ export const getAlphaToTaoRate = async (substrateApi, netuid, priceScaleDecimals = 9) => {
117
+ if (netuid === 0) {
119
118
  return '1';
120
119
  }
121
- const taoIn = subnetInfo.taoIn ? new BigN(subnetInfo.taoIn) : new BigN(0);
122
- const alphaIn = subnetInfo.alphaIn ? new BigN(subnetInfo.alphaIn) : new BigN(0);
123
- return netuid === 0 || alphaIn.lte(0) ? '1' : taoIn.dividedBy(alphaIn).toString();
120
+ const [rawSubnetPrice, rawRootPrice] = await Promise.all([substrateApi.api.call.swapRuntimeApi.currentAlphaPrice(netuid), substrateApi.api.call.swapRuntimeApi.currentAlphaPrice(0)]);
121
+ const subnetPrice = new BigN(rawSubnetPrice.toString());
122
+ const defaultScale = new BigN(10).pow(priceScaleDecimals);
123
+ const rootPrice = new BigN(rawRootPrice.toString());
124
+ const priceScale = rootPrice.lte(0) ? defaultScale : rootPrice;
125
+ return subnetPrice.lte(0) ? '0' : subnetPrice.dividedBy(priceScale).toFixed();
124
126
  };
125
127
  export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHandler {
126
128
  availableMethod = {
@@ -132,6 +134,9 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
132
134
  claimReward: false,
133
135
  changeValidator: true
134
136
  };
137
+ getAlphaPriceScaleDecimals() {
138
+ return _getAssetDecimals(this.nativeToken);
139
+ }
135
140
  async getMinBond(netuid) {
136
141
  var _cachedPool$metadata2, _cachedPool$statistic, _cachedPool$statistic2, _onlinePool$metadata2, _onlinePool$statistic, _onlinePool$statistic2;
137
142
  // @ts-ignore
@@ -469,7 +474,7 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
469
474
  const hotkey = selectedValidatorInfo.address;
470
475
  const netuid = (_subnetData$netuid = subnetData === null || subnetData === void 0 ? void 0 : subnetData.netuid) !== null && _subnetData$netuid !== void 0 ? _subnetData$netuid : 0;
471
476
  const slippage = (_subnetData$slippage = subnetData === null || subnetData === void 0 ? void 0 : subnetData.slippage) !== null && _subnetData$slippage !== void 0 ? _subnetData$slippage : DEFAULT_BITTENSOR_SLIPPAGE;
472
- const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid));
477
+ const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid, this.getAlphaPriceScaleDecimals()));
473
478
  const limitPrice = alphaToTaoPrice.multipliedBy(10 ** _getAssetDecimals(this.nativeToken)).multipliedBy(1 + slippage);
474
479
  const BNlimitPrice = new BigN(limitPrice.integerValue(BigN.ROUND_CEIL).toFixed());
475
480
  const extrinsic = chainApi.api.tx.subtensorModule.addStakeLimit(hotkey, netuid, binaryAmount.toFixed(), BNlimitPrice.toFixed(), false);
@@ -511,7 +516,7 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
511
516
  return Promise.reject(new TransactionError(BasicTxErrorType.INVALID_PARAMS));
512
517
  }
513
518
  const binaryAmount = new BigN(amount);
514
- const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid));
519
+ const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid, this.getAlphaPriceScaleDecimals()));
515
520
  const limitPrice = alphaToTaoPrice.multipliedBy(10 ** _getAssetDecimals(this.nativeToken)).multipliedBy(1 - slippage);
516
521
  const BNlimitPrice = new BigN(limitPrice.integerValue(BigN.ROUND_CEIL).toFixed());
517
522
  const extrinsic = apiPromise.api.tx.subtensorModule.removeStakeLimit(selectedTarget, netuid, binaryAmount.toFixed(), BNlimitPrice.toFixed(), false);
@@ -527,7 +532,7 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
527
532
  return [new TransactionError(BasicTxErrorType.INVALID_PARAMS)];
528
533
  }
529
534
  const netuid = (_poolInfo$metadata$su = poolInfo.metadata.subnetData) === null || _poolInfo$metadata$su === void 0 ? void 0 : _poolInfo$metadata$su.netuid;
530
- const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid || 0));
535
+ const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid || 0, this.getAlphaPriceScaleDecimals()));
531
536
  const minDelegatorStake = await this.getMinBond(netuid);
532
537
  const minUnstake = minDelegatorStake.dividedBy(alphaToTaoPrice);
533
538
  if (new BigN(amount).lt(minUnstake)) {
@@ -567,7 +572,7 @@ export default class TaoNativeStakingPoolHandler extends BaseParaStakingPoolHand
567
572
  if (originValidator === destValidator) {
568
573
  return Promise.reject(new TransactionError(BasicTxErrorType.INVALID_PARAMS, t('bg.EARNING.services.service.earning.nativeStaking.tao.fromValidatorSameAsTo')));
569
574
  }
570
- const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid));
575
+ const alphaToTaoPrice = new BigN(await getAlphaToTaoRate(this.substrateApi, netuid, this.getAlphaPriceScaleDecimals()));
571
576
  const bnMinStake = await this.getMinBond(netuid);
572
577
  const minUnstake = bnMinStake.dividedBy(alphaToTaoPrice);
573
578
  const formattedMinUnstake = minUnstake.dividedBy(1000000).integerValue(BigN.ROUND_CEIL).dividedBy(1000);
@@ -248,6 +248,7 @@ export default class BaseSpecialStakingPoolHandler extends BasePoolHandler {
248
248
  }
249
249
  const metadata = {
250
250
  sendingValue,
251
+ xcmDestinationFee,
251
252
  originTokenInfo: altInputTokenInfo,
252
253
  destinationTokenInfo: inputTokenInfo
253
254
  };
@@ -459,7 +460,8 @@ export default class BaseSpecialStakingPoolHandler extends BasePoolHandler {
459
460
  const {
460
461
  destinationTokenInfo,
461
462
  originTokenInfo,
462
- sendingValue
463
+ sendingValue,
464
+ xcmDestinationFee
463
465
  } = metadata;
464
466
  const originChainInfo = this.state.getChainInfo(originTokenInfo.originChain);
465
467
  const originTokenSlug = _getChainNativeTokenSlug(originChainInfo);
@@ -497,7 +499,12 @@ export default class BaseSpecialStakingPoolHandler extends BasePoolHandler {
497
499
  txData: xcmData,
498
500
  transferNativeAmount: sendingValue,
499
501
  chainType: ChainType.SUBSTRATE,
500
- xcmStepFee
502
+ xcmStepFee,
503
+ xcmDestinationFee: xcmDestinationFee ? {
504
+ decimals: _getAssetDecimals(destinationTokenInfo),
505
+ symbol: _getAssetSymbol(destinationTokenInfo),
506
+ value: xcmDestinationFee
507
+ } : undefined
501
508
  };
502
509
  }
503
510
  handleYieldJoin(data, path, currentStep) {
@@ -64,7 +64,10 @@ export class AssetHubSwapHandler {
64
64
  const {
65
65
  path,
66
66
  request: {
67
- fromAmount
67
+ address,
68
+ alternativeAddress,
69
+ fromAmount,
70
+ recipient
68
71
  },
69
72
  selectedQuote
70
73
  } = params;
@@ -86,12 +89,12 @@ export class AssetHubSwapHandler {
86
89
  const needModifyData = swapXcm || xcmSwapXcm;
87
90
  let bnSendingValue = BigN(fromAmount);
88
91
  let bnExpectedReceive = BigN(selectedQuote.toAmount);
89
- const sender = _reformatAddressWithChain(params.request.address, originChain);
90
- let receiver = _reformatAddressWithChain(params.request.recipient || params.request.address, destinationChain);
92
+ const sender = _reformatAddressWithChain(address, originChain, alternativeAddress);
93
+ let receiver = _reformatAddressWithChain(recipient || address, destinationChain);
91
94
  if (needModifyData) {
92
95
  bnSendingValue = bnSendingValue.multipliedBy(DEFAULT_EXCESS_AMOUNT_WEIGHT);
93
96
  bnExpectedReceive = bnExpectedReceive.multipliedBy(DEFAULT_EXCESS_AMOUNT_WEIGHT);
94
- receiver = _reformatAddressWithChain(params.request.address, destinationChain);
97
+ receiver = _reformatAddressWithChain(address, destinationChain, alternativeAddress);
95
98
  }
96
99
  const submitStep = {
97
100
  name: 'Swap',
@@ -1,7 +1,6 @@
1
1
  import { _ChainAsset } from '@subwallet/chain-list/types';
2
2
  import { ChainService } from '@subwallet/extension-base/services/chain-service';
3
3
  import { _SubstrateApi } from '@subwallet/extension-base/services/chain-service/types';
4
- import { AssetHubSwapEarlyValidation, SwapPair, SwapRequest } from '@subwallet/extension-base/types/swap';
5
4
  import { SubmittableExtrinsic } from '@polkadot/api/types';
6
5
  export declare class AssetHubRouter {
7
6
  private readonly chain;
@@ -9,8 +8,5 @@ export declare class AssetHubRouter {
9
8
  constructor(chain: string, chainService: ChainService);
10
9
  get substrateApi(): _SubstrateApi;
11
10
  get nativeToken(): _ChainAsset;
12
- buildPath(pair: SwapPair): Array<_ChainAsset>;
13
- earlyValidateSwapValidation(request: SwapRequest): Promise<AssetHubSwapEarlyValidation>;
14
- estimateAmountOut(pair: SwapPair, amountIn: string): Promise<string>;
15
11
  buildSwapExtrinsic(path: Array<_ChainAsset>, recipient: string, amountIn: string, amountOutMin: string): Promise<SubmittableExtrinsic<'promise'>>;
16
12
  }
@@ -1,10 +1,7 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-base
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import { _getTokenMinAmount } from '@subwallet/extension-base/services/chain-service/utils';
5
- import { buildSwapExtrinsic, checkLiquidityForPath, checkMinAmountForPath, estimatePriceImpactPct, estimateRateAfterForPath, estimateRateForPath, estimateTokensForPath, getReserveForPath } from '@subwallet/extension-base/services/swap-service/handler/asset-hub/utils';
6
- import { SwapErrorType } from '@subwallet/extension-base/types/swap';
7
- import BigN from 'bignumber.js';
4
+ import { buildSwapExtrinsic } from '@subwallet/extension-base/services/swap-service/handler/asset-hub/utils';
8
5
  export class AssetHubRouter {
9
6
  constructor(chain, chainService) {
10
7
  this.chain = chain;
@@ -16,66 +13,6 @@ export class AssetHubRouter {
16
13
  get nativeToken() {
17
14
  return this.chainService.getNativeTokenInfo(this.chain);
18
15
  }
19
- buildPath(pair) {
20
- // const nativeToken = this.nativeToken;
21
- // const nativeTokenSlug = nativeToken.slug;
22
-
23
- const assetFrom = this.chainService.getAssetBySlug(pair.from);
24
- const assetTo = this.chainService.getAssetBySlug(pair.to);
25
- return [assetFrom, assetTo];
26
- // if (pair.from === nativeTokenSlug || pair.to === nativeTokenSlug) {
27
- // return [assetFrom, assetTo];
28
- // } else {
29
- // return [assetFrom, nativeToken, assetTo];
30
- // }
31
- }
32
- async earlyValidateSwapValidation(request) {
33
- const substrateApi = await this.substrateApi.isReady;
34
- const paths = this.buildPath(request.pair);
35
- const api = await substrateApi.api.isReady;
36
- const amount = request.fromAmount;
37
- const reserves = await getReserveForPath(api, paths);
38
- const amounts = estimateTokensForPath(amount, reserves);
39
- const marketRate = estimateRateForPath(reserves);
40
- const marketRateAfter = estimateRateAfterForPath(amount, reserves);
41
- const priceImpactPct = estimatePriceImpactPct(marketRate, marketRateAfter);
42
- const errors = [];
43
-
44
- // Check liquidity
45
- const liquidityError = checkLiquidityForPath(amounts, reserves);
46
- if (liquidityError) {
47
- errors.push(liquidityError);
48
- }
49
-
50
- // Check amount token in pool after swap
51
- const minAmounts = paths.map(asset => _getTokenMinAmount(asset));
52
- const minAmountAfterSwapError = checkMinAmountForPath(reserves, amounts, minAmounts);
53
- if (minAmountAfterSwapError) {
54
- errors.push(minAmountAfterSwapError);
55
- }
56
- const bnAmount = new BigN(request.fromAmount);
57
- if (bnAmount.lte(0)) {
58
- errors.push(SwapErrorType.AMOUNT_CANNOT_BE_ZERO);
59
- }
60
- const metadata = {
61
- chain: this.chainService.getChainInfoByKey(this.chain),
62
- toAmount: amounts[amounts.length - 1],
63
- quoteRate: marketRate,
64
- priceImpactPct: priceImpactPct
65
- };
66
- return {
67
- error: errors[0],
68
- metadata
69
- };
70
- }
71
- async estimateAmountOut(pair, amountIn) {
72
- const substrateApi = await this.substrateApi.isReady;
73
- const paths = this.buildPath(pair);
74
- const api = await substrateApi.api.isReady;
75
- const reserves = await getReserveForPath(api, paths);
76
- const amounts = estimateTokensForPath(amountIn, reserves);
77
- return amounts[amounts.length - 1];
78
- }
79
16
  async buildSwapExtrinsic(path, recipient, amountIn, amountOutMin) {
80
17
  const substrateApi = await this.substrateApi.isReady;
81
18
  const api = await substrateApi.api.isReady;
@@ -71,6 +71,7 @@ export class SwapBaseHandler {
71
71
  path,
72
72
  request: {
73
73
  address,
74
+ alternativeAddress,
74
75
  fromAmount,
75
76
  recipient
76
77
  },
@@ -94,12 +95,12 @@ export class SwapBaseHandler {
94
95
  throw Error('Token or chain not found');
95
96
  }
96
97
  let recipientAddress;
97
- const senderAddress = _reformatAddressWithChain(address, fromChainInfo);
98
+ const senderAddress = _reformatAddressWithChain(address, fromChainInfo, alternativeAddress);
98
99
  if (stepIndex === 0) {
99
- recipientAddress = _reformatAddressWithChain(address, toChainInfo);
100
+ recipientAddress = _reformatAddressWithChain(address, toChainInfo, alternativeAddress);
100
101
  } else {
101
102
  // bridge after swap
102
- recipientAddress = _reformatAddressWithChain(recipient || address, toChainInfo);
103
+ recipientAddress = _reformatAddressWithChain(recipient || address, toChainInfo, alternativeAddress);
103
104
  }
104
105
  if (!_isXcmWithinSameConsensus(fromChainInfo, toChainInfo) || _isSnowBridgeXcm(fromChainInfo, toChainInfo) || _isAcrossBridgeXcm(fromChainInfo, toChainInfo)) {
105
106
  return undefined;
@@ -108,7 +108,11 @@ export class HydradxHandler {
108
108
  const {
109
109
  path,
110
110
  request: {
111
- fromAmount
111
+ address,
112
+ alternativeAddress,
113
+ fromAmount,
114
+ recipient,
115
+ slippage
112
116
  },
113
117
  selectedQuote
114
118
  } = params;
@@ -127,8 +131,8 @@ export class HydradxHandler {
127
131
  const destinationTokenInfo = this.chainService.getAssetBySlug(swapPairInfo.to);
128
132
  const originChain = this.chainService.getChainInfoByKey(originTokenInfo.originChain);
129
133
  const destinationChain = this.chainService.getChainInfoByKey(destinationTokenInfo.originChain);
130
- const sender = _reformatAddressWithChain(params.request.address, originChain);
131
- let receiver = _reformatAddressWithChain(params.request.recipient || params.request.address, destinationChain);
134
+ const sender = _reformatAddressWithChain(address, originChain, alternativeAddress);
135
+ let receiver = _reformatAddressWithChain(recipient || address, destinationChain);
132
136
  const actionList = JSON.stringify(path.map(step => step.action));
133
137
  const xcmSwapXcm = actionList === JSON.stringify([DynamicSwapType.BRIDGE, DynamicSwapType.SWAP, DynamicSwapType.BRIDGE]);
134
138
  const swapXcm = actionList === JSON.stringify([DynamicSwapType.SWAP, DynamicSwapType.BRIDGE]);
@@ -152,7 +156,7 @@ export class HydradxHandler {
152
156
  slug: swapPairInfo.slug
153
157
  },
154
158
  fromAmount: bnSendingValue.toFixed(0, 1),
155
- slippage: params.request.slippage
159
+ slippage: slippage
156
160
  });
157
161
  } catch (error) {
158
162
  throw new Error(`Failed to fetch swap quote: ${error.message}`);
@@ -163,7 +167,7 @@ export class HydradxHandler {
163
167
  }
164
168
  const overrideQuote = quoteAskResponse.quote;
165
169
  txHex = overrideQuote.metadata;
166
- receiver = _reformatAddressWithChain(params.request.address, destinationChain);
170
+ receiver = _reformatAddressWithChain(address, destinationChain, alternativeAddress);
167
171
  }
168
172
  if (!txHex || !isHex(txHex)) {
169
173
  return Promise.resolve(undefined);
@@ -103,8 +103,7 @@ export class SwapService {
103
103
  if (!params.selectedQuote) {
104
104
  return this.getDefaultProcessV2(params);
105
105
  } else {
106
- var _params$request$curre;
107
- const providerId = ((_params$request$curre = params.request.currentQuote) === null || _params$request$curre === void 0 ? void 0 : _params$request$curre.id) || params.selectedQuote.provider.id;
106
+ const providerId = params.selectedQuote.provider.id;
108
107
  const handler = this.handlers[providerId];
109
108
  if (handler) {
110
109
  // todo: handle error response from generateOptimalProcess
@@ -129,6 +128,8 @@ export class SwapService {
129
128
  console.group('Swap Logger');
130
129
  console.log('path', path);
131
130
  console.log('swapQuoteResponse', swapQuoteResponse);
131
+
132
+ // Just to log routing type for Uniswap Quote
132
133
  if (swapQuoteResponse.optimalQuote && swapQuoteResponse.optimalQuote.metadata) {
133
134
  const routing = swapQuoteResponse.optimalQuote.metadata.routing;
134
135
  if (routing) {
@@ -147,7 +148,7 @@ export class SwapService {
147
148
  }
148
149
 
149
150
  // override fee for quote because some cases need estimate network fee on Extension (i.e. Optimex)
150
- if (swapQuoteResponse.optimalQuote) {
151
+ if (swapQuoteResponse.optimalQuote && [SwapProviderId.OPTIMEX, SwapProviderId.OPTIMEX_TESTNET].includes(swapQuoteResponse.optimalQuote.provider.id)) {
151
152
  const swapIndex = optimalProcess.steps.findIndex(step => step.type === SwapStepType.SWAP);
152
153
  swapQuoteResponse.optimalQuote.feeInfo.feeComponent = optimalProcess.totalFee[swapIndex].feeComponent;
153
154
  }
@@ -190,7 +191,7 @@ export class SwapService {
190
191
  const swapAction = path.find(step => step.action === DynamicSwapType.SWAP);
191
192
  const directSwapRequest = swapAction ? {
192
193
  ...request,
193
- address: _reformatAddressWithChain(request.address, this.chainService.getChainInfoByKey(_getAssetOriginChain(this.chainService.getAssetBySlug(swapAction.pair.from)))),
194
+ address: _reformatAddressWithChain(request.address, this.chainService.getChainInfoByKey(_getAssetOriginChain(this.chainService.getAssetBySlug(swapAction.pair.from))), request.alternativeAddress),
194
195
  pair: swapAction.pair
195
196
  } : undefined;
196
197
  if (!directSwapRequest) {
@@ -1,6 +1,6 @@
1
- import { _ChainAsset, _ChainInfo } from '@subwallet/chain-list/types';
1
+ import { _ChainAsset } from '@subwallet/chain-list/types';
2
2
  import { SwapError } from '@subwallet/extension-base/background/errors/SwapError';
3
- import { AmountData, ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
3
+ import { ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
4
4
  import { BaseStepDetail, BaseStepType, CommonOptimalSwapPath, CommonStepFeeInfo } from '@subwallet/extension-base/types/service-base';
5
5
  import BigN from 'bignumber.js';
6
6
  import { BaseProcessRequestSign, TransactionData } from '../transaction';
@@ -73,7 +73,6 @@ export declare const _SUPPORTED_SWAP_PROVIDERS: SwapProviderId[];
73
73
  export interface SwapProvider {
74
74
  id: SwapProviderId;
75
75
  name: string;
76
- faq?: string;
77
76
  }
78
77
  export declare enum SwapFeeType {
79
78
  PLATFORM_FEE = "PLATFORM_FEE",
@@ -101,30 +100,13 @@ export interface HydradxSwapTxData extends SwapBaseTxData {
101
100
  txHex: string;
102
101
  }
103
102
  export declare type GenSwapStepFuncV2 = (params: OptimalSwapPathParamsV2, stepIndex: number) => Promise<[BaseStepDetail, CommonStepFeeInfo] | undefined>;
104
- export interface ChainflipPreValidationMetadata {
105
- minSwap: AmountData;
106
- maxSwap?: AmountData;
107
- chain: _ChainInfo;
108
- }
109
- export interface HydradxPreValidationMetadata {
110
- maxSwap: AmountData;
111
- chain: _ChainInfo;
112
- }
113
- export interface AssetHubPreValidationMetadata {
114
- chain: _ChainInfo;
115
- toAmount: string;
116
- quoteRate: string;
117
- priceImpactPct?: string;
118
- }
119
- export interface SimpleSwapValidationMetadata {
120
- minSwap: AmountData;
121
- maxSwap: AmountData;
122
- chain: _ChainInfo;
123
- }
124
103
  export interface ProcessedQuoteAskResponse {
125
104
  quote?: SwapQuote;
126
105
  error?: SwapError;
127
106
  }
107
+ /**
108
+ * @deprecated Use interface `SwapRequestV2` instead.
109
+ */
128
110
  export interface SwapRequest {
129
111
  address: string;
130
112
  pair: SwapPair;
@@ -136,6 +118,7 @@ export interface SwapRequest {
136
118
  }
137
119
  export interface SwapRequestV2 {
138
120
  address: string;
121
+ alternativeAddress?: string;
139
122
  pair: SwapPair;
140
123
  fromAmount: string;
141
124
  slippage: number;
@@ -182,22 +165,11 @@ export interface DynamicSwapAction {
182
165
  action: DynamicSwapType;
183
166
  pair: ActionPair;
184
167
  }
185
- export declare const enum BridgeStepPosition {
186
- FIRST = 0,
187
- AFTER_SWAP = 1
188
- }
189
168
  export interface OptimalSwapPathParamsV2 {
190
- request: SwapRequest;
169
+ request: SwapRequestV2;
191
170
  selectedQuote?: SwapQuote;
192
171
  path: DynamicSwapAction[];
193
172
  }
194
- export interface SwapEarlyValidation {
195
- error?: SwapErrorType;
196
- metadata?: ChainflipPreValidationMetadata | HydradxPreValidationMetadata | AssetHubPreValidationMetadata;
197
- }
198
- export interface AssetHubSwapEarlyValidation extends SwapEarlyValidation {
199
- metadata: AssetHubPreValidationMetadata;
200
- }
201
173
  export interface ValidateSwapProcessParams {
202
174
  address: string;
203
175
  process: CommonOptimalSwapPath;
@@ -1,8 +1,6 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-base
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- // core
5
-
6
4
  export let SwapErrorType;
7
5
  (function (SwapErrorType) {
8
6
  SwapErrorType["ERROR_FETCHING_QUOTE"] = "ERROR_FETCHING_QUOTE";
@@ -46,7 +44,6 @@ export let SwapProviderId;
46
44
  SwapProviderId["BITTENSOR_TESTNET"] = "BITTENSOR_TESTNET";
47
45
  })(SwapProviderId || (SwapProviderId = {}));
48
46
  export const _SUPPORTED_SWAP_PROVIDERS = [SwapProviderId.CHAIN_FLIP_TESTNET, SwapProviderId.CHAIN_FLIP_MAINNET, SwapProviderId.HYDRADX_MAINNET, SwapProviderId.POLKADOT_ASSET_HUB, SwapProviderId.KUSAMA_ASSET_HUB, SwapProviderId.SIMPLE_SWAP, SwapProviderId.UNISWAP, SwapProviderId.KYBER, SwapProviderId.OPTIMEX, SwapProviderId.OPTIMEX_TESTNET, SwapProviderId.BITTENSOR, SwapProviderId.BITTENSOR_TESTNET];
49
- // process handling
50
47
  export let SwapFeeType;
51
48
  (function (SwapFeeType) {
52
49
  SwapFeeType["PLATFORM_FEE"] = "PLATFORM_FEE";
@@ -54,15 +51,13 @@ export let SwapFeeType;
54
51
  SwapFeeType["WALLET_FEE"] = "WALLET_FEE";
55
52
  })(SwapFeeType || (SwapFeeType = {})); // todo: will be more
56
53
  // parameters & responses
54
+ /**
55
+ * @deprecated Use interface `SwapRequestV2` instead.
56
+ */
57
57
  export let DynamicSwapType;
58
58
  (function (DynamicSwapType) {
59
59
  DynamicSwapType["SWAP"] = "SWAP";
60
60
  DynamicSwapType["BRIDGE"] = "BRIDGE";
61
61
  })(DynamicSwapType || (DynamicSwapType = {}));
62
- export let BridgeStepPosition;
63
- (function (BridgeStepPosition) {
64
- BridgeStepPosition[BridgeStepPosition["FIRST"] = 0] = "FIRST";
65
- BridgeStepPosition[BridgeStepPosition["AFTER_SWAP"] = 1] = "AFTER_SWAP";
66
- })(BridgeStepPosition || (BridgeStepPosition = {}));
67
62
  export const CHAINFLIP_SLIPPAGE = 0.02; // Example: 0.01 for 1%
68
63
  export const SIMPLE_SWAP_SLIPPAGE = 0.05;
@@ -98,6 +98,7 @@ export interface OptimalYieldPath {
98
98
  export declare type GenStepFunction = (params: OptimalYieldPathParams) => Promise<YieldStepBaseInfo | undefined>;
99
99
  export interface XcmStepMetadataForLiqStaking {
100
100
  sendingValue: string;
101
+ xcmDestinationFee?: string;
101
102
  originTokenInfo: _ChainAsset;
102
103
  destinationTokenInfo: _ChainAsset;
103
104
  }
@@ -1,4 +1,4 @@
1
- import { _Address, ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
1
+ import { _Address, AmountData, ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
2
2
  import { BaseProcessRequestSign, BaseRequestSign, InternalRequestSign, TransactionData } from '../../../transaction';
3
3
  import { BittensorRootClaimType, NominationPoolInfo, ValidatorInfo, YieldPoolType, YieldPositionInfo } from '../../info';
4
4
  import { OptimalYieldPath } from './step';
@@ -10,6 +10,7 @@ export interface HandleYieldStepData {
10
10
  txData: any;
11
11
  transferNativeAmount: string;
12
12
  xcmStepFee?: string;
13
+ xcmDestinationFee?: AmountData;
13
14
  }
14
15
  export interface AbstractSubmitYieldJoinData {
15
16
  slug: string;