@subwallet/extension-base 1.1.54-0 → 1.1.55-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 (91) hide show
  1. package/background/KoniTypes.d.ts +21 -1
  2. package/background/KoniTypes.js +1 -0
  3. package/background/errors/SwapError.d.ts +6 -0
  4. package/background/errors/SwapError.js +57 -0
  5. package/background/errors/TransactionError.js +9 -0
  6. package/background/types.d.ts +2 -0
  7. package/cjs/background/KoniTypes.js +1 -0
  8. package/cjs/background/errors/SwapError.js +64 -0
  9. package/cjs/background/errors/TransactionError.js +9 -0
  10. package/cjs/koni/api/staking/bonding/utils.js +35 -6
  11. package/cjs/koni/background/handlers/Extension.js +214 -102
  12. package/cjs/koni/background/handlers/State.js +5 -2
  13. package/cjs/packageInfo.js +1 -1
  14. package/cjs/services/balance-service/index.js +6 -3
  15. package/cjs/services/chain-service/constants.js +1 -1
  16. package/cjs/services/chain-service/index.js +39 -18
  17. package/cjs/services/chain-service/utils/index.js +15 -4
  18. package/cjs/services/chain-service/utils/patch.js +1 -1
  19. package/cjs/services/earning-service/constants/chains.js +4 -2
  20. package/cjs/services/earning-service/handlers/native-staking/astar.js +4 -3
  21. package/cjs/services/earning-service/handlers/native-staking/relay-chain.js +22 -3
  22. package/cjs/services/migration-service/scripts/MigrateTransactionHistoryBySymbol.js +4 -17
  23. package/cjs/services/migration-service/scripts/databases/MigrateAssetSetting.js +4 -17
  24. package/cjs/services/migration-service/scripts/index.js +3 -3
  25. package/cjs/services/swap-service/handler/base-handler.js +189 -0
  26. package/cjs/services/swap-service/handler/chainflip-handler.js +407 -0
  27. package/cjs/services/swap-service/handler/hydradx-handler.js +531 -0
  28. package/cjs/services/swap-service/index.js +250 -0
  29. package/cjs/services/swap-service/utils.js +126 -0
  30. package/cjs/services/transaction-service/index.js +20 -0
  31. package/cjs/services/transaction-service/utils.js +6 -0
  32. package/cjs/types/fee/evm.js +1 -0
  33. package/cjs/types/fee/fee.js +70 -0
  34. package/cjs/types/fee/index.js +27 -1
  35. package/cjs/types/service-base.js +1 -0
  36. package/cjs/types/swap/index.js +50 -0
  37. package/cjs/utils/index.js +12 -0
  38. package/cjs/utils/swap.js +78 -0
  39. package/koni/api/staking/bonding/utils.d.ts +3 -1
  40. package/koni/api/staking/bonding/utils.js +32 -6
  41. package/koni/background/handlers/Extension.d.ts +6 -0
  42. package/koni/background/handlers/Extension.js +111 -0
  43. package/koni/background/handlers/State.d.ts +2 -0
  44. package/koni/background/handlers/State.js +5 -2
  45. package/package.json +65 -8
  46. package/packageInfo.js +1 -1
  47. package/services/balance-service/index.js +6 -3
  48. package/services/base/types.d.ts +4 -0
  49. package/services/chain-service/constants.js +1 -1
  50. package/services/chain-service/index.d.ts +4 -0
  51. package/services/chain-service/index.js +21 -1
  52. package/services/chain-service/utils/index.d.ts +7 -5
  53. package/services/chain-service/utils/index.js +9 -2
  54. package/services/chain-service/utils/patch.js +1 -1
  55. package/services/earning-service/constants/chains.d.ts +1 -0
  56. package/services/earning-service/constants/chains.js +1 -0
  57. package/services/earning-service/handlers/native-staking/astar.js +4 -3
  58. package/services/earning-service/handlers/native-staking/relay-chain.js +24 -5
  59. package/services/event-service/types.d.ts +1 -0
  60. package/services/migration-service/scripts/MigrateTransactionHistoryBySymbol.js +4 -17
  61. package/services/migration-service/scripts/databases/MigrateAssetSetting.js +4 -17
  62. package/services/migration-service/scripts/index.js +3 -3
  63. package/services/swap-service/handler/base-handler.d.ts +38 -0
  64. package/services/swap-service/handler/base-handler.js +180 -0
  65. package/services/swap-service/handler/chainflip-handler.d.ts +30 -0
  66. package/services/swap-service/handler/chainflip-handler.js +399 -0
  67. package/services/swap-service/handler/hydradx-handler.d.ts +36 -0
  68. package/services/swap-service/handler/hydradx-handler.js +522 -0
  69. package/services/swap-service/index.d.ts +32 -0
  70. package/services/swap-service/index.js +241 -0
  71. package/services/swap-service/utils.d.ts +18 -0
  72. package/services/swap-service/utils.js +105 -0
  73. package/services/transaction-service/index.js +20 -0
  74. package/services/transaction-service/utils.d.ts +2 -0
  75. package/services/transaction-service/utils.js +6 -2
  76. package/types/fee/evm.d.ts +49 -0
  77. package/types/fee/evm.js +1 -0
  78. package/types/fee/fee.d.ts +32 -0
  79. package/types/fee/fee.js +63 -0
  80. package/types/fee/index.d.ts +2 -49
  81. package/types/fee/index.js +5 -1
  82. package/types/service-base.d.ts +10 -0
  83. package/types/service-base.js +1 -0
  84. package/types/swap/index.d.ts +168 -0
  85. package/types/swap/index.js +41 -0
  86. package/types/yield/info/chain/target.d.ts +2 -0
  87. package/types/yield/info/pallet.d.ts +4 -0
  88. package/utils/index.d.ts +1 -0
  89. package/utils/index.js +2 -1
  90. package/utils/swap.d.ts +3 -0
  91. package/utils/swap.js +70 -0
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.swapCustomFormatter = exports.formatNumberString = void 0;
8
+ var _number = require("@subwallet/extension-base/utils/number");
9
+ var _bignumber = _interopRequireDefault(require("bignumber.js"));
10
+ // Copyright 2019-2022 @subwallet/extension-koni authors & contributors
11
+ // SPDX-License-Identifier: Apache-2.0
12
+
13
+ // Clear zero from end, use with decimal only
14
+ const clearZero = result => {
15
+ let index = result.length - 1;
16
+ while (result[index] === '0') {
17
+ result = result.slice(0, index);
18
+ index--;
19
+ }
20
+ return result;
21
+ };
22
+ const NUM_1T = new _bignumber.default(1e12);
23
+ const TLIM = new _bignumber.default(1e17);
24
+ const NUM_1B = new _bignumber.default(1e9);
25
+ const BLIM = new _bignumber.default(1e14);
26
+ const NUM_1M = new _bignumber.default(1e6);
27
+ const NUM_100M = new _bignumber.default(1e8);
28
+ const swapCustomFormatter = (input, metadata) => {
29
+ const minNumberFormat = 2;
30
+ const maxNumberFormat = (metadata === null || metadata === void 0 ? void 0 : metadata.maxNumberFormat) || 6;
31
+ const [int, decimal = '0'] = input.split('.');
32
+ let _decimal = '';
33
+ const intNumber = new _bignumber.default(int);
34
+ const max = _number.BN_TEN.pow(maxNumberFormat);
35
+
36
+ // If count of number in integer part greater or equal maxNumberFormat, do not show decimal
37
+ if (intNumber.gte(max)) {
38
+ if (intNumber.gte(NUM_100M)) {
39
+ if (intNumber.gte(BLIM)) {
40
+ if (intNumber.gte(TLIM)) {
41
+ return `${intNumber.dividedBy(NUM_1T).toFixed()} T`;
42
+ }
43
+ return `${intNumber.dividedBy(NUM_1B).toFixed()} B`;
44
+ }
45
+ return `${intNumber.dividedBy(NUM_1M).toFixed()} M`;
46
+ }
47
+ _decimal = decimal.slice(0, metadata === null || metadata === void 0 ? void 0 : metadata.maxNumberFormat);
48
+ return `${int}.${_decimal}`;
49
+ }
50
+
51
+ // Get only minNumberFormat number at decimal
52
+ if (decimal.length <= minNumberFormat || !(metadata !== null && metadata !== void 0 && metadata.maxNumberFormat)) {
53
+ _decimal = decimal;
54
+ } else {
55
+ _decimal = decimal.slice(0, maxNumberFormat);
56
+ }
57
+
58
+ // Clear zero number for decimal
59
+ _decimal = clearZero(_decimal);
60
+ if (_decimal) {
61
+ return `${int}.${_decimal}`;
62
+ }
63
+ return int;
64
+ };
65
+ exports.swapCustomFormatter = swapCustomFormatter;
66
+ const formatNumberString = numberString => {
67
+ const number = parseFloat(numberString);
68
+ const exponentNotation = number.toExponential();
69
+ let [coefficient, exponent] = exponentNotation.split('e');
70
+ if (parseInt(exponent) < 0) {
71
+ coefficient = coefficient.replace(/^0+|\./g, '');
72
+ coefficient = '0.' + '0'.repeat(Math.abs(parseInt(exponent)) - 1) + coefficient;
73
+ } else {
74
+ coefficient += '0'.repeat(parseInt(exponent) - coefficient.length + 1);
75
+ }
76
+ return coefficient;
77
+ };
78
+ exports.formatNumberString = formatNumberString;
@@ -1,7 +1,7 @@
1
1
  import { _ChainInfo } from '@subwallet/chain-list/types';
2
2
  import { NominationInfo, NominatorMetadata, StakingType, UnstakingInfo } from '@subwallet/extension-base/background/KoniTypes';
3
3
  import { _SubstrateInflationParams } from '@subwallet/extension-base/services/chain-service/constants';
4
- import { EarningStatus, YieldPoolInfo, YieldPositionInfo } from '@subwallet/extension-base/types';
4
+ import { EarningStatus, PalletStakingEraRewardPoints, YieldPoolInfo, YieldPositionInfo } from '@subwallet/extension-base/types';
5
5
  import BigNumber from 'bignumber.js';
6
6
  import { ApiPromise } from '@polkadot/api';
7
7
  import { Codec } from '@polkadot/types/types';
@@ -158,6 +158,8 @@ export declare function getEarningStatusByNominations(bnTotalActiveStake: BN, no
158
158
  export declare function getValidatorLabel(chain: string): "dApp" | "Validator" | "Collator";
159
159
  export declare function getAvgValidatorEraReward(supportedDays: number, eraRewardHistory: Codec[]): BigNumber;
160
160
  export declare function getSupportedDaysByHistoryDepth(erasPerDay: number, maxSupportedEras: number): 15 | 30;
161
+ export declare function getValidatorPointsMap(eraRewardMap: Record<string, PalletStakingEraRewardPoints>): Record<string, BigNumber>;
162
+ export declare function getTopValidatorByPoints(validatorPointsList: Record<string, BigNumber>): string[];
161
163
  export declare const getMinStakeErrorMessage: (chainInfo: _ChainInfo, bnMinStake: BN) => string;
162
164
  export declare const getMaxValidatorErrorMessage: (chainInfo: _ChainInfo, max: number) => string;
163
165
  export declare const getExistUnstakeErrorMessage: (chain: string, type?: StakingType, isStakeMore?: boolean) => string;
@@ -197,13 +197,13 @@ export function getYieldAvailableActionsByPosition(yieldPosition, yieldPoolInfo,
197
197
  const result = [];
198
198
  if ([YieldPoolType.NATIVE_STAKING, YieldPoolType.NOMINATION_POOL].includes(yieldPoolInfo.type)) {
199
199
  result.push(YieldAction.STAKE);
200
- const bnActiveStake = new BN(yieldPosition.activeStake);
201
- if (yieldPosition.activeStake && bnActiveStake.gt(BN_ZERO)) {
200
+ const bnActiveStake = new BigNumber(yieldPosition.activeStake);
201
+ if (yieldPosition.activeStake && bnActiveStake.gt('0')) {
202
202
  result.push(YieldAction.UNSTAKE);
203
203
  const isAstarNetwork = _STAKING_CHAIN_GROUP.astar.includes(yieldPosition.chain);
204
204
  const isAmplitudeNetwork = _STAKING_CHAIN_GROUP.amplitude.includes(yieldPosition.chain);
205
- const bnUnclaimedReward = new BN(unclaimedReward || '0');
206
- if ((yieldPosition.type === YieldPoolType.NOMINATION_POOL || isAmplitudeNetwork) && bnUnclaimedReward.gt(BN_ZERO) || isAstarNetwork) {
205
+ const bnUnclaimedReward = new BigNumber(unclaimedReward || '0');
206
+ if ((yieldPosition.type === YieldPoolType.NOMINATION_POOL || isAmplitudeNetwork) && bnUnclaimedReward.gt('0') || isAstarNetwork) {
207
207
  result.push(YieldAction.CLAIM_REWARD);
208
208
  }
209
209
  }
@@ -216,8 +216,8 @@ export function getYieldAvailableActionsByPosition(yieldPosition, yieldPoolInfo,
216
216
  }
217
217
  } else if (yieldPoolInfo.type === YieldPoolType.LIQUID_STAKING) {
218
218
  result.push(YieldAction.START_EARNING);
219
- const activeBalance = new BN(yieldPosition.activeStake || '0');
220
- if (activeBalance.gt(BN_ZERO)) {
219
+ const activeBalance = new BigNumber(yieldPosition.activeStake);
220
+ if (activeBalance.gt('0')) {
221
221
  result.push(YieldAction.UNSTAKE);
222
222
  }
223
223
  const hasWithdrawal = yieldPosition.unstakings.some(unstakingInfo => unstakingInfo.status === UnstakingStatus.CLAIMABLE);
@@ -350,6 +350,32 @@ export function getSupportedDaysByHistoryDepth(erasPerDay, maxSupportedEras) {
350
350
  return 15;
351
351
  }
352
352
  }
353
+ export function getValidatorPointsMap(eraRewardMap) {
354
+ // mapping store validator and totalPoints
355
+ const validatorTotalPointsMap = {};
356
+ Object.values(eraRewardMap).forEach(info => {
357
+ const individual = info.individual;
358
+ Object.entries(individual).forEach(([validator, rawPoints]) => {
359
+ const points = rawPoints.replaceAll(',', '');
360
+ if (!validatorTotalPointsMap[validator]) {
361
+ validatorTotalPointsMap[validator] = new BigNumber(points);
362
+ } else {
363
+ validatorTotalPointsMap[validator] = validatorTotalPointsMap[validator].plus(points);
364
+ }
365
+ });
366
+ });
367
+ return validatorTotalPointsMap;
368
+ }
369
+ export function getTopValidatorByPoints(validatorPointsList) {
370
+ const sortValidatorPointsList = Object.fromEntries(Object.entries(validatorPointsList).sort((a, b) => a[1].minus(b[1]).toNumber()).reverse());
371
+
372
+ // keep 50% first validator
373
+ const entries = Object.entries(sortValidatorPointsList);
374
+ const endIndex = Math.ceil(entries.length / 2);
375
+ const top50PercentEntries = entries.slice(0, endIndex);
376
+ const top50PercentRecord = Object.fromEntries(top50PercentEntries);
377
+ return Object.keys(top50PercentRecord);
378
+ }
353
379
  export const getMinStakeErrorMessage = (chainInfo, bnMinStake) => {
354
380
  const tokenInfo = _getChainNativeTokenBasicInfo(chainInfo);
355
381
  const number = formatNumber(bnMinStake.toString(), tokenInfo.decimals || 0, balanceFormatter);
@@ -108,6 +108,7 @@ export default class KoniExtension {
108
108
  private derivationCreateV2;
109
109
  private jsonRestoreV2;
110
110
  private batchRestoreV2;
111
+ private batchExportV2;
111
112
  private getNftCollection;
112
113
  private subscribeNftCollection;
113
114
  private getNft;
@@ -237,5 +238,10 @@ export default class KoniExtension {
237
238
  private completeCampaignBanner;
238
239
  private subscribeBuyTokens;
239
240
  private subscribeBuyServices;
241
+ private subscribeSwapPairs;
242
+ private handleSwapRequest;
243
+ private getLatestSwapQuote;
244
+ private validateSwapProcess;
245
+ private handleSwapStep;
240
246
  handle<TMessageType extends MessageTypes>(id: string, type: TMessageType, request: RequestTypes[TMessageType], port: chrome.runtime.Port): Promise<ResponseType<TMessageType>>;
241
247
  }
@@ -1393,6 +1393,26 @@ export default class KoniExtension {
1393
1393
  throw new Error(t('Wrong password'));
1394
1394
  }
1395
1395
  }
1396
+ async batchExportV2({
1397
+ addresses,
1398
+ password
1399
+ }) {
1400
+ try {
1401
+ if (addresses && !addresses.length) {
1402
+ throw new Error(t('No accounts found to export'));
1403
+ }
1404
+ return {
1405
+ exportedJson: await keyring.backupAccounts(password, addresses)
1406
+ };
1407
+ } catch (e) {
1408
+ const error = e;
1409
+ if (error.message === 'Invalid master password') {
1410
+ throw new Error(t('Wrong password'));
1411
+ } else {
1412
+ throw error;
1413
+ }
1414
+ }
1415
+ }
1396
1416
  getNftCollection() {
1397
1417
  return this.#koniState.getNftCollection();
1398
1418
  }
@@ -3943,6 +3963,82 @@ export default class KoniExtension {
3943
3963
 
3944
3964
  /* Buy service */
3945
3965
 
3966
+ /* Swap service */
3967
+ async subscribeSwapPairs(id, port) {
3968
+ const cb = createSubscription(id, port);
3969
+ let ready = false;
3970
+ await this.#koniState.swapService.waitForStarted();
3971
+ const callback = rs => {
3972
+ if (ready) {
3973
+ cb(rs);
3974
+ }
3975
+ };
3976
+ const subscription = this.#koniState.swapService.subscribeSwapPairs(callback);
3977
+ this.createUnsubscriptionHandle(id, subscription.unsubscribe);
3978
+ port.onDisconnect.addListener(() => {
3979
+ this.cancelSubscription(id);
3980
+ });
3981
+ ready = true;
3982
+ return this.#koniState.swapService.getSwapPairs();
3983
+ }
3984
+ async handleSwapRequest(request) {
3985
+ return this.#koniState.swapService.handleSwapRequest(request);
3986
+ }
3987
+ async getLatestSwapQuote(swapRequest) {
3988
+ return this.#koniState.swapService.getLatestQuotes(swapRequest);
3989
+ }
3990
+ async validateSwapProcess(params) {
3991
+ return this.#koniState.swapService.validateSwapProcess(params);
3992
+ }
3993
+ async handleSwapStep(inputData) {
3994
+ const {
3995
+ address,
3996
+ process,
3997
+ quote,
3998
+ recipient
3999
+ } = inputData;
4000
+ if (!quote || !address || !process) {
4001
+ return this.#koniState.transactionService.generateBeforeHandleResponseErrors([new TransactionError(BasicTxErrorType.INTERNAL_ERROR)]);
4002
+ }
4003
+ const isLastStep = inputData.currentStep + 1 === process.steps.length;
4004
+ const swapValidations = await this.#koniState.swapService.validateSwapProcess({
4005
+ address,
4006
+ process,
4007
+ selectedQuote: quote,
4008
+ recipient
4009
+ });
4010
+ if (swapValidations.length > 0) {
4011
+ return this.#koniState.transactionService.generateBeforeHandleResponseErrors(swapValidations);
4012
+ }
4013
+
4014
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
4015
+ const {
4016
+ chainType,
4017
+ extrinsic,
4018
+ extrinsicType,
4019
+ transferNativeAmount,
4020
+ txChain,
4021
+ txData
4022
+ } = await this.#koniState.swapService.handleSwapProcess(inputData);
4023
+ // const chosenFeeToken = process.steps.findIndex((step) => step.type === SwapStepType.SET_FEE_TOKEN) > -1;
4024
+ // const allowSkipValidation = [ExtrinsicType.SET_FEE_TOKEN, ExtrinsicType.SWAP].includes(extrinsicType);
4025
+
4026
+ return await this.#koniState.transactionService.handleTransaction({
4027
+ address,
4028
+ chain: txChain,
4029
+ transaction: extrinsic,
4030
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
4031
+ data: txData,
4032
+ extrinsicType,
4033
+ // change this depends on step
4034
+ chainType,
4035
+ resolveOnDone: !isLastStep,
4036
+ transferNativeAmount
4037
+ // skipFeeValidation: chosenFeeToken && allowSkipValidation
4038
+ });
4039
+ }
4040
+ /* Swap service */
4041
+
3946
4042
  // --------------------------------------------------------------
3947
4043
  // eslint-disable-next-line @typescript-eslint/require-await
3948
4044
  async handle(id, type, request, port) {
@@ -4074,6 +4170,8 @@ export default class KoniExtension {
4074
4170
  return this.subscribeCrowdloan(id, port);
4075
4171
  case 'pri(derivation.createV2)':
4076
4172
  return this.derivationCreateV2(request);
4173
+ case 'pri(accounts.batchExportV2)':
4174
+ return this.batchExportV2(request);
4077
4175
  case 'pri(json.restoreV2)':
4078
4176
  return this.jsonRestoreV2(request);
4079
4177
  case 'pri(json.batchRestoreV2)':
@@ -4472,6 +4570,19 @@ export default class KoniExtension {
4472
4570
  case 'pri(database.exportJson)':
4473
4571
  return this.#koniState.dbService.getExportJson();
4474
4572
  /* Database */
4573
+
4574
+ /* Swap service */
4575
+ case 'pri(swapService.subscribePairs)':
4576
+ return this.subscribeSwapPairs(id, port);
4577
+ case 'pri(swapService.handleSwapRequest)':
4578
+ return this.handleSwapRequest(request);
4579
+ case 'pri(swapService.getLatestQuote)':
4580
+ return this.getLatestSwapQuote(request);
4581
+ case 'pri(swapService.validateSwapProcess)':
4582
+ return this.validateSwapProcess(request);
4583
+ case 'pri(swapService.handleSwapStep)':
4584
+ return this.handleSwapStep(request);
4585
+ /* Swap service */
4475
4586
  // Default
4476
4587
  default:
4477
4588
  throw new Error(`Unable to handle message of type ${type}`);
@@ -21,6 +21,7 @@ import { AuthUrls, MetaRequest, SignRequest } from '@subwallet/extension-base/se
21
21
  import SettingService from '@subwallet/extension-base/services/setting-service/SettingService';
22
22
  import DatabaseService from '@subwallet/extension-base/services/storage-service/DatabaseService';
23
23
  import { SubscanService } from '@subwallet/extension-base/services/subscan-service';
24
+ import { SwapService } from '@subwallet/extension-base/services/swap-service';
24
25
  import TransactionService from '@subwallet/extension-base/services/transaction-service';
25
26
  import WalletConnectService from '@subwallet/extension-base/services/wallet-connect-service';
26
27
  import { BalanceMap, EvmFeeInfo } from '@subwallet/extension-base/types';
@@ -71,6 +72,7 @@ export default class KoniState {
71
72
  readonly buyService: BuyService;
72
73
  readonly earningService: EarningService;
73
74
  readonly feeService: FeeService;
75
+ readonly swapService: SwapService;
74
76
  private generalStatus;
75
77
  private waitSleeping;
76
78
  private waitStarting;
@@ -28,6 +28,7 @@ import SettingService from '@subwallet/extension-base/services/setting-service/S
28
28
  import DatabaseService from '@subwallet/extension-base/services/storage-service/DatabaseService';
29
29
  import { SubscanService } from '@subwallet/extension-base/services/subscan-service';
30
30
  import { SUBSCAN_API_CHAIN_MAP } from '@subwallet/extension-base/services/subscan-service/subscan-chain-map';
31
+ import { SwapService } from '@subwallet/extension-base/services/swap-service';
31
32
  import TransactionService from '@subwallet/extension-base/services/transaction-service';
32
33
  import WalletConnectService from '@subwallet/extension-base/services/wallet-connect-service';
33
34
  import AccountRefStore from '@subwallet/extension-base/stores/AccountRef';
@@ -104,6 +105,7 @@ export default class KoniState {
104
105
  this.transactionService = new TransactionService(this);
105
106
  this.earningService = new EarningService(this);
106
107
  this.feeService = new FeeService(this);
108
+ this.swapService = new SwapService(this);
107
109
  this.subscription = new KoniSubscription(this, this.dbService);
108
110
  this.cron = new KoniCron(this, this.subscription, this.dbService);
109
111
  this.logger = createLogger('State');
@@ -226,6 +228,7 @@ export default class KoniState {
226
228
  this.eventService.emit('chain.ready', true);
227
229
  await this.balanceService.init();
228
230
  await this.earningService.init();
231
+ await this.swapService.init();
229
232
  this.onReady();
230
233
  this.onAccountAdd();
231
234
  this.onAccountRemove();
@@ -1396,7 +1399,7 @@ export default class KoniState {
1396
1399
  // Stopping services
1397
1400
  await Promise.all([this.cron.stop(), this.subscription.stop()]);
1398
1401
  await this.pauseAllNetworks(undefined, 'IDLE mode');
1399
- await Promise.all([this.historyService.stop(), this.priceService.stop(), this.balanceService.stop(), this.earningService.stop()]);
1402
+ await Promise.all([this.historyService.stop(), this.priceService.stop(), this.balanceService.stop(), this.earningService.stop(), this.swapService.stop()]);
1400
1403
 
1401
1404
  // Complete sleeping
1402
1405
  sleeping.resolve();
@@ -1428,7 +1431,7 @@ export default class KoniState {
1428
1431
  }
1429
1432
 
1430
1433
  // Start services
1431
- await Promise.all([this.cron.start(), this.subscription.start(), this.historyService.start(), this.priceService.start(), this.balanceService.start(), this.earningService.start()]);
1434
+ await Promise.all([this.cron.start(), this.subscription.start(), this.historyService.start(), this.priceService.start(), this.balanceService.start(), this.earningService.start(), this.swapService.start()]);
1432
1435
 
1433
1436
  // Complete starting
1434
1437
  starting.resolve();
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "./cjs/detectPackage.js"
18
18
  ],
19
19
  "type": "module",
20
- "version": "1.1.54-0",
20
+ "version": "1.1.55-0",
21
21
  "main": "./cjs/index.js",
22
22
  "module": "./index.js",
23
23
  "types": "./index.d.ts",
@@ -44,6 +44,11 @@
44
44
  "require": "./cjs/background/errors/ProviderError.js",
45
45
  "default": "./background/errors/ProviderError.js"
46
46
  },
47
+ "./background/errors/SwapError": {
48
+ "types": "./background/errors/SwapError.d.ts",
49
+ "require": "./cjs/background/errors/SwapError.js",
50
+ "default": "./background/errors/SwapError.js"
51
+ },
47
52
  "./background/errors/SWError": {
48
53
  "types": "./background/errors/SWError.d.ts",
49
54
  "require": "./cjs/background/errors/SWError.js",
@@ -1355,6 +1360,31 @@
1355
1360
  "require": "./cjs/services/subscan-service/types.js",
1356
1361
  "default": "./services/subscan-service/types.js"
1357
1362
  },
1363
+ "./services/swap-service": {
1364
+ "types": "./services/swap-service/index.d.ts",
1365
+ "require": "./cjs/services/swap-service/index.js",
1366
+ "default": "./services/swap-service/index.js"
1367
+ },
1368
+ "./services/swap-service/handler/base-handler": {
1369
+ "types": "./services/swap-service/handler/base-handler.d.ts",
1370
+ "require": "./cjs/services/swap-service/handler/base-handler.js",
1371
+ "default": "./services/swap-service/handler/base-handler.js"
1372
+ },
1373
+ "./services/swap-service/handler/chainflip-handler": {
1374
+ "types": "./services/swap-service/handler/chainflip-handler.d.ts",
1375
+ "require": "./cjs/services/swap-service/handler/chainflip-handler.js",
1376
+ "default": "./services/swap-service/handler/chainflip-handler.js"
1377
+ },
1378
+ "./services/swap-service/handler/hydradx-handler": {
1379
+ "types": "./services/swap-service/handler/hydradx-handler.d.ts",
1380
+ "require": "./cjs/services/swap-service/handler/hydradx-handler.js",
1381
+ "default": "./services/swap-service/handler/hydradx-handler.js"
1382
+ },
1383
+ "./services/swap-service/utils": {
1384
+ "types": "./services/swap-service/utils.d.ts",
1385
+ "require": "./cjs/services/swap-service/utils.js",
1386
+ "default": "./services/swap-service/utils.js"
1387
+ },
1358
1388
  "./services/transaction-service": {
1359
1389
  "types": "./services/transaction-service/index.d.ts",
1360
1390
  "require": "./cjs/services/transaction-service/index.js",
@@ -1560,11 +1590,31 @@
1560
1590
  "require": "./cjs/types/fee/index.js",
1561
1591
  "default": "./types/fee/index.js"
1562
1592
  },
1593
+ "./types/fee/evm": {
1594
+ "types": "./types/fee/evm.d.ts",
1595
+ "require": "./cjs/types/fee/evm.js",
1596
+ "default": "./types/fee/evm.js"
1597
+ },
1598
+ "./types/fee/fee": {
1599
+ "types": "./types/fee/fee.d.ts",
1600
+ "require": "./cjs/types/fee/fee.js",
1601
+ "default": "./types/fee/fee.js"
1602
+ },
1563
1603
  "./types/ordinal": {
1564
1604
  "types": "./types/ordinal.d.ts",
1565
1605
  "require": "./cjs/types/ordinal.js",
1566
1606
  "default": "./types/ordinal.js"
1567
1607
  },
1608
+ "./types/service-base": {
1609
+ "types": "./types/service-base.d.ts",
1610
+ "require": "./cjs/types/service-base.js",
1611
+ "default": "./types/service-base.js"
1612
+ },
1613
+ "./types/swap": {
1614
+ "types": "./types/swap/index.d.ts",
1615
+ "require": "./cjs/types/swap/index.js",
1616
+ "default": "./types/swap/index.js"
1617
+ },
1568
1618
  "./types/transaction": {
1569
1619
  "types": "./types/transaction.d.ts",
1570
1620
  "require": "./cjs/types/transaction.js",
@@ -1781,6 +1831,11 @@
1781
1831
  "./utils/staticData/crowdloanFunds.json": "./utils/staticData/crowdloanFunds.json",
1782
1832
  "./utils/staticData/marketingCampaigns.json": "./utils/staticData/marketingCampaigns.json",
1783
1833
  "./utils/staticData/termAndCondition.json": "./utils/staticData/termAndCondition.json",
1834
+ "./utils/swap": {
1835
+ "types": "./utils/swap.d.ts",
1836
+ "require": "./cjs/utils/swap.js",
1837
+ "default": "./utils/swap.js"
1838
+ },
1784
1839
  "./utils/translate": {
1785
1840
  "types": "./utils/translate.d.ts",
1786
1841
  "require": "./cjs/utils/translate.js",
@@ -1791,10 +1846,12 @@
1791
1846
  "@acala-network/api": "^5.0.2",
1792
1847
  "@apollo/client": "^3.7.14",
1793
1848
  "@azns/resolver-core": "^1.4.0",
1849
+ "@chainflip/sdk": "^1.3.0",
1794
1850
  "@equilab/api": "~1.14.25",
1795
1851
  "@ethereumjs/common": "^4.1.0",
1796
1852
  "@ethereumjs/tx": "^5.1.0",
1797
1853
  "@ethersproject/abi": "^5.7.0",
1854
+ "@galacticcouncil/sdk": "^2.1.0",
1798
1855
  "@json-rpc-tools/utils": "^1.7.6",
1799
1856
  "@metamask/safe-event-emitter": "^2.0.0",
1800
1857
  "@metaverse-network-sdk/type-definitions": "^0.0.1-13",
@@ -1816,13 +1873,13 @@
1816
1873
  "@reduxjs/toolkit": "^1.9.1",
1817
1874
  "@sora-substrate/type-definitions": "^1.17.7",
1818
1875
  "@substrate/connect": "^0.7.26",
1819
- "@subwallet/chain-list": "0.2.54",
1820
- "@subwallet/extension-base": "^1.1.54-0",
1821
- "@subwallet/extension-chains": "^1.1.54-0",
1822
- "@subwallet/extension-dapp": "^1.1.54-0",
1823
- "@subwallet/extension-inject": "^1.1.54-0",
1824
- "@subwallet/keyring": "^0.1.3",
1825
- "@subwallet/ui-keyring": "^0.1.3",
1876
+ "@subwallet/chain-list": "0.2.55",
1877
+ "@subwallet/extension-base": "^1.1.55-0",
1878
+ "@subwallet/extension-chains": "^1.1.55-0",
1879
+ "@subwallet/extension-dapp": "^1.1.55-0",
1880
+ "@subwallet/extension-inject": "^1.1.55-0",
1881
+ "@subwallet/keyring": "^0.1.5",
1882
+ "@subwallet/ui-keyring": "^0.1.5",
1826
1883
  "@walletconnect/sign-client": "^2.8.4",
1827
1884
  "@walletconnect/types": "^2.8.4",
1828
1885
  "@walletconnect/utils": "^2.8.4",
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.1.54-0'
10
+ version: '1.1.55-0'
11
11
  };
@@ -185,7 +185,8 @@ export class BalanceService {
185
185
  const chainInfoMap = this.state.chainService.getChainInfoMap();
186
186
  const evmApiMap = this.state.chainService.getEvmApiMap();
187
187
  const substrateApiMap = this.state.chainService.getSubstrateApiMap();
188
- const unsub = subscribeBalance([address], [chain], [tSlug], assetMap, chainInfoMap, substrateApiMap, evmApiMap, result => {
188
+ let unsub = noop;
189
+ unsub = subscribeBalance([address], [chain], [tSlug], assetMap, chainInfoMap, substrateApiMap, evmApiMap, result => {
189
190
  const rs = result[0];
190
191
  if (rs.tokenSlug === tSlug) {
191
192
  hasError = false;
@@ -197,15 +198,17 @@ export class BalanceService {
197
198
  if (callback) {
198
199
  callback(balance);
199
200
  } else {
201
+ var _unsub;
200
202
  // Auto unsubscribe if no callback
201
- unsub();
203
+ (_unsub = unsub) === null || _unsub === void 0 ? void 0 : _unsub();
202
204
  }
203
205
  resolve([unsub, balance]);
204
206
  }
205
207
  });
206
208
  setTimeout(() => {
207
209
  if (hasError) {
208
- unsub();
210
+ var _unsub2;
211
+ (_unsub2 = unsub) === null || _unsub2 === void 0 ? void 0 : _unsub2();
209
212
  reject(new Error(t('Failed to get balance. Please check your internet connection or change your network endpoint')));
210
213
  }
211
214
  }, 9999);
@@ -1,3 +1,4 @@
1
+ import { OptimalProcessParams, OptimalProcessResult } from '@subwallet/extension-base/types/service-base';
1
2
  import { PromiseHandler } from '@subwallet/extension-base/utils/promise';
2
3
  export declare enum ServiceStatus {
3
4
  NOT_INITIALIZED = "not_initialized",
@@ -32,3 +33,6 @@ export interface CronServiceInterface {
32
33
  startCron: () => Promise<void>;
33
34
  stopCron: () => Promise<void>;
34
35
  }
36
+ export interface ServiceWithProcessInterface {
37
+ generateOptimalProcess(params: OptimalProcessParams): Promise<OptimalProcessResult>;
38
+ }
@@ -28,7 +28,7 @@ export const _BALANCE_CHAIN_GROUP = {
28
28
  kintsugi: ['kintsugi', 'interlay', 'kintsugi_test', 'mangatax_para'],
29
29
  genshiro: ['genshiro_testnet', 'genshiro'],
30
30
  equilibrium_parachain: ['equilibrium_parachain'],
31
- bifrost: ['bifrost', 'acala', 'karura', 'acala_testnet', 'pioneer', 'bitcountry', 'bifrost_dot', 'hydradx_main', 'pendulum', 'amplitude', 'continuum_network'],
31
+ bifrost: ['bifrost', 'acala', 'karura', 'acala_testnet', 'pioneer', 'bitcountry', 'bifrost_dot', 'hydradx_main', 'hydradx_rococo', 'pendulum', 'amplitude', 'continuum_network'],
32
32
  statemine: ['statemine', 'astar', 'shiden', 'statemint', 'moonbeam', 'moonbase', 'moonriver', 'crabParachain', 'darwinia2', 'parallel', 'calamari', 'manta_network', 'rococo_assethub', 'liberlandTest', 'liberland', 'dentnet', 'pangolin', 'crust', 'phala', 'shibuya'],
33
33
  kusama: ['kusama', 'kintsugi', 'kintsugi_test', 'interlay', 'acala', 'statemint', 'karura', 'bifrost'],
34
34
  // perhaps there are some runtime updates
@@ -23,6 +23,7 @@ export declare class ChainService {
23
23
  private assetRegistrySubject;
24
24
  private multiChainAssetMapSubject;
25
25
  private xcmRefMapSubject;
26
+ private swapRefMapSubject;
26
27
  private assetLogoMapSubject;
27
28
  private chainLogoMapSubject;
28
29
  private assetMapPatch;
@@ -31,7 +32,9 @@ export declare class ChainService {
31
32
  private assetSettingSubject;
32
33
  private logger;
33
34
  constructor(dbService: DatabaseService, eventService: EventService);
35
+ subscribeSwapRefMap(): Subject<Record<string, _AssetRef>>;
34
36
  get xcmRefMap(): Record<string, _AssetRef>;
37
+ get swapRefMap(): Record<string, _AssetRef>;
35
38
  getEvmApi(slug: string): import("./handler/EvmApi").EvmApi;
36
39
  getEvmApiMap(): Record<string, import("./handler/EvmApi").EvmApi>;
37
40
  getSubstrateApiMap(): Record<string, import("./handler/SubstrateApi").SubstrateApi>;
@@ -139,4 +142,5 @@ export declare class ChainService {
139
142
  getMetadataByHash(hash: string): import("dexie").PromiseExtended<IMetadataItem | undefined>;
140
143
  getSubscanChainMap(reverse?: boolean): Record<string, string>;
141
144
  get detectBalanceChainSlugMap(): Record<string, string>;
145
+ getFeeTokensByChain(chainSlug: string): string[];
142
146
  }
@@ -9,7 +9,7 @@ import { MantaPrivateHandler } from '@subwallet/extension-base/services/chain-se
9
9
  import { SubstrateChainHandler } from '@subwallet/extension-base/services/chain-service/handler/SubstrateChainHandler';
10
10
  import { _CHAIN_VALIDATION_ERROR } from '@subwallet/extension-base/services/chain-service/handler/types';
11
11
  import { _ChainConnectionStatus, _CUSTOM_PREFIX, _NFT_CONTRACT_STANDARDS, _SMART_CONTRACT_STANDARDS } from '@subwallet/extension-base/services/chain-service/types';
12
- import { _isAssetAutoEnable, _isAssetFungibleToken, _isChainEnabled, _isCustomAsset, _isCustomChain, _isCustomProvider, _isEqualContractAddress, _isEqualSmartContractAsset, _isMantaZkAsset, _isPureEvmChain, _isPureSubstrateChain, _parseAssetRefKey, fetchPatchData, randomizeProvider, updateLatestChainInfo } from '@subwallet/extension-base/services/chain-service/utils';
12
+ import { _isAssetAutoEnable, _isAssetCanPayTxFee, _isAssetFungibleToken, _isChainEnabled, _isCustomAsset, _isCustomChain, _isCustomProvider, _isEqualContractAddress, _isEqualSmartContractAsset, _isMantaZkAsset, _isPureEvmChain, _isPureSubstrateChain, _parseAssetRefKey, fetchPatchData, randomizeProvider, updateLatestChainInfo } from '@subwallet/extension-base/services/chain-service/utils';
13
13
  import AssetSettingStore from '@subwallet/extension-base/stores/AssetSetting';
14
14
  import { addLazy, fetchStaticData, filterAssetsByChainAndType, MODULE_SUPPORT } from '@subwallet/extension-base/utils';
15
15
  import { BehaviorSubject, Subject } from 'rxjs';
@@ -35,6 +35,7 @@ export class ChainService {
35
35
  assetRegistrySubject = new Subject();
36
36
  multiChainAssetMapSubject = new Subject();
37
37
  xcmRefMapSubject = new Subject();
38
+ swapRefMapSubject = new Subject();
38
39
  assetLogoMapSubject = new BehaviorSubject(AssetLogoMap);
39
40
  chainLogoMapSubject = new BehaviorSubject(ChainLogoMap);
40
41
  assetMapPatch = JSON.stringify({});
@@ -50,6 +51,7 @@ export class ChainService {
50
51
  this.chainStateMapSubject.next(this.dataMap.chainStateMap);
51
52
  this.assetRegistrySubject.next(this.dataMap.assetRegistry);
52
53
  this.xcmRefMapSubject.next(this.xcmRefMap);
54
+ this.swapRefMapSubject.next(this.swapRefMap);
53
55
  if (MODULE_SUPPORT.MANTA_ZK) {
54
56
  console.log('Init Manta ZK');
55
57
  this.mantaChainHandler = new MantaPrivateHandler(dbService);
@@ -58,6 +60,9 @@ export class ChainService {
58
60
  this.evmChainHandler = new EvmChainHandler(this);
59
61
  this.logger = createLogger('chain-service');
60
62
  }
63
+ subscribeSwapRefMap() {
64
+ return this.swapRefMapSubject;
65
+ }
61
66
 
62
67
  // Getter
63
68
  get xcmRefMap() {
@@ -69,6 +74,15 @@ export class ChainService {
69
74
  });
70
75
  return result;
71
76
  }
77
+ get swapRefMap() {
78
+ const result = {};
79
+ Object.entries(this.dataMap.assetRefMap).forEach(([key, assetRef]) => {
80
+ if (assetRef.path === _AssetRefPath.SWAP) {
81
+ result[key] = assetRef;
82
+ }
83
+ });
84
+ return result;
85
+ }
72
86
  getEvmApi(slug) {
73
87
  return this.evmChainHandler.getEvmApiByChain(slug);
74
88
  }
@@ -481,6 +495,7 @@ export class ChainService {
481
495
  });
482
496
  this.dataMap.assetRefMap = updatedAssetRefMap;
483
497
  this.xcmRefMapSubject.next(this.xcmRefMap);
498
+ this.swapRefMapSubject.next(this.swapRefMap);
484
499
  this.logger.log('Finished updating latest asset ref');
485
500
  }
486
501
  handleLatestPriceId(latestPriceIds) {
@@ -1610,4 +1625,9 @@ export class ChainService {
1610
1625
  }
1611
1626
  return result;
1612
1627
  }
1628
+ getFeeTokensByChain(chainSlug) {
1629
+ return Object.values(this.getAssetRegistry()).filter(chainAsset => {
1630
+ return chainAsset.originChain === chainSlug && (chainAsset.assetType === _AssetType.NATIVE || _isAssetCanPayTxFee(chainAsset));
1631
+ }).map(chainAsset => chainAsset.slug);
1632
+ }
1613
1633
  }