@swapkit/core 1.0.0-rc.11 → 1.0.0-rc.111

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 (44) hide show
  1. package/dist/index.cjs +2 -2
  2. package/dist/index.cjs.map +1 -0
  3. package/dist/index.d.ts +161 -26
  4. package/dist/index.es.js +6483 -1064
  5. package/dist/index.es.js.map +1 -0
  6. package/package.json +23 -30
  7. package/src/__tests__/helpers.test.ts +77 -0
  8. package/src/aggregator/contracts/avaxGeneric.ts +50 -50
  9. package/src/aggregator/contracts/avaxWoofi.ts +80 -80
  10. package/src/aggregator/contracts/bscGeneric.ts +59 -59
  11. package/src/aggregator/contracts/ethGeneric.ts +50 -50
  12. package/src/aggregator/contracts/index.ts +30 -28
  13. package/src/aggregator/contracts/pancakeV2.ts +80 -80
  14. package/src/aggregator/contracts/pangolin.ts +65 -65
  15. package/src/aggregator/contracts/routers/index.ts +58 -0
  16. package/src/aggregator/contracts/routers/kyber.ts +402 -0
  17. package/src/aggregator/contracts/routers/oneinch.ts +2188 -0
  18. package/src/aggregator/contracts/routers/pancakeswap.ts +340 -0
  19. package/src/aggregator/contracts/routers/pangolin.ts +340 -0
  20. package/src/aggregator/contracts/routers/sushiswap.ts +340 -0
  21. package/src/aggregator/contracts/routers/traderJoe.ts +340 -0
  22. package/src/aggregator/contracts/routers/uniswapv2.ts +340 -0
  23. package/src/aggregator/contracts/routers/uniswapv3.ts +254 -0
  24. package/src/aggregator/contracts/routers/woofi.ts +171 -0
  25. package/src/aggregator/contracts/sushiswap.ts +65 -65
  26. package/src/aggregator/contracts/traderJoe.ts +65 -65
  27. package/src/aggregator/contracts/uniswapV2.ts +65 -65
  28. package/src/aggregator/contracts/uniswapV2Leg.ts +70 -70
  29. package/src/aggregator/contracts/uniswapV3_100.ts +70 -70
  30. package/src/aggregator/contracts/uniswapV3_10000.ts +70 -70
  31. package/src/aggregator/contracts/uniswapV3_3000.ts +70 -70
  32. package/src/aggregator/contracts/uniswapV3_500.ts +70 -70
  33. package/src/aggregator/getSwapParams.ts +12 -12
  34. package/src/client/index.ts +212 -645
  35. package/src/client/old.ts +870 -0
  36. package/src/{client → helpers}/explorerUrls.ts +11 -10
  37. package/src/helpers/mayanode.ts +31 -0
  38. package/src/{client → helpers}/thornode.ts +7 -7
  39. package/src/index.ts +6 -4
  40. package/src/types.ts +149 -0
  41. package/dist/index-9e36735e.cjs +0 -1
  42. package/dist/index-cf1865cd.js +0 -649
  43. package/src/client/__tests__/helpers.test.ts +0 -69
  44. package/src/client/types.ts +0 -103
@@ -0,0 +1,870 @@
1
+ import type {
2
+ ErrorKeys,
3
+ MayanameRegisterParam,
4
+ QuoteRoute,
5
+ ThornameRegisterParam,
6
+ } from "@swapkit/helpers";
7
+ import {
8
+ AssetValue,
9
+ SwapKitError,
10
+ SwapKitNumber,
11
+ gasFeeMultiplier,
12
+ getMemoFor,
13
+ getMinAmountByChain,
14
+ } from "@swapkit/helpers";
15
+ import type { CosmosLikeToolbox } from "@swapkit/toolbox-cosmos";
16
+ import type { AVAXToolbox, BSCToolbox, ETHToolbox, EVMToolbox } from "@swapkit/toolbox-evm";
17
+ import type { UTXOToolbox } from "@swapkit/toolbox-utxo";
18
+ import type {
19
+ AddChainWalletParams,
20
+ EVMChain,
21
+ EVMWalletOptions,
22
+ ExtendParams,
23
+ WalletOption,
24
+ } from "@swapkit/types";
25
+ import {
26
+ AGG_SWAP,
27
+ Chain,
28
+ ChainToChainId,
29
+ FeeOption,
30
+ MemoType,
31
+ SWAP_IN,
32
+ SWAP_OUT,
33
+ TCAvalancheDepositABI,
34
+ TCBscDepositABI,
35
+ TCEthereumVaultAbi,
36
+ } from "@swapkit/types";
37
+
38
+ import type { AGG_CONTRACT_ADDRESS } from "../aggregator/contracts/index.ts";
39
+ import { lowercasedContractAbiMapping } from "../aggregator/contracts/index.ts";
40
+ import { getSwapInParams } from "../aggregator/getSwapParams.ts";
41
+
42
+ import { getExplorerAddressUrl, getExplorerTxUrl } from "../helpers/explorerUrls.ts";
43
+ import { getMayaMimirData } from "../helpers/mayanode.js";
44
+ import { getThorInboundData, getThorMimirData } from "../helpers/thornode.ts";
45
+ import type {
46
+ CoreTxParams,
47
+ EVMWallet,
48
+ OldWallet,
49
+ SwapWithRouteParams,
50
+ ThorchainWallet,
51
+ WalletMethods,
52
+ } from "../types.ts";
53
+
54
+ const getEmptyWalletStructure = () =>
55
+ (Object.values(Chain) as Chain[]).reduce(
56
+ (acc, chain) => {
57
+ acc[chain] = null;
58
+ return acc;
59
+ },
60
+ {} as Record<Chain, null>,
61
+ );
62
+
63
+ const validateAddressType = ({
64
+ chain,
65
+ address,
66
+ }: {
67
+ chain: Chain;
68
+ address?: string;
69
+ }) => {
70
+ if (!address) return false;
71
+
72
+ switch (chain) {
73
+ case Chain.Bitcoin:
74
+ // filter out taproot addresses
75
+ return !address.startsWith("bc1p");
76
+ default:
77
+ return true;
78
+ }
79
+ };
80
+
81
+ /**
82
+ * @deprecated Use SwapKit instead (import { SwapKit } from "@swapkit/core")
83
+ */
84
+ export class SwapKitCore<T = ""> {
85
+ public connectedChains: OldWallet = getEmptyWalletStructure();
86
+ public connectedWallets: WalletMethods = getEmptyWalletStructure();
87
+ public readonly stagenet: boolean = false;
88
+
89
+ constructor({ stagenet }: { stagenet?: boolean } | undefined = {}) {
90
+ this.stagenet = !!stagenet;
91
+ }
92
+
93
+ getAddress = (chain: Chain) => this.connectedChains[chain]?.address || "";
94
+ getExplorerTxUrl = (chain: Chain, txHash: string) => getExplorerTxUrl({ chain, txHash });
95
+ getWallet = <T extends Chain>(chain: Chain) => this.connectedWallets[chain] as WalletMethods[T];
96
+ getExplorerAddressUrl = (chain: Chain, address: string) =>
97
+ getExplorerAddressUrl({ chain, address });
98
+ getBalance = async (chain: Chain, potentialScamFilter?: boolean) => {
99
+ const wallet = await this.getWalletByChain(chain, potentialScamFilter);
100
+
101
+ return wallet?.balance || [];
102
+ };
103
+
104
+ swap = async ({
105
+ streamSwap,
106
+ recipient,
107
+ route,
108
+ feeOptionKey = FeeOption.Average,
109
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: <explanation>
110
+ }: SwapWithRouteParams) => {
111
+ const {
112
+ meta: { quoteMode },
113
+ // evmTransactionDetails: contractCallParams,
114
+ } = route as QuoteRoute;
115
+ const evmChain = quoteMode.startsWith("ERC20-")
116
+ ? Chain.Ethereum
117
+ : quoteMode.startsWith("ARC20-")
118
+ ? Chain.Avalanche
119
+ : quoteMode.startsWith("BEP20-")
120
+ ? Chain.BinanceSmartChain
121
+ : undefined;
122
+
123
+ if (!(route as QuoteRoute).complete) throw new SwapKitError("core_swap_route_not_complete");
124
+
125
+ // TODO enable when BE is ready
126
+ // if (contractCallParams && evmChain) {
127
+ // const walletMethods = this.connectedWallets[evmChain];
128
+
129
+ // if (!walletMethods?.call) {
130
+ // throw new SwapKitError('core_wallet_connection_not_found');
131
+ // }
132
+
133
+ // const { contractAddress, contractMethod, contractParams, contractParamsStreaming } =
134
+ // contractCallParams;
135
+
136
+ // if (!(streamSwap ? contractParamsStreaming : contractParams)) {
137
+ // throw new SwapKitError('core_swap_route_transaction_not_found');
138
+ // }
139
+
140
+ // return await walletMethods.call<string>({
141
+ // contractAddress,
142
+ // abi: lowercasedContractAbiMapping[contractAddress.toLowerCase()],
143
+ // funcName: contractMethod,
144
+ // funcParams: streamSwap ? contractParamsStreaming : contractParams,
145
+ // });
146
+ // }
147
+
148
+ if (AGG_SWAP.includes(quoteMode) && evmChain) {
149
+ const walletMethods = this.connectedWallets[evmChain];
150
+ if (!walletMethods?.sendTransaction) {
151
+ throw new SwapKitError("core_wallet_connection_not_found");
152
+ }
153
+
154
+ const transaction = streamSwap
155
+ ? (route as QuoteRoute)?.streamingSwap?.transaction
156
+ : (route as QuoteRoute)?.transaction;
157
+ if (!transaction) throw new SwapKitError("core_swap_route_transaction_not_found");
158
+
159
+ const { data, from, to, value } = (route as QuoteRoute).transaction;
160
+
161
+ const params = {
162
+ data,
163
+ from,
164
+ to: to.toLowerCase(),
165
+ chainId: BigInt(ChainToChainId[evmChain]),
166
+ value: value ? BigInt(value) : 0n,
167
+ };
168
+
169
+ return walletMethods.sendTransaction(params, feeOptionKey) as Promise<string>;
170
+ }
171
+
172
+ if (SWAP_OUT.includes(quoteMode)) {
173
+ if (!(route as QuoteRoute).calldata.fromAsset)
174
+ throw new SwapKitError("core_swap_asset_not_recognized");
175
+ // @ts-expect-error
176
+ const asset = await AssetValue.fromString((route as QuoteRoute).calldata.fromAsset);
177
+ if (!asset) throw new SwapKitError("core_swap_asset_not_recognized");
178
+
179
+ const { address: recipient } = await this.#getInboundDataByChain(asset.chain);
180
+ const {
181
+ contract: router,
182
+ calldata: { expiration, amountIn, memo, memoStreamingSwap },
183
+ } = route as QuoteRoute;
184
+
185
+ const assetValue = asset.add(SwapKitNumber.fromBigInt(BigInt(amountIn), asset.decimal));
186
+ const swapMemo = (streamSwap ? memoStreamingSwap || memo : memo) as string;
187
+
188
+ return this.deposit({
189
+ expiration,
190
+ assetValue,
191
+ memo: swapMemo,
192
+ feeOptionKey,
193
+ router,
194
+ recipient,
195
+ });
196
+ }
197
+
198
+ if (SWAP_IN.includes(quoteMode) && evmChain) {
199
+ const { calldata, contract: contractAddress } = route as QuoteRoute;
200
+ if (!contractAddress) throw new SwapKitError("core_swap_contract_not_found");
201
+
202
+ const walletMethods = this.connectedWallets[evmChain];
203
+ const from = this.getAddress(evmChain);
204
+
205
+ if (!(walletMethods?.sendTransaction && from)) {
206
+ throw new SwapKitError("core_wallet_connection_not_found");
207
+ }
208
+
209
+ const { getProvider, toChecksumAddress } = await import("@swapkit/toolbox-evm");
210
+ const provider = getProvider(evmChain);
211
+ const abi = lowercasedContractAbiMapping[contractAddress.toLowerCase()];
212
+
213
+ if (!abi)
214
+ throw new SwapKitError("core_swap_contract_not_supported", {
215
+ contractAddress,
216
+ });
217
+
218
+ const contract = await walletMethods.createContract?.(contractAddress, abi, provider);
219
+
220
+ const tx = await contract.getFunction("swapIn").populateTransaction(
221
+ ...getSwapInParams({
222
+ streamSwap,
223
+ toChecksumAddress,
224
+ contractAddress: contractAddress as AGG_CONTRACT_ADDRESS,
225
+ recipient,
226
+ calldata,
227
+ }),
228
+ { from },
229
+ );
230
+
231
+ return walletMethods.sendTransaction(tx, feeOptionKey) as Promise<string>;
232
+ }
233
+
234
+ throw new SwapKitError("core_swap_quote_mode_not_supported", { quoteMode });
235
+ };
236
+
237
+ getWalletByChain = async (chain: Chain, potentialScamFilter?: boolean) => {
238
+ const address = this.getAddress(chain);
239
+ if (!address) return null;
240
+ const defaultBalance = [AssetValue.fromChainOrSignature(chain)];
241
+ const walletType = this.connectedChains[chain]?.walletType as WalletOption;
242
+
243
+ try {
244
+ const balance = await this.getWallet(chain)?.getBalance(address, potentialScamFilter);
245
+
246
+ this.connectedChains[chain] = {
247
+ address,
248
+ balance: balance?.length ? balance : defaultBalance,
249
+ walletType,
250
+ };
251
+
252
+ return { ...this.connectedChains[chain] };
253
+ } catch (error) {
254
+ console.error(error);
255
+
256
+ return { address, balance: defaultBalance, walletType };
257
+ }
258
+ };
259
+
260
+ approveAssetValue = (assetValue: AssetValue, contractAddress?: string) =>
261
+ this.#approve({ assetValue, type: "approve", contractAddress });
262
+
263
+ isAssetValueApproved = (assetValue: AssetValue, contractAddress?: string) =>
264
+ this.#approve<boolean>({ assetValue, contractAddress, type: "checkOnly" });
265
+
266
+ validateAddress = ({ address, chain }: { address: string; chain: Chain }) =>
267
+ this.getWallet(chain)?.validateAddress?.(address);
268
+
269
+ transfer = async (params: CoreTxParams & { router?: string }) => {
270
+ const walletInstance = this.connectedWallets[params.assetValue.chain];
271
+ if (!walletInstance) throw new SwapKitError("core_wallet_connection_not_found");
272
+
273
+ try {
274
+ return await walletInstance.transfer(this.#prepareTxParams(params));
275
+ } catch (error) {
276
+ throw new SwapKitError("core_swap_transaction_error", error);
277
+ }
278
+ };
279
+
280
+ deposit = async ({
281
+ assetValue,
282
+ recipient,
283
+ router,
284
+ ...rest
285
+ }: // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: Refactor
286
+ CoreTxParams & { router?: string }) => {
287
+ const { chain, symbol, ticker } = assetValue;
288
+ const walletInstance = this.connectedWallets[chain];
289
+ const connectedWallet = this.connectedChains[chain];
290
+ const isAddressValidated = await validateAddressType({
291
+ address: connectedWallet?.address,
292
+ chain,
293
+ });
294
+
295
+ if (!isAddressValidated) {
296
+ throw new SwapKitError("core_transaction_invalid_sender_address");
297
+ }
298
+
299
+ if (!walletInstance) throw new SwapKitError("core_wallet_connection_not_found");
300
+
301
+ const params = this.#prepareTxParams({
302
+ assetValue,
303
+ recipient,
304
+ router,
305
+ ...rest,
306
+ });
307
+
308
+ try {
309
+ switch (chain) {
310
+ case Chain.THORChain:
311
+ case Chain.Maya: {
312
+ const wallet = walletInstance as ThorchainWallet;
313
+ return await (recipient === "" ? wallet.deposit(params) : wallet.transfer(params));
314
+ }
315
+
316
+ case Chain.Ethereum:
317
+ case Chain.BinanceSmartChain:
318
+ case Chain.Avalanche: {
319
+ const { getChecksumAddressFromAsset } = await import("@swapkit/toolbox-evm");
320
+
321
+ const abi =
322
+ chain === Chain.Avalanche
323
+ ? TCAvalancheDepositABI
324
+ : chain === Chain.BinanceSmartChain
325
+ ? TCBscDepositABI
326
+ : TCEthereumVaultAbi;
327
+
328
+ const response = await (
329
+ walletInstance as EVMWallet<typeof AVAXToolbox | typeof ETHToolbox | typeof BSCToolbox>
330
+ ).call({
331
+ abi,
332
+ contractAddress:
333
+ router || ((await this.#getInboundDataByChain(chain as EVMChain)).router as string),
334
+ funcName: "depositWithExpiry",
335
+ funcParams: [
336
+ recipient,
337
+ getChecksumAddressFromAsset({ chain, symbol, ticker }, chain),
338
+ assetValue.getBaseValue("string"),
339
+ params.memo,
340
+ rest.expiration || parseInt(`${(new Date().getTime() + 15 * 60 * 1000) / 1000}`),
341
+ ],
342
+ txOverrides: {
343
+ from: params.from,
344
+ value: assetValue.isGasAsset ? assetValue.getBaseValue("bigint") : undefined,
345
+ },
346
+ });
347
+
348
+ return response as string;
349
+ }
350
+
351
+ default: {
352
+ return await walletInstance.transfer(params);
353
+ }
354
+ }
355
+ } catch (error: any) {
356
+ const errorMessage =
357
+ typeof error === "string" ? error.toLowerCase() : error?.message.toLowerCase();
358
+ const isInsufficientFunds = errorMessage?.includes("insufficient funds");
359
+ const isGas = errorMessage?.includes("gas");
360
+ const isServer = errorMessage?.includes("server");
361
+ const isUserRejected = errorMessage?.includes("user rejected");
362
+ const errorKey: ErrorKeys = isInsufficientFunds
363
+ ? "core_transaction_deposit_insufficient_funds_error"
364
+ : isGas
365
+ ? "core_transaction_deposit_gas_error"
366
+ : isServer
367
+ ? "core_transaction_deposit_server_error"
368
+ : isUserRejected
369
+ ? "core_transaction_user_rejected"
370
+ : "core_transaction_deposit_error";
371
+
372
+ throw new SwapKitError(errorKey, error);
373
+ }
374
+ };
375
+
376
+ /**
377
+ * TC related Methods
378
+ */
379
+ createLiquidity = async ({
380
+ runeAssetValue,
381
+ assetValue,
382
+ }: {
383
+ runeAssetValue: AssetValue;
384
+ assetValue: AssetValue;
385
+ }) => {
386
+ if (runeAssetValue.lte(0) || assetValue.lte(0)) {
387
+ throw new SwapKitError("core_transaction_create_liquidity_invalid_params");
388
+ }
389
+
390
+ let runeTx = "";
391
+ let assetTx = "";
392
+
393
+ try {
394
+ runeTx = await this.#depositToPool({
395
+ assetValue: runeAssetValue,
396
+ memo: getMemoFor(MemoType.DEPOSIT, {
397
+ ...assetValue,
398
+ address: this.getAddress(assetValue.chain),
399
+ }),
400
+ });
401
+ } catch (error) {
402
+ throw new SwapKitError("core_transaction_create_liquidity_rune_error", error);
403
+ }
404
+
405
+ try {
406
+ assetTx = await this.#depositToPool({
407
+ assetValue,
408
+ memo: getMemoFor(MemoType.DEPOSIT, {
409
+ ...assetValue,
410
+ address: this.getAddress(Chain.THORChain),
411
+ }),
412
+ });
413
+ } catch (error) {
414
+ throw new SwapKitError("core_transaction_create_liquidity_asset_error", error);
415
+ }
416
+
417
+ return { runeTx, assetTx };
418
+ };
419
+
420
+ addLiquidity = async ({
421
+ runeAssetValue,
422
+ assetValue,
423
+ runeAddr,
424
+ assetAddr,
425
+ isPendingSymmAsset,
426
+ mode = "sym",
427
+ }: {
428
+ runeAssetValue: AssetValue;
429
+ assetValue: AssetValue;
430
+ isPendingSymmAsset?: boolean;
431
+ runeAddr?: string;
432
+ assetAddr?: string;
433
+ mode?: "sym" | "rune" | "asset";
434
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: Refactor
435
+ }) => {
436
+ const { chain, symbol } = assetValue;
437
+ const isSym = mode === "sym";
438
+ const runeTransfer = runeAssetValue?.gt(0) && (isSym || mode === "rune");
439
+ const assetTransfer = assetValue?.gt(0) && (isSym || mode === "asset");
440
+ const includeRuneAddress = isPendingSymmAsset || runeTransfer;
441
+ const runeAddress = includeRuneAddress ? runeAddr || this.getAddress(Chain.THORChain) : "";
442
+ const assetAddress = isSym || mode === "asset" ? assetAddr || this.getAddress(chain) : "";
443
+
444
+ if (!(runeTransfer || assetTransfer)) {
445
+ throw new SwapKitError("core_transaction_add_liquidity_invalid_params");
446
+ }
447
+ if (includeRuneAddress && !runeAddress) {
448
+ throw new SwapKitError("core_transaction_add_liquidity_no_rune_address");
449
+ }
450
+
451
+ let runeTx: string | undefined;
452
+ let assetTx: string | undefined;
453
+
454
+ if (runeTransfer && runeAssetValue) {
455
+ try {
456
+ runeTx = await this.#depositToPool({
457
+ assetValue: runeAssetValue,
458
+ memo: getMemoFor(MemoType.DEPOSIT, {
459
+ chain,
460
+ symbol,
461
+ address: assetAddress,
462
+ }),
463
+ });
464
+ } catch (error) {
465
+ throw new SwapKitError("core_transaction_add_liquidity_rune_error", error);
466
+ }
467
+ }
468
+
469
+ if (assetTransfer && assetValue) {
470
+ try {
471
+ assetTx = await this.#depositToPool({
472
+ assetValue,
473
+ memo: getMemoFor(MemoType.DEPOSIT, {
474
+ chain,
475
+ symbol,
476
+ address: runeAddress,
477
+ }),
478
+ });
479
+ } catch (error) {
480
+ throw new SwapKitError("core_transaction_add_liquidity_asset_error", error);
481
+ }
482
+ }
483
+
484
+ return { runeTx, assetTx };
485
+ };
486
+
487
+ addLiquidityPart = ({
488
+ assetValue,
489
+ poolAddress,
490
+ address,
491
+ symmetric,
492
+ }: {
493
+ assetValue: AssetValue;
494
+ address?: string;
495
+ poolAddress: string;
496
+ symmetric: boolean;
497
+ }) => {
498
+ if (symmetric && !address) {
499
+ throw new SwapKitError("core_transaction_add_liquidity_invalid_params");
500
+ }
501
+ const memo = getMemoFor(MemoType.DEPOSIT, {
502
+ chain: poolAddress.split(".")[0] as Chain,
503
+ symbol: poolAddress.split(".")[1],
504
+ address: symmetric ? address : "",
505
+ });
506
+
507
+ return this.#depositToPool({ assetValue, memo });
508
+ };
509
+
510
+ withdraw = ({
511
+ memo,
512
+ assetValue,
513
+ percent,
514
+ from,
515
+ to,
516
+ }: {
517
+ memo?: string;
518
+ assetValue: AssetValue;
519
+ percent: number;
520
+ from: "sym" | "rune" | "asset";
521
+ to: "sym" | "rune" | "asset";
522
+ }) => {
523
+ const targetAsset =
524
+ to === "rune" && from !== "rune"
525
+ ? AssetValue.fromChainOrSignature(Chain.THORChain)
526
+ : (from === "sym" && to === "sym") || from === "rune" || from === "asset"
527
+ ? undefined
528
+ : assetValue;
529
+
530
+ const value = getMinAmountByChain(from === "asset" ? assetValue.chain : Chain.THORChain);
531
+ const memoString =
532
+ memo ||
533
+ getMemoFor(MemoType.WITHDRAW, {
534
+ symbol: assetValue.symbol,
535
+ chain: assetValue.chain,
536
+ ticker: assetValue.ticker,
537
+ basisPoints: Math.min(10000, Math.round(percent * 100)),
538
+ targetAssetString: targetAsset?.toString(),
539
+ singleSide: false,
540
+ });
541
+
542
+ return this.#depositToPool({ assetValue: value, memo: memoString });
543
+ };
544
+
545
+ savings = ({
546
+ assetValue,
547
+ memo,
548
+ percent,
549
+ type,
550
+ }: { assetValue: AssetValue; memo?: string } & (
551
+ | { type: "add"; percent?: undefined }
552
+ | { type: "withdraw"; percent: number }
553
+ )) => {
554
+ const memoType = type === "add" ? MemoType.DEPOSIT : MemoType.WITHDRAW;
555
+ const memoString =
556
+ memo ||
557
+ getMemoFor(memoType, {
558
+ ticker: assetValue.ticker,
559
+ symbol: assetValue.symbol,
560
+ chain: assetValue.chain,
561
+ singleSide: true,
562
+ basisPoints: percent ? Math.min(10000, Math.round(percent * 100)) : undefined,
563
+ });
564
+
565
+ const value =
566
+ memoType === MemoType.DEPOSIT ? assetValue : getMinAmountByChain(assetValue.chain);
567
+
568
+ return this.#depositToPool({ memo: memoString, assetValue: value });
569
+ };
570
+
571
+ loan = ({
572
+ assetValue,
573
+ memo,
574
+ minAmount,
575
+ type,
576
+ }: {
577
+ assetValue: AssetValue;
578
+ memo?: string;
579
+ minAmount: AssetValue;
580
+ type: "open" | "close";
581
+ }) =>
582
+ this.#depositToPool({
583
+ assetValue,
584
+ memo:
585
+ memo ||
586
+ getMemoFor(type === "open" ? MemoType.OPEN_LOAN : MemoType.CLOSE_LOAN, {
587
+ asset: assetValue.toString(),
588
+ minAmount: minAmount.toString(),
589
+ address: this.getAddress(assetValue.chain),
590
+ }),
591
+ });
592
+
593
+ nodeAction = ({
594
+ type,
595
+ assetValue,
596
+ address,
597
+ }: { address: string } & (
598
+ | { type: "bond" | "unbond"; assetValue: AssetValue }
599
+ | { type: "leave"; assetValue?: undefined }
600
+ )) => {
601
+ const memoType =
602
+ type === "bond" ? MemoType.BOND : type === "unbond" ? MemoType.UNBOND : MemoType.LEAVE;
603
+ const memo = getMemoFor(memoType, {
604
+ address,
605
+ unbondAmount: type === "unbond" ? assetValue.getBaseValue("number") : undefined,
606
+ });
607
+
608
+ return this.#thorchainTransfer({
609
+ memo,
610
+ assetValue: type === "bond" ? assetValue : getMinAmountByChain(Chain.THORChain),
611
+ });
612
+ };
613
+
614
+ registerThorname = ({
615
+ assetValue,
616
+ ...param
617
+ }: ThornameRegisterParam & { assetValue: AssetValue }) =>
618
+ this.#thorchainTransfer({
619
+ assetValue,
620
+ memo: getMemoFor(MemoType.THORNAME_REGISTER, param),
621
+ });
622
+
623
+ registerMayaname = ({
624
+ assetValue,
625
+ ...param
626
+ }: MayanameRegisterParam & { assetValue: AssetValue }) =>
627
+ this.#mayachainTransfer({
628
+ assetValue,
629
+ memo: getMemoFor(MemoType.THORNAME_REGISTER, param),
630
+ });
631
+
632
+ extend = ({ wallets, config, apis = {}, rpcUrls = {} }: ExtendParams<T>) => {
633
+ try {
634
+ for (const wallet of wallets) {
635
+ // @ts-expect-error - this is fine as we are extending the class
636
+ this[wallet.connectMethodName] = wallet.connect({
637
+ addChain: this.#addConnectedChain,
638
+ config: config || {},
639
+ apis,
640
+ rpcUrls,
641
+ });
642
+ }
643
+ } catch (error) {
644
+ throw new SwapKitError("core_extend_error", error);
645
+ }
646
+ };
647
+
648
+ estimateMaxSendableAmount = async ({
649
+ chain,
650
+ params,
651
+ }: {
652
+ chain: Chain;
653
+ params: { from: string; recipient: string; assetValue: AssetValue };
654
+ }) => {
655
+ const walletMethods = this.getWallet<typeof chain>(chain);
656
+
657
+ switch (chain) {
658
+ case Chain.Arbitrum:
659
+ case Chain.Avalanche:
660
+ case Chain.BinanceSmartChain:
661
+ case Chain.Ethereum:
662
+ case Chain.Optimism:
663
+ case Chain.Polygon: {
664
+ const { estimateMaxSendableAmount } = await import("@swapkit/toolbox-evm");
665
+ return estimateMaxSendableAmount({
666
+ ...params,
667
+ toolbox: walletMethods as EVMToolbox,
668
+ });
669
+ }
670
+
671
+ case Chain.Bitcoin:
672
+ case Chain.BitcoinCash:
673
+ case Chain.Dogecoin:
674
+ case Chain.Litecoin:
675
+ return (walletMethods as UTXOToolbox).estimateMaxSendableAmount(params);
676
+
677
+ case Chain.Binance:
678
+ case Chain.THORChain:
679
+ case Chain.Cosmos: {
680
+ const { estimateMaxSendableAmount } = await import("@swapkit/toolbox-cosmos");
681
+ return estimateMaxSendableAmount({
682
+ ...params,
683
+ toolbox: walletMethods as CosmosLikeToolbox,
684
+ });
685
+ }
686
+
687
+ default:
688
+ throw new SwapKitError("core_estimated_max_spendable_chain_not_supported");
689
+ }
690
+ };
691
+
692
+ /**
693
+ * Wallet connection methods
694
+ */
695
+ // biome-ignore lint/nursery/useAwait: Extended methods
696
+ connectXDEFI = async (_chains: Chain[]): Promise<void> => {
697
+ throw new SwapKitError("core_wallet_xdefi_not_installed");
698
+ };
699
+ // biome-ignore lint/nursery/useAwait: Extended methods
700
+ connectEVMWallet = async (_chains: Chain[] | Chain, _wallet: EVMWalletOptions): Promise<void> => {
701
+ throw new SwapKitError("core_wallet_evmwallet_not_installed");
702
+ };
703
+ // biome-ignore lint/nursery/useAwait: Extended methods
704
+ connectWalletconnect = async (_chains: Chain[], _options?: any): Promise<void> => {
705
+ throw new SwapKitError("core_wallet_walletconnect_not_installed");
706
+ };
707
+ // biome-ignore lint/nursery/useAwait: Extended methods
708
+ connectKeepkey = async (_chains: Chain[], _derivationPath: number[][]): Promise<string> => {
709
+ throw new SwapKitError("core_wallet_keepkey_not_installed");
710
+ };
711
+ // biome-ignore lint/nursery/useAwait: Extended methods
712
+ connectKeystore = async (_chains: Chain[], _phrase: string): Promise<void> => {
713
+ throw new SwapKitError("core_wallet_keystore_not_installed");
714
+ };
715
+ // biome-ignore lint/nursery/useAwait: Extended methods
716
+ connectLedger = async (_chains: Chain, _derivationPath: number[]): Promise<void> => {
717
+ throw new SwapKitError("core_wallet_ledger_not_installed");
718
+ };
719
+ // biome-ignore lint/nursery/useAwait: Extended methods
720
+ connectTrezor = async (_chains: Chain, _derivationPath: number[]): Promise<void> => {
721
+ throw new SwapKitError("core_wallet_trezor_not_installed");
722
+ };
723
+ // biome-ignore lint/nursery/useAwait: Extended methods
724
+ connectKeplr = async (_chain: Chain): Promise<void> => {
725
+ throw new SwapKitError("core_wallet_keplr_not_installed");
726
+ };
727
+ // biome-ignore lint/nursery/useAwait: Extended methods
728
+ connectOkx = async (_chains: Chain[]): Promise<void> => {
729
+ throw new SwapKitError("core_wallet_okx_not_installed");
730
+ };
731
+
732
+ disconnectChain = (chain: Chain) => {
733
+ this.connectedChains[chain] = null;
734
+ this.connectedWallets[chain] = null;
735
+ };
736
+
737
+ #getInboundDataByChain = async (chain: Chain) => {
738
+ switch (chain) {
739
+ case Chain.Maya:
740
+ case Chain.THORChain:
741
+ return { gas_rate: "0", router: "", address: "", halted: false, chain };
742
+
743
+ default: {
744
+ const inboundData = await getThorInboundData(this.stagenet);
745
+ const chainAddressData = inboundData.find((item) => item.chain === chain);
746
+
747
+ if (!chainAddressData) throw new SwapKitError("core_inbound_data_not_found");
748
+ if (chainAddressData?.halted) throw new SwapKitError("core_chain_halted");
749
+
750
+ return chainAddressData;
751
+ }
752
+ }
753
+ };
754
+
755
+ #addConnectedChain = ({
756
+ chain,
757
+ address,
758
+ balance,
759
+ walletType,
760
+ ...rest
761
+ }: AddChainWalletParams<any>) => {
762
+ this.connectedChains[chain as Chain] = {
763
+ address: address || "",
764
+ balance: balance || [],
765
+ walletType: walletType || "unknown",
766
+ };
767
+ this.connectedWallets[chain as Chain] = { ...rest } as any;
768
+ };
769
+
770
+ #approve = async <T = string>({
771
+ assetValue,
772
+ type = "checkOnly",
773
+ contractAddress,
774
+ }: {
775
+ assetValue: AssetValue;
776
+ type?: "checkOnly" | "approve";
777
+ contractAddress?: string;
778
+ }) => {
779
+ const { address, chain, isGasAsset, isSynthetic } = assetValue;
780
+ const isEVMChain = [Chain.Ethereum, Chain.Avalanche, Chain.BinanceSmartChain].includes(chain);
781
+ const isNativeEVM = isEVMChain && isGasAsset;
782
+
783
+ if (isNativeEVM || !isEVMChain || isSynthetic) return true;
784
+
785
+ const walletMethods = this.connectedWallets[chain as EVMChain];
786
+ const walletAction = type === "checkOnly" ? walletMethods?.isApproved : walletMethods?.approve;
787
+
788
+ if (!walletAction) throw new SwapKitError("core_wallet_connection_not_found");
789
+
790
+ const from = this.getAddress(chain);
791
+
792
+ if (!(address && from)) throw new SwapKitError("core_approve_asset_address_or_from_not_found");
793
+
794
+ const spenderAddress =
795
+ contractAddress || ((await this.#getInboundDataByChain(chain)).router as string);
796
+
797
+ return walletAction({
798
+ amount: assetValue.getBaseValue("bigint"),
799
+ assetAddress: address,
800
+ from,
801
+ spenderAddress,
802
+ }) as Promise<T>;
803
+ };
804
+
805
+ #depositToPool = async ({
806
+ assetValue,
807
+ memo,
808
+ feeOptionKey = FeeOption.Fast,
809
+ }: {
810
+ assetValue: AssetValue;
811
+ memo: string;
812
+ feeOptionKey?: FeeOption;
813
+ }) => {
814
+ const {
815
+ gas_rate,
816
+ router,
817
+ address: poolAddress,
818
+ } = await this.#getInboundDataByChain(assetValue.chain);
819
+ const feeRate = (parseInt(gas_rate) || 0) * gasFeeMultiplier[feeOptionKey];
820
+
821
+ return this.deposit({
822
+ assetValue,
823
+ recipient: poolAddress,
824
+ memo,
825
+ router,
826
+ feeRate,
827
+ });
828
+ };
829
+
830
+ #thorchainTransfer = async ({
831
+ memo,
832
+ assetValue,
833
+ }: {
834
+ assetValue: AssetValue;
835
+ memo: string;
836
+ }) => {
837
+ const mimir = await getThorMimirData(this.stagenet);
838
+
839
+ // check if trading is halted or not
840
+ if (mimir.HALTCHAINGLOBAL >= 1 || mimir.HALTTHORCHAIN >= 1) {
841
+ throw new SwapKitError("core_chain_halted");
842
+ }
843
+
844
+ return this.deposit({ assetValue, recipient: "", memo });
845
+ };
846
+
847
+ #mayachainTransfer = async ({
848
+ memo,
849
+ assetValue,
850
+ }: {
851
+ assetValue: AssetValue;
852
+ memo: string;
853
+ }) => {
854
+ const mimir = await getMayaMimirData(this.stagenet);
855
+
856
+ // check if trading is halted or not
857
+ if (mimir.HALTCHAINGLOBAL >= 1 || mimir.HALTTHORCHAIN >= 1) {
858
+ throw new SwapKitError("core_chain_halted");
859
+ }
860
+
861
+ return this.deposit({ assetValue, recipient: "", memo });
862
+ };
863
+
864
+ #prepareTxParams = ({ assetValue, ...restTxParams }: CoreTxParams & { router?: string }) => ({
865
+ ...restTxParams,
866
+ memo: restTxParams.memo || "",
867
+ from: this.getAddress(assetValue.chain),
868
+ assetValue,
869
+ });
870
+ }