@suilend/sdk 1.1.74 → 1.1.76

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.
package/client.d.ts CHANGED
@@ -8,17 +8,8 @@ import { CreateReserveConfigArgs } from "./_generated/suilend/reserve-config/fun
8
8
  import { Side } from "./lib/types";
9
9
  export declare const ADMIN_ADDRESS: string;
10
10
  export declare const LENDING_MARKET_REGISTRY_ID: string;
11
- type UiLendingMarket = {
12
- name: string;
13
- slug: string;
14
- id: string;
15
- type: string;
16
- ownerCapId: string;
17
- isHidden?: boolean;
18
- };
19
- export declare const LENDING_MARKETS: UiLendingMarket[];
20
- export declare const LENDING_MARKET_ID: string;
21
- export declare const LENDING_MARKET_TYPE: string;
11
+ export declare const LENDING_MARKET_ID: string, LENDING_MARKET_TYPE: string;
12
+ export declare const STEAMM_LM_LENDING_MARKET_ID: string, STEAMM_LM_LENDING_MARKET_TYPE: string;
22
13
  export type ObligationWithUnclaimedRewards = {
23
14
  id: string;
24
15
  unclaimedRewards: {
@@ -89,4 +80,3 @@ export declare class SuilendClient {
89
80
  setFeeReceiversAndWeights(transaction: Transaction, lendingMarketOwnerCapId: string, receivers: string[], weights: bigint[]): import("@mysten/sui/transactions").TransactionResult;
90
81
  redeemCtokensAndWithdrawLiquidity(ownerId: string, ctokenCoinTypes: string[], transaction: Transaction): Promise<void>;
91
82
  }
92
- export {};
package/client.js CHANGED
@@ -8,8 +8,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
+ var _a, _b;
11
12
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.SuilendClient = exports.LENDING_MARKET_TYPE = exports.LENDING_MARKET_ID = exports.LENDING_MARKETS = exports.LENDING_MARKET_REGISTRY_ID = exports.ADMIN_ADDRESS = void 0;
13
+ exports.SuilendClient = exports.STEAMM_LM_LENDING_MARKET_TYPE = exports.STEAMM_LM_LENDING_MARKET_ID = exports.LENDING_MARKET_TYPE = exports.LENDING_MARKET_ID = exports.LENDING_MARKET_REGISTRY_ID = exports.ADMIN_ADDRESS = void 0;
13
14
  const utils_1 = require("@mysten/sui/utils");
14
15
  const pyth_sui_js_1 = require("@pythnetwork/pyth-sui-js");
15
16
  const sui_fe_1 = require("@suilend/sui-fe");
@@ -38,49 +39,24 @@ const SUILEND_UPGRADE_CAP_ID = process.env.NEXT_PUBLIC_SUILEND_USE_BETA_MARKET =
38
39
  exports.LENDING_MARKET_REGISTRY_ID = process.env.NEXT_PUBLIC_SUILEND_USE_BETA_MARKET === "true"
39
40
  ? "0x925c9a2336b02fc2b68099837bd66f6b5b4d45cd460e0a4b81708bac6c440eff"
40
41
  : "0x64faff8d91a56c4f55debbb44767b009ee744a70bc2cc8e3bbd2718c92f85931";
41
- exports.LENDING_MARKETS = process.env.NEXT_PUBLIC_SUILEND_USE_BETA_MARKET === "true"
42
+ _a = process.env.NEXT_PUBLIC_SUILEND_USE_BETA_MARKET === "true"
42
43
  ? [
43
- // {
44
- // name: "Old",
45
- // id: "0x850850ef3ec0aa8c3345a2c3c486b571fdc31f3ebcaff931d7f9b9707aace2f8",
46
- // type: "0x2::sui::SUI",
47
- // ownerCapId:
48
- // "0xa92aae3be305687d3abe36deb4d92f78ec17bfce7d8d07972722d1166e4bc6ab",
49
- // },
50
- {
51
- name: "Main market (beta)",
52
- slug: "main",
53
- id: "0x12e46de3eafaf0308a2dd64f1158782ed19e6621835bf883a1dd6b3061115667",
54
- type: "0x83556891f4a0f233ce7b05cfe7f957d4020492a34f5405b2cb9377d060bef4bf::spring_sui::SPRING_SUI",
55
- ownerCapId: "0xf0df3204ecd426bc83f5e5dccb07ea35f1af220a40ec02dfd63fb7f2fea00824", // Owner: beta owner (0xa902...c033)
56
- },
57
- {
58
- name: "STEAMM LM (beta)",
59
- slug: "steamm-lm",
60
- id: "0xb1d89cf9082cedce09d3647f0ebda4a8b5db125aff5d312a8bfd7eefa715bd35",
61
- type: "0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",
62
- ownerCapId: "0xed8262012d34105c5ac59cf2dd6473d492e6ab7529fe7f9ea6cb1fa8dc2dba56", // Owner: beta owner (0xa902...c033)
63
- },
44
+ "0x12e46de3eafaf0308a2dd64f1158782ed19e6621835bf883a1dd6b3061115667",
45
+ "0x83556891f4a0f233ce7b05cfe7f957d4020492a34f5405b2cb9377d060bef4bf::spring_sui::SPRING_SUI",
64
46
  ]
65
47
  : [
66
- {
67
- name: "Main market",
68
- slug: "main",
69
- id: "0x84030d26d85eaa7035084a057f2f11f701b7e2e4eda87551becbc7c97505ece1",
70
- type: "0xf95b06141ed4a174f239417323bde3f209b972f5930d8521ea38a52aff3a6ddf::suilend::MAIN_POOL",
71
- ownerCapId: "0xf7a4defe0b6566b6a2674a02a0c61c9f99bd012eed21bc741a069eaa82d35927",
72
- },
73
- {
74
- name: "STEAMM LM",
75
- slug: "steamm-lm",
76
- id: "0xc1888ec1b81a414e427a44829310508352aec38252ee0daa9f8b181b6947de9f",
77
- type: "0x0a071f4976abae1a7f722199cf0bfcbe695ef9408a878e7d12a7ca87b7e582a6::lp_rewards::LP_REWARDS",
78
- ownerCapId: "0x55a0f33b24e091830302726c8cfbff8cf8abd2ec1f83a4e6f4bf51c7ba3ad5ab",
79
- isHidden: true, // Only visible in the admin panel
80
- },
81
- ];
82
- exports.LENDING_MARKET_ID = exports.LENDING_MARKETS[0].id; // Main market, for backwards compatibility
83
- exports.LENDING_MARKET_TYPE = exports.LENDING_MARKETS[0].type; // Main market, for backwards compatibility
48
+ "0x84030d26d85eaa7035084a057f2f11f701b7e2e4eda87551becbc7c97505ece1",
49
+ "0xf95b06141ed4a174f239417323bde3f209b972f5930d8521ea38a52aff3a6ddf::suilend::MAIN_POOL",
50
+ ], exports.LENDING_MARKET_ID = _a[0], exports.LENDING_MARKET_TYPE = _a[1];
51
+ _b = process.env.NEXT_PUBLIC_SUILEND_USE_BETA_MARKET === "true"
52
+ ? [
53
+ "0xb1d89cf9082cedce09d3647f0ebda4a8b5db125aff5d312a8bfd7eefa715bd35",
54
+ "0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP",
55
+ ]
56
+ : [
57
+ "0xc1888ec1b81a414e427a44829310508352aec38252ee0daa9f8b181b6947de9f",
58
+ "0x0a071f4976abae1a7f722199cf0bfcbe695ef9408a878e7d12a7ca87b7e582a6::lp_rewards::LP_REWARDS",
59
+ ], exports.STEAMM_LM_LENDING_MARKET_ID = _b[0], exports.STEAMM_LM_LENDING_MARKET_TYPE = _b[1];
84
60
  function getLatestPackageId(client, upgradeCapId) {
85
61
  return __awaiter(this, void 0, void 0, function* () {
86
62
  var _a;
@@ -3,15 +3,13 @@ import BigNumber from "bignumber.js";
3
3
  import { Reserve } from "../_generated/suilend/reserve/structs";
4
4
  import { SuilendClient } from "../client";
5
5
  import { ParsedReserve } from "../parsers";
6
- import { StrategyOwnerCap } from "./types";
6
+ import { LendingMarketMetadata, StrategyOwnerCap } from "./types";
7
7
  export declare const RESERVES_CUSTOM_ORDER: string[];
8
8
  export declare const NORMALIZED_MAYA_COINTYPE: string;
9
9
  export declare const NORMALIZED_mPOINTS_COINTYPE: string;
10
10
  export declare const NORMALIZED_TREATS_COINTYPE: string;
11
- export declare const initializeSuilend: (suiClient: SuiClient, suilendClient: SuilendClient) => Promise<{
11
+ export declare const initializeSuilend: (suiClient: SuiClient, suilendClient: SuilendClient, lendingMarketMetadata?: LendingMarketMetadata) => Promise<{
12
12
  lendingMarket: {
13
- id: string;
14
- type: string;
15
13
  version: bigint;
16
14
  reserves: {
17
15
  config: {
@@ -139,10 +137,12 @@ export declare const initializeSuilend: (suiClient: SuiClient, suilendClient: Su
139
137
  depositedAmountUsd: BigNumber;
140
138
  borrowedAmountUsd: BigNumber;
141
139
  tvlUsd: BigNumber;
140
+ id: string;
141
+ type: string;
142
+ ownerCapId: string | undefined;
142
143
  name: string;
143
144
  slug: string;
144
145
  isHidden: boolean;
145
- ownerCapId: string;
146
146
  totalSupplyUsd: BigNumber;
147
147
  totalBorrowUsd: BigNumber;
148
148
  };
package/lib/initialize.js CHANGED
@@ -59,14 +59,17 @@ exports.RESERVES_CUSTOM_ORDER = [
59
59
  // MAIN ASSETS
60
60
  sui_fe_1.NORMALIZED_sSUI_COINTYPE,
61
61
  // MAIN ASSETS - Ecosystem LSTs
62
- sui_fe_1.NORMALIZED_kSUI_COINTYPE,
63
- sui_fe_1.NORMALIZED_iSUI_COINTYPE,
64
62
  sui_fe_1.NORMALIZED_mSUI_COINTYPE,
65
63
  sui_fe_1.NORMALIZED_fudSUI_COINTYPE,
64
+ sui_fe_1.NORMALIZED_kSUI_COINTYPE,
66
65
  sui_fe_1.NORMALIZED_trevinSUI_COINTYPE,
67
66
  sui_fe_1.NORMALIZED_upSUI_COINTYPE,
68
67
  sui_fe_1.NORMALIZED_yapSUI_COINTYPE,
68
+ sui_fe_1.NORMALIZED_iSUI_COINTYPE,
69
69
  sui_fe_1.NORMALIZED_flSUI_COINTYPE,
70
+ sui_fe_1.NORMALIZED_oshiSUI_COINTYPE,
71
+ sui_fe_1.NORMALIZED_jugSUI_COINTYPE,
72
+ sui_fe_1.NORMALIZED_stratSUI_COINTYPE,
70
73
  sui_fe_1.NORMALIZED_SUI_COINTYPE,
71
74
  sui_fe_1.NORMALIZED_USDC_COINTYPE,
72
75
  sui_fe_1.NORMALIZED_wUSDC_COINTYPE,
@@ -88,13 +91,14 @@ exports.RESERVES_CUSTOM_ORDER = [
88
91
  sui_fe_1.NORMALIZED_BLUE_COINTYPE,
89
92
  sui_fe_1.NORMALIZED_NS_COINTYPE,
90
93
  sui_fe_1.NORMALIZED_UP_COINTYPE,
91
- sui_fe_1.NORMALIZED_KOBAN_COINTYPE,
92
94
  sui_fe_1.NORMALIZED_DMC_COINTYPE,
95
+ sui_fe_1.NORMALIZED_STRAT_COINTYPE,
96
+ sui_fe_1.NORMALIZED_ALKIMI_COINTYPE,
97
+ sui_fe_1.NORMALIZED_KOBAN_COINTYPE,
93
98
  sui_fe_1.NORMALIZED_mUSD_COINTYPE,
94
99
  sui_fe_1.NORMALIZED_BUCK_COINTYPE,
95
100
  // ISOLATED ASSETS - Memecoins
96
101
  sui_fe_1.NORMALIZED_HIPPO_COINTYPE,
97
- sui_fe_1.NORMALIZED_LOFI_COINTYPE, // Not listed
98
102
  sui_fe_1.NORMALIZED_FUD_COINTYPE,
99
103
  ];
100
104
  const MAYA_COINTYPE = "0x3bf0aeb7b9698b18ec7937290a5701088fcd5d43ad11a2564b074d022a6d71ec::maya::MAYA";
@@ -103,7 +107,7 @@ const TREATS_COINTYPE = "0x0dadb7fa2771c2952f96161fc1f0c105d1f22d53926b9ff2498a8
103
107
  exports.NORMALIZED_MAYA_COINTYPE = (0, utils_1.normalizeStructTag)(MAYA_COINTYPE);
104
108
  exports.NORMALIZED_mPOINTS_COINTYPE = (0, utils_1.normalizeStructTag)(mPOINTS_COINTYPE);
105
109
  exports.NORMALIZED_TREATS_COINTYPE = (0, utils_1.normalizeStructTag)(TREATS_COINTYPE);
106
- const initializeSuilend = (suiClient, suilendClient) => __awaiter(void 0, void 0, void 0, function* () {
110
+ const initializeSuilend = (suiClient, suilendClient, lendingMarketMetadata) => __awaiter(void 0, void 0, void 0, function* () {
107
111
  const nowMs = Date.now();
108
112
  const nowS = Math.floor(nowMs / 1000);
109
113
  const interestCompoundedRawReserves = suilendClient.lendingMarket.reserves.map((r) => simulate.compoundReserveInterest(r, nowS));
@@ -186,7 +190,7 @@ const initializeSuilend = (suiClient, suilendClient) => __awaiter(void 0, void 0
186
190
  // (walReserve.price.value as bigint) = walPrice;
187
191
  // (walReserve.smoothedPrice.value as bigint) = walPrice;
188
192
  // }
189
- const lendingMarket = (0, parsers_1.parseLendingMarket)(suilendClient.lendingMarket, refreshedRawReserves, coinMetadataMap, nowS);
193
+ const lendingMarket = (0, parsers_1.parseLendingMarket)(suilendClient.lendingMarket, refreshedRawReserves, coinMetadataMap, nowS, lendingMarketMetadata);
190
194
  lendingMarket.reserves = lendingMarket.reserves.slice().sort((a, b) => {
191
195
  const aCustomOrderIndex = exports.RESERVES_CUSTOM_ORDER.indexOf(a.coinType);
192
196
  const bCustomOrderIndex = exports.RESERVES_CUSTOM_ORDER.indexOf(b.coinType);
@@ -238,6 +242,8 @@ const initializeObligations = (suiClient, suilendClient, refreshedRawReserves, r
238
242
  };
239
243
  const [strategyOwnerCaps, obligationOwnerCaps] = yield Promise.all([
240
244
  (() => __awaiter(void 0, void 0, void 0, function* () {
245
+ if (suilendClient.lendingMarket.id !== client_1.LENDING_MARKET_ID)
246
+ return []; // Only main lending market has strategy owner caps
241
247
  const objects = yield (0, sui_fe_1.getAllOwnedObjects)(suiClient, address, {
242
248
  StructType: `${strategyOwnerCap_1.STRATEGY_WRAPPER_PACKAGE_ID}::strategy_wrapper::StrategyOwnerCap<${suilendClient.lendingMarket.$typeArgs[0]}>`,
243
249
  });
@@ -250,7 +256,7 @@ const initializeObligations = (suiClient, suilendClient, refreshedRawReserves, r
250
256
  const obligationId = fields.inner_cap.fields.obligation_id;
251
257
  const result = {
252
258
  id,
253
- strategyType,
259
+ strategyType: `${strategyType}`,
254
260
  obligationOwnerCapId,
255
261
  obligationId,
256
262
  };
@@ -1,7 +1,7 @@
1
1
  import { CoinMetadata } from "@mysten/sui/client";
2
2
  import BigNumber from "bignumber.js";
3
3
  import { ParsedObligation, ParsedReserve } from "../parsers";
4
- import { Side } from "./types";
4
+ import { RewardsMap, Side } from "./types";
5
5
  export type RewardMap = {
6
6
  [coinType: string]: {
7
7
  [Side.DEPOSIT]: RewardSummary[];
@@ -52,4 +52,5 @@ export declare const getRewardsAprPercent: (side: Side, filteredRewards: RewardS
52
52
  export declare const getStakingYieldAprPercent: (side: Side, coinType: string, lstAprPercentMap: Record<string, BigNumber>) => BigNumber | undefined;
53
53
  export declare const getTotalAprPercent: (side: Side, aprPercent: BigNumber, filteredRewards: RewardSummary[], stakingYieldAprPercent?: BigNumber) => BigNumber;
54
54
  export declare const getNetAprPercent: (obligation: ParsedObligation, rewardMap: RewardMap, lstAprPercentMap: Record<string, BigNumber>, noShares?: boolean) => BigNumber;
55
+ export declare const getRewardsMap: (obligation: ParsedObligation | undefined, rewardMap: RewardMap, coinMetadataMap: Record<string, CoinMetadata>) => RewardsMap;
55
56
  export {};
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getNetAprPercent = exports.getTotalAprPercent = exports.getStakingYieldAprPercent = exports.getRewardsAprPercent = exports.getDedupedPerDayRewards = exports.getDedupedAprRewards = exports.getFilteredRewards = exports.formatRewards = exports.getBorrowShare = exports.getDepositShare = void 0;
6
+ exports.getRewardsMap = exports.getNetAprPercent = exports.getTotalAprPercent = exports.getStakingYieldAprPercent = exports.getRewardsAprPercent = exports.getDedupedPerDayRewards = exports.getDedupedAprRewards = exports.getFilteredRewards = exports.formatRewards = exports.getBorrowShare = exports.getDepositShare = void 0;
7
7
  const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
8
  const lodash_1 = require("lodash");
9
9
  const sui_fe_1 = require("@suilend/sui-fe");
@@ -179,3 +179,32 @@ const getNetAprPercent = (obligation, rewardMap, lstAprPercentMap, noShares) =>
179
179
  : new bignumber_js_1.default(0);
180
180
  };
181
181
  exports.getNetAprPercent = getNetAprPercent;
182
+ const getRewardsMap = (obligation, rewardMap, coinMetadataMap) => {
183
+ const result = {};
184
+ if (obligation) {
185
+ Object.values(rewardMap).flatMap((rewards) => [...rewards.deposit, ...rewards.borrow].forEach((r) => {
186
+ if ((0, sui_fe_1.isSendPoints)(r.stats.rewardCoinType))
187
+ return;
188
+ if (!r.obligationClaims[obligation.id])
189
+ return;
190
+ if (r.obligationClaims[obligation.id].claimableAmount.eq(0))
191
+ return;
192
+ const minAmount = 10 ** (-1 * r.stats.mintDecimals);
193
+ if (r.obligationClaims[obligation.id].claimableAmount.lt(minAmount))
194
+ return;
195
+ if (!result[r.stats.rewardCoinType])
196
+ result[r.stats.rewardCoinType] = {
197
+ amount: new bignumber_js_1.default(0),
198
+ rawAmount: new bignumber_js_1.default(0),
199
+ rewards: [],
200
+ };
201
+ result[r.stats.rewardCoinType].amount = result[r.stats.rewardCoinType].amount.plus(r.obligationClaims[obligation.id].claimableAmount);
202
+ result[r.stats.rewardCoinType].rawAmount = result[r.stats.rewardCoinType].amount
203
+ .times(10 ** coinMetadataMap[r.stats.rewardCoinType].decimals)
204
+ .integerValue(bignumber_js_1.default.ROUND_DOWN);
205
+ result[r.stats.rewardCoinType].rewards.push(r);
206
+ }));
207
+ }
208
+ return result;
209
+ };
210
+ exports.getRewardsMap = getRewardsMap;
@@ -1,11 +1,33 @@
1
+ import { AggregatorClient as CetusSdk } from "@cetusprotocol/aggregator-sdk";
1
2
  import { Transaction, TransactionObjectInput, TransactionResult } from "@mysten/sui/transactions";
2
- import { StrategyOwnerCap } from "./types";
3
- export declare const STRATEGY_WRAPPER_PACKAGE_ID = "0x2001629d6d87322ab0bd965a5d539acd318069ad589b644b6eaf6c50c606e99c";
4
- export declare const STRATEGY_SUI_LOOPING_SSUI = 1;
3
+ import { ParsedObligation, ParsedReserve } from "../parsers";
4
+ import { RewardsMap, StrategyOwnerCap } from "./types";
5
+ export declare const STRATEGY_WRAPPER_PACKAGE_ID = "0xba97dc73a07638d03d77ad2161484eb21db577edc9cadcd7035fef4b4f2f6fa1";
6
+ export declare enum StrategyType {
7
+ sSUI_SUI_LOOPING = "1",
8
+ stratSUI_SUI_LOOPING = "2",
9
+ USDC_sSUI_SUI_LOOPING = "3"
10
+ }
11
+ export declare const STRATEGY_TYPE_INFO_MAP: Record<StrategyType, {
12
+ queryParam: string;
13
+ header: {
14
+ coinTypes: string[];
15
+ title: string;
16
+ tooltip: string;
17
+ type: string;
18
+ };
19
+ defaultOpenCloseCoinType: string;
20
+ openCloseCoinTypeOptions: string[];
21
+ depositCoinTypes: string[];
22
+ borrowCoinType: string;
23
+ lstCoinType: string;
24
+ }>;
5
25
  export declare const strategyDeposit: (coin: TransactionObjectInput, coinType: string, strategyOwnerCap: TransactionObjectInput, reserveArrayIndex: bigint, transaction: Transaction) => TransactionResult;
6
26
  export declare const strategyBorrow: (coinType: string, strategyOwnerCap: TransactionObjectInput, reserveArrayIndex: bigint, value: bigint, transaction: Transaction) => TransactionResult;
7
27
  export declare const strategyWithdraw: (coinType: string, strategyOwnerCap: TransactionObjectInput, reserveArrayIndex: bigint, value: bigint, transaction: Transaction) => TransactionResult;
8
- export declare const createStrategyOwnerCapIfNoneExists: (transaction: Transaction, strategyOwnerCap?: StrategyOwnerCap) => {
28
+ export declare const strategyClaimRewardsAndSwap: (address: string, cetusSdk: CetusSdk, cetusPartnerId: string, rewardsMap: RewardsMap, lstReserve: ParsedReserve, strategyOwnerCap: TransactionObjectInput, isDepositing: boolean, transaction: Transaction) => Promise<void>;
29
+ export declare const strategySwapNonLstDepositsForLst: (cetusSdk: CetusSdk, cetusPartnerId: string, obligation: ParsedObligation, lstReserve: ParsedReserve, strategyOwnerCap: TransactionObjectInput, transaction: Transaction) => Promise<void>;
30
+ export declare const createStrategyOwnerCapIfNoneExists: (strategyType: StrategyType, strategyOwnerCap: StrategyOwnerCap | undefined, transaction: Transaction) => {
9
31
  strategyOwnerCapId: string | TransactionResult;
10
32
  didCreate: boolean;
11
33
  };
@@ -1,11 +1,81 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
2
14
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.sendStrategyOwnerCapToUser = exports.createStrategyOwnerCapIfNoneExists = exports.strategyWithdraw = exports.strategyBorrow = exports.strategyDeposit = exports.STRATEGY_SUI_LOOPING_SSUI = exports.STRATEGY_WRAPPER_PACKAGE_ID = void 0;
15
+ exports.sendStrategyOwnerCapToUser = exports.createStrategyOwnerCapIfNoneExists = exports.strategySwapNonLstDepositsForLst = exports.strategyClaimRewardsAndSwap = exports.strategyWithdraw = exports.strategyBorrow = exports.strategyDeposit = exports.STRATEGY_TYPE_INFO_MAP = exports.StrategyType = exports.STRATEGY_WRAPPER_PACKAGE_ID = void 0;
4
16
  const utils_1 = require("@mysten/sui/utils");
17
+ const bignumber_js_1 = require("bignumber.js");
18
+ const bn_js_1 = __importDefault(require("bn.js"));
5
19
  const sui_fe_1 = require("@suilend/sui-fe");
6
20
  const client_1 = require("../client");
7
- exports.STRATEGY_WRAPPER_PACKAGE_ID = "0x2001629d6d87322ab0bd965a5d539acd318069ad589b644b6eaf6c50c606e99c";
8
- exports.STRATEGY_SUI_LOOPING_SSUI = 1;
21
+ const types_1 = require("./types");
22
+ exports.STRATEGY_WRAPPER_PACKAGE_ID = "0xba97dc73a07638d03d77ad2161484eb21db577edc9cadcd7035fef4b4f2f6fa1";
23
+ var StrategyType;
24
+ (function (StrategyType) {
25
+ StrategyType["sSUI_SUI_LOOPING"] = "1";
26
+ StrategyType["stratSUI_SUI_LOOPING"] = "2";
27
+ StrategyType["USDC_sSUI_SUI_LOOPING"] = "3";
28
+ })(StrategyType || (exports.StrategyType = StrategyType = {}));
29
+ exports.STRATEGY_TYPE_INFO_MAP = {
30
+ [StrategyType.sSUI_SUI_LOOPING]: {
31
+ queryParam: "sSUI-SUI-looping",
32
+ header: {
33
+ coinTypes: [sui_fe_1.NORMALIZED_sSUI_COINTYPE, sui_fe_1.NORMALIZED_SUI_COINTYPE],
34
+ title: "sSUI/SUI",
35
+ tooltip: "Sets up a sSUI/SUI Looping strategy by depositing sSUI and borrowing SUI to the desired leverage",
36
+ type: "Looping",
37
+ },
38
+ defaultOpenCloseCoinType: sui_fe_1.NORMALIZED_SUI_COINTYPE,
39
+ openCloseCoinTypeOptions: [
40
+ sui_fe_1.NORMALIZED_SUI_COINTYPE,
41
+ sui_fe_1.NORMALIZED_sSUI_COINTYPE,
42
+ ],
43
+ depositCoinTypes: [sui_fe_1.NORMALIZED_sSUI_COINTYPE],
44
+ borrowCoinType: sui_fe_1.NORMALIZED_SUI_COINTYPE,
45
+ lstCoinType: sui_fe_1.NORMALIZED_sSUI_COINTYPE,
46
+ },
47
+ [StrategyType.stratSUI_SUI_LOOPING]: {
48
+ queryParam: "stratSUI-SUI-looping",
49
+ header: {
50
+ coinTypes: [sui_fe_1.NORMALIZED_stratSUI_COINTYPE, sui_fe_1.NORMALIZED_SUI_COINTYPE],
51
+ title: "stratSUI/SUI",
52
+ tooltip: "Sets up a stratSUI/SUI Looping strategy by depositing stratSUI and borrowing SUI to the desired leverage",
53
+ type: "Looping",
54
+ },
55
+ defaultOpenCloseCoinType: sui_fe_1.NORMALIZED_SUI_COINTYPE,
56
+ openCloseCoinTypeOptions: [
57
+ sui_fe_1.NORMALIZED_SUI_COINTYPE,
58
+ sui_fe_1.NORMALIZED_stratSUI_COINTYPE,
59
+ ],
60
+ depositCoinTypes: [sui_fe_1.NORMALIZED_stratSUI_COINTYPE],
61
+ borrowCoinType: sui_fe_1.NORMALIZED_SUI_COINTYPE,
62
+ lstCoinType: sui_fe_1.NORMALIZED_stratSUI_COINTYPE,
63
+ },
64
+ [StrategyType.USDC_sSUI_SUI_LOOPING]: {
65
+ queryParam: "USDC-sSUI-SUI-looping",
66
+ header: {
67
+ coinTypes: [sui_fe_1.NORMALIZED_USDC_COINTYPE],
68
+ title: "USDC",
69
+ tooltip: "Sets up a USDC sSUI/SUI Looping strategy by depositing USDC and looping sSUI/SUI to the desired leverage",
70
+ type: "Looping",
71
+ },
72
+ defaultOpenCloseCoinType: sui_fe_1.NORMALIZED_USDC_COINTYPE,
73
+ openCloseCoinTypeOptions: [sui_fe_1.NORMALIZED_USDC_COINTYPE],
74
+ depositCoinTypes: [sui_fe_1.NORMALIZED_USDC_COINTYPE, sui_fe_1.NORMALIZED_sSUI_COINTYPE],
75
+ borrowCoinType: sui_fe_1.NORMALIZED_SUI_COINTYPE,
76
+ lstCoinType: sui_fe_1.NORMALIZED_sSUI_COINTYPE,
77
+ },
78
+ };
9
79
  const strategyDeposit = (coin, coinType, strategyOwnerCap, reserveArrayIndex, transaction) => transaction.moveCall({
10
80
  target: `${exports.STRATEGY_WRAPPER_PACKAGE_ID}::strategy_wrapper::deposit_liquidity_and_deposit_into_obligation`,
11
81
  typeArguments: [client_1.LENDING_MARKET_TYPE, coinType],
@@ -55,7 +125,186 @@ const strategyWithdraw = (coinType, strategyOwnerCap, reserveArrayIndex, value,
55
125
  ],
56
126
  });
57
127
  exports.strategyWithdraw = strategyWithdraw;
58
- const createStrategyOwnerCapIfNoneExists = (transaction, strategyOwnerCap) => {
128
+ const strategyClaimRewards = (coinType, strategyOwnerCap, reserveArrayIndex, rewardIndex, side, transaction) => transaction.moveCall({
129
+ target: `${exports.STRATEGY_WRAPPER_PACKAGE_ID}::strategy_wrapper::claim_rewards`,
130
+ typeArguments: [client_1.LENDING_MARKET_TYPE, coinType],
131
+ arguments: [
132
+ transaction.object(strategyOwnerCap),
133
+ transaction.object(client_1.LENDING_MARKET_ID),
134
+ transaction.object(utils_1.SUI_CLOCK_OBJECT_ID),
135
+ transaction.pure.u64(reserveArrayIndex),
136
+ transaction.pure.u64(rewardIndex),
137
+ transaction.pure.bool(side === types_1.Side.DEPOSIT),
138
+ ],
139
+ });
140
+ const strategyClaimRewardsAndMergeCoins = (rewardsMap, strategyOwnerCap, transaction) => {
141
+ // 1) Get rewards
142
+ const rewards = Object.values(rewardsMap)
143
+ .flatMap((r) => r.rewards)
144
+ .map((r) => ({
145
+ reserveArrayIndex: Object.values(r.obligationClaims)[0].reserveArrayIndex,
146
+ rewardIndex: BigInt(r.stats.rewardIndex),
147
+ rewardCoinType: r.stats.rewardCoinType,
148
+ side: r.stats.side,
149
+ }));
150
+ // 2) Claim rewards and merge coins
151
+ const mergeCoinsMap = {};
152
+ for (const reward of rewards) {
153
+ const [claimedCoin] = strategyClaimRewards(reward.rewardCoinType, strategyOwnerCap, reward.reserveArrayIndex, reward.rewardIndex, reward.side, transaction);
154
+ if (mergeCoinsMap[reward.rewardCoinType] === undefined)
155
+ mergeCoinsMap[reward.rewardCoinType] = [];
156
+ mergeCoinsMap[reward.rewardCoinType].push(claimedCoin);
157
+ }
158
+ const mergedCoinsMap = {};
159
+ for (const [rewardCoinType, coins] of Object.entries(mergeCoinsMap)) {
160
+ const mergedCoin = coins[0];
161
+ if (coins.length > 1)
162
+ transaction.mergeCoins(mergedCoin, coins.slice(1));
163
+ mergedCoinsMap[rewardCoinType] = mergedCoin;
164
+ }
165
+ return mergedCoinsMap;
166
+ };
167
+ const strategyClaimRewardsAndSwap = (address, cetusSdk, cetusPartnerId, rewardsMap, lstReserve, strategyOwnerCap, isDepositing, transaction) => __awaiter(void 0, void 0, void 0, function* () {
168
+ // 1) Claim rewards and merge coins
169
+ const mergedCoinsMap = strategyClaimRewardsAndMergeCoins(rewardsMap, strategyOwnerCap, transaction);
170
+ // 2) Prepare
171
+ const nonSwappedCoinTypes = Object.keys(mergedCoinsMap).filter((coinType) => coinType === lstReserve.coinType);
172
+ const swappedCoinTypes = Object.keys(mergedCoinsMap).filter((coinType) => coinType !== lstReserve.coinType);
173
+ let resultCoin = undefined;
174
+ // 3.1) Non-swapped coins
175
+ for (const [coinType, coin] of Object.entries(mergedCoinsMap).filter(([coinType]) => nonSwappedCoinTypes.includes(coinType))) {
176
+ if (resultCoin)
177
+ transaction.mergeCoins(resultCoin, [coin]);
178
+ else
179
+ resultCoin = coin;
180
+ }
181
+ // 3.2) Swapped coins
182
+ // 3.2.1) Get routers
183
+ const amountsAndSortedQuotesMap = Object.fromEntries(yield Promise.all(Object.entries(mergedCoinsMap)
184
+ .filter(([coinType]) => swappedCoinTypes.includes(coinType))
185
+ .map(([coinType, coin]) => (() => __awaiter(void 0, void 0, void 0, function* () {
186
+ // Get amount
187
+ const { rawAmount: amount } = rewardsMap[coinType]; // Use underestimate (rewards keep accruing)
188
+ // Get routes
189
+ const routers = yield cetusSdk.findRouters({
190
+ from: coinType,
191
+ target: lstReserve.coinType,
192
+ amount: new bn_js_1.default(amount.toString()), // Underestimate (rewards keep accruing)
193
+ byAmountIn: true,
194
+ });
195
+ if (!routers)
196
+ throw new Error(`No swap quote found for ${coinType}`);
197
+ console.log("[strategyClaimRewardsAndSwap] routers", {
198
+ coinType,
199
+ routers,
200
+ });
201
+ return [coinType, { coin, routers }];
202
+ }))())));
203
+ console.log("[strategyClaimRewardsAndSwap] amountsAndSortedQuotesMap", {
204
+ amountsAndSortedQuotesMap,
205
+ });
206
+ // 3.2.2) Swap
207
+ for (const [coinType, { coin: coinIn, routers }] of Object.entries(amountsAndSortedQuotesMap)) {
208
+ console.log("[strategyClaimRewardsAndSwap] swapping coinType", coinType);
209
+ const slippagePercent = 3;
210
+ let coinOut;
211
+ try {
212
+ coinOut = yield cetusSdk.fixableRouterSwap({
213
+ routers,
214
+ inputCoin: coinIn,
215
+ slippage: slippagePercent / 100,
216
+ txb: transaction,
217
+ partner: cetusPartnerId,
218
+ });
219
+ }
220
+ catch (err) {
221
+ throw new Error(`No swap quote found for ${coinType}`);
222
+ }
223
+ if (resultCoin)
224
+ transaction.mergeCoins(resultCoin, [coinOut]);
225
+ else
226
+ resultCoin = coinOut;
227
+ }
228
+ // 4) Deposit
229
+ if (!resultCoin)
230
+ throw new Error("No coin to deposit or transfer");
231
+ if (isDepositing) {
232
+ (0, exports.strategyDeposit)(resultCoin, lstReserve.coinType, strategyOwnerCap, lstReserve.arrayIndex, transaction);
233
+ }
234
+ else {
235
+ transaction.transferObjects([resultCoin], transaction.pure.address(address));
236
+ }
237
+ });
238
+ exports.strategyClaimRewardsAndSwap = strategyClaimRewardsAndSwap;
239
+ const strategySwapNonLstDepositsForLst = (cetusSdk, cetusPartnerId, obligation, lstReserve, strategyOwnerCap, transaction) => __awaiter(void 0, void 0, void 0, function* () {
240
+ // 1) MAX Withdraw non-LST deposits
241
+ const nonLstDeposits = obligation.deposits.filter((deposit) => deposit.coinType !== lstReserve.coinType);
242
+ if (nonLstDeposits.length === 0)
243
+ return;
244
+ const withdrawnCoinsMap = {};
245
+ for (const deposit of nonLstDeposits) {
246
+ const [withdrawnCoin] = (0, exports.strategyWithdraw)(deposit.coinType, strategyOwnerCap, deposit.reserve.arrayIndex, BigInt(sui_fe_1.MAX_U64.toString()), transaction);
247
+ withdrawnCoinsMap[deposit.coinType] = {
248
+ deposit,
249
+ coin: withdrawnCoin,
250
+ };
251
+ }
252
+ // 2) Swap
253
+ let resultCoin = undefined;
254
+ // 2.1) Get routers
255
+ const amountsAndSortedQuotesMap = Object.fromEntries(yield Promise.all(Object.entries(withdrawnCoinsMap).map(([coinType, { deposit, coin }]) => (() => __awaiter(void 0, void 0, void 0, function* () {
256
+ // Get amount
257
+ const amount = deposit.depositedAmount
258
+ .times(10 ** deposit.reserve.token.decimals)
259
+ .integerValue(bignumber_js_1.BigNumber.ROUND_DOWN); // Use underestimate (deposits keep accruing if deposit APR >0)
260
+ // Get routes
261
+ const routers = yield cetusSdk.findRouters({
262
+ from: deposit.coinType,
263
+ target: lstReserve.coinType,
264
+ amount: new bn_js_1.default(amount.toString()), // Underestimate (deposits keep accruing if deposit APR >0)
265
+ byAmountIn: true,
266
+ });
267
+ if (!routers)
268
+ throw new Error(`No swap quote found for ${deposit.coinType}`);
269
+ console.log("[strategySwapNonLstDepositsForLst] routers", {
270
+ coinType: deposit.coinType,
271
+ routers,
272
+ });
273
+ return [deposit.coinType, { coin, routers }];
274
+ }))())));
275
+ console.log("[strategySwapNonLstDepositsForLst] amountsAndSortedQuotesMap", {
276
+ amountsAndSortedQuotesMap,
277
+ });
278
+ // 2.2) Swap
279
+ for (const [coinType, { coin: coinIn, routers }] of Object.entries(amountsAndSortedQuotesMap)) {
280
+ console.log("[strategySwapNonLstDepositsForLst] swapping coinType", coinType);
281
+ const slippagePercent = 3;
282
+ let coinOut;
283
+ try {
284
+ coinOut = yield cetusSdk.fixableRouterSwap({
285
+ routers,
286
+ inputCoin: coinIn,
287
+ slippage: slippagePercent / 100,
288
+ txb: transaction,
289
+ partner: cetusPartnerId,
290
+ });
291
+ }
292
+ catch (err) {
293
+ throw new Error(`No swap quote found for ${coinType}`);
294
+ }
295
+ if (resultCoin)
296
+ transaction.mergeCoins(resultCoin, [coinOut]);
297
+ else
298
+ resultCoin = coinOut;
299
+ }
300
+ // 3) Deposit
301
+ if (!resultCoin)
302
+ throw new Error("No coin to deposit or transfer");
303
+ console.log("[strategySwapNonLstDepositsForLst] depositing resultCoin");
304
+ (0, exports.strategyDeposit)(resultCoin, lstReserve.coinType, strategyOwnerCap, lstReserve.arrayIndex, transaction);
305
+ });
306
+ exports.strategySwapNonLstDepositsForLst = strategySwapNonLstDepositsForLst;
307
+ const createStrategyOwnerCapIfNoneExists = (strategyType, strategyOwnerCap, transaction) => {
59
308
  let strategyOwnerCapId;
60
309
  let didCreate = false;
61
310
  if (strategyOwnerCap)
@@ -66,7 +315,7 @@ const createStrategyOwnerCapIfNoneExists = (transaction, strategyOwnerCap) => {
66
315
  typeArguments: [client_1.LENDING_MARKET_TYPE],
67
316
  arguments: [
68
317
  transaction.object(client_1.LENDING_MARKET_ID),
69
- transaction.pure.u8(exports.STRATEGY_SUI_LOOPING_SSUI),
318
+ transaction.pure.u8(+strategyType),
70
319
  ],
71
320
  });
72
321
  didCreate = true;
package/lib/types.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { RewardSummary } from "./liquidityMining";
2
+ import { StrategyType } from "./strategyOwnerCap";
1
3
  export declare enum Side {
2
4
  DEPOSIT = "deposit",
3
5
  BORROW = "borrow"
@@ -200,7 +202,20 @@ export type ApiObligationDataEvent = {
200
202
  };
201
203
  export type StrategyOwnerCap = {
202
204
  id: string;
203
- strategyType: number;
205
+ strategyType: StrategyType;
204
206
  obligationOwnerCapId: string;
205
207
  obligationId: string;
206
208
  };
209
+ export type RewardsMap = Record<string, {
210
+ amount: BigNumber;
211
+ rawAmount: BigNumber;
212
+ rewards: RewardSummary[];
213
+ }>;
214
+ export type LendingMarketMetadata = {
215
+ id: string;
216
+ type: string;
217
+ lendingMarketOwnerCapId: string;
218
+ name?: string;
219
+ slug?: string;
220
+ isHidden?: boolean;
221
+ };
package/package.json CHANGED
@@ -1 +1 @@
1
- {"name":"@suilend/sdk","version":"1.1.74","private":false,"description":"A TypeScript SDK for interacting with the Suilend program","author":"Suilend","license":"MIT","main":"./index.js","exports":{".":"./index.js","./client":"./client.js","./api/events":"./api/events.js","./api":"./api/index.js","./lib/constants":"./lib/constants.js","./lib":"./lib/index.js","./lib/initialize":"./lib/initialize.js","./lib/liquidityMining":"./lib/liquidityMining.js","./lib/strategyOwnerCap":"./lib/strategyOwnerCap.js","./lib/transactions":"./lib/transactions.js","./lib/types":"./lib/types.js","./parsers/apiReserveAssetDataEvent":"./parsers/apiReserveAssetDataEvent.js","./parsers":"./parsers/index.js","./parsers/lendingMarket":"./parsers/lendingMarket.js","./parsers/obligation":"./parsers/obligation.js","./parsers/rateLimiter":"./parsers/rateLimiter.js","./parsers/reserve":"./parsers/reserve.js","./swap":"./swap/index.js","./swap/okxDex":"./swap/okxDex.js","./swap/quote":"./swap/quote.js","./swap/transaction":"./swap/transaction.js","./utils/events":"./utils/events.js","./utils":"./utils/index.js","./utils/obligation":"./utils/obligation.js","./utils/simulate":"./utils/simulate.js","./_generated/_framework/reified":"./_generated/_framework/reified.js","./_generated/_framework/util":"./_generated/_framework/util.js","./_generated/_framework/vector":"./_generated/_framework/vector.js","./_generated/suilend":"./_generated/suilend/index.js","./_generated/suilend/cell/structs":"./_generated/suilend/cell/structs.js","./_generated/suilend/decimal/structs":"./_generated/suilend/decimal/structs.js","./_generated/suilend/lending-market/functions":"./_generated/suilend/lending-market/functions.js","./_generated/suilend/lending-market/structs":"./_generated/suilend/lending-market/structs.js","./_generated/suilend/lending-market-registry/functions":"./_generated/suilend/lending-market-registry/functions.js","./_generated/suilend/liquidity-mining/structs":"./_generated/suilend/liquidity-mining/structs.js","./_generated/suilend/obligation/structs":"./_generated/suilend/obligation/structs.js","./_generated/suilend/rate-limiter/functions":"./_generated/suilend/rate-limiter/functions.js","./_generated/suilend/rate-limiter/structs":"./_generated/suilend/rate-limiter/structs.js","./_generated/suilend/reserve/structs":"./_generated/suilend/reserve/structs.js","./_generated/suilend/reserve-config/functions":"./_generated/suilend/reserve-config/functions.js","./_generated/suilend/reserve-config/structs":"./_generated/suilend/reserve-config/structs.js","./_generated/_dependencies/source/0x1":"./_generated/_dependencies/source/0x1/index.js","./_generated/_dependencies/source/0x2":"./_generated/_dependencies/source/0x2/index.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/index.js","./_generated/_dependencies/source/0x1/ascii/structs":"./_generated/_dependencies/source/0x1/ascii/structs.js","./_generated/_dependencies/source/0x1/option/structs":"./_generated/_dependencies/source/0x1/option/structs.js","./_generated/_dependencies/source/0x1/type-name/structs":"./_generated/_dependencies/source/0x1/type-name/structs.js","./_generated/_dependencies/source/0x2/bag/structs":"./_generated/_dependencies/source/0x2/bag/structs.js","./_generated/_dependencies/source/0x2/balance/structs":"./_generated/_dependencies/source/0x2/balance/structs.js","./_generated/_dependencies/source/0x2/object/structs":"./_generated/_dependencies/source/0x2/object/structs.js","./_generated/_dependencies/source/0x2/object-table/structs":"./_generated/_dependencies/source/0x2/object-table/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/i64/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/i64/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-feed/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-feed/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-identifier/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-identifier/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-info/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-info/structs.js"},"types":"./index.js","scripts":{"build":"rm -rf ./dist && bun tsc","eslint":"eslint --fix \"./src/**/*.ts\"","prettier":"prettier --write \"./src/**/*\"","lint":"bun eslint && bun prettier && bun tsc --noEmit","release":"bun run build && bun ts-node ./release.ts && cd ./dist && npm publish --access public"},"repository":{"type":"git","url":"git+https://github.com/suilend/suilend-fe-public.git"},"bugs":{"url":"https://github.com/suilend/suilend-fe-public/issues"},"dependencies":{"@7kprotocol/sdk-ts":"^3.2.0","@cetusprotocol/aggregator-sdk":"^0.14.1","@flowx-finance/sdk":"^1.11.2","@pythnetwork/pyth-sui-js":"^2.2.0","aftermath-ts-sdk":"^1.3.13","bignumber.js":"^9.1.2","bn.js":"^5.2.2","crypto-js":"^4.2.0","p-limit":"3.1.0","uuid":"^11.0.3"},"devDependencies":{"ts-node":"^10.9.2"},"peerDependencies":{"@mysten/bcs":"1.6.0","@mysten/sui":"1.28.2","@suilend/sui-fe":"^0.3.20"}}
1
+ {"name":"@suilend/sdk","version":"1.1.76","private":false,"description":"A TypeScript SDK for interacting with the Suilend program","author":"Suilend","license":"MIT","main":"./index.js","exports":{".":"./index.js","./client":"./client.js","./api/events":"./api/events.js","./api":"./api/index.js","./lib/constants":"./lib/constants.js","./lib":"./lib/index.js","./lib/initialize":"./lib/initialize.js","./lib/liquidityMining":"./lib/liquidityMining.js","./lib/strategyOwnerCap":"./lib/strategyOwnerCap.js","./lib/transactions":"./lib/transactions.js","./lib/types":"./lib/types.js","./parsers/apiReserveAssetDataEvent":"./parsers/apiReserveAssetDataEvent.js","./parsers":"./parsers/index.js","./parsers/lendingMarket":"./parsers/lendingMarket.js","./parsers/obligation":"./parsers/obligation.js","./parsers/rateLimiter":"./parsers/rateLimiter.js","./parsers/reserve":"./parsers/reserve.js","./swap":"./swap/index.js","./swap/quote":"./swap/quote.js","./swap/transaction":"./swap/transaction.js","./utils/events":"./utils/events.js","./utils":"./utils/index.js","./utils/obligation":"./utils/obligation.js","./utils/simulate":"./utils/simulate.js","./_generated/_framework/reified":"./_generated/_framework/reified.js","./_generated/_framework/util":"./_generated/_framework/util.js","./_generated/_framework/vector":"./_generated/_framework/vector.js","./_generated/suilend":"./_generated/suilend/index.js","./_generated/suilend/cell/structs":"./_generated/suilend/cell/structs.js","./_generated/suilend/decimal/structs":"./_generated/suilend/decimal/structs.js","./_generated/suilend/lending-market/functions":"./_generated/suilend/lending-market/functions.js","./_generated/suilend/lending-market/structs":"./_generated/suilend/lending-market/structs.js","./_generated/suilend/lending-market-registry/functions":"./_generated/suilend/lending-market-registry/functions.js","./_generated/suilend/liquidity-mining/structs":"./_generated/suilend/liquidity-mining/structs.js","./_generated/suilend/obligation/structs":"./_generated/suilend/obligation/structs.js","./_generated/suilend/rate-limiter/functions":"./_generated/suilend/rate-limiter/functions.js","./_generated/suilend/rate-limiter/structs":"./_generated/suilend/rate-limiter/structs.js","./_generated/suilend/reserve/structs":"./_generated/suilend/reserve/structs.js","./_generated/suilend/reserve-config/functions":"./_generated/suilend/reserve-config/functions.js","./_generated/suilend/reserve-config/structs":"./_generated/suilend/reserve-config/structs.js","./_generated/_dependencies/source/0x1":"./_generated/_dependencies/source/0x1/index.js","./_generated/_dependencies/source/0x2":"./_generated/_dependencies/source/0x2/index.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/index.js","./_generated/_dependencies/source/0x1/ascii/structs":"./_generated/_dependencies/source/0x1/ascii/structs.js","./_generated/_dependencies/source/0x1/option/structs":"./_generated/_dependencies/source/0x1/option/structs.js","./_generated/_dependencies/source/0x1/type-name/structs":"./_generated/_dependencies/source/0x1/type-name/structs.js","./_generated/_dependencies/source/0x2/bag/structs":"./_generated/_dependencies/source/0x2/bag/structs.js","./_generated/_dependencies/source/0x2/balance/structs":"./_generated/_dependencies/source/0x2/balance/structs.js","./_generated/_dependencies/source/0x2/object/structs":"./_generated/_dependencies/source/0x2/object/structs.js","./_generated/_dependencies/source/0x2/object-table/structs":"./_generated/_dependencies/source/0x2/object-table/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/i64/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/i64/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-feed/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-feed/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-identifier/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-identifier/structs.js","./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-info/structs":"./_generated/_dependencies/source/0x8d97f1cd6ac663735be08d1d2b6d02a159e711586461306ce60a2b7a6a565a9e/price-info/structs.js"},"types":"./index.js","scripts":{"build":"rm -rf ./dist && bun tsc","eslint":"eslint --fix \"./src/**/*.ts\"","prettier":"prettier --write \"./src/**/*\"","lint":"bun eslint && bun prettier && bun tsc --noEmit","release":"bun run build && bun ts-node ./release.ts && cd ./dist && npm publish --access public"},"repository":{"type":"git","url":"git+https://github.com/suilend/suilend-fe-public.git"},"bugs":{"url":"https://github.com/suilend/suilend-fe-public/issues"},"dependencies":{"@7kprotocol/sdk-ts":"^3.4.0","@cetusprotocol/aggregator-sdk":"^0.14.2","@flowx-finance/sdk":"^1.11.3","@pythnetwork/pyth-sui-js":"^2.2.0","aftermath-ts-sdk":"^1.3.14","bignumber.js":"^9.1.2","bn.js":"^5.2.2","crypto-js":"^4.2.0","p-limit":"3.1.0","uuid":"^11.0.3"},"devDependencies":{"@types/bn.js":"^5.2.0","ts-node":"^10.9.2"},"peerDependencies":{"@mysten/bcs":"1.6.0","@mysten/sui":"1.28.2","@suilend/sui-fe":"^0.3.29"}}
@@ -2,10 +2,9 @@ import { CoinMetadata } from "@mysten/sui/client";
2
2
  import BigNumber from "bignumber.js";
3
3
  import { LendingMarket } from "../_generated/suilend/lending-market/structs";
4
4
  import { Reserve } from "../_generated/suilend/reserve/structs";
5
+ import { LendingMarketMetadata } from "../lib";
5
6
  export type ParsedLendingMarket = ReturnType<typeof parseLendingMarket>;
6
- export declare const parseLendingMarket: (lendingMarket: LendingMarket<string>, reserves: Reserve<string>[], coinMetadataMap: Record<string, CoinMetadata>, nowS: number) => {
7
- id: string;
8
- type: string;
7
+ export declare const parseLendingMarket: (lendingMarket: LendingMarket<string>, reserves: Reserve<string>[], coinMetadataMap: Record<string, CoinMetadata>, nowS: number, lendingMarketMetadata?: LendingMarketMetadata) => {
9
8
  version: bigint;
10
9
  reserves: {
11
10
  config: {
@@ -133,10 +132,12 @@ export declare const parseLendingMarket: (lendingMarket: LendingMarket<string>,
133
132
  depositedAmountUsd: BigNumber;
134
133
  borrowedAmountUsd: BigNumber;
135
134
  tvlUsd: BigNumber;
135
+ id: string;
136
+ type: string;
137
+ ownerCapId: string | undefined;
136
138
  name: string;
137
139
  slug: string;
138
140
  isHidden: boolean;
139
- ownerCapId: string;
140
141
  /**
141
142
  * @deprecated since version 1.0.3. Use `depositedAmountUsd` instead.
142
143
  */
@@ -5,10 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.parseLendingMarket = void 0;
7
7
  const bignumber_js_1 = __importDefault(require("bignumber.js"));
8
- const client_1 = require("../client");
9
8
  const rateLimiter_1 = require("./rateLimiter");
10
9
  const reserve_1 = require("./reserve");
11
- const parseLendingMarket = (lendingMarket, reserves, coinMetadataMap, nowS) => {
10
+ const parseLendingMarket = (lendingMarket, reserves, coinMetadataMap, nowS, lendingMarketMetadata) => {
12
11
  var _a, _b, _c, _d;
13
12
  const id = lendingMarket.id;
14
13
  const type = lendingMarket.$typeArgs[0];
@@ -28,16 +27,7 @@ const parseLendingMarket = (lendingMarket, reserves, coinMetadataMap, nowS) => {
28
27
  borrowedAmountUsd = borrowedAmountUsd.plus(parsedReserve.borrowedAmountUsd);
29
28
  tvlUsd = tvlUsd.plus(parsedReserve.availableAmountUsd);
30
29
  });
31
- const LENDING_MARKET = client_1.LENDING_MARKETS.find((lm) => lm.id === id);
32
- if (!LENDING_MARKET)
33
- console.error(`Missing LENDING_MARKETS definition for lending market with id: ${id}`);
34
- const name = (_a = LENDING_MARKET === null || LENDING_MARKET === void 0 ? void 0 : LENDING_MARKET.name) !== null && _a !== void 0 ? _a : "Unknown";
35
- const slug = (_b = LENDING_MARKET === null || LENDING_MARKET === void 0 ? void 0 : LENDING_MARKET.slug) !== null && _b !== void 0 ? _b : "unknown";
36
- const isHidden = (_c = LENDING_MARKET === null || LENDING_MARKET === void 0 ? void 0 : LENDING_MARKET.isHidden) !== null && _c !== void 0 ? _c : false;
37
- const ownerCapId = (_d = LENDING_MARKET === null || LENDING_MARKET === void 0 ? void 0 : LENDING_MARKET.ownerCapId) !== null && _d !== void 0 ? _d : "Unknown";
38
30
  return {
39
- id,
40
- type,
41
31
  version,
42
32
  reserves: parsedReserves,
43
33
  obligations,
@@ -48,10 +38,13 @@ const parseLendingMarket = (lendingMarket, reserves, coinMetadataMap, nowS) => {
48
38
  depositedAmountUsd,
49
39
  borrowedAmountUsd,
50
40
  tvlUsd,
51
- name,
52
- slug,
53
- isHidden,
54
- ownerCapId,
41
+ // Metadata
42
+ id,
43
+ type,
44
+ ownerCapId: (_a = lendingMarketMetadata === null || lendingMarketMetadata === void 0 ? void 0 : lendingMarketMetadata.lendingMarketOwnerCapId) !== null && _a !== void 0 ? _a : undefined,
45
+ name: (_b = lendingMarketMetadata === null || lendingMarketMetadata === void 0 ? void 0 : lendingMarketMetadata.name) !== null && _b !== void 0 ? _b : type.split("::").slice(1).join(" "),
46
+ slug: (_c = lendingMarketMetadata === null || lendingMarketMetadata === void 0 ? void 0 : lendingMarketMetadata.slug) !== null && _c !== void 0 ? _c : type.split("::").slice(1).join("-").toLowerCase(),
47
+ isHidden: (_d = lendingMarketMetadata === null || lendingMarketMetadata === void 0 ? void 0 : lendingMarketMetadata.isHidden) !== null && _d !== void 0 ? _d : true,
55
48
  /**
56
49
  * @deprecated since version 1.0.3. Use `depositedAmountUsd` instead.
57
50
  */
package/swap/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- export * from "./okxDex";
2
1
  export * from "./quote";
3
2
  export * from "./transaction";
package/swap/index.js CHANGED
@@ -14,6 +14,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./okxDex"), exports);
18
17
  __exportStar(require("./quote"), exports);
19
18
  __exportStar(require("./transaction"), exports);
package/swap/quote.d.ts CHANGED
@@ -4,20 +4,17 @@ import { AggregatorQuoter as FlowXAggregatorQuoter, GetRoutesResult as FlowXGetR
4
4
  import { RouterCompleteTradeRoute as AftermathQuote, Aftermath as AftermathSdk } from "aftermath-ts-sdk";
5
5
  import BigNumber from "bignumber.js";
6
6
  import { Token } from "@suilend/sui-fe";
7
- import { OkxDexQuote } from "./okxDex";
8
7
  export declare enum QuoteProvider {
9
8
  AFTERMATH = "aftermath",
10
9
  CETUS = "cetus",
11
10
  _7K = "7k",
12
- FLOWX = "flowx",
13
- OKX_DEX = "okxDex"
11
+ FLOWX = "flowx"
14
12
  }
15
13
  export declare const QUOTE_PROVIDER_NAME_MAP: {
16
14
  aftermath: string;
17
15
  cetus: string;
18
16
  "7k": string;
19
17
  flowx: string;
20
- okxDex: string;
21
18
  };
22
19
  export type StandardizedRoutePath = {
23
20
  id: string;
@@ -67,9 +64,6 @@ export type StandardizedQuote = {
67
64
  } | {
68
65
  provider: QuoteProvider.FLOWX;
69
66
  quote: FlowXGetRoutesResult<any, any>;
70
- } | {
71
- provider: QuoteProvider.OKX_DEX;
72
- quote: OkxDexQuote;
73
67
  });
74
68
  export declare const getAggQuotes: (sdkMap: {
75
69
  [QuoteProvider.AFTERMATH]: AftermathSdk;
package/swap/quote.js CHANGED
@@ -53,21 +53,18 @@ const bignumber_js_1 = __importDefault(require("bignumber.js"));
53
53
  const bn_js_1 = __importDefault(require("bn.js"));
54
54
  const uuid_1 = require("uuid");
55
55
  const lib_1 = require("../lib");
56
- const okxDex_1 = require("./okxDex");
57
56
  var QuoteProvider;
58
57
  (function (QuoteProvider) {
59
58
  QuoteProvider["AFTERMATH"] = "aftermath";
60
59
  QuoteProvider["CETUS"] = "cetus";
61
60
  QuoteProvider["_7K"] = "7k";
62
61
  QuoteProvider["FLOWX"] = "flowx";
63
- QuoteProvider["OKX_DEX"] = "okxDex";
64
62
  })(QuoteProvider || (exports.QuoteProvider = QuoteProvider = {}));
65
63
  exports.QUOTE_PROVIDER_NAME_MAP = {
66
64
  [QuoteProvider.AFTERMATH]: "Aftermath",
67
65
  [QuoteProvider.CETUS]: "Cetus",
68
66
  [QuoteProvider._7K]: "7K",
69
67
  [QuoteProvider.FLOWX]: "FlowX",
70
- [QuoteProvider.OKX_DEX]: "OKX DEX",
71
68
  };
72
69
  const getPoolProviders = (standardizedQuote) => {
73
70
  return Array.from(new Set(standardizedQuote.routes.reduce((acc, route) => [
@@ -259,60 +256,6 @@ const getFlowXQuote = (sdk, tokenIn, tokenOut, amountIn) => __awaiter(void 0, vo
259
256
  };
260
257
  return standardizedQuote;
261
258
  });
262
- const getOkxDexQuote = (amountIn, tokenIn, tokenOut) => __awaiter(void 0, void 0, void 0, function* () {
263
- const quote = yield (0, okxDex_1.getOkxDexQuote)(amountIn, tokenIn.coinType, tokenOut.coinType);
264
- const flattenedDexRouterList = [];
265
- for (const dexRouter of quote.dexRouterList) {
266
- const indexes = [];
267
- for (const subRouter of dexRouter.subRouterList) {
268
- indexes.push(Array.from({ length: subRouter.dexProtocol.length }, (_, j) => j));
269
- }
270
- const combinations = (0, okxDex_1.cartesianProduct)(indexes);
271
- for (const combination of combinations) {
272
- const flattenedRouter = Object.assign(Object.assign({}, dexRouter), { routerPercent: "", subRouterList: dexRouter.subRouterList.map((subRouter, index) => (Object.assign(Object.assign({}, subRouter), { dexProtocol: [subRouter.dexProtocol[combination[index]]] }))) });
273
- let routerPercent = new bignumber_js_1.default(dexRouter.routerPercent);
274
- for (const subRouter of flattenedRouter.subRouterList) {
275
- const dexProtocol = subRouter.dexProtocol[0];
276
- routerPercent = routerPercent.times(new bignumber_js_1.default(dexProtocol.percent).div(100));
277
- }
278
- flattenedRouter.routerPercent = routerPercent.toString();
279
- flattenedDexRouterList.push(flattenedRouter);
280
- }
281
- }
282
- const standardizedQuote = {
283
- id: (0, uuid_1.v4)(),
284
- provider: QuoteProvider.OKX_DEX,
285
- in: {
286
- coinType: tokenIn.coinType,
287
- amount: new bignumber_js_1.default(quote.fromTokenAmount).div(10 ** tokenIn.decimals),
288
- },
289
- out: {
290
- coinType: tokenOut.coinType,
291
- amount: new bignumber_js_1.default(quote.toTokenAmount).div(10 ** tokenOut.decimals),
292
- },
293
- routes: flattenedDexRouterList.map((dexRouter, routeIndex) => {
294
- return {
295
- percent: new bignumber_js_1.default(dexRouter.routerPercent),
296
- path: dexRouter.subRouterList.map((subRouter) => ({
297
- id: (0, uuid_1.v4)(),
298
- poolId: undefined, // Missing data
299
- routeIndex,
300
- provider: subRouter.dexProtocol[0].dexName,
301
- in: {
302
- coinType: (0, utils_1.normalizeStructTag)(subRouter.fromToken.tokenContractAddress),
303
- amount: new bignumber_js_1.default(0).div(10 ** tokenIn.decimals), // Missing data
304
- },
305
- out: {
306
- coinType: (0, utils_1.normalizeStructTag)(subRouter.toToken.tokenContractAddress),
307
- amount: new bignumber_js_1.default(0).div(10 ** tokenIn.decimals), // Missing data
308
- },
309
- })),
310
- };
311
- }),
312
- quote,
313
- };
314
- return standardizedQuote;
315
- });
316
259
  const getAggQuotes = (sdkMap, activeProviders, onGetAggQuote, tokenIn, tokenOut, amountIn) => __awaiter(void 0, void 0, void 0, function* () {
317
260
  const timeoutMs = 15000;
318
261
  // Get quotes in parallel
@@ -344,13 +287,6 @@ const getAggQuotes = (sdkMap, activeProviders, onGetAggQuote, tokenIn, tokenOut,
344
287
  onGetAggQuote(standardizedQuote);
345
288
  }))();
346
289
  }
347
- // OKX DEX
348
- if (activeProviders.includes(QuoteProvider.OKX_DEX)) {
349
- (() => __awaiter(void 0, void 0, void 0, function* () {
350
- const standardizedQuote = yield getAggQuoteWrapper(QuoteProvider.OKX_DEX, () => getOkxDexQuote(amountIn, tokenIn, tokenOut), timeoutMs);
351
- onGetAggQuote(standardizedQuote);
352
- }))();
353
- }
354
290
  });
355
291
  exports.getAggQuotes = getAggQuotes;
356
292
  const getAggSortedQuotesAll = (sdkMap, activeProviders, tokenIn, tokenOut, amountIn) => __awaiter(void 0, void 0, void 0, function* () {
@@ -369,9 +305,6 @@ const getAggSortedQuotesAll = (sdkMap, activeProviders, tokenIn, tokenOut, amoun
369
305
  activeProviders.includes(QuoteProvider.FLOWX)
370
306
  ? getAggQuoteWrapper(QuoteProvider.FLOWX, () => getFlowXQuote(sdkMap[QuoteProvider.FLOWX], tokenIn, tokenOut, amountIn), timeoutMs)
371
307
  : null,
372
- activeProviders.includes(QuoteProvider.OKX_DEX)
373
- ? getAggQuoteWrapper(QuoteProvider.OKX_DEX, () => getOkxDexQuote(amountIn, tokenIn, tokenOut), timeoutMs)
374
- : null,
375
308
  ].filter(Boolean));
376
309
  const sortedQuotes = quotes.filter(Boolean)
377
310
  .slice()
@@ -47,7 +47,6 @@ const cjs_1 = require("@7kprotocol/sdk-ts/cjs");
47
47
  const sdk_1 = require("@flowx-finance/sdk");
48
48
  const Sentry = __importStar(require("@sentry/nextjs"));
49
49
  const sui_fe_1 = require("@suilend/sui-fe");
50
- const okxDex_1 = require("./okxDex");
51
50
  const quote_1 = require("./quote");
52
51
  const getSwapTransactionWrapper = (provider, getSwapTransaction) => __awaiter(void 0, void 0, void 0, function* () {
53
52
  console.log(`[getSwapTransactionWrapper] fetching transaction for ${provider} quote`);
@@ -141,12 +140,6 @@ const getSwapTransaction = (suiClient, address, quote, slippagePercent, sdkMap,
141
140
  return { transaction, coinOut: coinOut };
142
141
  }));
143
142
  }
144
- else if (quote.provider === quote_1.QuoteProvider.OKX_DEX) {
145
- return getSwapTransactionWrapper(quote_1.QuoteProvider.OKX_DEX, () => __awaiter(void 0, void 0, void 0, function* () {
146
- const transaction2 = yield (0, okxDex_1.getOkxDexSwapTransaction)(quote.quote.fromTokenAmount, quote.in.coinType, quote.out.coinType, slippagePercent, address); // Does not use `transaction` or `coinIn`
147
- return { transaction: transaction2, coinOut: undefined };
148
- }));
149
- }
150
143
  else
151
144
  throw new Error("Unknown quote type");
152
145
  });
package/swap/okxDex.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import { Transaction } from "@mysten/sui/transactions";
2
- export declare const cartesianProduct: (arrays: number[][]) => number[][];
3
- export type OkxDexQuote = {
4
- fromTokenAmount: string;
5
- toTokenAmount: string;
6
- dexRouterList: {
7
- router: string;
8
- routerPercent: string;
9
- subRouterList: {
10
- dexProtocol: {
11
- percent: string;
12
- dexName: string;
13
- }[];
14
- fromToken: {
15
- tokenContractAddress: string;
16
- };
17
- toToken: {
18
- tokenContractAddress: string;
19
- };
20
- }[];
21
- }[];
22
- };
23
- export type OkxDexSwap = {
24
- tx: {
25
- signatureData: string[];
26
- from: string;
27
- gas: string;
28
- gasPrice: string;
29
- maxPriorityFeePerGas: string;
30
- to: string;
31
- value: string;
32
- maxSpendAmount: string;
33
- minReceiveAmount: string;
34
- data: string;
35
- slippage: string;
36
- };
37
- };
38
- export declare const getOkxDexQuote: (amountIn: string, tokenInCoinType: string, tokenOutCoinType: string) => Promise<OkxDexQuote>;
39
- export declare const getOkxDexSwapTransaction: (amountIn: string, tokenInCoinType: string, tokenOutCoinType: string, slippagePercent: number, address: string) => Promise<Transaction>;
40
- export declare const getHeaders: (timestamp: string, method: string, requestPath: string, queryString: string) => {
41
- "Content-Type": string;
42
- "OK-ACCESS-KEY": string;
43
- "OK-ACCESS-SIGN": string;
44
- "OK-ACCESS-TIMESTAMP": string;
45
- "OK-ACCESS-PASSPHRASE": string;
46
- "OK-ACCESS-PROJECT": string;
47
- };
package/swap/okxDex.js DELETED
@@ -1,74 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.getHeaders = exports.getOkxDexSwapTransaction = exports.getOkxDexQuote = exports.cartesianProduct = void 0;
16
- const transactions_1 = require("@mysten/sui/transactions");
17
- const crypto_js_1 = __importDefault(require("crypto-js"));
18
- const cartesianProduct = (arrays) => {
19
- return arrays.reduce((a, b) => a.map((x) => b.map((y) => [...x, y])).reduce((a, b) => [...a, ...b], []), [[]]);
20
- };
21
- exports.cartesianProduct = cartesianProduct;
22
- const getOkxDexQuote = (amountIn, tokenInCoinType, tokenOutCoinType) => __awaiter(void 0, void 0, void 0, function* () {
23
- var _a;
24
- const res = yield fetch("/api/okx-dex/quote", {
25
- method: "POST",
26
- body: JSON.stringify({
27
- amountIn,
28
- tokenInCoinType,
29
- tokenOutCoinType,
30
- }),
31
- headers: {
32
- "Content-Type": "application/json",
33
- },
34
- });
35
- if (!res.ok)
36
- throw new Error(`Failed to get OKX DEX quote: ${(_a = (yield res.json())) === null || _a === void 0 ? void 0 : _a.error}`);
37
- const json = yield res.json();
38
- return json;
39
- });
40
- exports.getOkxDexQuote = getOkxDexQuote;
41
- const getOkxDexSwapTransaction = (amountIn, tokenInCoinType, tokenOutCoinType, slippagePercent, address) => __awaiter(void 0, void 0, void 0, function* () {
42
- var _a;
43
- const res = yield fetch("/api/okx-dex/swap", {
44
- method: "POST",
45
- body: JSON.stringify({
46
- amountIn,
47
- tokenInCoinType,
48
- tokenOutCoinType,
49
- slippagePercent,
50
- address,
51
- }),
52
- headers: {
53
- "Content-Type": "application/json",
54
- },
55
- });
56
- if (!res.ok)
57
- throw new Error(`Failed to get OKX DEX swap transaction: ${(_a = (yield res.json())) === null || _a === void 0 ? void 0 : _a.error}`);
58
- const json = yield res.json();
59
- return transactions_1.Transaction.from(json.tx.data);
60
- });
61
- exports.getOkxDexSwapTransaction = getOkxDexSwapTransaction;
62
- // Used on server-side only
63
- const getHeaders = (timestamp, method, requestPath, queryString) => {
64
- const stringToSign = `${timestamp}${method}${requestPath}${queryString}`;
65
- return {
66
- "Content-Type": "application/json",
67
- "OK-ACCESS-KEY": process.env.OKX_API_KEY,
68
- "OK-ACCESS-SIGN": crypto_js_1.default.enc.Base64.stringify(crypto_js_1.default.HmacSHA256(stringToSign, process.env.OKX_SECRET_KEY)),
69
- "OK-ACCESS-TIMESTAMP": timestamp,
70
- "OK-ACCESS-PASSPHRASE": process.env.OKX_API_PASSPHRASE,
71
- "OK-ACCESS-PROJECT": process.env.OKX_PROJECT_ID,
72
- };
73
- };
74
- exports.getHeaders = getHeaders;