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

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