@subwallet/extension-base 1.3.21-0 → 1.3.23-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 (223) hide show
  1. package/background/KoniTypes.d.ts +75 -2
  2. package/background/KoniTypes.js +2 -0
  3. package/cjs/background/KoniTypes.js +2 -0
  4. package/cjs/constants/environment.js +4 -2
  5. package/cjs/constants/signing.js +6 -2
  6. package/cjs/core/logic-validation/recipientAddress.js +9 -1
  7. package/cjs/core/logic-validation/transfer.js +35 -29
  8. package/cjs/core/types.js +1 -0
  9. package/cjs/core/utils.js +12 -1
  10. package/cjs/defaults.js +1 -1
  11. package/cjs/koni/api/dotsama/crowdloan.js +1 -1
  12. package/cjs/koni/api/nft/index.js +9 -16
  13. package/cjs/koni/api/staking/index.js +3 -4
  14. package/cjs/koni/background/handlers/Extension.js +234 -96
  15. package/cjs/koni/background/handlers/State.js +15 -0
  16. package/cjs/packageInfo.js +1 -1
  17. package/cjs/services/balance-service/helpers/subscribe/cardano/consts.js +11 -0
  18. package/cjs/services/balance-service/helpers/subscribe/cardano/index.js +63 -0
  19. package/cjs/services/balance-service/helpers/subscribe/cardano/types.js +1 -0
  20. package/cjs/services/balance-service/helpers/subscribe/cardano/utils.js +74 -0
  21. package/cjs/services/balance-service/helpers/subscribe/index.js +21 -7
  22. package/cjs/services/balance-service/helpers/subscribe/ton/utils.js +2 -2
  23. package/cjs/services/balance-service/index.js +4 -2
  24. package/cjs/services/balance-service/transfer/cardano-transfer.js +122 -0
  25. package/cjs/services/balance-service/transfer/token.js +4 -4
  26. package/cjs/services/chain-service/constants.js +8 -3
  27. package/cjs/services/chain-service/handler/CardanoApi.js +176 -0
  28. package/cjs/services/chain-service/handler/CardanoChainHandler.js +83 -0
  29. package/cjs/services/chain-service/handler/SubstrateChainHandler.js +3 -2
  30. package/cjs/services/chain-service/handler/TonApi.js +2 -5
  31. package/cjs/services/chain-service/index.js +38 -7
  32. package/cjs/services/chain-service/utils/index.js +40 -11
  33. package/cjs/services/chain-service/utils/patch.js +1 -1
  34. package/cjs/services/earning-service/constants/chains.js +2 -1
  35. package/cjs/services/earning-service/handlers/liquid-staking/bifrost-manta.js +1 -1
  36. package/cjs/services/earning-service/handlers/liquid-staking/bifrost.js +1 -1
  37. package/cjs/services/earning-service/handlers/native-staking/mythos.js +337 -0
  38. package/cjs/services/earning-service/service.js +10 -12
  39. package/cjs/services/earning-service/utils/index.js +2 -0
  40. package/cjs/services/fee-service/service.js +19 -8
  41. package/cjs/services/history-service/index.js +4 -6
  42. package/cjs/services/inapp-notification-service/index.js +12 -4
  43. package/cjs/services/keyring-service/context/account-context.js +17 -2
  44. package/cjs/services/keyring-service/context/handlers/Derive.js +10 -7
  45. package/cjs/services/keyring-service/context/handlers/Migration.js +268 -0
  46. package/cjs/services/keyring-service/context/handlers/Mnemonic.js +2 -2
  47. package/cjs/services/keyring-service/context/handlers/Secret.js +1 -1
  48. package/cjs/services/keyring-service/utils.js +18 -0
  49. package/cjs/services/migration-service/scripts/databases/ClearMetadataDatabase.js +3 -23
  50. package/cjs/services/migration-service/scripts/databases/ClearMetadataForChains.js +40 -0
  51. package/cjs/services/migration-service/scripts/databases/ClearMetadataForMythos.js +15 -0
  52. package/cjs/services/migration-service/scripts/index.js +6 -2
  53. package/cjs/services/request-service/handler/CardanoRequestHandler.js +172 -0
  54. package/cjs/services/request-service/handler/EvmRequestHandler.js +1 -1
  55. package/cjs/services/request-service/index.js +20 -2
  56. package/cjs/services/setting-service/constants.js +10 -1
  57. package/cjs/services/storage-service/DatabaseService.js +6 -0
  58. package/cjs/services/storage-service/db-stores/InappNotification.js +6 -0
  59. package/cjs/services/storage-service/db-stores/Metadata.js +3 -0
  60. package/cjs/services/storage-service/db-stores/Migration.js +6 -1
  61. package/cjs/services/swap-service/handler/asset-hub/handler.js +0 -59
  62. package/cjs/services/swap-service/handler/chainflip-handler.js +33 -281
  63. package/cjs/services/swap-service/handler/hydradx-handler.js +23 -190
  64. package/cjs/services/swap-service/handler/simpleswap-handler.js +1 -222
  65. package/cjs/services/swap-service/handler/uniswap-handler.js +331 -0
  66. package/cjs/services/swap-service/index.js +31 -22
  67. package/cjs/services/swap-service/utils.js +21 -38
  68. package/cjs/services/transaction-service/helpers/index.js +6 -1
  69. package/cjs/services/transaction-service/index.js +278 -21
  70. package/cjs/services/transaction-service/utils.js +5 -1
  71. package/cjs/types/account/info/keyring.js +12 -1
  72. package/cjs/types/fee/cardano.js +1 -0
  73. package/cjs/types/swap/index.js +7 -2
  74. package/cjs/utils/account/analyze.js +2 -1
  75. package/cjs/utils/account/common.js +29 -20
  76. package/cjs/utils/account/derive/info/solo.js +9 -4
  77. package/cjs/utils/account/derive/validate.js +36 -2
  78. package/cjs/utils/account/transform.js +38 -13
  79. package/cjs/utils/fee/transfer.js +40 -7
  80. package/cjs/utils/index.js +2 -2
  81. package/cjs/utils/staticData/index.js +7 -2
  82. package/constants/environment.d.ts +1 -0
  83. package/constants/environment.js +2 -1
  84. package/constants/signing.js +6 -2
  85. package/core/logic-validation/recipientAddress.js +11 -3
  86. package/core/logic-validation/transfer.js +9 -3
  87. package/core/substrate/xcm-parser.d.ts +1 -1
  88. package/core/types.d.ts +1 -0
  89. package/core/types.js +1 -0
  90. package/core/utils.d.ts +1 -0
  91. package/core/utils.js +13 -3
  92. package/defaults.d.ts +1 -1
  93. package/defaults.js +1 -1
  94. package/koni/api/dotsama/crowdloan.js +3 -3
  95. package/koni/api/nft/index.js +10 -16
  96. package/koni/api/nft/story_odyssey_nft/index.d.ts +1 -1
  97. package/koni/api/staking/index.js +4 -5
  98. package/koni/background/handlers/Extension.d.ts +9 -0
  99. package/koni/background/handlers/Extension.js +144 -8
  100. package/koni/background/handlers/State.d.ts +5 -1
  101. package/koni/background/handlers/State.js +16 -1
  102. package/package.json +102 -25
  103. package/packageInfo.js +1 -1
  104. package/services/balance-service/helpers/subscribe/cardano/consts.d.ts +1 -0
  105. package/services/balance-service/helpers/subscribe/cardano/consts.js +4 -0
  106. package/services/balance-service/helpers/subscribe/cardano/index.d.ts +2 -0
  107. package/services/balance-service/helpers/subscribe/cardano/index.js +57 -0
  108. package/services/balance-service/helpers/subscribe/cardano/types.d.ts +34 -0
  109. package/services/balance-service/helpers/subscribe/cardano/types.js +1 -0
  110. package/services/balance-service/helpers/subscribe/cardano/utils.d.ts +15 -0
  111. package/services/balance-service/helpers/subscribe/cardano/utils.js +62 -0
  112. package/services/balance-service/helpers/subscribe/index.d.ts +2 -2
  113. package/services/balance-service/helpers/subscribe/index.js +23 -9
  114. package/services/balance-service/helpers/subscribe/ton/utils.d.ts +1 -1
  115. package/services/balance-service/helpers/subscribe/ton/utils.js +1 -1
  116. package/services/balance-service/index.js +4 -2
  117. package/services/balance-service/transfer/cardano-transfer.d.ts +24 -0
  118. package/services/balance-service/transfer/cardano-transfer.js +114 -0
  119. package/services/balance-service/transfer/token.d.ts +1 -1
  120. package/services/balance-service/transfer/token.js +2 -2
  121. package/services/chain-service/constants.js +8 -3
  122. package/services/chain-service/handler/CardanoApi.d.ts +38 -0
  123. package/services/chain-service/handler/CardanoApi.js +167 -0
  124. package/services/chain-service/handler/CardanoChainHandler.d.ts +17 -0
  125. package/services/chain-service/handler/CardanoChainHandler.js +75 -0
  126. package/services/chain-service/handler/SubstrateChainHandler.js +3 -2
  127. package/services/chain-service/handler/TonApi.js +3 -6
  128. package/services/chain-service/handler/types.d.ts +1 -0
  129. package/services/chain-service/index.d.ts +4 -1
  130. package/services/chain-service/index.js +38 -7
  131. package/services/chain-service/types.d.ts +9 -1
  132. package/services/chain-service/utils/index.d.ts +4 -0
  133. package/services/chain-service/utils/index.js +32 -11
  134. package/services/chain-service/utils/patch.js +1 -1
  135. package/services/earning-service/constants/chains.d.ts +1 -0
  136. package/services/earning-service/constants/chains.js +2 -1
  137. package/services/earning-service/handlers/liquid-staking/bifrost-manta.js +1 -1
  138. package/services/earning-service/handlers/liquid-staking/bifrost.js +1 -1
  139. package/services/earning-service/handlers/native-staking/mythos.d.ts +35 -0
  140. package/services/earning-service/handlers/native-staking/mythos.js +329 -0
  141. package/services/earning-service/service.js +12 -14
  142. package/services/earning-service/utils/index.js +2 -0
  143. package/services/fee-service/service.js +19 -8
  144. package/services/history-service/index.js +6 -8
  145. package/services/inapp-notification-service/index.d.ts +3 -4
  146. package/services/inapp-notification-service/index.js +14 -6
  147. package/services/keyring-service/context/account-context.d.ts +6 -2
  148. package/services/keyring-service/context/account-context.js +17 -2
  149. package/services/keyring-service/context/handlers/Derive.d.ts +1 -1
  150. package/services/keyring-service/context/handlers/Derive.js +10 -8
  151. package/services/keyring-service/context/handlers/Migration.d.ts +17 -0
  152. package/services/keyring-service/context/handlers/Migration.js +258 -0
  153. package/services/keyring-service/context/handlers/Mnemonic.js +2 -2
  154. package/services/keyring-service/context/handlers/Secret.js +2 -2
  155. package/services/keyring-service/utils.d.ts +2 -0
  156. package/services/keyring-service/utils.js +11 -0
  157. package/services/migration-service/scripts/databases/ClearMetadataDatabase.d.ts +3 -3
  158. package/services/migration-service/scripts/databases/ClearMetadataDatabase.js +3 -23
  159. package/services/migration-service/scripts/databases/ClearMetadataForChains.d.ts +5 -0
  160. package/services/migration-service/scripts/databases/ClearMetadataForChains.js +32 -0
  161. package/services/migration-service/scripts/databases/ClearMetadataForMythos.d.ts +4 -0
  162. package/services/migration-service/scripts/databases/ClearMetadataForMythos.js +7 -0
  163. package/services/migration-service/scripts/index.d.ts +1 -0
  164. package/services/migration-service/scripts/index.js +4 -1
  165. package/services/request-service/handler/CardanoRequestHandler.d.ts +16 -0
  166. package/services/request-service/handler/CardanoRequestHandler.js +163 -0
  167. package/services/request-service/handler/EvmRequestHandler.js +1 -1
  168. package/services/request-service/index.d.ts +6 -3
  169. package/services/request-service/index.js +19 -5
  170. package/services/setting-service/constants.d.ts +3 -0
  171. package/services/setting-service/constants.js +6 -0
  172. package/services/storage-service/DatabaseService.d.ts +2 -0
  173. package/services/storage-service/DatabaseService.js +6 -0
  174. package/services/storage-service/db-stores/InappNotification.d.ts +1 -0
  175. package/services/storage-service/db-stores/InappNotification.js +6 -0
  176. package/services/storage-service/db-stores/Metadata.d.ts +1 -0
  177. package/services/storage-service/db-stores/Metadata.js +3 -0
  178. package/services/storage-service/db-stores/Migration.d.ts +1 -0
  179. package/services/storage-service/db-stores/Migration.js +6 -1
  180. package/services/swap-service/handler/asset-hub/handler.d.ts +1 -4
  181. package/services/swap-service/handler/asset-hub/handler.js +2 -61
  182. package/services/swap-service/handler/base-handler.d.ts +1 -4
  183. package/services/swap-service/handler/chainflip-handler.d.ts +2 -9
  184. package/services/swap-service/handler/chainflip-handler.js +31 -280
  185. package/services/swap-service/handler/hydradx-handler.d.ts +1 -6
  186. package/services/swap-service/handler/hydradx-handler.js +13 -180
  187. package/services/swap-service/handler/simpleswap-handler.d.ts +1 -4
  188. package/services/swap-service/handler/simpleswap-handler.js +5 -226
  189. package/services/swap-service/handler/uniswap-handler.d.ts +41 -0
  190. package/services/swap-service/handler/uniswap-handler.js +323 -0
  191. package/services/swap-service/index.js +30 -22
  192. package/services/swap-service/utils.d.ts +1 -5
  193. package/services/swap-service/utils.js +7 -21
  194. package/services/transaction-service/helpers/index.d.ts +2 -0
  195. package/services/transaction-service/helpers/index.js +4 -0
  196. package/services/transaction-service/index.d.ts +8 -2
  197. package/services/transaction-service/index.js +263 -10
  198. package/services/transaction-service/types.d.ts +7 -0
  199. package/services/transaction-service/utils.js +7 -2
  200. package/types/account/info/keyring.d.ts +4 -1
  201. package/types/account/info/keyring.js +9 -0
  202. package/types/account/info/proxy.d.ts +2 -0
  203. package/types/balance/index.d.ts +4 -1
  204. package/types/fee/base.d.ts +1 -1
  205. package/types/fee/cardano.d.ts +18 -0
  206. package/types/fee/cardano.js +1 -0
  207. package/types/fee/subscription.d.ts +4 -3
  208. package/types/swap/index.d.ts +11 -3
  209. package/types/swap/index.js +7 -2
  210. package/utils/account/analyze.js +2 -1
  211. package/utils/account/common.d.ts +11 -6
  212. package/utils/account/common.js +28 -19
  213. package/utils/account/derive/info/solo.js +10 -5
  214. package/utils/account/derive/validate.d.ts +1 -0
  215. package/utils/account/derive/validate.js +34 -1
  216. package/utils/account/transform.d.ts +2 -1
  217. package/utils/account/transform.js +37 -13
  218. package/utils/fee/transfer.d.ts +2 -1
  219. package/utils/fee/transfer.js +44 -11
  220. package/utils/index.js +4 -4
  221. package/utils/staticData/index.d.ts +4 -1
  222. package/utils/staticData/index.js +5 -1
  223. package/utils/staticData/oldChainPrefix.json +1 -0
@@ -4,15 +4,14 @@
4
4
  import { SwapError } from '@subwallet/extension-base/background/errors/SwapError';
5
5
  import { TransactionError } from '@subwallet/extension-base/background/errors/TransactionError';
6
6
  import { ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
7
- import { _getSimpleSwapEarlyValidationError } from '@subwallet/extension-base/core/logic-validation/swap';
8
- import { _getAssetDecimals, _getChainNativeTokenSlug, _getContractAddressOfToken, _isChainSubstrateCompatible, _isNativeToken } from '@subwallet/extension-base/services/chain-service/utils';
9
- import { BasicTxErrorType, CommonStepType, SwapErrorType, SwapFeeType, SwapProviderId, SwapStepType } from '@subwallet/extension-base/types';
7
+ import { _getAssetDecimals, _getContractAddressOfToken, _isChainSubstrateCompatible, _isNativeToken } from '@subwallet/extension-base/services/chain-service/utils';
8
+ import { BasicTxErrorType, CommonStepType, SwapErrorType, SwapProviderId, SwapStepType } from '@subwallet/extension-base/types';
10
9
  import { _reformatAddressWithChain, formatNumber } from '@subwallet/extension-base/utils';
11
10
  import { getId } from '@subwallet/extension-base/utils/getId';
12
11
  import BigN, { BigNumber } from 'bignumber.js';
13
12
  import { getERC20TransactionObject, getEVMTransactionObject } from "../../balance-service/transfer/smart-contract.js";
14
- import { createTransferExtrinsic, getTransferMockTxFee } from "../../balance-service/transfer/token.js";
15
- import { calculateSwapRate, SIMPLE_SWAP_SUPPORTED_TESTNET_ASSET_MAPPING, SWAP_QUOTE_TIMEOUT_MAP } from "../utils.js";
13
+ import { createSubstrateExtrinsic } from "../../balance-service/transfer/token.js";
14
+ import { SIMPLE_SWAP_SUPPORTED_TESTNET_ASSET_MAPPING } from "../utils.js";
16
15
  import { SwapBaseHandler } from "./base-handler.js";
17
16
  const apiUrl = 'https://api.simpleswap.io';
18
17
  export const simpleSwapApiKey = process.env.SIMPLE_SWAP_API_KEY || '';
@@ -20,72 +19,6 @@ const toBNString = (input, decimal) => {
20
19
  const raw = new BigNumber(input);
21
20
  return raw.shiftedBy(decimal).integerValue(BigNumber.ROUND_CEIL).toFixed();
22
21
  };
23
- const fetchSwapList = async params => {
24
- const swapListParams = new URLSearchParams({
25
- api_key: `${simpleSwapApiKey}`,
26
- fixed: 'false',
27
- symbol: params.fromSymbol
28
- });
29
- const response = await fetch(`${apiUrl}/get_pairs?${swapListParams.toString()}`, {
30
- headers: {
31
- accept: 'application/json'
32
- }
33
- });
34
- return await response.json();
35
- };
36
- const fetchRanges = async params => {
37
- const rangesParams = new URLSearchParams({
38
- api_key: `${simpleSwapApiKey}`,
39
- fixed: 'false',
40
- currency_from: params.fromSymbol,
41
- currency_to: params.toSymbol
42
- });
43
- const response = await fetch(`${apiUrl}/get_ranges?${rangesParams.toString()}`, {
44
- headers: {
45
- accept: 'application/json'
46
- }
47
- });
48
- return await response.json();
49
- };
50
- async function getEstimate(request, fromAsset, toAsset) {
51
- const fromSymbol = SIMPLE_SWAP_SUPPORTED_TESTNET_ASSET_MAPPING[fromAsset.slug];
52
- const toSymbol = SIMPLE_SWAP_SUPPORTED_TESTNET_ASSET_MAPPING[toAsset.slug];
53
- const assetDecimals = _getAssetDecimals(fromAsset);
54
- if (!fromSymbol || !toSymbol) {
55
- throw new SwapError(SwapErrorType.ASSET_NOT_SUPPORTED);
56
- }
57
- const formatedAmount = formatNumber(request.fromAmount, assetDecimals, s => s);
58
- const params = new URLSearchParams({
59
- api_key: `${simpleSwapApiKey}`,
60
- fixed: 'false',
61
- currency_from: fromSymbol,
62
- currency_to: toSymbol,
63
- amount: formatedAmount
64
- });
65
- try {
66
- const response = await fetch(`${apiUrl}/get_estimated?${params.toString()}`, {
67
- headers: {
68
- accept: 'application/json'
69
- }
70
- });
71
- if (!response.ok) {
72
- throw new SwapError(SwapErrorType.ERROR_FETCHING_QUOTE);
73
- }
74
- const resToAmount = await response.json();
75
- const toAmount = toBNString(resToAmount, _getAssetDecimals(toAsset));
76
- const bnToAmount = new BigN(toAmount);
77
- const walletFeeRate = 4 / 1000;
78
- const toAmountBeforeFee = bnToAmount.dividedBy(new BigN(1 - walletFeeRate));
79
- const walletFeeAmount = toAmountBeforeFee.multipliedBy(4).dividedBy(1000).toString();
80
- return {
81
- toAmount,
82
- walletFeeAmount
83
- };
84
- } catch (err) {
85
- console.error('Error:', err);
86
- throw new SwapError(SwapErrorType.ERROR_FETCHING_QUOTE);
87
- }
88
- }
89
22
  const createSwapRequest = async params => {
90
23
  const fromDecimals = _getAssetDecimals(params.fromAsset);
91
24
  const toDecimals = _getAssetDecimals(params.toAsset);
@@ -169,70 +102,6 @@ export class SimpleSwapHandler {
169
102
  get slug() {
170
103
  return this.swapBaseHandler.slug;
171
104
  }
172
- async getSwapQuote(request) {
173
- try {
174
- var _metadata$maxSwap;
175
- const fromAsset = this.chainService.getAssetBySlug(request.pair.from);
176
- const toAsset = this.chainService.getAssetBySlug(request.pair.to);
177
- if (!fromAsset || !toAsset) {
178
- return new SwapError(SwapErrorType.UNKNOWN);
179
- }
180
- const earlyValidation = await this.validateSwapRequest(request);
181
- const metadata = earlyValidation.metadata;
182
- if (earlyValidation.error) {
183
- return _getSimpleSwapEarlyValidationError(earlyValidation.error, metadata);
184
- }
185
- const {
186
- toAmount,
187
- walletFeeAmount
188
- } = await getEstimate(request, fromAsset, toAsset);
189
- const fromAmount = request.fromAmount;
190
- const rate = calculateSwapRate(request.fromAmount, toAmount, fromAsset, toAsset);
191
- const fromChain = this.chainService.getChainInfoByKey(fromAsset.originChain);
192
- const fromChainNativeTokenSlug = _getChainNativeTokenSlug(fromChain);
193
- const defaultFeeToken = _isNativeToken(fromAsset) ? fromAsset.slug : fromChainNativeTokenSlug;
194
- const chainType = _isChainSubstrateCompatible(fromChain) ? ChainType.SUBSTRATE : ChainType.EVM;
195
- let api;
196
- if (chainType === ChainType.SUBSTRATE) {
197
- api = this.chainService.getSubstrateApi(fromChain.slug);
198
- } else {
199
- api = this.chainService.getEvmApi(fromChain.slug);
200
- }
201
- const networkFeeAmount = await getTransferMockTxFee(request.address, fromChain, fromAsset, api);
202
- const networkFee = {
203
- tokenSlug: fromChainNativeTokenSlug,
204
- amount: networkFeeAmount.toString(),
205
- feeType: SwapFeeType.NETWORK_FEE
206
- };
207
- const walletFee = {
208
- tokenSlug: toAsset.slug,
209
- amount: walletFeeAmount,
210
- feeType: SwapFeeType.WALLET_FEE
211
- };
212
- return {
213
- pair: request.pair,
214
- fromAmount,
215
- toAmount,
216
- rate,
217
- provider: this.providerInfo,
218
- aliveUntil: +Date.now() + (SWAP_QUOTE_TIMEOUT_MAP[this.slug] || SWAP_QUOTE_TIMEOUT_MAP.default),
219
- minSwap: toBNString(metadata.minSwap.value, _getAssetDecimals(fromAsset)),
220
- maxSwap: toBNString((_metadata$maxSwap = metadata.maxSwap) === null || _metadata$maxSwap === void 0 ? void 0 : _metadata$maxSwap.value, _getAssetDecimals(fromAsset)),
221
- estimatedArrivalTime: 3600,
222
- isLowLiquidity: false,
223
- feeInfo: {
224
- feeComponent: [networkFee, walletFee],
225
- defaultFeeToken,
226
- feeOptions: [defaultFeeToken]
227
- },
228
- route: {
229
- path: [fromAsset.slug, toAsset.slug]
230
- }
231
- };
232
- } catch (e) {
233
- return new SwapError(SwapErrorType.UNKNOWN);
234
- }
235
- }
236
105
  generateOptimalProcess(params) {
237
106
  return this.swapBaseHandler.generateOptimalProcess(params, [this.getSubmitStep.bind(this)]);
238
107
  }
@@ -246,96 +115,6 @@ export class SimpleSwapHandler {
246
115
  }
247
116
  return Promise.resolve(undefined);
248
117
  }
249
- async validateSwapRequest(request) {
250
- try {
251
- const fromAsset = this.chainService.getAssetBySlug(request.pair.from);
252
- const toAsset = this.chainService.getAssetBySlug(request.pair.to);
253
- if (!fromAsset || !toAsset) {
254
- return {
255
- error: SwapErrorType.ERROR_FETCHING_QUOTE
256
- };
257
- }
258
- const fromSymbol = SIMPLE_SWAP_SUPPORTED_TESTNET_ASSET_MAPPING[fromAsset.slug];
259
- const toSymbol = SIMPLE_SWAP_SUPPORTED_TESTNET_ASSET_MAPPING[toAsset.slug];
260
- if (!fromSymbol || !toSymbol) {
261
- return {
262
- error: SwapErrorType.ASSET_NOT_SUPPORTED
263
- };
264
- }
265
- try {
266
- const swapList = await fetchSwapList({
267
- fromSymbol
268
- });
269
- if (!swapList.includes(toSymbol)) {
270
- return {
271
- error: SwapErrorType.ASSET_NOT_SUPPORTED
272
- };
273
- }
274
- } catch (err) {
275
- console.error('Error:', err);
276
- }
277
- const ranges = await fetchRanges({
278
- fromSymbol,
279
- toSymbol
280
- });
281
- const {
282
- max,
283
- min
284
- } = ranges;
285
- const bnMin = toBNString(min, _getAssetDecimals(fromAsset));
286
- const bnAmount = BigInt(request.fromAmount);
287
- if (bnAmount < BigInt(bnMin)) {
288
- return {
289
- error: SwapErrorType.NOT_MEET_MIN_SWAP,
290
- metadata: {
291
- minSwap: {
292
- value: min,
293
- symbol: fromAsset.symbol
294
- },
295
- maxSwap: max ? {
296
- value: max,
297
- symbol: fromAsset.symbol
298
- } : undefined,
299
- chain: this.chainService.getChainInfoByKey(fromAsset.originChain)
300
- }
301
- };
302
- }
303
- if (max && bnAmount > BigInt(toBNString(max, _getAssetDecimals(fromAsset)))) {
304
- return {
305
- error: SwapErrorType.SWAP_EXCEED_ALLOWANCE,
306
- metadata: {
307
- minSwap: {
308
- value: min,
309
- symbol: fromAsset.symbol
310
- },
311
- maxSwap: {
312
- value: max,
313
- symbol: fromAsset.symbol
314
- },
315
- chain: this.chainService.getChainInfoByKey(fromAsset.originChain)
316
- }
317
- };
318
- }
319
- return {
320
- metadata: {
321
- minSwap: {
322
- value: min,
323
- symbol: fromAsset.symbol
324
- },
325
- maxSwap: max ? {
326
- value: max,
327
- symbol: fromAsset.symbol
328
- } : undefined,
329
- chain: this.chainService.getChainInfoByKey(fromAsset.originChain)
330
- }
331
- };
332
- } catch (e) {
333
- console.error(e);
334
- return {
335
- error: SwapErrorType.UNKNOWN
336
- };
337
- }
338
- }
339
118
  async handleSwapProcess(params) {
340
119
  const {
341
120
  currentStep,
@@ -405,7 +184,7 @@ export class SimpleSwapHandler {
405
184
  if (chainType === ChainType.SUBSTRATE) {
406
185
  const chainApi = this.chainService.getSubstrateApi(chainInfo.slug);
407
186
  const substrateApi = await chainApi.isReady;
408
- const [submittableExtrinsic] = await createTransferExtrinsic({
187
+ const [submittableExtrinsic] = await createSubstrateExtrinsic({
409
188
  from: address,
410
189
  networkKey: chainInfo.slug,
411
190
  substrateApi,
@@ -0,0 +1,41 @@
1
+ import { TransactionError } from '@subwallet/extension-base/background/errors/TransactionError';
2
+ import { ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
3
+ import TransactionService from '@subwallet/extension-base/services/transaction-service';
4
+ import { BaseStepDetail, CommonOptimalPath, CommonStepFeeInfo, OptimalSwapPathParams, PermitSwapData, SwapProviderId, SwapSubmitParams, SwapSubmitStepData, ValidateSwapProcessParams } from '@subwallet/extension-base/types';
5
+ import { TransactionConfig } from 'web3-core';
6
+ import { BalanceService } from '../../balance-service';
7
+ import { ChainService } from '../../chain-service';
8
+ import FeeService from '../../fee-service/service';
9
+ import { SwapBaseInterface } from './base-handler';
10
+ export declare type PermitData = {
11
+ domain: Record<string, unknown>;
12
+ types: Record<string, unknown>;
13
+ values: unknown;
14
+ };
15
+ export declare class UniswapHandler implements SwapBaseInterface {
16
+ private swapBaseHandler;
17
+ transactionService: TransactionService;
18
+ providerSlug: SwapProviderId;
19
+ constructor(chainService: ChainService, balanceService: BalanceService, transactionService: TransactionService, feeService: FeeService);
20
+ get chainService(): ChainService;
21
+ get balanceService(): BalanceService;
22
+ get feeService(): FeeService;
23
+ get providerInfo(): import("@subwallet/extension-base/types").SwapProvider;
24
+ generateOptimalProcess(params: OptimalSwapPathParams): Promise<CommonOptimalPath>;
25
+ getApprovalStep(params: OptimalSwapPathParams): Promise<[BaseStepDetail, CommonStepFeeInfo] | undefined>;
26
+ getPermitStep(params: OptimalSwapPathParams): Promise<[BaseStepDetail, CommonStepFeeInfo] | undefined>;
27
+ getSubmitStep(params: OptimalSwapPathParams): Promise<[BaseStepDetail, CommonStepFeeInfo] | undefined>;
28
+ validateSwapProcess(params: ValidateSwapProcessParams): Promise<TransactionError[]>;
29
+ handleSwapProcess(params: SwapSubmitParams): Promise<SwapSubmitStepData>;
30
+ private tokenApproveSpending;
31
+ handleSubmitStep(params: SwapSubmitParams): Promise<SwapSubmitStepData>;
32
+ handlePermitStep(params: SwapSubmitParams): {
33
+ txChain: string;
34
+ txData: PermitSwapData;
35
+ extrinsic: TransactionConfig;
36
+ extrinsicType: ExtrinsicType;
37
+ transferNativeAmount: string;
38
+ chainType: ChainType;
39
+ isPermit: boolean;
40
+ };
41
+ }
@@ -0,0 +1,323 @@
1
+ // Copyright 2019-2022 @subwallet/extension-base
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { TransactionError } from '@subwallet/extension-base/background/errors/TransactionError';
5
+ import { ChainType, ExtrinsicType } from '@subwallet/extension-base/background/KoniTypes';
6
+ import { validateTypedSignMessageDataV3V4 } from '@subwallet/extension-base/core/logic-validation';
7
+ import { BasicTxErrorType, CommonStepType, FeeOptionKey, SwapFeeType, SwapProviderId, SwapStepType } from '@subwallet/extension-base/types';
8
+ import BigNumber from 'bignumber.js';
9
+ import { _getContractAddressOfToken, _isNativeToken } from "../../chain-service/utils/index.js";
10
+ import { calculateGasFeeParams } from "../../fee-service/utils/index.js";
11
+ import { SwapBaseHandler } from "./base-handler.js";
12
+ const API_URL = 'https://trade-api.gateway.uniswap.org/v1';
13
+ const headers = {
14
+ 'x-api-key': process.env.UNISWAP_API_KEY || ''
15
+ };
16
+ async function fetchCheckApproval(walletAddress, fromAmount, quote) {
17
+ const chainId = quote.chainId;
18
+ const response = await fetch(`${API_URL}/check_approval`, {
19
+ method: 'POST',
20
+ headers: {
21
+ ...headers,
22
+ 'Content-Type': 'application/json'
23
+ },
24
+ body: JSON.stringify({
25
+ walletAddress,
26
+ amount: BigNumber(fromAmount).multipliedBy(2).toString(),
27
+ token: quote.input.token,
28
+ chainId: chainId,
29
+ tokenOut: quote.output.token,
30
+ tokenOutChainId: chainId
31
+ })
32
+ });
33
+ const data = await response.json();
34
+ return data;
35
+ }
36
+ export class UniswapHandler {
37
+ constructor(chainService, balanceService, transactionService, feeService) {
38
+ this.swapBaseHandler = new SwapBaseHandler({
39
+ chainService,
40
+ balanceService,
41
+ feeService,
42
+ providerName: 'Uniswap',
43
+ providerSlug: SwapProviderId.UNISWAP
44
+ });
45
+ this.transactionService = transactionService;
46
+ this.providerSlug = SwapProviderId.UNISWAP;
47
+ }
48
+ get chainService() {
49
+ return this.swapBaseHandler.chainService;
50
+ }
51
+ get balanceService() {
52
+ return this.swapBaseHandler.balanceService;
53
+ }
54
+ get feeService() {
55
+ return this.swapBaseHandler.feeService;
56
+ }
57
+ get providerInfo() {
58
+ return this.swapBaseHandler.providerInfo;
59
+ }
60
+ generateOptimalProcess(params) {
61
+ return this.swapBaseHandler.generateOptimalProcess(params, [this.getApprovalStep.bind(this), this.getPermitStep.bind(this), this.getSubmitStep.bind(this)]);
62
+ }
63
+ async getApprovalStep(params) {
64
+ if (params.selectedQuote) {
65
+ const walletAddress = params.request.address;
66
+ const fromAmount = params.selectedQuote.fromAmount;
67
+ const inputTokenInfo = this.chainService.getAssetBySlug(params.selectedQuote.pair.from);
68
+ const {
69
+ quote
70
+ } = params.selectedQuote.metadata;
71
+ const checkApprovalResponse = await fetchCheckApproval(walletAddress, fromAmount, quote);
72
+ const approval = checkApprovalResponse.approval;
73
+ if (approval) {
74
+ let spender = '';
75
+ try {
76
+ const valueLength = 40;
77
+ spender = approval.data.slice(-(valueLength * 2), -valueLength);
78
+ } catch (e) {
79
+ // Empty
80
+ }
81
+ const metadata = {
82
+ tokenApprove: inputTokenInfo.slug,
83
+ contractAddress: _getContractAddressOfToken(inputTokenInfo),
84
+ spenderAddress: spender
85
+ };
86
+ const submitStep = {
87
+ name: 'Approve token',
88
+ type: CommonStepType.TOKEN_APPROVAL,
89
+ metadata: metadata
90
+ };
91
+ return Promise.resolve([submitStep, params.selectedQuote.feeInfo]);
92
+ }
93
+ }
94
+ return Promise.resolve(undefined);
95
+ }
96
+ async getPermitStep(params) {
97
+ if (params.selectedQuote && params.selectedQuote.metadata.permitData) {
98
+ const submitStep = {
99
+ name: 'Permit Step',
100
+ type: SwapStepType.PERMIT
101
+ };
102
+ // TODO: GET NATIVE TOKEN
103
+ const defaultFeeToken = params.selectedQuote.feeInfo.defaultFeeToken;
104
+ const feeInfo = {
105
+ feeComponent: [{
106
+ amount: '0',
107
+ feeType: SwapFeeType.NETWORK_FEE,
108
+ tokenSlug: defaultFeeToken
109
+ }],
110
+ defaultFeeToken: defaultFeeToken,
111
+ feeOptions: [defaultFeeToken]
112
+ };
113
+ return Promise.resolve([submitStep, feeInfo]);
114
+ }
115
+ return Promise.resolve(undefined);
116
+ }
117
+ async getSubmitStep(params) {
118
+ if (params.selectedQuote) {
119
+ const submitStep = {
120
+ name: 'Swap',
121
+ type: SwapStepType.SWAP
122
+ };
123
+ return Promise.resolve([submitStep, params.selectedQuote.feeInfo]);
124
+ }
125
+ return Promise.resolve(undefined);
126
+ }
127
+ async validateSwapProcess(params) {
128
+ const amount = params.selectedQuote.fromAmount;
129
+ const bnAmount = BigInt(amount);
130
+ if (bnAmount <= BigInt(0)) {
131
+ return Promise.resolve([new TransactionError(BasicTxErrorType.INVALID_PARAMS, 'Amount must be greater than 0')]);
132
+ }
133
+ let isXcmOk = false;
134
+ for (const [index, step] of params.process.steps.entries()) {
135
+ const getErrors = async () => {
136
+ switch (step.type) {
137
+ case CommonStepType.DEFAULT:
138
+ return Promise.resolve([]);
139
+ case CommonStepType.TOKEN_APPROVAL:
140
+ return Promise.resolve([]);
141
+ default:
142
+ return this.swapBaseHandler.validateSwapStep(params, isXcmOk, index);
143
+ }
144
+ };
145
+ const errors = await getErrors();
146
+ if (errors.length) {
147
+ return errors;
148
+ } else if (step.type === CommonStepType.XCM) {
149
+ isXcmOk = true;
150
+ }
151
+ }
152
+ return [];
153
+ }
154
+ async handleSwapProcess(params) {
155
+ const {
156
+ currentStep,
157
+ process
158
+ } = params;
159
+ const type = process.steps[currentStep].type;
160
+ switch (type) {
161
+ case CommonStepType.DEFAULT:
162
+ return Promise.reject(new TransactionError(BasicTxErrorType.UNSUPPORTED));
163
+ case CommonStepType.TOKEN_APPROVAL:
164
+ return this.tokenApproveSpending(params);
165
+ case SwapStepType.SWAP:
166
+ return this.handleSubmitStep(params);
167
+ case SwapStepType.PERMIT:
168
+ return this.handlePermitStep(params);
169
+ default:
170
+ return this.handleSubmitStep(params);
171
+ }
172
+ }
173
+ async tokenApproveSpending(params) {
174
+ const fromAsset = this.chainService.getAssetBySlug(params.quote.pair.from);
175
+ const walletAddress = params.address;
176
+ const fromAmount = params.quote.fromAmount;
177
+ const {
178
+ quote
179
+ } = params.quote.metadata;
180
+ const checkApprovalResponse = await fetchCheckApproval(walletAddress, fromAmount, quote);
181
+ let transactionConfig = {};
182
+ const approval = checkApprovalResponse.approval;
183
+ if (approval) {
184
+ var _priority$options, _priority$options$Fee, _priority$options2;
185
+ const evmApi = this.chainService.getEvmApi(fromAsset.originChain);
186
+ const priority = await calculateGasFeeParams(evmApi, evmApi.chainSlug);
187
+ transactionConfig = {
188
+ from: approval.from,
189
+ to: approval.to,
190
+ value: approval.value,
191
+ data: approval.data,
192
+ gasPrice: priority.gasPrice,
193
+ maxFeePerGas: (_priority$options = priority.options) === null || _priority$options === void 0 ? void 0 : (_priority$options$Fee = _priority$options[FeeOptionKey.AVERAGE].maxFeePerGas) === null || _priority$options$Fee === void 0 ? void 0 : _priority$options$Fee.toString(),
194
+ maxPriorityFeePerGas: (_priority$options2 = priority.options) === null || _priority$options2 === void 0 ? void 0 : _priority$options2[FeeOptionKey.AVERAGE].maxPriorityFeePerGas.toString()
195
+ };
196
+ const gasLimit = await evmApi.api.eth.estimateGas(transactionConfig).catch(() => 200000);
197
+ transactionConfig.gas = gasLimit.toString();
198
+ }
199
+ const chain = fromAsset.originChain;
200
+ const _data = {
201
+ spenderAddress: quote.output.token,
202
+ contractAddress: quote.input.token,
203
+ amount: params.quote.fromAmount,
204
+ owner: params.address,
205
+ chain: quote.chainId.toString()
206
+ };
207
+ return Promise.resolve({
208
+ txChain: chain,
209
+ extrinsicType: ExtrinsicType.TOKEN_SPENDING_APPROVAL,
210
+ extrinsic: transactionConfig,
211
+ txData: _data,
212
+ transferNativeAmount: '0',
213
+ chainType: ChainType.EVM
214
+ });
215
+ }
216
+ async handleSubmitStep(params) {
217
+ const fromAsset = this.chainService.getAssetBySlug(params.quote.pair.from);
218
+ const {
219
+ permitData,
220
+ quote,
221
+ routing
222
+ } = params.quote.metadata;
223
+ const processId = params.cacheProcessId;
224
+ let signature;
225
+ if (permitData) {
226
+ signature = this.transactionService.getCacheInfo(processId, SwapStepType.PERMIT);
227
+ }
228
+ let postTransactionResponse;
229
+ let extrinsic;
230
+ if (routing === 'CLASSIC' || routing === 'WRAP' || routing === 'UNWRAP') {
231
+ const body = {
232
+ signature: signature,
233
+ quote: quote
234
+ };
235
+ if (permitData) {
236
+ body.permitData = permitData;
237
+ }
238
+ postTransactionResponse = await fetch(`${API_URL}/swap`, {
239
+ method: 'POST',
240
+ headers: {
241
+ ...headers,
242
+ 'Content-Type': 'application/json'
243
+ },
244
+ body: JSON.stringify(body)
245
+ });
246
+ const transactionResponse = await postTransactionResponse.json();
247
+ extrinsic = transactionResponse.swap;
248
+ } else if (routing === 'DUTCH_LIMIT' || routing === 'DUTCH_V2') {
249
+ postTransactionResponse = await fetch(`${API_URL}/order`, {
250
+ method: 'POST',
251
+ headers: {
252
+ ...headers,
253
+ 'Content-Type': 'application/json'
254
+ },
255
+ body: JSON.stringify({
256
+ signature: signature,
257
+ quote: quote
258
+ })
259
+ });
260
+ }
261
+ const txData = {
262
+ address: params.address,
263
+ provider: this.providerInfo,
264
+ quote: params.quote,
265
+ slippage: params.slippage,
266
+ recipient: params.recipient,
267
+ process: params.process
268
+ };
269
+ return {
270
+ txChain: fromAsset.originChain,
271
+ txData,
272
+ extrinsic: extrinsic,
273
+ transferNativeAmount: _isNativeToken(fromAsset) ? params.quote.fromAmount : '0',
274
+ extrinsicType: ExtrinsicType.SWAP,
275
+ chainType: ChainType.EVM
276
+ };
277
+ }
278
+ handlePermitStep(params) {
279
+ const fromAsset = this.chainService.getAssetBySlug(params.quote.pair.from);
280
+ const {
281
+ permitData
282
+ } = params.quote.metadata;
283
+ const processId = params.cacheProcessId;
284
+ let validatePayload;
285
+ if (permitData) {
286
+ const payload = {
287
+ types: {
288
+ EIP712Domain: [{
289
+ name: 'name',
290
+ type: 'string'
291
+ }, {
292
+ name: 'chainId',
293
+ type: 'uint256'
294
+ }, {
295
+ name: 'verifyingContract',
296
+ type: 'address'
297
+ }],
298
+ ...permitData.types
299
+ },
300
+ domain: permitData.domain,
301
+ primaryType: 'PermitSingle',
302
+ message: permitData.values
303
+ };
304
+ validatePayload = validateTypedSignMessageDataV3V4({
305
+ data: payload,
306
+ from: params.address
307
+ });
308
+ }
309
+ const txData = {
310
+ processId,
311
+ step: SwapStepType.PERMIT
312
+ };
313
+ return {
314
+ txChain: fromAsset.originChain,
315
+ txData,
316
+ extrinsic: validatePayload,
317
+ extrinsicType: ExtrinsicType.TOKEN_SPENDING_APPROVAL,
318
+ transferNativeAmount: '0',
319
+ chainType: ChainType.EVM,
320
+ isPermit: true
321
+ };
322
+ }
323
+ }