@subwallet/extension-base 1.3.30-0 → 1.3.31-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 (73) hide show
  1. package/background/KoniTypes.d.ts +12 -0
  2. package/cjs/constants/paraspell-chain-map.js +13 -0
  3. package/cjs/core/logic-validation/transfer.js +13 -1
  4. package/cjs/core/substrate/xcm-parser.js +5 -1
  5. package/cjs/core/utils.js +36 -15
  6. package/cjs/koni/background/handlers/Extension.js +136 -90
  7. package/cjs/koni/background/handlers/State.js +8 -1
  8. package/cjs/packageInfo.js +1 -1
  9. package/cjs/services/balance-service/helpers/process.js +27 -0
  10. package/cjs/services/balance-service/index.js +9 -0
  11. package/cjs/services/balance-service/transfer/xcm/acrossBridge/index.js +229 -0
  12. package/cjs/services/balance-service/transfer/xcm/index.js +96 -7
  13. package/cjs/services/balance-service/transfer/xcm/utils.js +213 -0
  14. package/cjs/services/chain-service/constants.js +2 -4
  15. package/cjs/services/chain-service/index.js +71 -17
  16. package/cjs/services/chain-service/utils/patch.js +1 -1
  17. package/cjs/services/earning-service/handlers/special.js +18 -9
  18. package/cjs/services/keyring-service/context/handlers/Ledger.js +1 -1
  19. package/cjs/services/keyring-service/context/state.js +3 -0
  20. package/cjs/services/migration-service/scripts/DisableZeroBalanceTokens.js +60 -0
  21. package/cjs/services/migration-service/scripts/EnableChain.js +1 -1
  22. package/cjs/services/migration-service/scripts/index.js +3 -2
  23. package/cjs/services/swap-service/handler/base-handler.js +24 -11
  24. package/cjs/services/transaction-service/utils.js +38 -14
  25. package/cjs/utils/fee/transfer.js +52 -28
  26. package/cjs/utils/staticData/index.js +7 -2
  27. package/constants/paraspell-chain-map.d.ts +1 -0
  28. package/constants/paraspell-chain-map.js +7 -0
  29. package/core/logic-validation/transfer.d.ts +1 -0
  30. package/core/logic-validation/transfer.js +12 -1
  31. package/core/substrate/xcm-parser.d.ts +1 -0
  32. package/core/substrate/xcm-parser.js +4 -1
  33. package/core/utils.d.ts +2 -2
  34. package/core/utils.js +36 -15
  35. package/koni/background/handlers/Extension.d.ts +1 -0
  36. package/koni/background/handlers/Extension.js +60 -15
  37. package/koni/background/handlers/State.d.ts +1 -0
  38. package/koni/background/handlers/State.js +7 -1
  39. package/package.json +23 -7
  40. package/packageInfo.js +1 -1
  41. package/services/balance-service/helpers/process.d.ts +2 -1
  42. package/services/balance-service/helpers/process.js +26 -0
  43. package/services/balance-service/index.js +11 -2
  44. package/services/balance-service/transfer/xcm/acrossBridge/index.d.ts +15 -0
  45. package/services/balance-service/transfer/xcm/acrossBridge/index.js +216 -0
  46. package/services/balance-service/transfer/xcm/index.d.ts +5 -1
  47. package/services/balance-service/transfer/xcm/index.js +85 -1
  48. package/services/balance-service/transfer/xcm/utils.d.ts +11 -0
  49. package/services/balance-service/transfer/xcm/utils.js +208 -0
  50. package/services/chain-service/constants.d.ts +0 -1
  51. package/services/chain-service/constants.js +1 -2
  52. package/services/chain-service/index.d.ts +9 -2
  53. package/services/chain-service/index.js +72 -18
  54. package/services/chain-service/utils/patch.js +1 -1
  55. package/services/earning-service/handlers/special.js +19 -10
  56. package/services/keyring-service/context/handlers/Ledger.js +1 -1
  57. package/services/keyring-service/context/state.d.ts +1 -0
  58. package/services/keyring-service/context/state.js +3 -0
  59. package/services/migration-service/scripts/DisableZeroBalanceTokens.d.ts +4 -0
  60. package/services/migration-service/scripts/DisableZeroBalanceTokens.js +51 -0
  61. package/services/migration-service/scripts/EnableChain.js +1 -1
  62. package/services/migration-service/scripts/index.js +3 -2
  63. package/services/swap-service/handler/base-handler.js +25 -12
  64. package/services/transaction-service/types.d.ts +3 -2
  65. package/services/transaction-service/utils.d.ts +1 -0
  66. package/services/transaction-service/utils.js +38 -15
  67. package/types/balance/transfer.d.ts +1 -0
  68. package/types/transaction/request.d.ts +7 -0
  69. package/utils/fee/transfer.d.ts +1 -0
  70. package/utils/fee/transfer.js +54 -30
  71. package/utils/staticData/index.d.ts +4 -1
  72. package/utils/staticData/index.js +5 -1
  73. package/utils/staticData/paraSpellChainMap.json +1 -0
@@ -1,7 +1,6 @@
1
1
  // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- import AutoEnableSomeTokens from "./databases/AutoEnableSomeTokens.js";
5
4
  import ClearMetadataDatabase from "./databases/ClearMetadataDatabase.js";
6
5
  import ClearMetadataForMythos from "./databases/ClearMetadataForMythos.js";
7
6
  import MigrateAssetSetting from "./databases/MigrateAssetSetting.js";
@@ -18,6 +17,7 @@ import MigratePolygonUSDCProvider from "./tokens/MigratePolygonUSDCProvider.js";
18
17
  import DeleteChain from "./DeleteChain.js";
19
18
  import DeleteChainStaking from "./DeleteChainStaking.js";
20
19
  import DeleteEarningData from "./DeleteEarningData.js";
20
+ import DisableZeroBalanceTokens from "./DisableZeroBalanceTokens.js";
21
21
  import EnableVaraChain from "./EnableVaraChain.js";
22
22
  import MigrateAuthUrls from "./MigrateAuthUrls.js";
23
23
  import MigrateImportedToken from "./MigrateImportedToken.js";
@@ -52,7 +52,7 @@ export default {
52
52
  '1.1.28-01': MigrateEarningVersion,
53
53
  '1.1.33-01': MigrateLedgerAccountV2,
54
54
  '1.1.41-01': DeleteChainStaking,
55
- '1.1.46-01': AutoEnableSomeTokens,
55
+ // '1.1.46-01': AutoEnableSomeTokens,
56
56
  '1.2.28-01': MigrateAssetSetting,
57
57
  '1.2.28-02': MigrateTransactionHistoryBySymbol,
58
58
  '1.2.69-01': MigrateRemoveGenesisHash,
@@ -60,6 +60,7 @@ export default {
60
60
  '1.2.32-01': MigratePairData,
61
61
  '1.3.6-01': MigrateTransactionHistoryBridge,
62
62
  '1.3.10-01': ClearMetadataDatabase,
63
+ '1.3.26-01': DisableZeroBalanceTokens,
63
64
  [MYTHOS_MIGRATION_KEY]: ClearMetadataForMythos
64
65
  // [`${EVERYTIME}-1.1.42-02`]: MigrateTransactionHistoryBySymbol
65
66
  // [`${EVERYTIME}-1`]: AutoEnableChainsTokens
@@ -5,8 +5,9 @@ import { TransactionError } from '@subwallet/extension-base/background/errors/Tr
5
5
  import { ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
6
6
  import { validateSpendingAndFeePayment } from '@subwallet/extension-base/core/logic-validation';
7
7
  import { _isAccountActive } from '@subwallet/extension-base/core/substrate/system-pallet';
8
- import { _isSnowBridgeXcm } from '@subwallet/extension-base/core/substrate/xcm-parser';
8
+ import { _isAcrossBridgeXcm, _isSnowBridgeXcm, _isXcmWithinSameConsensus } from '@subwallet/extension-base/core/substrate/xcm-parser';
9
9
  import { _isSufficientToken } from '@subwallet/extension-base/core/utils';
10
+ import { createXcmExtrinsicV2, dryRunXcmExtrinsicV2 } from '@subwallet/extension-base/services/balance-service/transfer/xcm';
10
11
  import { _getAssetDecimals, _getAssetSymbol, _getChainNativeTokenSlug, _getTokenMinAmount, _isChainEvmCompatible, _isNativeToken } from '@subwallet/extension-base/services/chain-service/utils';
11
12
  import { DEFAULT_EXCESS_AMOUNT_WEIGHT, FEE_RATE_MULTIPLIER } from '@subwallet/extension-base/services/swap-service/utils';
12
13
  import { BasicTxErrorType, SwapStepType, TransferTxErrorType } from '@subwallet/extension-base/types';
@@ -17,7 +18,6 @@ import { getId } from '@subwallet/extension-base/utils/getId';
17
18
  import BigN from 'bignumber.js';
18
19
  import { t } from 'i18next';
19
20
  import { isEthereumAddress } from '@polkadot/util-crypto';
20
- import { createXcmExtrinsic } from "../../balance-service/transfer/xcm/index.js";
21
21
  export class SwapBaseHandler {
22
22
  constructor({
23
23
  balanceService,
@@ -90,6 +90,9 @@ export class SwapBaseHandler {
90
90
  // bridge after swap
91
91
  recipientAddress = _reformatAddressWithChain(recipient || address, toChainInfo);
92
92
  }
93
+ if (!_isXcmWithinSameConsensus(fromChainInfo, toChainInfo) || _isSnowBridgeXcm(fromChainInfo, toChainInfo) || _isAcrossBridgeXcm(fromChainInfo, toChainInfo)) {
94
+ return undefined;
95
+ }
93
96
  try {
94
97
  if (!this.chainService.getChainStateByKey(toTokenInfo.originChain).active) {
95
98
  await this.chainService.enableChain(toTokenInfo.originChain);
@@ -97,7 +100,8 @@ export class SwapBaseHandler {
97
100
  const substrateApi = await this.chainService.getSubstrateApi(fromTokenInfo.originChain).isReady;
98
101
  const id = getId();
99
102
  const [feeInfo, toTokenBalance] = await Promise.all([this.feeService.subscribeChainFee(id, fromTokenInfo.originChain, 'substrate'), this.balanceService.getTotalBalance(senderAddress, toTokenInfo.originChain, toTokenInfo.slug, ExtrinsicType.TRANSFER_BALANCE)]);
100
- const xcmTransfer = await createXcmExtrinsic({
103
+ const mockSendingValue = stepIndex === 0 ? fromAmount : (selectedQuote === null || selectedQuote === void 0 ? void 0 : selectedQuote.toAmount) || '0';
104
+ const xcmRequest = {
101
105
  originTokenInfo: fromTokenInfo,
102
106
  destinationTokenInfo: toTokenInfo,
103
107
  originChain: fromChainInfo,
@@ -105,13 +109,17 @@ export class SwapBaseHandler {
105
109
  substrateApi: substrateApi,
106
110
  feeInfo,
107
111
  // Mock sending value to get payment info
108
- sendingValue: fromAmount,
112
+ sendingValue: mockSendingValue,
109
113
  sender: senderAddress,
110
114
  recipient: recipientAddress
111
- });
112
- const _xcmFeeInfo = await xcmTransfer.paymentInfo(senderAddress);
113
- const xcmFeeInfo = _xcmFeeInfo.toPrimitive();
114
- const estimatedBridgeFee = Math.ceil(xcmFeeInfo.partialFee * FEE_RATE_MULTIPLIER.medium).toString();
115
+ };
116
+
117
+ // TODO: calculate fee for destination chain
118
+ const bridgeFeeByDryRun = await dryRunXcmExtrinsicV2(xcmRequest);
119
+ if (!bridgeFeeByDryRun.fee) {
120
+ return undefined;
121
+ }
122
+ const estimatedBridgeFee = BigN(bridgeFeeByDryRun.fee).multipliedBy(FEE_RATE_MULTIPLIER.medium).toFixed(0, 1);
115
123
  const fee = {
116
124
  feeComponent: [{
117
125
  feeType: SwapFeeType.NETWORK_FEE,
@@ -188,7 +196,7 @@ export class SwapBaseHandler {
188
196
  const substrateApi = this.chainService.getSubstrateApi(originAsset.originChain);
189
197
  const chainApi = await substrateApi.isReady;
190
198
  const feeInfo = await this.feeService.subscribeChainFee(getId(), originAsset.originChain, 'substrate');
191
- const xcmTransfer = await createXcmExtrinsic({
199
+ const xcmRequest = {
192
200
  originTokenInfo: originAsset,
193
201
  destinationTokenInfo: destinationAsset,
194
202
  sendingValue: briefXcmStep.sendingValue,
@@ -198,7 +206,11 @@ export class SwapBaseHandler {
198
206
  destinationChain,
199
207
  originChain,
200
208
  feeInfo
201
- });
209
+ };
210
+ const extrinsic = await createXcmExtrinsicV2(xcmRequest);
211
+ if (!extrinsic) {
212
+ throw new Error('XCM extrinsic error');
213
+ }
202
214
  const xcmData = {
203
215
  originNetworkKey: originAsset.originChain,
204
216
  destinationNetworkKey: destinationAsset.originChain,
@@ -210,7 +222,7 @@ export class SwapBaseHandler {
210
222
  };
211
223
  return {
212
224
  txChain: originAsset.originChain,
213
- extrinsic: xcmTransfer,
225
+ extrinsic,
214
226
  transferNativeAmount: _isNativeToken(originAsset) ? briefXcmStep.sendingValue : '0',
215
227
  extrinsicType: ExtrinsicType.TRANSFER_XCM,
216
228
  chainType: ChainType.SUBSTRATE,
@@ -252,12 +264,13 @@ export class SwapBaseHandler {
252
264
 
253
265
  // By here, we know that the user is receiving a valid amount of toToken
254
266
  const toChainApi = this.chainService.getSubstrateApi(toToken.originChain);
267
+ const sufficientChain = this.chainService.value.sufficientChains;
255
268
  if (!toChainApi) {
256
269
  return [new TransactionError(BasicTxErrorType.INTERNAL_ERROR)];
257
270
  }
258
271
 
259
272
  // Only need to check if account is alive with the receiving toToken
260
- const isToTokenSufficient = await _isSufficientToken(toToken, toChainApi);
273
+ const isToTokenSufficient = await _isSufficientToken(toToken, toChainApi, sufficientChain);
261
274
  if (!isToTokenSufficient && !_isNativeToken(toToken)) {
262
275
  // sending token cannot keep account alive, must check with native token
263
276
  const toChainNativeTokenBalance = await this.balanceService.getTotalBalance(receiver, toToken.originChain, toChainNativeToken.slug, ExtrinsicType.TRANSFER_BALANCE);
@@ -20,6 +20,7 @@ export interface SWTransaction extends ValidateTransactionResponse, Partial<Pick
20
20
  createdAt: number;
21
21
  updatedAt: number;
22
22
  estimateFee?: FeeData;
23
+ xcmFeeDryRun?: string;
23
24
  transaction: SubmittableExtrinsic | TransactionConfig | TonTransactionConfig;
24
25
  additionalValidator?: (inputTransaction: SWTransactionResponse) => Promise<void>;
25
26
  eventsHandler?: (eventEmitter: TransactionEmitter) => void;
@@ -35,7 +36,7 @@ export interface SWTransactionResult extends Omit<SWTransaction, 'transaction' |
35
36
  process?: ProcessTransactionData;
36
37
  }
37
38
  declare type SwInputBase = Pick<SWTransaction, 'address' | 'url' | 'data' | 'extrinsicType' | 'chain' | 'chainType' | 'ignoreWarnings' | 'transferNativeAmount'> & Partial<Pick<SWTransaction, 'additionalValidator' | 'eventsHandler'>>;
38
- export interface SWTransactionInput extends SwInputBase, Partial<Pick<SWTransaction, 'estimateFee' | 'signAfterCreate' | 'isPassConfirmation' | 'step' | 'errorOnTimeOut'>>, TransactionFee {
39
+ export interface SWTransactionInput extends SwInputBase, Partial<Pick<SWTransaction, 'estimateFee' | 'signAfterCreate' | 'isPassConfirmation' | 'step' | 'errorOnTimeOut' | 'xcmFeeDryRun'>>, TransactionFee {
39
40
  id?: string;
40
41
  transaction?: SWTransaction['transaction'] | null;
41
42
  warnings?: SWTransaction['warnings'];
@@ -49,7 +50,7 @@ export interface SWTransactionInput extends SwInputBase, Partial<Pick<SWTransact
49
50
  export interface SWPermitTransactionInput extends Omit<SWTransactionInput, 'transaction'> {
50
51
  transaction?: SWPermitTransaction['transaction'] | null;
51
52
  }
52
- export declare type SWTransactionResponse = SwInputBase & Pick<SWTransaction, 'warnings' | 'errors'> & Partial<Pick<SWTransaction, 'id' | 'extrinsicHash' | 'status' | 'estimateFee'>> & TransactionFee & {
53
+ export declare type SWTransactionResponse = SwInputBase & Pick<SWTransaction, 'warnings' | 'errors'> & Partial<Pick<SWTransaction, 'id' | 'extrinsicHash' | 'status' | 'estimateFee' | 'xcmFeeDryRun'>> & TransactionFee & {
53
54
  processId?: string;
54
55
  };
55
56
  export declare type ValidateTransactionResponseInput = SWTransactionInput;
@@ -2,6 +2,7 @@ import { _ChainInfo } from '@subwallet/chain-list/types';
2
2
  import { ExtrinsicDataTypeMap, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
3
3
  import { ChainflipSwapTxData, SimpleSwapTxData } from '@subwallet/extension-base/types/swap';
4
4
  export declare function parseTransactionData<T extends ExtrinsicType>(data: unknown): ExtrinsicDataTypeMap[T];
5
+ export declare function getTransactionId(value: string): Promise<string>;
5
6
  export declare function getExplorerLink(chainInfo: _ChainInfo, value: string, type: 'account' | 'tx'): string | undefined;
6
7
  export declare function getChainflipExplorerLink(data: ChainflipSwapTxData, chainInfo: _ChainInfo): string;
7
8
  export declare function getSimpleSwapExplorerLink(data: SimpleSwapTxData): string;
@@ -3,7 +3,8 @@
3
3
 
4
4
  import { _getBlockExplorerFromChain, _isChainTestNet, _isPureCardanoChain, _isPureEvmChain } from '@subwallet/extension-base/services/chain-service/utils';
5
5
  import { CHAIN_FLIP_MAINNET_EXPLORER, CHAIN_FLIP_TESTNET_EXPLORER, SIMPLE_SWAP_EXPLORER } from '@subwallet/extension-base/services/swap-service/utils';
6
- import { hexAddPrefix, isHex } from '@polkadot/util';
6
+ import { hexAddPrefix, isHex, u8aToHex } from '@polkadot/util';
7
+ import { decodeAddress } from '@polkadot/util-crypto';
7
8
 
8
9
  // @ts-ignore
9
10
  export function parseTransactionData(data) {
@@ -24,19 +25,7 @@ function getBlockExplorerAccountRoute(explorerLink) {
24
25
  if (explorerLink.includes('3dpscan.io')) {
25
26
  return 'account';
26
27
  }
27
- if (explorerLink.includes('explorer.polimec.org')) {
28
- return 'account';
29
- }
30
- if (explorerLink.includes('invarch.statescan.io')) {
31
- return '#/accounts';
32
- }
33
- if (explorerLink.includes('tangle.statescan.io')) {
34
- return '#/accounts';
35
- }
36
- if (explorerLink.includes('laos.statescan.io')) {
37
- return '#/accounts';
38
- }
39
- if (explorerLink.includes('polimec.statescan.io')) {
28
+ if (explorerLink.includes('statescan.io')) {
40
29
  return '#/accounts';
41
30
  }
42
31
  if (explorerLink.includes('explorer.zkverify.io')) {
@@ -60,15 +49,38 @@ function getBlockExplorerTxRoute(chainInfo) {
60
49
  if (['aventus', 'deeper_network'].includes(chainInfo.slug)) {
61
50
  return 'transaction';
62
51
  }
63
- if (['invarch', 'tangle', 'polimec'].includes(chainInfo.slug)) {
52
+ const explorerLink = _getBlockExplorerFromChain(chainInfo);
53
+ if (explorerLink && explorerLink.includes('statescan.io')) {
64
54
  return '#/extrinsics';
65
55
  }
66
56
  return 'extrinsic';
67
57
  }
58
+ export function getTransactionId(value) {
59
+ const query = `
60
+ query ExtrinsicQuery {
61
+ extrinsics(where: {hash_eq: ${value}}, limit: 1) {
62
+ id
63
+ }
64
+ }`;
65
+ const apiUrl = 'https://archive-explorer.truth-network.io/graphql';
66
+ return fetch(apiUrl, {
67
+ method: 'POST',
68
+ headers: {
69
+ 'Content-Type': 'application/json'
70
+ },
71
+ body: JSON.stringify({
72
+ query
73
+ })
74
+ }).then(response => response.json()).then(result => result.data.extrinsics[0].id);
75
+ }
68
76
  export function getExplorerLink(chainInfo, value, type) {
69
77
  const explorerLink = _getBlockExplorerFromChain(chainInfo);
70
78
  if (explorerLink && type === 'account') {
71
79
  const route = getBlockExplorerAccountRoute(explorerLink);
80
+ if (chainInfo.slug === 'truth_network') {
81
+ const address = u8aToHex(decodeAddress(value));
82
+ return `${explorerLink}${explorerLink.endsWith('/') ? '' : '/'}${route}/${address}`;
83
+ }
72
84
  return `${explorerLink}${explorerLink.endsWith('/') ? '' : '/'}${route}/${value}`;
73
85
  }
74
86
  if (explorerLink && isHex(hexAddPrefix(value))) {
@@ -76,6 +88,17 @@ export function getExplorerLink(chainInfo, value, type) {
76
88
  if (chainInfo.slug === 'tangle') {
77
89
  return `${explorerLink}${explorerLink.endsWith('/') ? '' : '/'}extrinsic/${value}${route}/${value}`;
78
90
  }
91
+ if (chainInfo.slug === 'truth_network') {
92
+ // getTransactionId(value)
93
+ // .then((transactionId) => {
94
+ // return (`${explorerLink}${explorerLink.endsWith('/') ? '' : '/'}${route}/${transactionId}`);
95
+ // })
96
+ // .catch((err) => {
97
+ // console.error(err);
98
+ // });
99
+
100
+ return undefined;
101
+ }
79
102
  return `${explorerLink}${explorerLink.endsWith('/') ? '' : '/'}${route}/${value}`;
80
103
  }
81
104
  return undefined;
@@ -3,6 +3,7 @@ import { FeeChainType, FeeDetail, TransactionFee } from '../fee';
3
3
  export interface RequestSubscribeTransfer extends TransactionFee {
4
4
  address: string;
5
5
  chain: string;
6
+ value: string;
6
7
  token: string;
7
8
  destChain: string;
8
9
  }
@@ -22,6 +22,12 @@ export interface RequestCheckCrossChainTransfer extends RequestBaseTransfer, Tra
22
22
  originNetworkKey: string;
23
23
  destinationNetworkKey: string;
24
24
  showExtraWarning?: boolean;
25
+ metadata?: AcrossMetadata;
26
+ }
27
+ interface AcrossMetadata {
28
+ amountOut: string;
29
+ destChainSlug: string;
30
+ rate: string;
25
31
  }
26
32
  export declare type RequestCrossChainTransfer = InternalRequestSign<RequestCheckCrossChainTransfer>;
27
33
  export interface RequestGetTokensCanPayFee {
@@ -34,3 +40,4 @@ export interface RequestGetAmountForPair {
34
40
  nativeTokenSlug: string;
35
41
  toTokenSlug: string;
36
42
  }
43
+ export {};
@@ -5,6 +5,7 @@ import { FeeChainType, FeeInfo, TransactionFee } from '@subwallet/extension-base
5
5
  import { ResponseSubscribeTransfer } from '@subwallet/extension-base/types/balance/transfer';
6
6
  export interface CalculateMaxTransferable extends TransactionFee {
7
7
  address: string;
8
+ value: string;
8
9
  srcToken: _ChainAsset;
9
10
  destToken?: _ChainAsset;
10
11
  srcChain: _ChainInfo;
@@ -8,11 +8,12 @@ import { createCardanoTransaction } from '@subwallet/extension-base/services/bal
8
8
  import { getERC20TransactionObject, getEVMTransactionObject } from '@subwallet/extension-base/services/balance-service/transfer/smart-contract';
9
9
  import { createSubstrateExtrinsic } from '@subwallet/extension-base/services/balance-service/transfer/token';
10
10
  import { createTonTransaction } from '@subwallet/extension-base/services/balance-service/transfer/ton-transfer';
11
- import { createAvailBridgeExtrinsicFromAvail, createAvailBridgeTxFromEth, createPolygonBridgeExtrinsic, createSnowBridgeExtrinsic, createXcmExtrinsic } from '@subwallet/extension-base/services/balance-service/transfer/xcm';
11
+ import { createAcrossBridgeExtrinsic, createAvailBridgeExtrinsicFromAvail, createAvailBridgeTxFromEth, createPolygonBridgeExtrinsic, createSnowBridgeExtrinsic, createXcmExtrinsicV2, dryRunXcmExtrinsicV2 } from '@subwallet/extension-base/services/balance-service/transfer/xcm';
12
+ import { _isAcrossChainBridge, _isAcrossTestnetBridge } from '@subwallet/extension-base/services/balance-service/transfer/xcm/acrossBridge';
12
13
  import { isAvailChainBridge } from '@subwallet/extension-base/services/balance-service/transfer/xcm/availBridge';
13
14
  import { _isPolygonChainBridge } from '@subwallet/extension-base/services/balance-service/transfer/xcm/polygonBridge';
14
15
  import { _isPosChainBridge } from '@subwallet/extension-base/services/balance-service/transfer/xcm/posBridge';
15
- import { _getContractAddressOfToken, _isChainCardanoCompatible, _isChainEvmCompatible, _isChainTonCompatible, _isLocalToken, _isNativeToken, _isPureEvmChain, _isTokenEvmSmartContract, _isTokenTransferredByCardano, _isTokenTransferredByEvm, _isTokenTransferredByTon } from '@subwallet/extension-base/services/chain-service/utils';
16
+ import { _getAssetDecimals, _getContractAddressOfToken, _isChainCardanoCompatible, _isChainEvmCompatible, _isChainTonCompatible, _isLocalToken, _isNativeToken, _isPureEvmChain, _isTokenEvmSmartContract, _isTokenTransferredByCardano, _isTokenTransferredByEvm, _isTokenTransferredByTon } from '@subwallet/extension-base/services/chain-service/utils';
16
17
  import { calculateToAmountByReservePool, FEE_COVERAGE_PERCENTAGE_SPECIAL_CASE } from '@subwallet/extension-base/services/fee-service/utils';
17
18
  import { getHydrationRate } from '@subwallet/extension-base/services/fee-service/utils/tokenPayFee';
18
19
  import { isCardanoTransaction, isTonTransaction } from '@subwallet/extension-base/services/transaction-service/helpers';
@@ -29,7 +30,8 @@ export const detectTransferTxType = (srcToken, srcChain, destChain) => {
29
30
  const isSnowBridgeEvmTransfer = _isPureEvmChain(srcChain) && _isSnowBridgeXcm(srcChain, destChain) && !isAvailBridgeFromEvm;
30
31
  const isPolygonBridgeTransfer = _isPolygonChainBridge(srcChain.slug, destChain.slug);
31
32
  const isPosBridgeTransfer = _isPosChainBridge(srcChain.slug, destChain.slug);
32
- return isAvailBridgeFromEvm || isSnowBridgeEvmTransfer || isPolygonBridgeTransfer || isPosBridgeTransfer ? 'evm' : 'substrate';
33
+ const isAcrossBridgeTransfer = _isAcrossChainBridge(srcChain.slug, destChain.slug);
34
+ return isAvailBridgeFromEvm || isSnowBridgeEvmTransfer || isPolygonBridgeTransfer || isPosBridgeTransfer || isAcrossBridgeTransfer ? 'evm' : 'substrate';
33
35
  } else {
34
36
  if (_isChainEvmCompatible(srcChain) && _isTokenTransferredByEvm(srcToken)) {
35
37
  return 'evm';
@@ -77,7 +79,8 @@ export const calculateTransferMaxTransferable = async (id, request, freeBalance,
77
79
  srcChain,
78
80
  srcToken,
79
81
  substrateApi,
80
- tonApi
82
+ tonApi,
83
+ value
81
84
  } = request;
82
85
  const feeChainType = fee.type;
83
86
  let estimatedFee;
@@ -105,7 +108,7 @@ export const calculateTransferMaxTransferable = async (id, request, freeBalance,
105
108
  from: address,
106
109
  to: recipient,
107
110
  transferAll: false,
108
- value: '0',
111
+ value,
109
112
  fallbackFee: true
110
113
  });
111
114
  } else {
@@ -118,7 +121,7 @@ export const calculateTransferMaxTransferable = async (id, request, freeBalance,
118
121
  from: address,
119
122
  to: recipient,
120
123
  transferAll: false,
121
- value: '0',
124
+ value,
122
125
  fallbackFee: true
123
126
  });
124
127
  }
@@ -128,19 +131,18 @@ export const calculateTransferMaxTransferable = async (id, request, freeBalance,
128
131
  from: address,
129
132
  to: address,
130
133
  networkKey: srcChain.slug,
131
- value: '0',
134
+ value,
132
135
  transferAll: false,
133
136
  // currently not used
134
137
  tonApi
135
138
  });
136
139
  } else if (isCardanoAddress(address) && _isTokenTransferredByCardano(srcToken)) {
137
- const isTransferNativeToken = _isNativeToken(srcToken);
138
140
  [transaction] = await createCardanoTransaction({
139
141
  tokenInfo: srcToken,
140
142
  from: address,
141
143
  to: address,
142
144
  networkKey: srcChain.slug,
143
- value: isTransferNativeToken ? '1000000' : '1',
145
+ value,
144
146
  cardanoTtlOffset: DEFAULT_CARDANO_TTL_OFFSET,
145
147
  transferAll: false,
146
148
  cardanoApi,
@@ -149,7 +151,7 @@ export const calculateTransferMaxTransferable = async (id, request, freeBalance,
149
151
  } else {
150
152
  [transaction] = await createSubstrateExtrinsic({
151
153
  transferAll: false,
152
- value: '0',
154
+ value,
153
155
  from: address,
154
156
  networkKey: srcChain.slug,
155
157
  tokenInfo: srcToken,
@@ -285,10 +287,11 @@ export const calculateXcmMaxTransferable = async (id, request, freeBalance, fee)
285
287
  nativeToken,
286
288
  srcChain,
287
289
  srcToken,
288
- substrateApi
290
+ substrateApi,
291
+ value
289
292
  } = request;
290
293
  const feeChainType = fee.type;
291
- let estimatedFee;
294
+ let estimatedFee = '0';
292
295
  let feeOptions;
293
296
  let maxTransferable;
294
297
  let error;
@@ -297,20 +300,22 @@ export const calculateXcmMaxTransferable = async (id, request, freeBalance, fee)
297
300
  const isSnowBridgeEvmTransfer = _isPureEvmChain(srcChain) && _isSnowBridgeXcm(srcChain, destChain) && !isAvailBridgeFromEvm;
298
301
  const isPolygonBridgeTransfer = _isPolygonChainBridge(srcChain.slug, destChain.slug);
299
302
  const isPosBridgeTransfer = _isPosChainBridge(srcChain.slug, destChain.slug);
303
+ const isAcrossBridgeTransfer = _isAcrossChainBridge(srcChain.slug, destChain.slug);
304
+ const isSubstrateXcm = !(isAvailBridgeFromEvm || isAvailBridgeFromAvail || isSnowBridgeEvmTransfer || isPolygonBridgeTransfer || isPosBridgeTransfer || isAcrossBridgeTransfer);
300
305
  const fakeAddress = '5DRewsYzhJqZXU3SRaWy1FSt5iDr875ao91aw5fjrJmDG4Ap'; // todo: move this
301
306
  const substrateAddress = fakeAddress; // todo: move this
302
307
  const evmAddress = u8aToHex(addressToEvm(fakeAddress)); // todo: move this
303
-
308
+ const bnFreeBalance = new BigN(freeBalance.value);
304
309
  const recipient = _isChainEvmCompatible(destChain) ? evmAddress : substrateAddress;
310
+ if (!destToken) {
311
+ throw Error('Destination token is not available');
312
+ }
305
313
  try {
306
- if (!destToken) {
307
- throw Error('Destination token is not available');
308
- }
309
314
  const params = {
310
315
  destinationTokenInfo: destToken,
311
316
  originTokenInfo: srcToken,
312
317
  // If value is 0, substrate will throw error when estimating fee
313
- sendingValue: feeChainType === 'substrate' ? '1000000000000000000' : '0',
318
+ sendingValue: value,
314
319
  sender: address,
315
320
  recipient,
316
321
  destinationChain: destChain,
@@ -324,6 +329,13 @@ export const calculateXcmMaxTransferable = async (id, request, freeBalance, fee)
324
329
  let funcCreateExtrinsic;
325
330
  if (isPosBridgeTransfer || isPolygonBridgeTransfer) {
326
331
  funcCreateExtrinsic = createPolygonBridgeExtrinsic;
332
+ } else if (isAcrossBridgeTransfer) {
333
+ funcCreateExtrinsic = createAcrossBridgeExtrinsic;
334
+ if (_isAcrossTestnetBridge(srcChain.slug)) {
335
+ params.sendingValue = BigN(0.0037).shiftedBy(_getAssetDecimals(srcToken)).toFixed(0, 1);
336
+ } else {
337
+ params.sendingValue = BigN(1).shiftedBy(_getAssetDecimals(srcToken)).toFixed(0, 1);
338
+ }
327
339
  } else if (isSnowBridgeEvmTransfer) {
328
340
  funcCreateExtrinsic = createSnowBridgeExtrinsic;
329
341
  } else if (isAvailBridgeFromEvm) {
@@ -331,9 +343,12 @@ export const calculateXcmMaxTransferable = async (id, request, freeBalance, fee)
331
343
  } else if (isAvailBridgeFromAvail) {
332
344
  funcCreateExtrinsic = createAvailBridgeExtrinsicFromAvail;
333
345
  } else {
334
- funcCreateExtrinsic = createXcmExtrinsic;
346
+ funcCreateExtrinsic = createXcmExtrinsicV2;
347
+ params.sendingValue = '1';
335
348
  }
336
349
  const extrinsic = await funcCreateExtrinsic(params);
350
+
351
+ // todo: refactor condition
337
352
  if (feeChainType === 'evm') {
338
353
  var _tx$gas2;
339
354
  // Calculate fee for evm transaction
@@ -353,12 +368,17 @@ export const calculateXcmMaxTransferable = async (id, request, freeBalance, fee)
353
368
  };
354
369
  } else if (feeChainType === 'substrate') {
355
370
  // Calculate fee for substrate transaction
356
- try {
357
- var _paymentInfo$partialF2;
358
- const paymentInfo = await extrinsic.paymentInfo(address);
359
- estimatedFee = (paymentInfo === null || paymentInfo === void 0 ? void 0 : (_paymentInfo$partialF2 = paymentInfo.partialFee) === null || _paymentInfo$partialF2 === void 0 ? void 0 : _paymentInfo$partialF2.toString()) || '0';
360
- } catch (e) {
361
- estimatedFee = '0';
371
+ if (isSubstrateXcm) {
372
+ const estimatedFeeByDryRun = await dryRunXcmExtrinsicV2(params);
373
+ estimatedFee = estimatedFeeByDryRun.fee || '0';
374
+ } else {
375
+ try {
376
+ var _paymentInfo$partialF2;
377
+ const paymentInfo = await extrinsic.paymentInfo(address);
378
+ estimatedFee = (paymentInfo === null || paymentInfo === void 0 ? void 0 : (_paymentInfo$partialF2 = paymentInfo.partialFee) === null || _paymentInfo$partialF2 === void 0 ? void 0 : _paymentInfo$partialF2.toString()) || '0';
379
+ } catch (e) {
380
+ estimatedFee = '0';
381
+ }
362
382
  }
363
383
  const _feeCustom = feeCustom;
364
384
  const tip = combineSubstrateFee(fee, feeOption, _feeCustom).tip;
@@ -398,12 +418,12 @@ export const calculateXcmMaxTransferable = async (id, request, freeBalance, fee)
398
418
  if (_SUPPORT_TOKEN_PAY_FEE_GROUP.assetHub.includes(srcChain.slug)) {
399
419
  const estimatedFeeNative = (BigInt(estimatedFee) * BigInt(FEE_COVERAGE_PERCENTAGE_SPECIAL_CASE) / BigInt(100)).toString();
400
420
  const estimatedFeeLocal = await calculateToAmountByReservePool(substrateApi.api, nativeToken, srcToken, estimatedFeeNative);
401
- maxTransferable = BigN(freeBalance.value).minus(estimatedFeeLocal);
421
+ maxTransferable = bnFreeBalance.minus(estimatedFeeLocal);
402
422
  } else if (_SUPPORT_TOKEN_PAY_FEE_GROUP.hydration.includes(srcChain.slug)) {
403
423
  const rate = await getHydrationRate(address, nativeToken, srcToken);
404
424
  if (rate) {
405
425
  const estimatedFeeLocal = new BigN(estimatedFee).multipliedBy(rate).integerValue(BigN.ROUND_UP).toString();
406
- maxTransferable = BigN(freeBalance.value).minus(estimatedFeeLocal);
426
+ maxTransferable = bnFreeBalance.minus(estimatedFeeLocal);
407
427
  } else {
408
428
  throw new Error(`Unable to estimate fee for ${srcChain.slug}.`);
409
429
  }
@@ -411,16 +431,20 @@ export const calculateXcmMaxTransferable = async (id, request, freeBalance, fee)
411
431
  throw new Error(`Unable to estimate fee for ${srcChain.slug}.`);
412
432
  }
413
433
  } else if (isTransferNativeTokenAndPayLocalTokenAsFee) {
414
- maxTransferable = BigN(freeBalance.value);
434
+ maxTransferable = bnFreeBalance;
415
435
  } else {
416
436
  if (!_isNativeToken(srcToken)) {
417
- maxTransferable = BigN(freeBalance.value);
437
+ maxTransferable = bnFreeBalance;
418
438
  } else {
419
- maxTransferable = BigN(freeBalance.value).minus(new BigN(estimatedFee).multipliedBy(XCM_FEE_RATIO));
439
+ maxTransferable = bnFreeBalance.minus(BigN(estimatedFee).multipliedBy(XCM_FEE_RATIO));
420
440
  }
421
441
  }
442
+ if (isAvailBridgeFromAvail) {
443
+ const addedAmount = BigN(1).shiftedBy(_getAssetDecimals(srcToken));
444
+ maxTransferable = maxTransferable.minus(addedAmount);
445
+ }
422
446
  return {
423
- maxTransferable: maxTransferable.gt(BN_ZERO) ? maxTransferable.toFixed(0) || '0' : '0',
447
+ maxTransferable: maxTransferable.gt(BN_ZERO) ? maxTransferable.toFixed(0) : '0',
424
448
  feeOptions: feeOptions,
425
449
  feeType: feeChainType,
426
450
  id: id,
@@ -10,6 +10,7 @@ export declare const blockedActionsFeatures: BlockedActionsFeaturesMap;
10
10
  export declare const remindNotificationTime: Record<NotificationActionType, number>;
11
11
  export declare const blockedActions: Record<string, EnvConfig>;
12
12
  export declare const oldChainPrefix: Record<string, EnvConfig>;
13
+ export declare const paraSpellChainMap: Record<string, EnvConfig>;
13
14
  export declare enum StaticKey {
14
15
  BUY_SERVICE_INFOS = "buy-service-infos",
15
16
  CHAINS = "chains",
@@ -21,7 +22,8 @@ export declare enum StaticKey {
21
22
  BLOCKED_ACTIONS_FEATURES = "blocked-actions-features",
22
23
  REMIND_NOTIFICATION_TIME = "remind-notification-time",
23
24
  BLOCKED_ACTIONS = "blocked-actions",
24
- OLD_CHAIN_PREFIX = "old-chain-prefix"
25
+ OLD_CHAIN_PREFIX = "old-chain-prefix",
26
+ PARASPELL_CHAIN_MAP = "paraspell-chain-map"
25
27
  }
26
28
  export declare const staticData: {
27
29
  chains: import("@subwallet/chain-list/types")._ChainInfo[];
@@ -35,4 +37,5 @@ export declare const staticData: {
35
37
  "remind-notification-time": Record<NotificationActionType, number>;
36
38
  "blocked-actions": Record<string, EnvConfig>;
37
39
  "old-chain-prefix": Record<string, EnvConfig>;
40
+ "paraspell-chain-map": Record<string, EnvConfig>;
38
41
  };
@@ -23,6 +23,8 @@ export const remindNotificationTime = require("./remindNotificationTime.json");
23
23
  export const blockedActions = require("./blockedActions.json");
24
24
  // eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment
25
25
  export const oldChainPrefix = require("./oldChainPrefix.json");
26
+ // eslint-disable-next-line @typescript-eslint/no-var-requires,@typescript-eslint/no-unsafe-assignment
27
+ export const paraSpellChainMap = require("./paraSpellChainMap.json");
26
28
  export let StaticKey;
27
29
  (function (StaticKey) {
28
30
  StaticKey["BUY_SERVICE_INFOS"] = "buy-service-infos";
@@ -36,6 +38,7 @@ export let StaticKey;
36
38
  StaticKey["REMIND_NOTIFICATION_TIME"] = "remind-notification-time";
37
39
  StaticKey["BLOCKED_ACTIONS"] = "blocked-actions";
38
40
  StaticKey["OLD_CHAIN_PREFIX"] = "old-chain-prefix";
41
+ StaticKey["PARASPELL_CHAIN_MAP"] = "paraspell-chain-map";
39
42
  })(StaticKey || (StaticKey = {}));
40
43
  export const staticData = {
41
44
  [StaticKey.CHAINS]: Object.values(ChainInfoMap),
@@ -48,5 +51,6 @@ export const staticData = {
48
51
  [StaticKey.BLOCKED_ACTIONS_FEATURES]: blockedActionsFeatures,
49
52
  [StaticKey.REMIND_NOTIFICATION_TIME]: remindNotificationTime,
50
53
  [StaticKey.BLOCKED_ACTIONS]: blockedActions,
51
- [StaticKey.OLD_CHAIN_PREFIX]: oldChainPrefix
54
+ [StaticKey.OLD_CHAIN_PREFIX]: oldChainPrefix,
55
+ [StaticKey.PARASPELL_CHAIN_MAP]: paraSpellChainMap
52
56
  };