@scallop-io/sui-scallop-sdk 0.46.55 → 0.46.56

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 (53) hide show
  1. package/dist/constants/common.d.ts +1 -1
  2. package/dist/constants/pyth.d.ts +1 -1
  3. package/dist/index.js +1752 -1602
  4. package/dist/index.js.map +1 -1
  5. package/dist/index.mjs +1720 -1570
  6. package/dist/index.mjs.map +1 -1
  7. package/dist/models/scallop.d.ts +1 -1
  8. package/dist/models/scallopAddress.d.ts +4 -4
  9. package/dist/models/scallopBuilder.d.ts +2 -2
  10. package/dist/models/scallopCache.d.ts +2 -2
  11. package/dist/models/scallopClient.d.ts +7 -2
  12. package/dist/models/scallopIndexer.d.ts +3 -3
  13. package/dist/models/scallopPrice.d.ts +0 -0
  14. package/dist/models/scallopQuery.d.ts +10 -4
  15. package/dist/models/scallopUtils.d.ts +8 -7
  16. package/dist/queries/borrowIncentiveQuery.d.ts +10 -4
  17. package/dist/queries/coreQuery.d.ts +8 -4
  18. package/dist/queries/priceQuery.d.ts +7 -3
  19. package/dist/queries/referralQuery.d.ts +2 -2
  20. package/dist/queries/sCoinQuery.d.ts +18 -4
  21. package/dist/queries/spoolQuery.d.ts +10 -4
  22. package/dist/queries/vescaQuery.d.ts +7 -5
  23. package/dist/types/builder/vesca.d.ts +2 -1
  24. package/dist/types/model.d.ts +27 -12
  25. package/dist/types/query/core.d.ts +1 -0
  26. package/package.json +1 -1
  27. package/src/builders/borrowIncentiveBuilder.ts +19 -21
  28. package/src/builders/coreBuilder.ts +10 -8
  29. package/src/builders/spoolBuilder.ts +2 -2
  30. package/src/builders/vescaBuilder.ts +12 -4
  31. package/src/constants/common.ts +2 -0
  32. package/src/constants/enum.ts +4 -0
  33. package/src/constants/pyth.ts +2 -2
  34. package/src/models/scallop.ts +14 -20
  35. package/src/models/scallopAddress.ts +15 -5
  36. package/src/models/scallopBuilder.ts +29 -25
  37. package/src/models/scallopCache.ts +2 -2
  38. package/src/models/scallopClient.ts +91 -32
  39. package/src/models/scallopIndexer.ts +15 -8
  40. package/src/models/scallopPrice.ts +0 -0
  41. package/src/models/scallopQuery.ts +47 -25
  42. package/src/models/scallopUtils.ts +75 -74
  43. package/src/queries/borrowIncentiveQuery.ts +40 -29
  44. package/src/queries/coreQuery.ts +38 -24
  45. package/src/queries/portfolioQuery.ts +1 -2
  46. package/src/queries/priceQuery.ts +20 -9
  47. package/src/queries/referralQuery.ts +4 -4
  48. package/src/queries/sCoinQuery.ts +95 -17
  49. package/src/queries/spoolQuery.ts +26 -14
  50. package/src/queries/vescaQuery.ts +32 -26
  51. package/src/types/builder/vesca.ts +8 -1
  52. package/src/types/model.ts +40 -11
  53. package/src/types/query/core.ts +1 -0
package/dist/index.js CHANGED
@@ -133,7 +133,9 @@ var SUPPORT_SCOIN = [
133
133
  "svsui",
134
134
  "seth",
135
135
  "ssca",
136
- "scetus"
136
+ "scetus",
137
+ "ssol",
138
+ "sbtc"
137
139
  ];
138
140
  var SUPPORT_SPOOLS_REWARDS = ["sui"];
139
141
  var SUPPORT_BORROW_INCENTIVE_POOLS = [
@@ -227,7 +229,9 @@ var sCoins = {
227
229
  safsui: "safsui",
228
230
  shasui: "shasui",
229
231
  svsui: "svsui",
230
- ssca: "ssca"
232
+ ssca: "ssca",
233
+ ssol: "ssol",
234
+ sbtc: "sbtc"
231
235
  };
232
236
  var stakeMarketCoins = {
233
237
  seth: "seth",
@@ -293,7 +297,9 @@ var sCoinIds = {
293
297
  seth: "0x67540ceb850d418679e69f1fb6b2093d6df78a2a699ffc733f7646096d552e9b::scallop_wormhole_eth::SCALLOP_WORMHOLE_ETH",
294
298
  safsui: "0x00671b1fa2a124f5be8bdae8b91ee711462c5d9e31bda232e70fd9607b523c88::scallop_af_sui::SCALLOP_AF_SUI",
295
299
  shasui: "0x9a2376943f7d22f88087c259c5889925f332ca4347e669dc37d54c2bf651af3c::scallop_ha_sui::SCALLOP_HA_SUI",
296
- svsui: "0xe1a1cc6bcf0001a015eab84bcc6713393ce20535f55b8b6f35c142e057a25fbe::scallop_v_sui::SCALLOP_V_SUI"
300
+ svsui: "0xe1a1cc6bcf0001a015eab84bcc6713393ce20535f55b8b6f35c142e057a25fbe::scallop_v_sui::SCALLOP_V_SUI",
301
+ ssol: "0x1392650f2eca9e3f6ffae3ff89e42a3590d7102b80e2b430f674730bc30d3259::scallop_wormhole_sol::SCALLOP_WORMHOLE_SOL",
302
+ sbtc: "0x2cf76a9cf5d3337961d1154283234f94da2dcff18544dfe5cbdef65f319591b5::scallop_wormhole_btc::SCALLOP_WORMHOLE_BTC"
297
303
  };
298
304
 
299
305
  // src/constants/vesca.ts
@@ -320,7 +326,10 @@ var FlashLoanFeeObjectMap = {
320
326
  };
321
327
 
322
328
  // src/models/scallop.ts
323
- var import_sui_kit14 = require("@scallop-io/sui-kit");
329
+ var import_sui_kit16 = require("@scallop-io/sui-kit");
330
+
331
+ // src/models/scallopAddress.ts
332
+ var import_sui_kit2 = require("@scallop-io/sui-kit");
324
333
 
325
334
  // src/models/scallopCache.ts
326
335
  var import_query_core = require("@tanstack/query-core");
@@ -927,7 +936,7 @@ var callWithRateLimit = async (tokenBucket, fn, retryDelayInMs = DEFAULT_INTERVA
927
936
 
928
937
  // src/models/scallopCache.ts
929
938
  var ScallopCache = class {
930
- constructor(cacheOptions, suiKit, tokenBucket) {
939
+ constructor(suiKit, cacheOptions, tokenBucket) {
931
940
  this.queryClient = new import_query_core.QueryClient(cacheOptions ?? DEFAULT_CACHE_OPTIONS);
932
941
  this._suiKit = suiKit;
933
942
  this.tokenBucket = tokenBucket ?? new TokenBucket(DEFAULT_TOKENS_PER_INTERVAL, DEFAULT_INTERVAL_IN_MS);
@@ -1917,9 +1926,12 @@ var EMPTY_ADDRESSES = {
1917
1926
  }
1918
1927
  };
1919
1928
  var ScallopAddress = class {
1920
- constructor(params, cache) {
1929
+ constructor(params, instance) {
1921
1930
  const { id, auth, network } = params;
1922
- this._cache = cache ?? new ScallopCache(DEFAULT_CACHE_OPTIONS);
1931
+ this.cache = instance?.cache ?? new ScallopCache(
1932
+ instance?.suiKit ?? new import_sui_kit2.SuiKit({}),
1933
+ DEFAULT_CACHE_OPTIONS
1934
+ );
1923
1935
  this._requestClient = import_axios.default.create({
1924
1936
  baseURL: API_BASE_URL,
1925
1937
  headers: {
@@ -2095,7 +2107,7 @@ var ScallopAddress = class {
2095
2107
  async read(id) {
2096
2108
  const addressesId = id || this._id || void 0;
2097
2109
  if (addressesId !== void 0) {
2098
- const response = await this._cache.queryClient.fetchQuery({
2110
+ const response = await this.cache.queryClient.fetchQuery({
2099
2111
  queryKey: ["api-getAddresses", addressesId],
2100
2112
  queryFn: async () => {
2101
2113
  return await this._requestClient.get(`/addresses/${addressesId}`, {
@@ -2223,16 +2235,13 @@ var ScallopAddress = class {
2223
2235
 
2224
2236
  // src/models/scallopClient.ts
2225
2237
  var import_utils25 = require("@mysten/sui.js/utils");
2226
- var import_sui_kit13 = require("@scallop-io/sui-kit");
2238
+ var import_sui_kit15 = require("@scallop-io/sui-kit");
2227
2239
 
2228
2240
  // src/models/scallopUtils.ts
2229
- var import_utils11 = require("@mysten/sui.js/utils");
2241
+ var import_utils10 = require("@mysten/sui.js/utils");
2230
2242
  var import_sui_kit4 = require("@scallop-io/sui-kit");
2231
2243
  var import_pyth_sui_js = require("@pythnetwork/pyth-sui-js");
2232
2244
 
2233
- // src/models/scallopQuery.ts
2234
- var import_sui_kit3 = require("@scallop-io/sui-kit");
2235
-
2236
2245
  // src/queries/coreQuery.ts
2237
2246
  var import_utils3 = require("@mysten/sui.js/utils");
2238
2247
  var import_bignumber2 = __toESM(require("bignumber.js"));
@@ -2300,6 +2309,9 @@ var queryMarket = async (query, indexer = false) => {
2300
2309
  symbol: query.utils.parseSymbol(poolCoinName),
2301
2310
  coinType,
2302
2311
  marketCoinType: query.utils.parseMarketCoinType(poolCoinName),
2312
+ sCoinType: query.utils.parseSCoinType(
2313
+ query.utils.parseMarketCoinName(poolCoinName)
2314
+ ),
2303
2315
  coinWrappedType: query.utils.getCoinWrappedType(poolCoinName),
2304
2316
  coinDecimal: query.utils.getCoinDecimal(poolCoinName),
2305
2317
  coinPrice,
@@ -2518,6 +2530,9 @@ var getMarketPool = async (query, poolCoinName, indexer = false, marketObject, c
2518
2530
  symbol: query.utils.parseSymbol(poolCoinName),
2519
2531
  coinType: query.utils.parseCoinType(poolCoinName),
2520
2532
  marketCoinType: query.utils.parseMarketCoinType(poolCoinName),
2533
+ sCoinType: query.utils.parseSCoinType(
2534
+ query.utils.parseMarketCoinName(poolCoinName)
2535
+ ),
2521
2536
  coinWrappedType: query.utils.getCoinWrappedType(poolCoinName),
2522
2537
  coinDecimal: query.utils.getCoinDecimal(poolCoinName),
2523
2538
  coinPrice: coinPrice ?? 0,
@@ -2662,14 +2677,16 @@ var getMarketCollateral = async (query, collateralCoinName, indexer = false, mar
2662
2677
  }
2663
2678
  return marketCollateral;
2664
2679
  };
2665
- var getObligations = async (query, ownerAddress) => {
2666
- const owner = ownerAddress || query.suiKit.currentAddress();
2667
- const protocolObjectId = query.address.get("core.object") || PROTOCOL_OBJECT_ID;
2680
+ var getObligations = async ({
2681
+ address
2682
+ }, ownerAddress) => {
2683
+ const owner = ownerAddress;
2684
+ const protocolObjectId = address.get("core.object") || PROTOCOL_OBJECT_ID;
2668
2685
  const keyObjectsResponse = [];
2669
2686
  let hasNextPage = false;
2670
2687
  let nextCursor = null;
2671
2688
  do {
2672
- const paginatedKeyObjectsResponse = await query.cache.queryGetOwnedObjects({
2689
+ const paginatedKeyObjectsResponse = await address.cache.queryGetOwnedObjects({
2673
2690
  owner,
2674
2691
  filter: {
2675
2692
  StructType: `${protocolObjectId}::obligation::ObligationKey`
@@ -2677,7 +2694,7 @@ var getObligations = async (query, ownerAddress) => {
2677
2694
  cursor: nextCursor
2678
2695
  });
2679
2696
  if (!paginatedKeyObjectsResponse)
2680
- continue;
2697
+ break;
2681
2698
  keyObjectsResponse.push(...paginatedKeyObjectsResponse.data);
2682
2699
  if (paginatedKeyObjectsResponse.hasNextPage && paginatedKeyObjectsResponse.nextCursor) {
2683
2700
  hasNextPage = true;
@@ -2687,7 +2704,7 @@ var getObligations = async (query, ownerAddress) => {
2687
2704
  }
2688
2705
  } while (hasNextPage);
2689
2706
  const keyObjectIds = keyObjectsResponse.map((ref) => ref?.data?.objectId).filter((id) => id !== void 0);
2690
- const keyObjects = await query.cache.queryGetObjects(keyObjectIds);
2707
+ const keyObjects = await address.cache.queryGetObjects(keyObjectIds);
2691
2708
  const obligations = [];
2692
2709
  await Promise.allSettled(
2693
2710
  keyObjects.map(async (keyObject) => {
@@ -2695,18 +2712,17 @@ var getObligations = async (query, ownerAddress) => {
2695
2712
  if (keyObject.content && "fields" in keyObject.content) {
2696
2713
  const fields = keyObject.content.fields;
2697
2714
  const obligationId = String(fields.ownership.fields.of);
2698
- const locked = await getObligationLocked(query, obligationId);
2715
+ const locked = await getObligationLocked(address.cache, obligationId);
2699
2716
  obligations.push({ id: obligationId, keyId, locked });
2700
2717
  }
2701
2718
  })
2702
2719
  );
2703
2720
  return obligations;
2704
2721
  };
2705
- var getObligationLocked = async (query, obligationId) => {
2706
- const obligationObjectResponse = await query.cache.queryGetObject(
2707
- obligationId,
2708
- { showContent: true }
2709
- );
2722
+ var getObligationLocked = async (cache, obligationId) => {
2723
+ const obligationObjectResponse = await cache.queryGetObject(obligationId, {
2724
+ showContent: true
2725
+ });
2710
2726
  let obligationLocked = false;
2711
2727
  if (obligationObjectResponse?.data && obligationObjectResponse?.data?.content?.dataType === "moveObject" && "lock_key" in obligationObjectResponse.data.content.fields) {
2712
2728
  obligationLocked = Boolean(
@@ -2715,11 +2731,13 @@ var getObligationLocked = async (query, obligationId) => {
2715
2731
  }
2716
2732
  return obligationLocked;
2717
2733
  };
2718
- var queryObligation = async (query, obligationId) => {
2719
- const packageId = query.address.get("core.packages.query.id");
2734
+ var queryObligation = async ({
2735
+ address
2736
+ }, obligationId) => {
2737
+ const packageId = address.get("core.packages.query.id");
2720
2738
  const queryTarget = `${packageId}::obligation_query::obligation_data`;
2721
2739
  const args = [obligationId];
2722
- const queryResult = await query.cache.queryInspectTxn(
2740
+ const queryResult = await address.cache.queryInspectTxn(
2723
2741
  { queryTarget, args }
2724
2742
  // txBlock
2725
2743
  );
@@ -2973,15 +2991,17 @@ var getSpool = async (query, marketCoinName, indexer = false, marketPool, coinPr
2973
2991
  }
2974
2992
  return spool;
2975
2993
  };
2976
- var getStakeAccounts = async (query, ownerAddress) => {
2977
- const owner = ownerAddress || query.suiKit.currentAddress();
2978
- const spoolObjectId = query.address.get("spool.object");
2994
+ var getStakeAccounts = async ({
2995
+ utils
2996
+ }, ownerAddress) => {
2997
+ const owner = ownerAddress || utils.suiKit.currentAddress();
2998
+ const spoolObjectId = utils.address.get("spool.object");
2979
2999
  const stakeAccountType = `${spoolObjectId}::spool_account::SpoolAccount`;
2980
3000
  const stakeObjectsResponse = [];
2981
3001
  let hasNextPage = false;
2982
3002
  let nextCursor = null;
2983
3003
  do {
2984
- const paginatedStakeObjectsResponse = await query.cache.queryGetOwnedObjects({
3004
+ const paginatedStakeObjectsResponse = await utils.cache.queryGetOwnedObjects({
2985
3005
  owner,
2986
3006
  filter: { StructType: stakeAccountType },
2987
3007
  options: {
@@ -3013,15 +3033,15 @@ var getStakeAccounts = async (query, ownerAddress) => {
3013
3033
  };
3014
3034
  const stakeMarketCoinTypes = Object.keys(stakeAccounts).reduce(
3015
3035
  (types, stakeMarketCoinName) => {
3016
- const stakeCoinName = query.utils.parseCoinName(stakeMarketCoinName);
3017
- const marketCoinType = query.utils.parseMarketCoinType(stakeCoinName);
3036
+ const stakeCoinName = utils.parseCoinName(stakeMarketCoinName);
3037
+ const marketCoinType = utils.parseMarketCoinType(stakeCoinName);
3018
3038
  types[stakeMarketCoinName] = `${spoolObjectId}::spool_account::SpoolAccount<${marketCoinType}>`;
3019
3039
  return types;
3020
3040
  },
3021
3041
  {}
3022
3042
  );
3023
3043
  const stakeObjectIds = stakeObjectsResponse.map((ref) => ref?.data?.objectId).filter((id) => id !== void 0);
3024
- const stakeObjects = await query.cache.queryGetObjects(stakeObjectIds);
3044
+ const stakeObjects = await utils.cache.queryGetObjects(stakeObjectIds);
3025
3045
  for (const stakeObject of stakeObjects) {
3026
3046
  const id = stakeObject.objectId;
3027
3047
  const type = stakeObject.type;
@@ -3126,10 +3146,12 @@ var getStakeAccounts = async (query, ownerAddress) => {
3126
3146
  }
3127
3147
  return stakeAccounts;
3128
3148
  };
3129
- var getStakePool = async (query, marketCoinName) => {
3130
- const poolId = query.address.get(`spool.pools.${marketCoinName}.id`);
3149
+ var getStakePool = async ({
3150
+ utils
3151
+ }, marketCoinName) => {
3152
+ const poolId = utils.address.get(`spool.pools.${marketCoinName}.id`);
3131
3153
  let stakePool = void 0;
3132
- const stakePoolObjectResponse = await query.cache.queryGetObject(poolId, {
3154
+ const stakePoolObjectResponse = await utils.cache.queryGetObject(poolId, {
3133
3155
  showContent: true,
3134
3156
  showType: true
3135
3157
  });
@@ -3167,12 +3189,14 @@ var getStakePool = async (query, marketCoinName) => {
3167
3189
  }
3168
3190
  return stakePool;
3169
3191
  };
3170
- var getStakeRewardPool = async (query, marketCoinName) => {
3171
- const poolId = query.address.get(
3192
+ var getStakeRewardPool = async ({
3193
+ utils
3194
+ }, marketCoinName) => {
3195
+ const poolId = utils.address.get(
3172
3196
  `spool.pools.${marketCoinName}.rewardPoolId`
3173
3197
  );
3174
3198
  let stakeRewardPool = void 0;
3175
- const stakeRewardPoolObjectResponse = await query.cache.queryGetObject(
3199
+ const stakeRewardPoolObjectResponse = await utils.cache.queryGetObject(
3176
3200
  poolId,
3177
3201
  {
3178
3202
  showContent: true,
@@ -3300,24 +3324,26 @@ var queryBorrowIncentivePools = async (query, borrowIncentiveCoinNames, indexer
3300
3324
  }
3301
3325
  return borrowIncentivePools;
3302
3326
  };
3303
- var queryBorrowIncentiveAccounts = async (query, obligationId, borrowIncentiveCoinNames) => {
3327
+ var queryBorrowIncentiveAccounts = async ({
3328
+ utils
3329
+ }, obligationId, borrowIncentiveCoinNames) => {
3304
3330
  borrowIncentiveCoinNames = borrowIncentiveCoinNames || [
3305
3331
  ...SUPPORT_BORROW_INCENTIVE_POOLS
3306
3332
  ];
3307
- const queryPkgId = query.address.get("borrowIncentive.query");
3308
- const incentiveAccountsId = query.address.get(
3333
+ const queryPkgId = utils.address.get("borrowIncentive.query");
3334
+ const incentiveAccountsId = utils.address.get(
3309
3335
  "borrowIncentive.incentiveAccounts"
3310
3336
  );
3311
3337
  const queryTarget = `${queryPkgId}::incentive_account_query::incentive_account_data`;
3312
3338
  const args = [incentiveAccountsId, obligationId];
3313
- const queryResult = await query.cache.queryInspectTxn({ queryTarget, args });
3339
+ const queryResult = await utils.cache.queryInspectTxn({ queryTarget, args });
3314
3340
  const borrowIncentiveAccountsQueryData = queryResult?.events[0].parsedJson;
3315
3341
  const borrowIncentiveAccounts = Object.values(
3316
3342
  borrowIncentiveAccountsQueryData?.pool_records ?? []
3317
3343
  ).reduce((accounts, accountData) => {
3318
3344
  const parsedBorrowIncentiveAccount = parseOriginBorrowIncentiveAccountData(accountData);
3319
3345
  const poolType = parsedBorrowIncentiveAccount.poolType;
3320
- const coinName = query.utils.parseCoinNameFromType(poolType);
3346
+ const coinName = utils.parseCoinNameFromType(poolType);
3321
3347
  if (borrowIncentiveCoinNames && borrowIncentiveCoinNames.includes(coinName)) {
3322
3348
  accounts[coinName] = parsedBorrowIncentiveAccount;
3323
3349
  }
@@ -3325,11 +3351,13 @@ var queryBorrowIncentiveAccounts = async (query, obligationId, borrowIncentiveCo
3325
3351
  }, {});
3326
3352
  return borrowIncentiveAccounts;
3327
3353
  };
3328
- var getBindedObligationId = async (query, veScaKeyId) => {
3329
- const borrowIncentiveObjectId = query.address.get("borrowIncentive.object");
3330
- const incentivePoolsId = query.address.get("borrowIncentive.incentivePools");
3331
- const veScaObjId = query.address.get("vesca.object");
3332
- const incentivePoolsResponse = await query.cache.queryGetObject(
3354
+ var getBindedObligationId = async ({
3355
+ address
3356
+ }, veScaKeyId) => {
3357
+ const borrowIncentiveObjectId = address.get("borrowIncentive.object");
3358
+ const incentivePoolsId = address.get("borrowIncentive.incentivePools");
3359
+ const veScaObjId = address.get("vesca.object");
3360
+ const incentivePoolsResponse = await address.cache.queryGetObject(
3333
3361
  incentivePoolsId,
3334
3362
  {
3335
3363
  showContent: true
@@ -3340,26 +3368,28 @@ var getBindedObligationId = async (query, veScaKeyId) => {
3340
3368
  const incentivePoolFields = incentivePoolsResponse.data.content.fields;
3341
3369
  const veScaBindTableId = incentivePoolFields.ve_sca_bind.fields.id.id;
3342
3370
  const keyType = `${borrowIncentiveObjectId}::typed_id::TypedID<${veScaObjId}::ve_sca::VeScaKey>`;
3343
- const veScaBindTableResponse = await query.cache.queryGetDynamicFieldObject({
3344
- parentId: veScaBindTableId,
3345
- name: {
3346
- type: keyType,
3347
- value: veScaKeyId
3371
+ const veScaBindTableResponse = await address.cache.queryGetDynamicFieldObject(
3372
+ {
3373
+ parentId: veScaBindTableId,
3374
+ name: {
3375
+ type: keyType,
3376
+ value: veScaKeyId
3377
+ }
3348
3378
  }
3349
- });
3379
+ );
3350
3380
  if (veScaBindTableResponse?.data?.content?.dataType !== "moveObject")
3351
3381
  return null;
3352
3382
  const veScaBindTableFields = veScaBindTableResponse.data.content.fields;
3353
3383
  const obligationId = veScaBindTableFields.value.fields.id;
3354
3384
  return obligationId;
3355
3385
  };
3356
- var getBindedVeScaKey = async (query, obliationId) => {
3357
- const borrowIncentiveObjectId = query.address.get("borrowIncentive.object");
3358
- const incentiveAccountsId = query.address.get(
3359
- "borrowIncentive.incentiveAccounts"
3360
- );
3361
- const corePkg = query.address.get("core.object");
3362
- const incentiveAccountsObject = await query.cache.queryGetObject(
3386
+ var getBindedVeScaKey = async ({
3387
+ address
3388
+ }, obliationId) => {
3389
+ const borrowIncentiveObjectId = address.get("borrowIncentive.object");
3390
+ const incentiveAccountsId = address.get("borrowIncentive.incentiveAccounts");
3391
+ const corePkg = address.get("core.object");
3392
+ const incentiveAccountsObject = await address.cache.queryGetObject(
3363
3393
  incentiveAccountsId,
3364
3394
  {
3365
3395
  showContent: true
@@ -3368,7 +3398,7 @@ var getBindedVeScaKey = async (query, obliationId) => {
3368
3398
  if (incentiveAccountsObject?.data?.content?.dataType !== "moveObject")
3369
3399
  return null;
3370
3400
  const incentiveAccountsTableId = incentiveAccountsObject.data.content.fields.accounts.fields.id.id;
3371
- const bindedIncentiveAcc = await query.cache.queryGetDynamicFieldObject({
3401
+ const bindedIncentiveAcc = await address.cache.queryGetDynamicFieldObject({
3372
3402
  parentId: incentiveAccountsTableId,
3373
3403
  name: {
3374
3404
  type: `${borrowIncentiveObjectId}::typed_id::TypedID<${corePkg}::obligation::Obligation>`,
@@ -3382,11 +3412,15 @@ var getBindedVeScaKey = async (query, obliationId) => {
3382
3412
  };
3383
3413
 
3384
3414
  // src/queries/priceQuery.ts
3385
- var getPythPrice = async (query, assetCoinName, priceFeedObject) => {
3386
- const pythFeedObjectId = query.address.get(
3415
+ var getPythPrice = async ({
3416
+ address
3417
+ }, assetCoinName, priceFeedObject) => {
3418
+ const pythFeedObjectId = address.get(
3387
3419
  `core.coins.${assetCoinName}.oracle.pyth.feedObject`
3388
3420
  );
3389
- priceFeedObject = priceFeedObject || (await query.cache.queryGetObject(pythFeedObjectId, { showContent: true }))?.data;
3421
+ priceFeedObject = priceFeedObject || (await address.cache.queryGetObject(pythFeedObjectId, {
3422
+ showContent: true
3423
+ }))?.data;
3390
3424
  if (priceFeedObject) {
3391
3425
  const priceFeedPoolObject = priceFeedObject;
3392
3426
  if (priceFeedPoolObject.content && "fields" in priceFeedPoolObject.content) {
@@ -3408,10 +3442,12 @@ var getPythPrice = async (query, assetCoinName, priceFeedObject) => {
3408
3442
  }
3409
3443
  return 0;
3410
3444
  };
3411
- var getPythPrices = async (query, assetCoinNames) => {
3445
+ var getPythPrices = async ({
3446
+ address
3447
+ }, assetCoinNames) => {
3412
3448
  const pythPriceFeedIds = assetCoinNames.reduce(
3413
3449
  (prev, assetCoinName) => {
3414
- const pythPriceFeed = query.address.get(
3450
+ const pythPriceFeed = address.get(
3415
3451
  `core.coins.${assetCoinName}.oracle.pyth.feedObject`
3416
3452
  );
3417
3453
  if (!prev[pythPriceFeed]) {
@@ -3423,7 +3459,7 @@ var getPythPrices = async (query, assetCoinNames) => {
3423
3459
  },
3424
3460
  {}
3425
3461
  );
3426
- const priceFeedObjects = await query.cache.queryGetObjects(
3462
+ const priceFeedObjects = await address.cache.queryGetObjects(
3427
3463
  Object.keys(pythPriceFeedIds),
3428
3464
  { showContent: true }
3429
3465
  );
@@ -3441,7 +3477,7 @@ var getPythPrices = async (query, assetCoinNames) => {
3441
3477
  async ([assetCoinName, priceFeedObject]) => ({
3442
3478
  coinName: assetCoinName,
3443
3479
  price: await getPythPrice(
3444
- query,
3480
+ { address },
3445
3481
  assetCoinName,
3446
3482
  priceFeedObject
3447
3483
  )
@@ -3458,8 +3494,7 @@ var getPythPrices = async (query, assetCoinNames) => {
3458
3494
 
3459
3495
  // src/queries/portfolioQuery.ts
3460
3496
  var import_bignumber4 = __toESM(require("bignumber.js"));
3461
- var getLendings = async (query, poolCoinNames, ownerAddress, indexer = false) => {
3462
- poolCoinNames = poolCoinNames || [...SUPPORT_POOLS];
3497
+ var getLendings = async (query, poolCoinNames = [...SUPPORT_POOLS], ownerAddress, indexer = false) => {
3463
3498
  const marketCoinNames = poolCoinNames.map(
3464
3499
  (poolCoinName) => query.utils.parseMarketCoinName(poolCoinName)
3465
3500
  );
@@ -3976,18 +4011,18 @@ var getTotalValueLocked = async (query, indexer = false) => {
3976
4011
 
3977
4012
  // src/queries/vescaQuery.ts
3978
4013
  var import_bignumber5 = __toESM(require("bignumber.js"));
3979
- var import_sui_kit2 = require("@scallop-io/sui-kit");
4014
+ var import_sui_kit3 = require("@scallop-io/sui-kit");
3980
4015
  var import_bcs = require("@mysten/sui.js/bcs");
3981
4016
  var import_zod = require("zod");
3982
- var getVescaKeys = async (query, ownerAddress) => {
3983
- const owner = ownerAddress || query.suiKit.currentAddress();
3984
- const veScaObjId = query.address.get("vesca.object");
4017
+ var getVescaKeys = async (utils, ownerAddress) => {
4018
+ const owner = ownerAddress || utils.suiKit.currentAddress();
4019
+ const veScaObjId = utils.address.get("vesca.object");
3985
4020
  const veScaKeyType = `${veScaObjId}::ve_sca::VeScaKey`;
3986
4021
  const keyObjectsResponse = [];
3987
4022
  let hasNextPage = false;
3988
4023
  let nextCursor = null;
3989
4024
  do {
3990
- const paginatedKeyObjectsResponse = await query.cache.queryGetOwnedObjects({
4025
+ const paginatedKeyObjectsResponse = await utils.cache.queryGetOwnedObjects({
3991
4026
  owner,
3992
4027
  filter: {
3993
4028
  StructType: veScaKeyType
@@ -4007,11 +4042,13 @@ var getVescaKeys = async (query, ownerAddress) => {
4007
4042
  const keyObjectDatas = keyObjectsResponse.map((objResponse) => objResponse.data).filter((data) => !!data);
4008
4043
  return keyObjectDatas;
4009
4044
  };
4010
- var getVeScas = async (query, ownerAddress) => {
4011
- const keyObjectDatas = await getVescaKeys(query, ownerAddress);
4045
+ var getVeScas = async ({
4046
+ utils
4047
+ }, ownerAddress) => {
4048
+ const keyObjectDatas = await getVescaKeys(utils, ownerAddress);
4012
4049
  const veScas = Array(keyObjectDatas.length).fill(null);
4013
4050
  const tasks = keyObjectDatas.map(async (veScaKey, idx) => {
4014
- const veSca = await getVeSca(query, veScaKey);
4051
+ const veSca = await getVeSca(utils, veScaKey);
4015
4052
  if (veSca) {
4016
4053
  veScas[idx] = veSca;
4017
4054
  }
@@ -4024,16 +4061,16 @@ var SuiObjectRefZod = import_zod.z.object({
4024
4061
  digest: import_zod.z.string(),
4025
4062
  version: import_zod.z.string()
4026
4063
  });
4027
- var getVeSca = async (query, veScaKey, ownerAddress) => {
4028
- const tableId = query.address.get(`vesca.tableId`);
4029
- veScaKey = veScaKey || (await getVescaKeys(query, ownerAddress))[0];
4064
+ var getVeSca = async (utils, veScaKey, ownerAddress) => {
4065
+ const tableId = utils.address.get(`vesca.tableId`);
4066
+ veScaKey = veScaKey || (await getVescaKeys(utils, ownerAddress))[0];
4030
4067
  if (!veScaKey)
4031
4068
  return void 0;
4032
4069
  if (typeof veScaKey === "object") {
4033
4070
  veScaKey = SuiObjectRefZod.parse(veScaKey);
4034
4071
  }
4035
4072
  let vesca = void 0;
4036
- const veScaDynamicFieldObjectResponse = await query.cache.queryGetDynamicFieldObject({
4073
+ const veScaDynamicFieldObjectResponse = await utils.cache.queryGetDynamicFieldObject({
4037
4074
  parentId: tableId,
4038
4075
  name: {
4039
4076
  type: "0x2::object::ID",
@@ -4065,18 +4102,18 @@ var getVeSca = async (query, veScaKey, ownerAddress) => {
4065
4102
  }
4066
4103
  return vesca;
4067
4104
  };
4068
- var getTotalVeScaTreasuryAmount = async (query, veScaTreasury) => {
4069
- const veScaPkgId = query.address.get("vesca.id");
4070
- const veScaConfig = query.address.get("vesca.config");
4071
- veScaTreasury = veScaTreasury ?? query.address.get("vesca.treasury");
4105
+ var getTotalVeScaTreasuryAmount = async (utils, veScaTreasury) => {
4106
+ const veScaPkgId = utils.address.get("vesca.id");
4107
+ const veScaConfig = utils.address.get("vesca.config");
4108
+ veScaTreasury = veScaTreasury ?? utils.address.get("vesca.treasury");
4072
4109
  const refreshQueryTarget = `${veScaPkgId}::treasury::refresh`;
4073
- const refreshArgs = [veScaConfig, veScaTreasury, import_sui_kit2.SUI_CLOCK_OBJECT_ID];
4110
+ const refreshArgs = [veScaConfig, veScaTreasury, import_sui_kit3.SUI_CLOCK_OBJECT_ID];
4074
4111
  const veScaAmountQueryTarget = `${veScaPkgId}::treasury::total_ve_sca_amount`;
4075
- const veScaAmountArgs = [veScaTreasury, import_sui_kit2.SUI_CLOCK_OBJECT_ID];
4112
+ const veScaAmountArgs = [veScaTreasury, import_sui_kit3.SUI_CLOCK_OBJECT_ID];
4076
4113
  const resolvedRefreshArgs = await Promise.all(
4077
4114
  refreshArgs.map(async (arg) => {
4078
4115
  if (typeof arg === "string") {
4079
- return (await query.cache.queryGetObject(arg, { showContent: true }))?.data;
4116
+ return (await utils.cache.queryGetObject(arg, { showContent: true }))?.data;
4080
4117
  }
4081
4118
  return arg;
4082
4119
  })
@@ -4084,26 +4121,25 @@ var getTotalVeScaTreasuryAmount = async (query, veScaTreasury) => {
4084
4121
  const resolvedVeScaAmountArgs = await Promise.all(
4085
4122
  veScaAmountArgs.map(async (arg) => {
4086
4123
  if (typeof arg === "string") {
4087
- return (await query.cache.queryGetObject(arg, { showContent: true }))?.data;
4124
+ return (await utils.cache.queryGetObject(arg, { showContent: true }))?.data;
4088
4125
  }
4089
4126
  return arg;
4090
4127
  })
4091
4128
  );
4092
- const txb = new import_sui_kit2.SuiTxBlock();
4129
+ const txb = new import_sui_kit3.SuiTxBlock();
4093
4130
  txb.moveCall(refreshQueryTarget, resolvedRefreshArgs);
4094
4131
  txb.moveCall(veScaAmountQueryTarget, resolvedVeScaAmountArgs);
4095
4132
  const txBytes = await txb.txBlock.build({
4096
- client: query.suiKit.client(),
4097
- onlyTransactionKind: true,
4098
- protocolConfig: await query.cache.getProtocolConfig() ?? void 0
4133
+ client: utils.suiKit.client(),
4134
+ onlyTransactionKind: true
4099
4135
  });
4100
- const res = await query.cache.queryClient.fetchQuery({
4136
+ const res = await utils.cache.queryClient.fetchQuery({
4101
4137
  queryKey: [
4102
4138
  "getTotalVeScaTreasuryAmount",
4103
4139
  JSON.stringify([...refreshArgs, ...veScaAmountArgs])
4104
4140
  ],
4105
4141
  queryFn: async () => {
4106
- return await query.suiKit.inspectTxn(txBytes);
4142
+ return await utils.suiKit.inspectTxn(txBytes);
4107
4143
  }
4108
4144
  });
4109
4145
  const results = res.results;
@@ -4114,9 +4150,9 @@ var getTotalVeScaTreasuryAmount = async (query, veScaTreasury) => {
4114
4150
  }
4115
4151
  return "0";
4116
4152
  };
4117
- var getVeScaTreasuryInfo = async (query) => {
4118
- const veScaTreasuryId = query.address.get("vesca.treasury");
4119
- const veScaTreasury = await query.cache.queryGetObject(veScaTreasuryId, {
4153
+ var getVeScaTreasuryInfo = async (utils) => {
4154
+ const veScaTreasuryId = utils.address.get("vesca.treasury");
4155
+ const veScaTreasury = await utils.cache.queryGetObject(veScaTreasuryId, {
4120
4156
  showContent: true
4121
4157
  });
4122
4158
  if (!veScaTreasury || veScaTreasury.data?.content?.dataType !== "moveObject")
@@ -4126,7 +4162,7 @@ var getVeScaTreasuryInfo = async (query) => {
4126
4162
  treasuryFields.unlock_schedule.fields.locked_sca_amount
4127
4163
  ).shiftedBy(-9).toNumber();
4128
4164
  const totalVeSca = (0, import_bignumber5.default)(
4129
- await getTotalVeScaTreasuryAmount(query, veScaTreasury.data) ?? 0
4165
+ await getTotalVeScaTreasuryAmount(utils, veScaTreasury.data) ?? 0
4130
4166
  ).shiftedBy(-9).toNumber();
4131
4167
  const averageLockingPeriod = totalLockedSca > 0 ? totalVeSca / totalLockedSca * 4 : 0;
4132
4168
  const averageLockingPeriodUnit = "year";
@@ -4139,9 +4175,9 @@ var getVeScaTreasuryInfo = async (query) => {
4139
4175
  };
4140
4176
 
4141
4177
  // src/queries/referralQuery.ts
4142
- var queryVeScaKeyIdFromReferralBindings = async (query, refereeAddress) => {
4143
- const referralBindingTableId = query.address.get("referral.bindingTableId");
4144
- const referralBindResponse = await query.cache.queryGetDynamicFieldObject({
4178
+ var queryVeScaKeyIdFromReferralBindings = async (address, refereeAddress) => {
4179
+ const referralBindingTableId = address.get("referral.bindingTableId");
4180
+ const referralBindResponse = await address.cache.queryGetDynamicFieldObject({
4145
4181
  parentId: referralBindingTableId,
4146
4182
  name: {
4147
4183
  type: "address",
@@ -4205,1257 +4241,588 @@ var getLoyaltyProgramInformations = async (query, veScaKey) => {
4205
4241
  return result;
4206
4242
  };
4207
4243
 
4208
- // src/models/scallopIndexer.ts
4209
- var import_axios2 = __toESM(require("axios"));
4210
- var ScallopIndexer = class {
4244
+ // src/constants/pyth.ts
4245
+ var PYTH_ENDPOINTS = {
4246
+ testnet: ["https://hermes-beta.pyth.network"],
4247
+ mainnet: ["https://hermes.pyth.network", "https://scallop.rpc.p2p.world"]
4248
+ };
4249
+
4250
+ // src/models/scallopUtils.ts
4251
+ var ScallopUtils = class {
4211
4252
  constructor(params, instance) {
4212
- this.params = params;
4213
- this._cache = instance?.cache ?? new ScallopCache();
4214
- this._requestClient = import_axios2.default.create({
4215
- baseURL: SDK_API_BASE_URL,
4216
- headers: {
4217
- "Content-Type": "application/json",
4218
- Accept: "application/json"
4219
- },
4220
- timeout: 3e4
4221
- });
4253
+ this._priceMap = /* @__PURE__ */ new Map();
4254
+ /**
4255
+ * Get reward type of spool.
4256
+ *
4257
+ * @param stakeMarketCoinName - Support stake market coin.
4258
+ * @return Spool reward coin name.
4259
+ */
4260
+ this.getSpoolRewardCoinName = (stakeMarketCoinName) => {
4261
+ return spoolRewardCoins[stakeMarketCoinName];
4262
+ };
4263
+ /**
4264
+ * Get reward type of borrow incentive pool.
4265
+ *
4266
+ * @param borrowIncentiveCoinName - Support borrow incentive coin.
4267
+ * @return Borrow incentive reward coin name.
4268
+ */
4269
+ this.getBorrowIncentiveRewardCoinName = (borrowIncentiveCoinName) => {
4270
+ return borrowIncentiveRewardCoins[borrowIncentiveCoinName];
4271
+ };
4272
+ this.params = {
4273
+ pythEndpoints: params.pythEndpoints ?? PYTH_ENDPOINTS["mainnet"],
4274
+ ...params
4275
+ };
4276
+ this.suiKit = instance?.suiKit ?? instance?.address?.cache._suiKit ?? new import_sui_kit4.SuiKit(params);
4277
+ if (instance?.address) {
4278
+ this.address = instance.address;
4279
+ this.cache = this.address.cache;
4280
+ this.suiKit = this.address.cache._suiKit;
4281
+ } else {
4282
+ this.cache = new ScallopCache(this.suiKit, DEFAULT_CACHE_OPTIONS);
4283
+ this.address = instance?.address ?? new ScallopAddress(
4284
+ {
4285
+ id: params?.addressesId || ADDRESSES_ID,
4286
+ network: params?.networkType
4287
+ },
4288
+ {
4289
+ cache: this.cache
4290
+ }
4291
+ );
4292
+ }
4293
+ this.isTestnet = params.networkType ? params.networkType === "testnet" : false;
4222
4294
  }
4223
4295
  /**
4224
- * Get market index data.
4296
+ * Request the scallop API to initialize data.
4225
4297
  *
4226
- * @return Market data.
4298
+ * @param force - Whether to force initialization.
4299
+ * @param address - ScallopAddress instance.
4227
4300
  */
4228
- async getMarket() {
4229
- const response = await this._cache.queryClient.fetchQuery({
4230
- queryKey: ["market"],
4231
- queryFn: async () => {
4232
- return await this._requestClient.get(`/api/market`);
4233
- }
4234
- });
4235
- if (response.status === 200) {
4236
- return {
4237
- pools: response.data.pools.reduce((marketPools, marketPool) => {
4238
- marketPools[marketPool.coinName] = marketPool;
4239
- return marketPools;
4240
- }, {}),
4241
- collaterals: response.data.collaterals.reduce(
4242
- (marketCollaterals, marketCollateral) => {
4243
- marketCollaterals[marketCollateral.coinName] = marketCollateral;
4244
- return marketCollaterals;
4245
- },
4246
- {}
4247
- )
4248
- };
4301
+ async init(force = false, address) {
4302
+ if (force || !this.address.getAddresses() || !address?.getAddresses()) {
4303
+ await this.address.read();
4249
4304
  } else {
4250
- throw Error("Failed to getMarket.");
4305
+ this.address = address;
4251
4306
  }
4252
4307
  }
4253
4308
  /**
4254
- * Get market pools index data.
4309
+ * Convert coin name to symbol.
4255
4310
  *
4256
- * @return Market pools data.
4311
+ * @param coinName - Specific support coin name.
4312
+ * @return Symbol string.
4257
4313
  */
4258
- async getMarketPools() {
4259
- const response = (await this.getMarket()).pools;
4260
- return response;
4314
+ parseSymbol(coinName) {
4315
+ if (isMarketCoin(coinName)) {
4316
+ const assetCoinName = coinName.slice(1).toLowerCase();
4317
+ return coinName.slice(0, 1).toLowerCase() + parseAssetSymbol(assetCoinName);
4318
+ } else {
4319
+ return parseAssetSymbol(coinName);
4320
+ }
4261
4321
  }
4262
4322
  /**
4263
- * Get market pool index data.
4323
+ * Convert coin name to coin type.
4264
4324
  *
4265
- * @return Market pool data.
4325
+ * @description
4326
+ * The Coin type of wormhole is fixed `coin:Coin`. Here using package id
4327
+ * to determine and return the type.
4328
+ *
4329
+ * @param coinPackageId - Package id of coin.
4330
+ * @param coinName - Specific support coin name.
4331
+ * @return Coin type.
4266
4332
  */
4267
- async getMarketPool(poolCoinName) {
4268
- return (await this.getMarketPools())[poolCoinName];
4333
+ parseCoinType(coinName) {
4334
+ coinName = isMarketCoin(coinName) ? this.parseCoinName(coinName) : coinName;
4335
+ const coinPackageId = this.address.get(`core.coins.${coinName}.id`) || coinIds[coinName] || void 0;
4336
+ if (!coinPackageId) {
4337
+ throw Error(`Coin ${coinName} is not supported`);
4338
+ }
4339
+ if (coinName === "sui")
4340
+ return (0, import_utils10.normalizeStructTag)(`${coinPackageId}::sui::SUI`);
4341
+ const wormHolePackageIds = [
4342
+ this.address.get("core.coins.usdc.id") ?? wormholeCoinIds.usdc,
4343
+ this.address.get("core.coins.usdt.id") ?? wormholeCoinIds.usdt,
4344
+ this.address.get("core.coins.eth.id") ?? wormholeCoinIds.eth,
4345
+ this.address.get("core.coins.btc.id") ?? wormholeCoinIds.btc,
4346
+ this.address.get("core.coins.sol.id") ?? wormholeCoinIds.sol,
4347
+ this.address.get("core.coins.apt.id") ?? wormholeCoinIds.apt
4348
+ ];
4349
+ const voloPackageIds = [
4350
+ this.address.get("core.coins.vsui.id") ?? voloCoinIds.vsui
4351
+ ];
4352
+ if (wormHolePackageIds.includes(coinPackageId)) {
4353
+ return `${coinPackageId}::coin::COIN`;
4354
+ } else if (voloPackageIds.includes(coinPackageId)) {
4355
+ return `${coinPackageId}::cert::CERT`;
4356
+ } else {
4357
+ return `${coinPackageId}::${coinName}::${coinName.toUpperCase()}`;
4358
+ }
4269
4359
  }
4270
4360
  /**
4271
- * Get market collaterals index data.
4361
+ * Convert coin name to sCoin name.
4272
4362
  *
4273
- * @return Market collaterals data.
4363
+ * @param coinName - Specific support coin name.
4364
+ * @return sCoin name.
4274
4365
  */
4275
- async getMarketCollaterals() {
4276
- return (await this.getMarket()).collaterals;
4366
+ parseSCoinName(coinName) {
4367
+ if (isMarketCoin(coinName) && SUPPORT_SCOIN.includes(coinName)) {
4368
+ return coinName;
4369
+ } else {
4370
+ const marketCoinName = `s${coinName}`;
4371
+ if (SUPPORT_SCOIN.includes(marketCoinName)) {
4372
+ return marketCoinName;
4373
+ }
4374
+ return void 0;
4375
+ }
4277
4376
  }
4278
4377
  /**
4279
- * Get market collateral index data.
4378
+ * Convert sCoin name into sCoin type
4379
+ * @param sCoinName
4380
+ * @returns sCoin type
4381
+ */
4382
+ parseSCoinType(sCoinName) {
4383
+ return sCoinIds[sCoinName];
4384
+ }
4385
+ /**
4386
+ * Convert sCoin name into its underlying coin type
4387
+ * @param sCoinName
4388
+ * @returns coin type
4389
+ */
4390
+ parseUnderlyingSCoinType(sCoinName) {
4391
+ const coinName = this.parseCoinName(sCoinName);
4392
+ return this.parseCoinType(coinName);
4393
+ }
4394
+ /**
4395
+ * Get sCoin treasury id from sCoin name
4396
+ * @param sCoinName
4397
+ * @returns sCoin treasury id
4398
+ */
4399
+ getSCoinTreasury(sCoinName) {
4400
+ return this.address.get(`scoin.coins.${sCoinName}.treasury`);
4401
+ }
4402
+ /**
4403
+ * Convert coin name to market coin type.
4280
4404
  *
4281
- * @return Market collateral data.
4405
+ * @param coinPackageId - Package id of coin.
4406
+ * @param coinName - Specific support coin name.
4407
+ * @return Market coin type.
4282
4408
  */
4283
- async getMarketCollateral(collateralCoinName) {
4284
- return (await this.getMarketCollaterals())[collateralCoinName];
4409
+ parseMarketCoinType(coinName) {
4410
+ const protocolObjectId = this.address.get("core.object") || PROTOCOL_OBJECT_ID;
4411
+ const coinType = this.parseCoinType(coinName);
4412
+ return `${protocolObjectId}::reserve::MarketCoin<${coinType}>`;
4413
+ }
4414
+ parseCoinNameFromType(coinType) {
4415
+ coinType = (0, import_utils10.normalizeStructTag)(coinType);
4416
+ const coinTypeRegex = new RegExp(`((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)`);
4417
+ const coinTypeMatch = coinType.match(coinTypeRegex);
4418
+ const isMarketCoinType = coinType.includes("reserve::MarketCoin");
4419
+ coinType = coinTypeMatch?.[1] || coinType;
4420
+ const wormHoleCoinTypeMap = {
4421
+ [`${this.address.get("core.coins.usdc.id") ?? wormholeCoinIds.usdc}::coin::COIN`]: "usdc",
4422
+ [`${this.address.get("core.coins.usdt.id") ?? wormholeCoinIds.usdt}::coin::COIN`]: "usdt",
4423
+ [`${this.address.get("core.coins.eth.id") ?? wormholeCoinIds.eth}::coin::COIN`]: "eth",
4424
+ [`${this.address.get("core.coins.btc.id") ?? wormholeCoinIds.btc}::coin::COIN`]: "btc",
4425
+ [`${this.address.get("core.coins.sol.id") ?? wormholeCoinIds.sol}::coin::COIN`]: "sol",
4426
+ [`${this.address.get("core.coins.apt.id") ?? wormholeCoinIds.apt}::coin::COIN`]: "apt"
4427
+ };
4428
+ const voloCoinTypeMap = {
4429
+ [`${this.address.get("core.coins.vsui.id") ?? voloCoinIds.vsui}::cert::CERT`]: "vsui"
4430
+ };
4431
+ const assetCoinName = wormHoleCoinTypeMap[coinType] || voloCoinTypeMap[coinType] || coinType.split("::")[2].toLowerCase();
4432
+ return isMarketCoinType ? this.parseMarketCoinName(assetCoinName) : assetCoinName;
4285
4433
  }
4286
4434
  /**
4287
- * Get spools index data.
4435
+ * Convert marke coin name to coin name.
4288
4436
  *
4289
- * @return Spools data.
4437
+ * @param marketCoinName - Specific support market coin name.
4438
+ * @return Coin Name.
4290
4439
  */
4291
- async getSpools() {
4292
- const response = await this._cache.queryClient.fetchQuery({
4293
- queryKey: ["spools"],
4294
- queryFn: async () => {
4295
- return await this._requestClient.get(`/api/spools`);
4296
- }
4297
- });
4298
- if (response.status === 200) {
4299
- return response.data.spools.reduce((spools, spool) => {
4300
- spools[spool.marketCoinName] = spool;
4301
- return spools;
4302
- }, {});
4303
- } else {
4304
- throw Error("Failed to getSpools.");
4305
- }
4440
+ parseCoinName(marketCoinName) {
4441
+ return marketCoinName.slice(1);
4306
4442
  }
4307
4443
  /**
4308
- * Get spool index data.
4444
+ * Convert coin name to market coin name.
4309
4445
  *
4310
- * @return Spool data.
4446
+ * @param coinName - Specific support coin name.
4447
+ * @return Market coin name.
4311
4448
  */
4312
- async getSpool(marketCoinName) {
4313
- return (await this.getSpools())[marketCoinName];
4449
+ parseMarketCoinName(coinName) {
4450
+ return `s${coinName}`;
4314
4451
  }
4315
4452
  /**
4316
- * Get borrow incentive pools index data.
4453
+ * Get coin decimal.
4317
4454
  *
4318
- * @return Borrow incentive pools data.
4455
+ * return Coin decimal.
4319
4456
  */
4320
- async getBorrowIncentivePools() {
4321
- const response = await this._cache.queryClient.fetchQuery({
4322
- queryKey: ["borrowIncentivePools"],
4323
- queryFn: async () => {
4324
- return await this._requestClient.get(`/api/borrowIncentivePools`);
4325
- }
4326
- });
4327
- if (response.status === 200) {
4328
- return response.data.borrowIncentivePools.reduce(
4329
- (borrowIncentivePools, borrowIncentivePool) => {
4330
- if (Array.isArray(borrowIncentivePool.points)) {
4331
- borrowIncentivePool.points = borrowIncentivePool.points.reduce(
4332
- (prev, curr) => {
4333
- prev[curr.coinName] = curr;
4334
- return prev;
4335
- },
4336
- {}
4337
- );
4338
- }
4339
- borrowIncentivePools[borrowIncentivePool.coinName] = borrowIncentivePool;
4340
- return borrowIncentivePools;
4341
- },
4342
- {}
4343
- );
4344
- } else {
4345
- throw Error("Failed to getBorrowIncentivePools.");
4346
- }
4457
+ getCoinDecimal(coinName) {
4458
+ return coinDecimals[coinName];
4347
4459
  }
4348
4460
  /**
4349
- * Get borrow incentive pool index data.
4461
+ * Get coin wrapped type.
4350
4462
  *
4351
- * @return Borrow incentive pool data.
4463
+ * return Coin wrapped type.
4352
4464
  */
4353
- async getBorrowIncentivePool(borrowIncentiveCoinName) {
4354
- return (await this.getBorrowIncentivePools())[borrowIncentiveCoinName];
4465
+ getCoinWrappedType(assetCoinName) {
4466
+ return assetCoinName === "usdc" || assetCoinName === "usdt" || assetCoinName === "eth" || assetCoinName === "btc" || assetCoinName === "apt" || assetCoinName === "sol" ? {
4467
+ from: "Wormhole",
4468
+ type: "Portal from Ethereum"
4469
+ } : void 0;
4355
4470
  }
4356
4471
  /**
4357
- * Get total value locked index data.
4472
+ * Select coin id that add up to the given amount as transaction arguments.
4358
4473
  *
4359
- * @return Total value locked.
4474
+ * @param ownerAddress - The address of the owner.
4475
+ * @param amount - The amount that including coin decimals.
4476
+ * @param coinType - The coin type, default is 0x2::SUI::SUI.
4477
+ * @return The selected transaction coin arguments.
4360
4478
  */
4361
- async getTotalValueLocked() {
4362
- const response = await this._cache.queryClient.fetchQuery({
4363
- queryKey: ["totalValueLocked"],
4364
- queryFn: async () => {
4365
- return await this._requestClient.get(`/api/market/tvl`);
4366
- }
4367
- });
4368
- if (response.status === 200) {
4369
- return response.data;
4370
- } else {
4371
- throw Error("Failed to getTotalValueLocked.");
4372
- }
4373
- }
4374
- };
4375
-
4376
- // src/queries/sCoinQuery.ts
4377
- var import_bcs2 = require("@mysten/sui.js/bcs");
4378
- var import_assert = __toESM(require("assert"));
4379
- var import_bignumber7 = __toESM(require("bignumber.js"));
4380
- var getSCoinTotalSupply = async (query, sCoinName) => {
4381
- const sCoinPkgId = query.address.get("scoin.id");
4382
- const args = [query.utils.getSCoinTreasury(sCoinName)];
4383
- const typeArgs = [
4384
- query.utils.parseSCoinType(sCoinName),
4385
- query.utils.parseUnderlyingSCoinType(sCoinName)
4386
- ];
4387
- const queryTarget = `${sCoinPkgId}::s_coin_converter::total_supply`;
4388
- const queryResults = await query.cache.queryInspectTxn({
4389
- queryTarget,
4390
- args,
4391
- typeArgs
4392
- });
4393
- const results = queryResults?.results;
4394
- if (results && results[0].returnValues) {
4395
- const value = Uint8Array.from(results[0].returnValues[0][0]);
4396
- const type = results[0].returnValues[0][1];
4397
- (0, import_assert.default)(type === "u64", "Result type is not u64");
4398
- return (0, import_bignumber7.default)(import_bcs2.bcs.de(type, value)).shiftedBy(
4399
- query.utils.getCoinDecimal(query.utils.parseCoinName(sCoinName))
4400
- ).toNumber();
4401
- }
4402
- return 0;
4403
- };
4404
- var getSCoinAmounts = async (query, sCoinNames, ownerAddress) => {
4405
- sCoinNames = sCoinNames || [...SUPPORT_SCOIN];
4406
- const owner = ownerAddress || query.suiKit.currentAddress();
4407
- const sCoins2 = {};
4408
- await Promise.allSettled(
4409
- sCoinNames.map(async (sCoinName) => {
4410
- const sCoin = await getSCoinAmount(query, sCoinName, owner);
4411
- sCoins2[sCoinName] = sCoin;
4412
- })
4413
- );
4414
- return sCoins2;
4415
- };
4416
- var getSCoinAmount = async (query, sCoinName, ownerAddress) => {
4417
- const owner = ownerAddress || query.suiKit.currentAddress();
4418
- const sCoinType = query.utils.parseSCoinType(sCoinName);
4419
- const amount = await query.cache.queryGetCoinBalance({
4420
- owner,
4421
- coinType: sCoinType
4422
- });
4423
- return (0, import_bignumber7.default)(amount).toNumber();
4424
- };
4425
-
4426
- // src/models/scallopQuery.ts
4427
- var import_utils10 = require("@mysten/sui.js/utils");
4428
- var ScallopQuery = class {
4429
- constructor(params, instance) {
4430
- this.params = params;
4431
- this.suiKit = instance?.suiKit ?? new import_sui_kit3.SuiKit(params);
4432
- this.cache = instance?.cache ?? new ScallopCache(DEFAULT_CACHE_OPTIONS, this.suiKit);
4433
- this.address = instance?.address ?? new ScallopAddress(
4434
- {
4435
- id: params?.addressesId || ADDRESSES_ID,
4436
- network: params?.networkType
4437
- },
4438
- this.cache
4439
- );
4440
- this.utils = instance?.utils ?? new ScallopUtils(this.params, {
4441
- suiKit: this.suiKit,
4442
- address: this.address,
4443
- cache: this.cache,
4444
- query: this
4445
- });
4446
- this.indexer = new ScallopIndexer(this.params, { cache: this.cache });
4447
- this.walletAddress = (0, import_utils10.normalizeSuiAddress)(
4448
- params?.walletAddress || this.suiKit.currentAddress()
4479
+ async selectCoins(amount, coinType = import_utils10.SUI_TYPE_ARG, ownerAddress) {
4480
+ ownerAddress = ownerAddress || this.suiKit.currentAddress();
4481
+ const coins = await this.suiKit.suiInteractor.selectCoins(
4482
+ ownerAddress,
4483
+ amount,
4484
+ coinType
4449
4485
  );
4486
+ return coins;
4450
4487
  }
4451
4488
  /**
4452
- * Request the scallop API to initialize data.
4453
- *
4454
- * @param force - Whether to force initialization.
4455
- * @param address - ScallopAddress instance.
4489
+ * Merge coins with type `coinType` to dest
4490
+ * @param txBlock
4491
+ * @param dest
4492
+ * @param coinType
4493
+ * @param sender
4456
4494
  */
4457
- async init(force = false, address) {
4458
- if (force || !this.address.getAddresses() || !address?.getAddresses()) {
4459
- await this.address.read();
4460
- } else {
4461
- this.address = address;
4495
+ async mergeSimilarCoins(txBlock, dest, coinType, sender) {
4496
+ try {
4497
+ const existingCoins = await this.selectCoins(
4498
+ Number.MAX_SAFE_INTEGER,
4499
+ coinType,
4500
+ sender
4501
+ );
4502
+ if (existingCoins.length > 0) {
4503
+ txBlock.mergeCoins(dest, existingCoins.slice(0, 500));
4504
+ }
4505
+ } catch (e) {
4462
4506
  }
4463
- await this.utils.init(force, this.address);
4464
- }
4465
- /* ==================== Core Query Methods ==================== */
4466
- /**
4467
- * Query market data.
4468
- * @param indexer - Whether to use indexer.
4469
- * @return Market data.
4470
- */
4471
- async queryMarket(indexer = false) {
4472
- return await queryMarket(this, indexer);
4473
4507
  }
4474
4508
  /**
4475
- * Get market pools.
4509
+ * Get all asset coin names in the obligation record by obligation id.
4476
4510
  *
4477
4511
  * @description
4478
- * To obtain all market pools at once, it is recommended to use
4479
- * the `queryMarket` method to reduce time consumption.
4480
- *
4481
- * @param poolCoinNames - Specific an array of support pool coin name.
4482
- * @param indexer - Whether to use indexer.
4483
- * @return Market pools data.
4484
- */
4485
- async getMarketPools(poolCoinNames, indexer = false) {
4486
- return await getMarketPools(this, poolCoinNames, indexer);
4487
- }
4488
- /**
4489
- * Get market pool
4512
+ * This can often be used to determine which assets in an obligation require
4513
+ * price updates before interacting with specific instructions of the Scallop contract.
4490
4514
  *
4491
- * @param poolCoinName - Specific support pool coin name.
4492
- * @param indexer - Whether to use indexer.
4493
- * @return Market pool data.
4515
+ * @param obligationId - The obligation id.
4516
+ * @return Asset coin Names.
4494
4517
  */
4495
- async getMarketPool(poolCoinName, indexer = false) {
4496
- return await getMarketPool(this, poolCoinName, indexer);
4518
+ async getObligationCoinNames(obligationId) {
4519
+ const obligation = await queryObligation(this, obligationId);
4520
+ if (!obligation)
4521
+ return void 0;
4522
+ const collateralCoinTypes = obligation.collaterals.map((collateral) => {
4523
+ return `0x${collateral.type.name}`;
4524
+ });
4525
+ const debtCoinTypes = obligation.debts.map((debt) => {
4526
+ return `0x${debt.type.name}`;
4527
+ });
4528
+ const obligationCoinTypes = [
4529
+ .../* @__PURE__ */ new Set([...collateralCoinTypes, ...debtCoinTypes])
4530
+ ];
4531
+ const obligationCoinNames = obligationCoinTypes.map((coinType) => {
4532
+ return this.parseCoinNameFromType(coinType);
4533
+ });
4534
+ return obligationCoinNames;
4497
4535
  }
4498
4536
  /**
4499
- * Get market collaterals.
4537
+ * Get asset coin price.
4500
4538
  *
4501
4539
  * @description
4502
- * To obtain all market collaterals at once, it is recommended to use
4503
- * the `queryMarket` method to reduce time consumption.
4504
- *
4505
- * @param collateralCoinNames - Specific an array of support collateral coin name.
4506
- * @param indexer - Whether to use indexer.
4507
- * @return Market collaterals data.
4508
- */
4509
- async getMarketCollaterals(collateralCoinNames, indexer = false) {
4510
- return await getMarketCollaterals(this, collateralCoinNames, indexer);
4511
- }
4512
- /**
4513
- * Get market collateral
4514
- *
4515
- * @param collateralCoinName - Specific support collateral coin name.
4516
- * @param indexer - Whether to use indexer.
4517
- * @return Market collateral data.
4518
- */
4519
- async getMarketCollateral(collateralCoinName, indexer = false) {
4520
- return await getMarketCollateral(this, collateralCoinName, indexer);
4521
- }
4522
- /**
4523
- * Get obligations data.
4524
- *
4525
- * @param ownerAddress - The owner address.
4526
- * @return Obligations data.
4527
- */
4528
- async getObligations(ownerAddress = this.walletAddress) {
4529
- return await getObligations(this, ownerAddress);
4530
- }
4531
- /**
4532
- * Query obligation data.
4533
- *
4534
- * @param obligationId - The obligation id.
4535
- * @return Obligation data.
4536
- */
4537
- async queryObligation(obligationId) {
4538
- return queryObligation(this, obligationId);
4539
- }
4540
- /**
4541
- * Get all asset coin amounts.
4540
+ * The strategy for obtaining the price is to get it through API first,
4541
+ * and then on-chain data if API cannot be retrieved.
4542
+ * Currently, we only support obtaining from pyth protocol, other
4543
+ * oracles will be supported in the future.
4542
4544
  *
4543
4545
  * @param assetCoinNames - Specific an array of support asset coin name.
4544
- * @param ownerAddress - The owner address.
4545
- * @return All coin amounts.
4546
- */
4547
- async getCoinAmounts(assetCoinNames, ownerAddress = this.walletAddress) {
4548
- return await getCoinAmounts(this, assetCoinNames, ownerAddress);
4549
- }
4550
- /**
4551
- * Get asset coin amount.
4552
- *
4553
- * @param assetCoinName - Specific support asset coin name.
4554
- * @param ownerAddress - The owner address.
4555
- * @return Coin amount.
4556
- */
4557
- async getCoinAmount(assetCoinName, ownerAddress = this.walletAddress) {
4558
- return await getCoinAmount(this, assetCoinName, ownerAddress);
4559
- }
4560
- /**
4561
- * Get all market coin amounts.
4562
- *
4563
- * @param coinNames - Specific an array of support market coin name.
4564
- * @param ownerAddress - The owner address.
4565
- * @return All market market coin amounts.
4546
+ * @return Asset coin price.
4566
4547
  */
4567
- async getMarketCoinAmounts(marketCoinNames, ownerAddress = this.walletAddress) {
4568
- return await getMarketCoinAmounts(this, marketCoinNames, ownerAddress);
4569
- }
4570
- /**
4571
- * Get market coin amount.
4572
- *
4573
- * @param coinNames - Specific support market coin name.
4574
- * @param ownerAddress - The owner address.
4575
- * @return Market market coin amount.
4576
- */
4577
- async getMarketCoinAmount(marketCoinName, ownerAddress = this.walletAddress) {
4578
- return await getMarketCoinAmount(this, marketCoinName, ownerAddress);
4579
- }
4580
- /**
4581
- * Get price from pyth fee object.
4582
- *
4583
- * @param assetCoinName - Specific support asset coin name.
4584
- * @return Asset coin price.
4585
- */
4586
- async getPriceFromPyth(assetCoinName) {
4587
- return await getPythPrice(this, assetCoinName);
4588
- }
4589
- /**
4590
- * Get prices from pyth fee object.
4591
- *
4592
- * @param assetCoinNames - Array of supported asset coin names.
4593
- * @return Array of asset coin prices.
4594
- */
4595
- async getPricesFromPyth(assetCoinNames) {
4596
- return await getPythPrices(this, assetCoinNames);
4597
- }
4598
- /* ==================== Spool Query Methods ==================== */
4599
- /**
4600
- * Get spools data.
4601
- *
4602
- * @param stakeMarketCoinNames - Specific an array of support stake market coin name.
4603
- * @param indexer - Whether to use indexer.
4604
- * @return Spools data.
4605
- */
4606
- async getSpools(stakeMarketCoinNames, indexer = false) {
4607
- return await getSpools(this, stakeMarketCoinNames, indexer);
4608
- }
4609
- /**
4610
- * Get spool data.
4611
- *
4612
- * @param stakeMarketCoinName - Specific support stake market coin name.
4613
- * @param indexer - Whether to use indexer.
4614
- * @return Spool data.
4615
- */
4616
- async getSpool(stakeMarketCoinName, indexer = false) {
4617
- return await getSpool(this, stakeMarketCoinName, indexer);
4548
+ async getCoinPrices(assetCoinNames) {
4549
+ assetCoinNames = assetCoinNames || [
4550
+ .../* @__PURE__ */ new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS])
4551
+ ];
4552
+ const coinPrices = {};
4553
+ const existPricesCoinNames = [];
4554
+ const lackPricesCoinNames = [];
4555
+ assetCoinNames.forEach((assetCoinName) => {
4556
+ if (this._priceMap.has(assetCoinName) && Date.now() - this._priceMap.get(assetCoinName).publishTime < 1e3 * 60) {
4557
+ existPricesCoinNames.push(assetCoinName);
4558
+ } else {
4559
+ lackPricesCoinNames.push(assetCoinName);
4560
+ }
4561
+ });
4562
+ if (existPricesCoinNames.length > 0) {
4563
+ for (const coinName of existPricesCoinNames) {
4564
+ coinPrices[coinName] = this._priceMap.get(coinName).price;
4565
+ }
4566
+ }
4567
+ if (lackPricesCoinNames.length > 0) {
4568
+ const endpoints = this.params.pythEndpoints ?? PYTH_ENDPOINTS[this.isTestnet ? "testnet" : "mainnet"];
4569
+ const failedRequests = new Set(
4570
+ lackPricesCoinNames
4571
+ );
4572
+ for (const endpoint of endpoints) {
4573
+ const priceIds = Array.from(failedRequests.values()).reduce(
4574
+ (acc, coinName) => {
4575
+ const priceId = this.address.get(
4576
+ `core.coins.${coinName}.oracle.pyth.feed`
4577
+ );
4578
+ acc[coinName] = priceId;
4579
+ return acc;
4580
+ },
4581
+ {}
4582
+ );
4583
+ await Promise.allSettled(
4584
+ Object.entries(priceIds).map(async ([coinName, priceId]) => {
4585
+ const pythConnection = new import_pyth_sui_js.SuiPriceServiceConnection(endpoint);
4586
+ try {
4587
+ const feed = await this.address.cache.queryClient.fetchQuery({
4588
+ queryKey: [priceId],
4589
+ queryFn: async () => {
4590
+ return await pythConnection.getLatestPriceFeeds([priceId]);
4591
+ }
4592
+ });
4593
+ if (feed) {
4594
+ const data = parseDataFromPythPriceFeed(feed[0], this.address);
4595
+ this._priceMap.set(coinName, {
4596
+ price: data.price,
4597
+ publishTime: data.publishTime
4598
+ });
4599
+ coinPrices[coinName] = data.price;
4600
+ }
4601
+ failedRequests.delete(coinName);
4602
+ } catch (e) {
4603
+ console.warn(
4604
+ `Failed to get price ${coinName} feeds with endpoint ${endpoint}: ${e}`
4605
+ );
4606
+ }
4607
+ })
4608
+ );
4609
+ if (failedRequests.size === 0)
4610
+ break;
4611
+ }
4612
+ if (failedRequests.size > 0) {
4613
+ await Promise.allSettled(
4614
+ Array.from(failedRequests.values()).map(async (coinName) => {
4615
+ const price = await getPythPrice(this, coinName);
4616
+ this._priceMap.set(coinName, {
4617
+ price,
4618
+ publishTime: Date.now()
4619
+ });
4620
+ coinPrices[coinName] = price;
4621
+ })
4622
+ );
4623
+ }
4624
+ }
4625
+ return coinPrices;
4618
4626
  }
4619
4627
  /**
4620
- * Get stake accounts data for all stake pools (spools).
4628
+ * Convert apr to apy.
4621
4629
  *
4622
- * @param ownerAddress - The owner address.
4623
- * @return All Stake accounts data.
4630
+ * @param apr The annual percentage rate (APR).
4631
+ * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).
4632
+ * @return The equivalent annual percentage yield (APY) for the given APR and compounding frequency.
4624
4633
  */
4625
- async getAllStakeAccounts(ownerAddress = this.walletAddress) {
4626
- return await getStakeAccounts(this, ownerAddress);
4634
+ parseAprToApy(apr, compoundFrequency = 365) {
4635
+ return (1 + apr / compoundFrequency) ** compoundFrequency - 1;
4627
4636
  }
4628
4637
  /**
4629
- * Get stake accounts data for specific stake pool (spool).
4638
+ * Convert apr to apy.
4630
4639
  *
4631
- * @param stakeMarketCoinName - Specific support stake market coin name.
4632
- * @param ownerAddress - The owner address.
4633
- * @return Stake accounts data.
4640
+ * @param apr The equivalent annual percentage yield (APY).
4641
+ * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).
4642
+ * @return The equivalent annual percentage rate (APR) for the given APY and compounding frequency.
4634
4643
  */
4635
- async getStakeAccounts(stakeMarketCoinName, ownerAddress = this.walletAddress) {
4636
- const allStakeAccount = await this.getAllStakeAccounts(ownerAddress);
4637
- return allStakeAccount[stakeMarketCoinName] ?? [];
4644
+ parseApyToApr(apy, compoundFrequency = 365) {
4645
+ return ((1 + apy) ** (1 / compoundFrequency) - 1) * compoundFrequency;
4638
4646
  }
4639
4647
  /**
4640
- * Get stake pools (spools) data.
4648
+ * Give extend lock period to get unlock at in seconds timestamp.
4641
4649
  *
4642
4650
  * @description
4643
- * For backward compatible, it is recommended to use `getSpools` method
4644
- * to get all spools data.
4651
+ * - When the user without remaining unlock period, If the extended unlock day is not specified,
4652
+ * the unlock period will be increased by one day by default.
4653
+ * - When the given extended day plus the user's remaining unlock period exceeds the maximum
4654
+ * unlock period, the maximum unlock period is used as unlock period.
4645
4655
  *
4646
- * @param stakeMarketCoinNames - Specific an array of support stake market coin name.
4647
- * @return Stake pools data.
4656
+ * @param extendLockPeriodInDay The extend lock period in day.
4657
+ * @param unlockAtInSecondTimestamp The unlock timestamp from veSca object.
4658
+ * @return New unlock at in seconds timestamp.
4648
4659
  */
4649
- async getStakePools(stakeMarketCoinNames) {
4650
- stakeMarketCoinNames = stakeMarketCoinNames ?? [...SUPPORT_SPOOLS];
4651
- const stakePools = {};
4652
- for (const stakeMarketCoinName of stakeMarketCoinNames) {
4653
- const stakePool = await getStakePool(this, stakeMarketCoinName);
4654
- if (stakePool) {
4655
- stakePools[stakeMarketCoinName] = stakePool;
4660
+ getUnlockAt(extendLockPeriodInDay, unlockAtInMillisTimestamp) {
4661
+ const now = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
4662
+ const remainingLockPeriod = unlockAtInMillisTimestamp ? Math.max(Math.floor(unlockAtInMillisTimestamp / 1e3) - now, 0) : 0;
4663
+ let newUnlockAtInSecondTimestamp = 0;
4664
+ if (remainingLockPeriod === 0) {
4665
+ const lockPeriod = (extendLockPeriodInDay ?? 1) * UNLOCK_ROUND_DURATION;
4666
+ newUnlockAtInSecondTimestamp = Math.min(
4667
+ now + lockPeriod,
4668
+ now + MAX_LOCK_DURATION
4669
+ );
4670
+ } else {
4671
+ const lockPeriod = Math.min(
4672
+ extendLockPeriodInDay ? extendLockPeriodInDay * UNLOCK_ROUND_DURATION + remainingLockPeriod : remainingLockPeriod,
4673
+ MAX_LOCK_DURATION
4674
+ );
4675
+ newUnlockAtInSecondTimestamp = now + lockPeriod;
4676
+ }
4677
+ return findClosestUnlockRound(newUnlockAtInSecondTimestamp);
4678
+ }
4679
+ };
4680
+
4681
+ // src/models/scallopBuilder.ts
4682
+ var import_utils24 = require("@mysten/sui.js/utils");
4683
+ var import_sui_kit14 = require("@scallop-io/sui-kit");
4684
+
4685
+ // src/builders/coreBuilder.ts
4686
+ var import_transactions = require("@mysten/sui.js/transactions");
4687
+ var import_utils13 = require("@mysten/sui.js/utils");
4688
+ var import_sui_kit5 = require("@scallop-io/sui-kit");
4689
+
4690
+ // src/builders/oracle.ts
4691
+ var import_utils12 = require("@mysten/sui.js/utils");
4692
+ var import_pyth_sui_js2 = require("@pythnetwork/pyth-sui-js");
4693
+ var updateOracles = async (builder, txBlock, assetCoinNames) => {
4694
+ assetCoinNames = assetCoinNames ?? [
4695
+ .../* @__PURE__ */ new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS])
4696
+ ];
4697
+ const rules = builder.isTestnet ? ["pyth"] : ["pyth"];
4698
+ if (rules.includes("pyth")) {
4699
+ const pythClient = new import_pyth_sui_js2.SuiPythClient(
4700
+ builder.suiKit.client(),
4701
+ builder.address.get("core.oracles.pyth.state"),
4702
+ builder.address.get("core.oracles.pyth.wormholeState")
4703
+ );
4704
+ const priceIds = assetCoinNames.map(
4705
+ (assetCoinName) => builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feed`)
4706
+ );
4707
+ const endpoints = builder.params.pythEndpoints ?? PYTH_ENDPOINTS[builder.isTestnet ? "testnet" : "mainnet"];
4708
+ for (const endpoint of endpoints) {
4709
+ try {
4710
+ const pythConnection = new import_pyth_sui_js2.SuiPriceServiceConnection(endpoint);
4711
+ const priceUpdateData = await pythConnection.getPriceFeedsUpdateData(priceIds);
4712
+ await pythClient.updatePriceFeeds(
4713
+ txBlock.txBlock,
4714
+ priceUpdateData,
4715
+ priceIds
4716
+ );
4717
+ break;
4718
+ } catch (e) {
4719
+ console.warn(
4720
+ `Failed to update price feeds with endpoint ${endpoint}: ${e}`
4721
+ );
4656
4722
  }
4657
4723
  }
4658
- return stakePools;
4659
4724
  }
4660
- /**
4661
- * Get stake pool (spool) data.
4662
- *
4663
- * @description
4664
- * For backward compatible, it is recommended to use `getSpool` method
4665
- * to get all spool data.
4666
- *
4667
- * @param stakeMarketCoinName - Specific support stake market coin name.
4668
- * @return Stake pool data.
4669
- */
4670
- async getStakePool(stakeMarketCoinName) {
4671
- return await getStakePool(this, stakeMarketCoinName);
4725
+ const updateAssetCoinNames = [...new Set(assetCoinNames)];
4726
+ for (const assetCoinName of updateAssetCoinNames) {
4727
+ await updateOracle(builder, txBlock, assetCoinName, rules);
4672
4728
  }
4673
- /**
4674
- * Get stake reward pools data.
4675
- *
4676
- * @description
4677
- * For backward compatible, it is recommended to use `getSpools` method
4678
- * to get all spools data.
4679
- *
4680
- * @param stakeMarketCoinNames - Specific an array of stake market coin name.
4681
- * @return Stake reward pools data.
4682
- */
4683
- async getStakeRewardPools(stakeMarketCoinNames) {
4684
- stakeMarketCoinNames = stakeMarketCoinNames ?? [...SUPPORT_SPOOLS];
4685
- const stakeRewardPools = {};
4686
- await Promise.allSettled(
4687
- stakeMarketCoinNames.map(async (stakeMarketCoinName) => {
4688
- const stakeRewardPool = await getStakeRewardPool(
4689
- this,
4690
- stakeMarketCoinName
4691
- );
4692
- if (stakeRewardPool) {
4693
- stakeRewardPools[stakeMarketCoinName] = stakeRewardPool;
4694
- }
4695
- })
4729
+ };
4730
+ var updateOracle = async (builder, txBlock, assetCoinName, rules) => {
4731
+ const coinType = builder.utils.parseCoinType(assetCoinName);
4732
+ updatePrice(
4733
+ txBlock,
4734
+ rules,
4735
+ builder.address.get("core.packages.xOracle.id"),
4736
+ builder.address.get("core.oracles.xOracle"),
4737
+ builder.address.get("core.packages.pyth.id"),
4738
+ builder.address.get("core.oracles.pyth.registry"),
4739
+ builder.address.get("core.oracles.pyth.state"),
4740
+ builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feedObject`),
4741
+ builder.address.get("core.packages.switchboard.id"),
4742
+ builder.address.get("core.oracles.switchboard.registry"),
4743
+ builder.address.get(`core.coins.${assetCoinName}.oracle.switchboard`),
4744
+ builder.address.get("core.packages.supra.id"),
4745
+ builder.address.get("core.oracles.supra.registry"),
4746
+ builder.address.get(`core.oracles.supra.holder`),
4747
+ coinType
4748
+ );
4749
+ };
4750
+ var updatePrice = (txBlock, rules, xOraclePackageId, xOracleId, pythPackageId, pythRegistryId, pythStateId, pythFeedObjectId, switchboardPackageId, switchboardRegistryId, switchboardAggregatorId, supraPackageId, supraRegistryId, supraHolderId, coinType) => {
4751
+ const request = priceUpdateRequest(
4752
+ txBlock,
4753
+ xOraclePackageId,
4754
+ xOracleId,
4755
+ coinType
4756
+ );
4757
+ if (rules.includes("pyth")) {
4758
+ updatePythPrice(
4759
+ txBlock,
4760
+ pythPackageId,
4761
+ request,
4762
+ pythStateId,
4763
+ pythFeedObjectId,
4764
+ pythRegistryId,
4765
+ coinType
4696
4766
  );
4697
- return stakeRewardPools;
4698
- }
4699
- /**
4700
- * Get stake reward pool data.
4701
- *
4702
- * @description
4703
- * For backward compatible, it is recommended to use `getSpool` method
4704
- * to get spool data.
4705
- *
4706
- * @param marketCoinName - Specific support stake market coin name.
4707
- * @return Stake reward pool data.
4708
- */
4709
- async getStakeRewardPool(stakeMarketCoinName) {
4710
- return await getStakeRewardPool(this, stakeMarketCoinName);
4711
- }
4712
- /**
4713
- * Get borrow incentive pools data.
4714
- *
4715
- * @param coinNames - Specific an array of support borrow incentive coin name.
4716
- * @param indexer - Whether to use indexer.
4717
- * @return Borrow incentive pools data.
4718
- */
4719
- async getBorrowIncentivePools(coinNames, indexer = false) {
4720
- return await queryBorrowIncentivePools(this, coinNames, indexer);
4721
4767
  }
4722
- /**
4723
- * Get borrow incentive accounts data.
4724
- *
4725
- * @param coinNames - Specific support borrow incentive coin name.
4726
- * @param ownerAddress - The owner address.
4727
- * @return Borrow incentive accounts data.
4728
- */
4729
- async getBorrowIncentiveAccounts(obligationId, coinNames) {
4730
- return await queryBorrowIncentiveAccounts(this, obligationId, coinNames);
4731
- }
4732
- /**
4733
- * Get user lending and spool infomation for specific pools.
4734
- *
4735
- * @param poolCoinNames - Specific an array of support pool coin name.
4736
- * @param ownerAddress - The owner address.
4737
- * @param indexer - Whether to use indexer.
4738
- * @return All lending and spool infomation.
4739
- */
4740
- async getLendings(poolCoinNames, ownerAddress = this.walletAddress, indexer = false) {
4741
- return await getLendings(this, poolCoinNames, ownerAddress, indexer);
4742
- }
4743
- /**
4744
- * Get user lending and spool information for specific pool.
4745
- *
4746
- * @param poolCoinName - Specific support pool coin name.
4747
- * @param ownerAddress - The owner address.
4748
- * @param indexer - Whether to use indexer.
4749
- * @return Lending pool data.
4750
- */
4751
- async getLending(poolCoinName, ownerAddress = this.walletAddress, indexer = false) {
4752
- return await getLending(this, poolCoinName, ownerAddress, indexer);
4753
- }
4754
- /**
4755
- * Get user all obligation accounts information.
4756
- *
4757
- * @description
4758
- * All collateral and borrowing information in all obligation accounts owned by the user.
4759
- *
4760
- * @param ownerAddress - The owner address.
4761
- * @param indexer - Whether to use indexer.
4762
- * @return All obligation accounts information.
4763
- */
4764
- async getObligationAccounts(ownerAddress = this.walletAddress, indexer = false) {
4765
- return await getObligationAccounts(this, ownerAddress, indexer);
4766
- }
4767
- /**
4768
- * Get obligation account information for specific id.
4769
- *
4770
- * @description
4771
- * borrowing and obligation information for specific pool.
4772
- *
4773
- * @param obligationId - The obligation id.
4774
- * @param ownerAddress - The owner address.
4775
- * @param indexer - Whether to use indexer.
4776
- * @return Borrowing and collateral information.
4777
- */
4778
- async getObligationAccount(obligationId, ownerAddress = this.walletAddress, indexer = false) {
4779
- return await getObligationAccount(
4780
- this,
4781
- obligationId,
4782
- ownerAddress,
4783
- indexer
4768
+ if (rules.includes("switchboard")) {
4769
+ updateSwitchboardPrice(
4770
+ txBlock,
4771
+ switchboardPackageId,
4772
+ request,
4773
+ switchboardAggregatorId,
4774
+ switchboardRegistryId,
4775
+ coinType
4784
4776
  );
4785
4777
  }
4786
- /**
4787
- * Get total value locked.
4788
- *
4789
- * @param indexer - Whether to use indexer.
4790
- * @description
4791
- * Include total supplied value and total borrowed value.
4792
- *
4793
- * @return Total value locked.
4794
- */
4795
- async getTvl(indexer = false) {
4796
- return await getTotalValueLocked(this, indexer);
4797
- }
4798
- /**
4799
- * Get all veSca from walletAdddress
4800
- * @param walletAddress
4801
- * @returns array of veSca
4802
- */
4803
- async getVeScas(walletAddress) {
4804
- return await getVeScas(this, walletAddress);
4805
- }
4806
- /**
4807
- * Get total vesca treasury with movecall
4808
- * @returns Promise<string | undefined>
4809
- */
4810
- async getVeScaTreasuryInfo() {
4811
- return await getVeScaTreasuryInfo(this);
4812
- }
4813
- /**
4814
- * Return binded referrer veScaKeyId of referee walletAddress if exist
4815
- * @param walletAddress
4816
- * @returns veScaKeyId
4817
- */
4818
- async getVeScaKeyIdFromReferralBindings(walletAddress) {
4819
- return await queryVeScaKeyIdFromReferralBindings(this, walletAddress);
4820
- }
4821
- /**
4822
- * Get binded obligationId from a veScaKey if it exists.
4823
- * @param veScaKey
4824
- * @returns obligationId
4825
- */
4826
- async getBindedObligationId(veScaKey) {
4827
- return await getBindedObligationId(this, veScaKey);
4828
- }
4829
- /**
4830
- * Get binded veSCA key from a obligationId if it exists.
4831
- * @param obligationId
4832
- * @returns veScaKey
4833
- */
4834
- async getBindedVeScaKey(obligationId) {
4835
- return await getBindedVeScaKey(this, obligationId);
4836
- }
4837
- /**
4838
- * Get user's veSCA loyalty program informations
4839
- * @param walletAddress
4840
- * @returns Loyalty program information
4841
- */
4842
- async getLoyaltyProgramInfos(veScaKey) {
4843
- return await getLoyaltyProgramInformations(this, veScaKey);
4844
- }
4845
- /**
4846
- * Get total supply of sCoin
4847
- * @param sCoinName - Supported sCoin name
4848
- * @returns Total Supply
4849
- */
4850
- async getSCoinTotalSupply(sCoinName) {
4851
- return await getSCoinTotalSupply(this, sCoinName);
4852
- }
4853
- /**
4854
- * Get all sCoin amounts.
4855
- *
4856
- * @param sCoinNames - Specific an array of support sCoin name.
4857
- * @param ownerAddress - The owner address.
4858
- * @return All market sCoin amounts.
4859
- */
4860
- async getSCoinAmounts(sCoinNames, ownerAddress = this.walletAddress) {
4861
- return await getSCoinAmounts(this, sCoinNames, ownerAddress);
4862
- }
4863
- /**
4864
- * Get sCoin amount.
4865
- *
4866
- * @param coinNames - Specific support sCoin name.
4867
- * @param ownerAddress - The owner address.
4868
- * @return sCoin amount.
4869
- */
4870
- async getSCoinAmount(sCoinName, ownerAddress = this.walletAddress) {
4871
- const parsedSCoinName = this.utils.parseSCoinName(sCoinName);
4872
- return parsedSCoinName ? await getSCoinAmount(this, parsedSCoinName, ownerAddress) : 0;
4873
- }
4874
- /*
4875
- * Get flashloan fee for specified assets
4876
- */
4877
- async getFlashLoanFees(assetCoinNames = [...SUPPORT_POOLS]) {
4878
- return await getFlashLoanFees(this, assetCoinNames);
4778
+ if (rules.includes("supra")) {
4779
+ updateSupraPrice(
4780
+ txBlock,
4781
+ supraPackageId,
4782
+ request,
4783
+ supraHolderId,
4784
+ supraRegistryId,
4785
+ coinType
4786
+ );
4879
4787
  }
4788
+ confirmPriceUpdateRequest(
4789
+ txBlock,
4790
+ xOraclePackageId,
4791
+ xOracleId,
4792
+ request,
4793
+ coinType
4794
+ );
4795
+ return txBlock;
4880
4796
  };
4881
-
4882
- // src/constants/pyth.ts
4883
- var PYTH_ENDPOINTS = {
4884
- testnet: ["https://hermes-beta.pyth.network"],
4885
- mainnet: ["https://hermes.pyth.network", "https://scallop.rpc.p2p.world"]
4886
- };
4887
-
4888
- // src/models/scallopUtils.ts
4889
- var ScallopUtils = class {
4890
- constructor(params, instance) {
4891
- this._priceMap = /* @__PURE__ */ new Map();
4892
- /**
4893
- * Get reward type of spool.
4894
- *
4895
- * @param stakeMarketCoinName - Support stake market coin.
4896
- * @return Spool reward coin name.
4897
- */
4898
- this.getSpoolRewardCoinName = (stakeMarketCoinName) => {
4899
- return spoolRewardCoins[stakeMarketCoinName];
4900
- };
4901
- /**
4902
- * Get reward type of borrow incentive pool.
4903
- *
4904
- * @param borrowIncentiveCoinName - Support borrow incentive coin.
4905
- * @return Borrow incentive reward coin name.
4906
- */
4907
- this.getBorrowIncentiveRewardCoinName = (borrowIncentiveCoinName) => {
4908
- return borrowIncentiveRewardCoins[borrowIncentiveCoinName];
4909
- };
4910
- this.params = params;
4911
- this._suiKit = instance?.suiKit ?? new import_sui_kit4.SuiKit(params);
4912
- this._cache = instance?.cache ?? new ScallopCache(DEFAULT_CACHE_OPTIONS, this._suiKit);
4913
- this._address = instance?.address ?? new ScallopAddress(
4914
- {
4915
- id: params?.addressesId || ADDRESSES_ID,
4916
- network: params?.networkType
4917
- },
4918
- this._cache
4919
- );
4920
- this._query = instance?.query ?? new ScallopQuery(params, {
4921
- suiKit: this._suiKit,
4922
- address: this._address,
4923
- cache: this._cache
4924
- });
4925
- this.isTestnet = params.networkType ? params.networkType === "testnet" : false;
4926
- }
4927
- /**
4928
- * Request the scallop API to initialize data.
4929
- *
4930
- * @param force - Whether to force initialization.
4931
- * @param address - ScallopAddress instance.
4932
- */
4933
- async init(force = false, address) {
4934
- if (force || !this._address.getAddresses() || !address?.getAddresses()) {
4935
- await this._address.read();
4936
- } else {
4937
- this._address = address;
4938
- }
4939
- if (!this._query.address.getAddresses()) {
4940
- await this._query.init(force, this._address);
4941
- }
4942
- }
4943
- /**
4944
- * Convert coin name to symbol.
4945
- *
4946
- * @param coinName - Specific support coin name.
4947
- * @return Symbol string.
4948
- */
4949
- parseSymbol(coinName) {
4950
- if (isMarketCoin(coinName)) {
4951
- const assetCoinName = coinName.slice(1).toLowerCase();
4952
- return coinName.slice(0, 1).toLowerCase() + parseAssetSymbol(assetCoinName);
4953
- } else {
4954
- return parseAssetSymbol(coinName);
4955
- }
4956
- }
4957
- /**
4958
- * Convert coin name to coin type.
4959
- *
4960
- * @description
4961
- * The Coin type of wormhole is fixed `coin:Coin`. Here using package id
4962
- * to determine and return the type.
4963
- *
4964
- * @param coinPackageId - Package id of coin.
4965
- * @param coinName - Specific support coin name.
4966
- * @return Coin type.
4967
- */
4968
- parseCoinType(coinName) {
4969
- coinName = isMarketCoin(coinName) ? this.parseCoinName(coinName) : coinName;
4970
- const coinPackageId = this._address.get(`core.coins.${coinName}.id`) || coinIds[coinName] || void 0;
4971
- if (!coinPackageId) {
4972
- throw Error(`Coin ${coinName} is not supported`);
4973
- }
4974
- if (coinName === "sui")
4975
- return (0, import_utils11.normalizeStructTag)(`${coinPackageId}::sui::SUI`);
4976
- const wormHolePckageIds = [
4977
- this._address.get("core.coins.usdc.id") ?? wormholeCoinIds.usdc,
4978
- this._address.get("core.coins.usdt.id") ?? wormholeCoinIds.usdt,
4979
- this._address.get("core.coins.eth.id") ?? wormholeCoinIds.eth,
4980
- this._address.get("core.coins.btc.id") ?? wormholeCoinIds.btc,
4981
- this._address.get("core.coins.sol.id") ?? wormholeCoinIds.sol,
4982
- this._address.get("core.coins.apt.id") ?? wormholeCoinIds.apt
4983
- ];
4984
- const voloPckageIds = [
4985
- this._address.get("core.coins.vsui.id") ?? voloCoinIds.vsui
4986
- ];
4987
- if (wormHolePckageIds.includes(coinPackageId)) {
4988
- return `${coinPackageId}::coin::COIN`;
4989
- } else if (voloPckageIds.includes(coinPackageId)) {
4990
- return `${coinPackageId}::cert::CERT`;
4991
- } else {
4992
- return `${coinPackageId}::${coinName}::${coinName.toUpperCase()}`;
4993
- }
4994
- }
4995
- /**
4996
- * Convert coin name to sCoin name.
4997
- *
4998
- * @param coinName - Specific support coin name.
4999
- * @return sCoin name.
5000
- */
5001
- parseSCoinName(coinName) {
5002
- if (isMarketCoin(coinName) && SUPPORT_SCOIN.includes(coinName)) {
5003
- return coinName;
5004
- } else {
5005
- const marketCoinName = `s${coinName}`;
5006
- if (SUPPORT_SCOIN.includes(marketCoinName)) {
5007
- return marketCoinName;
5008
- }
5009
- return void 0;
5010
- }
5011
- }
5012
- /**
5013
- * Convert sCoin name into sCoin type
5014
- * @param sCoinName
5015
- * @returns sCoin type
5016
- */
5017
- parseSCoinType(sCoinName) {
5018
- return sCoinIds[sCoinName];
5019
- }
5020
- /**
5021
- * Convert sCoin name into its underlying coin type
5022
- * @param sCoinName
5023
- * @returns coin type
5024
- */
5025
- parseUnderlyingSCoinType(sCoinName) {
5026
- const coinName = this.parseCoinName(sCoinName);
5027
- return this.parseCoinType(coinName);
5028
- }
5029
- /**
5030
- * Get sCoin treasury id from sCoin name
5031
- * @param sCoinName
5032
- * @returns sCoin treasury id
5033
- */
5034
- getSCoinTreasury(sCoinName) {
5035
- return this._address.get(`scoin.coins.${sCoinName}.treasury`);
5036
- }
5037
- /**
5038
- * Convert coin name to market coin type.
5039
- *
5040
- * @param coinPackageId - Package id of coin.
5041
- * @param coinName - Specific support coin name.
5042
- * @return Market coin type.
5043
- */
5044
- parseMarketCoinType(coinName) {
5045
- const protocolObjectId = this._address.get("core.object") || PROTOCOL_OBJECT_ID;
5046
- const coinType = this.parseCoinType(coinName);
5047
- return `${protocolObjectId}::reserve::MarketCoin<${coinType}>`;
5048
- }
5049
- parseCoinNameFromType(coinType) {
5050
- coinType = (0, import_utils11.normalizeStructTag)(coinType);
5051
- const coinTypeRegex = new RegExp(`((0x[^:]+::[^:]+::[^<>]+))(?![^<>]*<)`);
5052
- const coinTypeMatch = coinType.match(coinTypeRegex);
5053
- const isMarketCoinType = coinType.includes("reserve::MarketCoin");
5054
- coinType = coinTypeMatch?.[1] || coinType;
5055
- const wormHoleCoinTypeMap = {
5056
- [`${this._address.get("core.coins.usdc.id") ?? wormholeCoinIds.usdc}::coin::COIN`]: "usdc",
5057
- [`${this._address.get("core.coins.usdt.id") ?? wormholeCoinIds.usdt}::coin::COIN`]: "usdt",
5058
- [`${this._address.get("core.coins.eth.id") ?? wormholeCoinIds.eth}::coin::COIN`]: "eth",
5059
- [`${this._address.get("core.coins.btc.id") ?? wormholeCoinIds.btc}::coin::COIN`]: "btc",
5060
- [`${this._address.get("core.coins.sol.id") ?? wormholeCoinIds.sol}::coin::COIN`]: "sol",
5061
- [`${this._address.get("core.coins.apt.id") ?? wormholeCoinIds.apt}::coin::COIN`]: "apt"
5062
- };
5063
- const voloCoinTypeMap = {
5064
- [`${this._address.get("core.coins.vsui.id") ?? voloCoinIds.vsui}::cert::CERT`]: "vsui"
5065
- };
5066
- const assetCoinName = wormHoleCoinTypeMap[coinType] || voloCoinTypeMap[coinType] || coinType.split("::")[2].toLowerCase();
5067
- return isMarketCoinType ? this.parseMarketCoinName(assetCoinName) : assetCoinName;
5068
- }
5069
- /**
5070
- * Convert marke coin name to coin name.
5071
- *
5072
- * @param marketCoinName - Specific support market coin name.
5073
- * @return Coin Name.
5074
- */
5075
- parseCoinName(marketCoinName) {
5076
- return marketCoinName.slice(1);
5077
- }
5078
- /**
5079
- * Convert coin name to market coin name.
5080
- *
5081
- * @param coinName - Specific support coin name.
5082
- * @return Market coin name.
5083
- */
5084
- parseMarketCoinName(coinName) {
5085
- return `s${coinName}`;
5086
- }
5087
- /**
5088
- * Get coin decimal.
5089
- *
5090
- * return Coin decimal.
5091
- */
5092
- getCoinDecimal(coinName) {
5093
- return coinDecimals[coinName];
5094
- }
5095
- /**
5096
- * Get coin wrapped type.
5097
- *
5098
- * return Coin wrapped type.
5099
- */
5100
- getCoinWrappedType(assetCoinName) {
5101
- return assetCoinName === "usdc" || assetCoinName === "usdt" || assetCoinName === "eth" || assetCoinName === "btc" || assetCoinName === "apt" || assetCoinName === "sol" ? {
5102
- from: "Wormhole",
5103
- type: "Portal from Ethereum"
5104
- } : void 0;
5105
- }
5106
- /**
5107
- * Select coin id that add up to the given amount as transaction arguments.
5108
- *
5109
- * @param ownerAddress - The address of the owner.
5110
- * @param amount - The amount that including coin decimals.
5111
- * @param coinType - The coin type, default is 0x2::SUI::SUI.
5112
- * @return The selected transaction coin arguments.
5113
- */
5114
- async selectCoins(amount, coinType = import_utils11.SUI_TYPE_ARG, ownerAddress) {
5115
- ownerAddress = ownerAddress || this._suiKit.currentAddress();
5116
- const coins = await this._suiKit.suiInteractor.selectCoins(
5117
- ownerAddress,
5118
- amount,
5119
- coinType
5120
- );
5121
- return coins;
5122
- }
5123
- /**
5124
- * Merge coins with type `coinType` to dest
5125
- * @param txBlock
5126
- * @param dest
5127
- * @param coinType
5128
- * @param sender
5129
- */
5130
- async mergeSimilarCoins(txBlock, dest, coinType, sender) {
5131
- try {
5132
- const existingSCoin = await this.selectCoins(
5133
- Number.MAX_SAFE_INTEGER,
5134
- coinType,
5135
- sender
5136
- );
5137
- if (existingSCoin.length > 0) {
5138
- txBlock.mergeCoins(dest, existingSCoin);
5139
- }
5140
- } catch (e) {
5141
- }
5142
- }
5143
- /**
5144
- * Get all asset coin names in the obligation record by obligation id.
5145
- *
5146
- * @description
5147
- * This can often be used to determine which assets in an obligation require
5148
- * price updates before interacting with specific instructions of the Scallop contract.
5149
- *
5150
- * @param obligationId - The obligation id.
5151
- * @return Asset coin Names.
5152
- */
5153
- async getObligationCoinNames(obligationId) {
5154
- const obligation = await queryObligation(this._query, obligationId);
5155
- const collateralCoinTypes = obligation?.collaterals.map((collateral) => {
5156
- return `0x${collateral.type.name}`;
5157
- }) ?? [];
5158
- const debtCoinTypes = obligation?.debts.map((debt) => {
5159
- return `0x${debt.type.name}`;
5160
- }) ?? [];
5161
- const obligationCoinTypes = [
5162
- .../* @__PURE__ */ new Set([...collateralCoinTypes, ...debtCoinTypes])
5163
- ];
5164
- const obligationCoinNames = obligationCoinTypes.map((coinType) => {
5165
- return this.parseCoinNameFromType(coinType);
5166
- });
5167
- return obligationCoinNames;
5168
- }
5169
- /**
5170
- * Get asset coin price.
5171
- *
5172
- * @description
5173
- * The strategy for obtaining the price is to get it through API first,
5174
- * and then on-chain data if API cannot be retrieved.
5175
- * Currently, we only support obtaining from pyth protocol, other
5176
- * oracles will be supported in the future.
5177
- *
5178
- * @param assetCoinNames - Specific an array of support asset coin name.
5179
- * @return Asset coin price.
5180
- */
5181
- async getCoinPrices(assetCoinNames) {
5182
- assetCoinNames = assetCoinNames || [
5183
- .../* @__PURE__ */ new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS])
5184
- ];
5185
- const coinPrices = {};
5186
- const existPricesCoinNames = [];
5187
- const lackPricesCoinNames = [];
5188
- assetCoinNames.forEach((assetCoinName) => {
5189
- if (this._priceMap.has(assetCoinName) && Date.now() - this._priceMap.get(assetCoinName).publishTime < 1e3 * 60) {
5190
- existPricesCoinNames.push(assetCoinName);
5191
- } else {
5192
- lackPricesCoinNames.push(assetCoinName);
5193
- }
5194
- });
5195
- if (existPricesCoinNames.length > 0) {
5196
- for (const coinName of existPricesCoinNames) {
5197
- coinPrices[coinName] = this._priceMap.get(coinName).price;
5198
- }
5199
- }
5200
- if (lackPricesCoinNames.length > 0) {
5201
- const endpoints = this.params.pythEndpoints ?? PYTH_ENDPOINTS[this.isTestnet ? "testnet" : "mainnet"];
5202
- const failedRequests = new Set(
5203
- lackPricesCoinNames
5204
- );
5205
- for (const endpoint of endpoints) {
5206
- const priceIds = Array.from(failedRequests.values()).reduce(
5207
- (acc, coinName) => {
5208
- const priceId = this._address.get(
5209
- `core.coins.${coinName}.oracle.pyth.feed`
5210
- );
5211
- acc[coinName] = priceId;
5212
- return acc;
5213
- },
5214
- {}
5215
- );
5216
- await Promise.allSettled(
5217
- Object.entries(priceIds).map(async ([coinName, priceId]) => {
5218
- const pythConnection = new import_pyth_sui_js.SuiPriceServiceConnection(endpoint);
5219
- try {
5220
- const feed = await this._cache.queryClient.fetchQuery({
5221
- queryKey: [priceId],
5222
- queryFn: async () => {
5223
- return await pythConnection.getLatestPriceFeeds([priceId]);
5224
- }
5225
- });
5226
- if (feed) {
5227
- const data = parseDataFromPythPriceFeed(feed[0], this._address);
5228
- this._priceMap.set(coinName, {
5229
- price: data.price,
5230
- publishTime: data.publishTime
5231
- });
5232
- coinPrices[coinName] = data.price;
5233
- }
5234
- failedRequests.delete(coinName);
5235
- } catch (e) {
5236
- console.warn(
5237
- `Failed to get price ${coinName} feeds with endpoint ${endpoint}: ${e}`
5238
- );
5239
- }
5240
- })
5241
- );
5242
- if (failedRequests.size === 0)
5243
- break;
5244
- }
5245
- if (failedRequests.size > 0) {
5246
- await Promise.allSettled(
5247
- Array.from(failedRequests.values()).map(async (coinName) => {
5248
- const price = await this._query.getPriceFromPyth(coinName);
5249
- this._priceMap.set(coinName, {
5250
- price,
5251
- publishTime: Date.now()
5252
- });
5253
- coinPrices[coinName] = price;
5254
- })
5255
- );
5256
- }
5257
- }
5258
- return coinPrices;
5259
- }
5260
- /**
5261
- * Convert apr to apy.
5262
- *
5263
- * @param apr The annual percentage rate (APR).
5264
- * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).
5265
- * @return The equivalent annual percentage yield (APY) for the given APR and compounding frequency.
5266
- */
5267
- parseAprToApy(apr, compoundFrequency = 365) {
5268
- return (1 + apr / compoundFrequency) ** compoundFrequency - 1;
5269
- }
5270
- /**
5271
- * Convert apr to apy.
5272
- *
5273
- * @param apr The equivalent annual percentage yield (APY).
5274
- * @param compoundFrequency How often interest is compounded per year. Default is daily (365 times a year).
5275
- * @return The equivalent annual percentage rate (APR) for the given APY and compounding frequency.
5276
- */
5277
- parseApyToApr(apy, compoundFrequency = 365) {
5278
- return ((1 + apy) ** (1 / compoundFrequency) - 1) * compoundFrequency;
5279
- }
5280
- /**
5281
- * Give extend lock period to get unlock at in seconds timestamp.
5282
- *
5283
- * @description
5284
- * - When the user without remaining unlock period, If the extended unlock day is not specified,
5285
- * the unlock period will be increased by one day by default.
5286
- * - When the given extended day plus the user's remaining unlock period exceeds the maximum
5287
- * unlock period, the maximum unlock period is used as unlock period.
5288
- *
5289
- * @param extendLockPeriodInDay The extend lock period in day.
5290
- * @param unlockAtInSecondTimestamp The unlock timestamp from veSca object.
5291
- * @return New unlock at in seconds timestamp.
5292
- */
5293
- getUnlockAt(extendLockPeriodInDay, unlockAtInMillisTimestamp) {
5294
- const now = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
5295
- const remainingLockPeriod = unlockAtInMillisTimestamp ? Math.max(Math.floor(unlockAtInMillisTimestamp / 1e3) - now, 0) : 0;
5296
- let newUnlockAtInSecondTimestamp = 0;
5297
- if (remainingLockPeriod === 0) {
5298
- const lockPeriod = (extendLockPeriodInDay ?? 1) * UNLOCK_ROUND_DURATION;
5299
- newUnlockAtInSecondTimestamp = Math.min(
5300
- now + lockPeriod,
5301
- now + MAX_LOCK_DURATION
5302
- );
5303
- } else {
5304
- const lockPeriod = Math.min(
5305
- extendLockPeriodInDay ? extendLockPeriodInDay * UNLOCK_ROUND_DURATION + remainingLockPeriod : remainingLockPeriod,
5306
- MAX_LOCK_DURATION
5307
- );
5308
- newUnlockAtInSecondTimestamp = now + lockPeriod;
5309
- }
5310
- return findClosestUnlockRound(newUnlockAtInSecondTimestamp);
5311
- }
5312
- };
5313
-
5314
- // src/models/scallopBuilder.ts
5315
- var import_utils24 = require("@mysten/sui.js/utils");
5316
- var import_sui_kit12 = require("@scallop-io/sui-kit");
5317
-
5318
- // src/builders/coreBuilder.ts
5319
- var import_transactions = require("@mysten/sui.js/transactions");
5320
- var import_utils14 = require("@mysten/sui.js/utils");
5321
- var import_sui_kit5 = require("@scallop-io/sui-kit");
5322
-
5323
- // src/builders/oracle.ts
5324
- var import_utils13 = require("@mysten/sui.js/utils");
5325
- var import_pyth_sui_js2 = require("@pythnetwork/pyth-sui-js");
5326
- var updateOracles = async (builder, txBlock, assetCoinNames) => {
5327
- assetCoinNames = assetCoinNames ?? [
5328
- .../* @__PURE__ */ new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS])
5329
- ];
5330
- const rules = builder.isTestnet ? ["pyth"] : ["pyth"];
5331
- if (rules.includes("pyth")) {
5332
- const pythClient = new import_pyth_sui_js2.SuiPythClient(
5333
- builder.suiKit.client(),
5334
- builder.address.get("core.oracles.pyth.state"),
5335
- builder.address.get("core.oracles.pyth.wormholeState")
5336
- );
5337
- const priceIds = assetCoinNames.map(
5338
- (assetCoinName) => builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feed`)
5339
- );
5340
- const endpoints = builder.params.pythEndpoints ?? PYTH_ENDPOINTS[builder.isTestnet ? "testnet" : "mainnet"];
5341
- for (const endpoint of endpoints) {
5342
- try {
5343
- const pythConnection = new import_pyth_sui_js2.SuiPriceServiceConnection(endpoint);
5344
- const priceUpdateData = await pythConnection.getPriceFeedsUpdateData(priceIds);
5345
- await pythClient.updatePriceFeeds(
5346
- txBlock.txBlock,
5347
- priceUpdateData,
5348
- priceIds
5349
- );
5350
- break;
5351
- } catch (e) {
5352
- console.warn(
5353
- `Failed to update price feeds with endpoint ${endpoint}: ${e}`
5354
- );
5355
- }
5356
- }
5357
- }
5358
- const updateAssetCoinNames = [...new Set(assetCoinNames)];
5359
- for (const assetCoinName of updateAssetCoinNames) {
5360
- await updateOracle(builder, txBlock, assetCoinName, rules);
5361
- }
5362
- };
5363
- var updateOracle = async (builder, txBlock, assetCoinName, rules) => {
5364
- const coinType = builder.utils.parseCoinType(assetCoinName);
5365
- updatePrice(
5366
- txBlock,
5367
- rules,
5368
- builder.address.get("core.packages.xOracle.id"),
5369
- builder.address.get("core.oracles.xOracle"),
5370
- builder.address.get("core.packages.pyth.id"),
5371
- builder.address.get("core.oracles.pyth.registry"),
5372
- builder.address.get("core.oracles.pyth.state"),
5373
- builder.address.get(`core.coins.${assetCoinName}.oracle.pyth.feedObject`),
5374
- builder.address.get("core.packages.switchboard.id"),
5375
- builder.address.get("core.oracles.switchboard.registry"),
5376
- builder.address.get(`core.coins.${assetCoinName}.oracle.switchboard`),
5377
- builder.address.get("core.packages.supra.id"),
5378
- builder.address.get("core.oracles.supra.registry"),
5379
- builder.address.get(`core.oracles.supra.holder`),
5380
- coinType
5381
- );
5382
- };
5383
- var updatePrice = (txBlock, rules, xOraclePackageId, xOracleId, pythPackageId, pythRegistryId, pythStateId, pythFeedObjectId, switchboardPackageId, switchboardRegistryId, switchboardAggregatorId, supraPackageId, supraRegistryId, supraHolderId, coinType) => {
5384
- const request = priceUpdateRequest(
5385
- txBlock,
5386
- xOraclePackageId,
5387
- xOracleId,
5388
- coinType
5389
- );
5390
- if (rules.includes("pyth")) {
5391
- updatePythPrice(
5392
- txBlock,
5393
- pythPackageId,
5394
- request,
5395
- pythStateId,
5396
- pythFeedObjectId,
5397
- pythRegistryId,
5398
- coinType
5399
- );
5400
- }
5401
- if (rules.includes("switchboard")) {
5402
- updateSwitchboardPrice(
5403
- txBlock,
5404
- switchboardPackageId,
5405
- request,
5406
- switchboardAggregatorId,
5407
- switchboardRegistryId,
5408
- coinType
5409
- );
5410
- }
5411
- if (rules.includes("supra")) {
5412
- updateSupraPrice(
5413
- txBlock,
5414
- supraPackageId,
5415
- request,
5416
- supraHolderId,
5417
- supraRegistryId,
5418
- coinType
5419
- );
5420
- }
5421
- confirmPriceUpdateRequest(
5422
- txBlock,
5423
- xOraclePackageId,
5424
- xOracleId,
5425
- request,
5426
- coinType
5427
- );
5428
- return txBlock;
5429
- };
5430
- var priceUpdateRequest = (txBlock, packageId, xOracleId, coinType) => {
5431
- const target = `${packageId}::x_oracle::price_update_request`;
5432
- const typeArgs = [coinType];
5433
- return txBlock.moveCall(target, [xOracleId], typeArgs);
4797
+ var priceUpdateRequest = (txBlock, packageId, xOracleId, coinType) => {
4798
+ const target = `${packageId}::x_oracle::price_update_request`;
4799
+ const typeArgs = [coinType];
4800
+ return txBlock.moveCall(target, [xOracleId], typeArgs);
5434
4801
  };
5435
4802
  var confirmPriceUpdateRequest = (txBlock, packageId, xOracleId, request, coinType) => {
5436
4803
  const target = `${packageId}::x_oracle::confirm_price_update_request`;
5437
4804
  const typeArgs = [coinType];
5438
- txBlock.moveCall(target, [xOracleId, request, import_utils13.SUI_CLOCK_OBJECT_ID], typeArgs);
4805
+ txBlock.moveCall(target, [xOracleId, request, import_utils12.SUI_CLOCK_OBJECT_ID], typeArgs);
5439
4806
  return txBlock;
5440
4807
  };
5441
4808
  var updateSupraPrice = (txBlock, packageId, request, holderId, registryId, coinType) => {
5442
4809
  txBlock.moveCall(
5443
4810
  `${packageId}::rule::set_price`,
5444
- [request, holderId, registryId, import_utils13.SUI_CLOCK_OBJECT_ID],
4811
+ [request, holderId, registryId, import_utils12.SUI_CLOCK_OBJECT_ID],
5445
4812
  [coinType]
5446
4813
  );
5447
4814
  };
5448
4815
  var updateSwitchboardPrice = (txBlock, packageId, request, aggregatorId, registryId, coinType) => {
5449
4816
  txBlock.moveCall(
5450
4817
  `${packageId}::rule::set_price`,
5451
- [request, aggregatorId, registryId, import_utils13.SUI_CLOCK_OBJECT_ID],
4818
+ [request, aggregatorId, registryId, import_utils12.SUI_CLOCK_OBJECT_ID],
5452
4819
  [coinType]
5453
4820
  );
5454
4821
  };
5455
4822
  var updatePythPrice = (txBlock, packageId, request, stateId, feedObjectId, registryId, coinType) => {
5456
4823
  txBlock.moveCall(
5457
4824
  `${packageId}::rule::set_price`,
5458
- [request, stateId, feedObjectId, registryId, import_utils13.SUI_CLOCK_OBJECT_ID],
4825
+ [request, stateId, feedObjectId, registryId, import_utils12.SUI_CLOCK_OBJECT_ID],
5459
4826
  [coinType]
5460
4827
  );
5461
4828
  };
@@ -5468,7 +4835,7 @@ var requireObligationInfo = async (...params) => {
5468
4835
  if (params.length === 4 && obligationId && obligationKey)
5469
4836
  return { obligationId, obligationKey };
5470
4837
  const sender = requireSender(txBlock);
5471
- const obligations = await getObligations(builder.query, sender);
4838
+ const obligations = await getObligations(builder, sender);
5472
4839
  if (obligations.length === 0) {
5473
4840
  throw new Error(`No obligation found for sender ${sender}`);
5474
4841
  }
@@ -5526,7 +4893,7 @@ var generateCoreNormalMethod = ({
5526
4893
  coreIds.coinDecimalsRegistry,
5527
4894
  amount,
5528
4895
  coreIds.xOracle,
5529
- import_utils14.SUI_CLOCK_OBJECT_ID
4896
+ import_utils13.SUI_CLOCK_OBJECT_ID
5530
4897
  ],
5531
4898
  [coinType]
5532
4899
  );
@@ -5535,7 +4902,7 @@ var generateCoreNormalMethod = ({
5535
4902
  const coinType = builder.utils.parseCoinType(poolCoinName);
5536
4903
  return txBlock.moveCall(
5537
4904
  `${coreIds.protocolPkg}::mint::mint`,
5538
- [coreIds.version, coreIds.market, coin, import_utils14.SUI_CLOCK_OBJECT_ID],
4905
+ [coreIds.version, coreIds.market, coin, import_utils13.SUI_CLOCK_OBJECT_ID],
5539
4906
  [coinType]
5540
4907
  );
5541
4908
  },
@@ -5543,7 +4910,7 @@ var generateCoreNormalMethod = ({
5543
4910
  const coinType = builder.utils.parseCoinType(poolCoinName);
5544
4911
  return txBlock.moveCall(
5545
4912
  `${coreIds.protocolPkg}::mint::mint_entry`,
5546
- [coreIds.version, coreIds.market, coin, import_utils14.SUI_CLOCK_OBJECT_ID],
4913
+ [coreIds.version, coreIds.market, coin, import_utils13.SUI_CLOCK_OBJECT_ID],
5547
4914
  [coinType]
5548
4915
  );
5549
4916
  },
@@ -5551,7 +4918,7 @@ var generateCoreNormalMethod = ({
5551
4918
  const coinType = builder.utils.parseCoinType(poolCoinName);
5552
4919
  return txBlock.moveCall(
5553
4920
  `${coreIds.protocolPkg}::redeem::redeem`,
5554
- [coreIds.version, coreIds.market, marketCoin, import_utils14.SUI_CLOCK_OBJECT_ID],
4921
+ [coreIds.version, coreIds.market, marketCoin, import_utils13.SUI_CLOCK_OBJECT_ID],
5555
4922
  [coinType]
5556
4923
  );
5557
4924
  },
@@ -5559,7 +4926,7 @@ var generateCoreNormalMethod = ({
5559
4926
  const coinType = builder.utils.parseCoinType(poolCoinName);
5560
4927
  return txBlock.moveCall(
5561
4928
  `${coreIds.protocolPkg}::redeem::redeem_entry`,
5562
- [coreIds.version, coreIds.market, marketCoin, import_utils14.SUI_CLOCK_OBJECT_ID],
4929
+ [coreIds.version, coreIds.market, marketCoin, import_utils13.SUI_CLOCK_OBJECT_ID],
5563
4930
  [coinType]
5564
4931
  );
5565
4932
  },
@@ -5575,7 +4942,7 @@ var generateCoreNormalMethod = ({
5575
4942
  coreIds.coinDecimalsRegistry,
5576
4943
  amount,
5577
4944
  coreIds.xOracle,
5578
- import_utils14.SUI_CLOCK_OBJECT_ID
4945
+ import_utils13.SUI_CLOCK_OBJECT_ID
5579
4946
  ],
5580
4947
  [coinType]
5581
4948
  );
@@ -5593,7 +4960,7 @@ var generateCoreNormalMethod = ({
5593
4960
  borrowReferral,
5594
4961
  amount,
5595
4962
  coreIds.xOracle,
5596
- import_utils14.SUI_CLOCK_OBJECT_ID
4963
+ import_utils13.SUI_CLOCK_OBJECT_ID
5597
4964
  ],
5598
4965
  [coinType, referralWitnessType]
5599
4966
  );
@@ -5610,7 +4977,7 @@ var generateCoreNormalMethod = ({
5610
4977
  coreIds.coinDecimalsRegistry,
5611
4978
  amount,
5612
4979
  coreIds.xOracle,
5613
- import_utils14.SUI_CLOCK_OBJECT_ID
4980
+ import_utils13.SUI_CLOCK_OBJECT_ID
5614
4981
  ],
5615
4982
  [coinType]
5616
4983
  );
@@ -5624,7 +4991,7 @@ var generateCoreNormalMethod = ({
5624
4991
  obligation,
5625
4992
  coreIds.market,
5626
4993
  coin,
5627
- import_utils14.SUI_CLOCK_OBJECT_ID
4994
+ import_utils13.SUI_CLOCK_OBJECT_ID
5628
4995
  ],
5629
4996
  [coinType]
5630
4997
  );
@@ -5765,8 +5132,8 @@ var generateCoreQuickMethod = ({
5765
5132
  );
5766
5133
  const obligationCoinNames = await builder.utils.getObligationCoinNames(
5767
5134
  obligationInfo.obligationId
5768
- );
5769
- const updateCoinNames = [...obligationCoinNames, poolCoinName];
5135
+ ) ?? [];
5136
+ const updateCoinNames = [...obligationCoinNames ?? [], poolCoinName];
5770
5137
  await updateOracles(builder, txBlock, updateCoinNames);
5771
5138
  return txBlock.borrow(
5772
5139
  obligationInfo.obligationId,
@@ -5784,7 +5151,7 @@ var generateCoreQuickMethod = ({
5784
5151
  );
5785
5152
  const obligationCoinNames = await builder.utils.getObligationCoinNames(
5786
5153
  obligationInfo.obligationId
5787
- );
5154
+ ) ?? [];
5788
5155
  const updateCoinNames = [...obligationCoinNames, poolCoinName];
5789
5156
  await updateOracles(builder, txBlock, updateCoinNames);
5790
5157
  return txBlock.borrowWithReferral(
@@ -5859,14 +5226,14 @@ var newCoreTxBlock = (builder, initTxBlock) => {
5859
5226
 
5860
5227
  // src/builders/spoolBuilder.ts
5861
5228
  var import_transactions2 = require("@mysten/sui.js/transactions");
5862
- var import_utils16 = require("@mysten/sui.js/utils");
5229
+ var import_utils15 = require("@mysten/sui.js/utils");
5863
5230
  var import_sui_kit6 = require("@scallop-io/sui-kit");
5864
5231
  var requireStakeAccountIds = async (...params) => {
5865
5232
  const [builder, txBlock, stakeMarketCoinName, stakeAccountId] = params;
5866
5233
  if (params.length === 4 && stakeAccountId)
5867
5234
  return [stakeAccountId];
5868
5235
  const sender = requireSender(txBlock);
5869
- const stakeAccounts = await getStakeAccounts(builder.query, sender);
5236
+ const stakeAccounts = await getStakeAccounts(builder, sender);
5870
5237
  if (stakeAccounts[stakeMarketCoinName].length === 0) {
5871
5238
  throw new Error(`No stake account id found for sender ${sender}`);
5872
5239
  }
@@ -5875,7 +5242,7 @@ var requireStakeAccountIds = async (...params) => {
5875
5242
  var requireStakeAccounts = async (...params) => {
5876
5243
  const [builder, txBlock, stakeMarketCoinName, stakeAccountId] = params;
5877
5244
  const sender = requireSender(txBlock);
5878
- const stakeAccounts = await getStakeAccounts(builder.query, sender);
5245
+ const stakeAccounts = await getStakeAccounts(builder, sender);
5879
5246
  if (stakeAccounts[stakeMarketCoinName].length === 0) {
5880
5247
  throw new Error(`No stake account found for sender ${sender}`);
5881
5248
  }
@@ -5914,7 +5281,7 @@ var generateSpoolNormalMethod = ({
5914
5281
  );
5915
5282
  return txBlock.moveCall(
5916
5283
  `${spoolIds.spoolPkg}::user::new_spool_account`,
5917
- [stakePoolId, import_utils16.SUI_CLOCK_OBJECT_ID],
5284
+ [stakePoolId, import_utils15.SUI_CLOCK_OBJECT_ID],
5918
5285
  [marketCoinType]
5919
5286
  );
5920
5287
  },
@@ -5925,7 +5292,7 @@ var generateSpoolNormalMethod = ({
5925
5292
  );
5926
5293
  txBlock.moveCall(
5927
5294
  `${spoolIds.spoolPkg}::user::stake`,
5928
- [stakePoolId, stakeAccount, coin, import_utils16.SUI_CLOCK_OBJECT_ID],
5295
+ [stakePoolId, stakeAccount, coin, import_utils15.SUI_CLOCK_OBJECT_ID],
5929
5296
  [marketCoinType]
5930
5297
  );
5931
5298
  },
@@ -5936,7 +5303,7 @@ var generateSpoolNormalMethod = ({
5936
5303
  );
5937
5304
  return txBlock.moveCall(
5938
5305
  `${spoolIds.spoolPkg}::user::unstake`,
5939
- [stakePoolId, stakeAccount, amount, import_utils16.SUI_CLOCK_OBJECT_ID],
5306
+ [stakePoolId, stakeAccount, amount, import_utils15.SUI_CLOCK_OBJECT_ID],
5940
5307
  [marketCoinType]
5941
5308
  );
5942
5309
  },
@@ -5952,7 +5319,7 @@ var generateSpoolNormalMethod = ({
5952
5319
  const rewardCoinType = builder.utils.parseCoinType(rewardCoinName);
5953
5320
  return txBlock.moveCall(
5954
5321
  `${spoolIds.spoolPkg}::user::redeem_rewards`,
5955
- [stakePoolId, rewardPoolId, stakeAccount, import_utils16.SUI_CLOCK_OBJECT_ID],
5322
+ [stakePoolId, rewardPoolId, stakeAccount, import_utils15.SUI_CLOCK_OBJECT_ID],
5956
5323
  [marketCoinType, rewardCoinType]
5957
5324
  );
5958
5325
  }
@@ -6081,7 +5448,7 @@ var newSpoolTxBlock = (builder, initTxBlock) => {
6081
5448
 
6082
5449
  // src/builders/borrowIncentiveBuilder.ts
6083
5450
  var import_transactions3 = require("@mysten/sui.js/transactions");
6084
- var import_utils19 = require("@mysten/sui.js/utils");
5451
+ var import_utils18 = require("@mysten/sui.js/utils");
6085
5452
  var import_sui_kit8 = require("@scallop-io/sui-kit");
6086
5453
 
6087
5454
  // src/builders/vescaBuilder.ts
@@ -6089,14 +5456,14 @@ var import_sui_kit7 = require("@scallop-io/sui-kit");
6089
5456
  var requireVeSca = async (...params) => {
6090
5457
  const [builder, txBlock, veScaKey] = params;
6091
5458
  if (params.length === 3 && veScaKey && typeof veScaKey === "string") {
6092
- const veSca = await getVeSca(builder.query, veScaKey);
5459
+ const veSca = await getVeSca(builder.utils, veScaKey);
6093
5460
  if (!veSca) {
6094
5461
  return void 0;
6095
5462
  }
6096
5463
  return veSca;
6097
5464
  }
6098
5465
  const sender = requireSender(txBlock);
6099
- const veScas = await getVeScas(builder.query, sender);
5466
+ const veScas = await getVeScas(builder, sender);
6100
5467
  if (veScas.length === 0) {
6101
5468
  return void 0;
6102
5469
  }
@@ -6317,13 +5684,17 @@ var generateQuickVeScaMethod = ({
6317
5684
  txBlock.transferObjects(transferObjects, sender);
6318
5685
  }
6319
5686
  },
6320
- redeemScaQuick: async (veScaKey) => {
5687
+ redeemScaQuick: async (veScaKey, transferSca = true) => {
6321
5688
  const sender = requireSender(txBlock);
6322
5689
  const veSca = await requireVeSca(builder, txBlock, veScaKey);
6323
5690
  checkVesca(veSca?.unlockAt);
6324
5691
  if (veSca) {
6325
5692
  const sca = txBlock.redeemSca(veSca.keyId);
6326
- txBlock.transferObjects([sca], sender);
5693
+ if (transferSca) {
5694
+ txBlock.transferObjects([sca], sender);
5695
+ return;
5696
+ }
5697
+ return sca;
6327
5698
  }
6328
5699
  }
6329
5700
  };
@@ -6361,13 +5732,13 @@ var requireObligationInfo2 = async (...params) => {
6361
5732
  const [builder, txBlock, obligationId, obligationKey] = params;
6362
5733
  if (params.length === 4 && obligationId && obligationKey && typeof obligationId === "string") {
6363
5734
  const obligationLocked = await getObligationLocked(
6364
- builder.query,
5735
+ builder.cache,
6365
5736
  obligationId
6366
5737
  );
6367
5738
  return { obligationId, obligationKey, obligationLocked };
6368
5739
  }
6369
5740
  const sender = requireSender(txBlock);
6370
- const obligations = await getObligations(builder.query, sender);
5741
+ const obligations = await getObligations(builder, sender);
6371
5742
  if (obligations.length === 0) {
6372
5743
  throw new Error(`No obligation found for sender ${sender}`);
6373
5744
  }
@@ -6407,7 +5778,7 @@ var generateBorrowIncentiveNormalMethod = ({ builder, txBlock }) => {
6407
5778
  obligationKey,
6408
5779
  obligationId,
6409
5780
  borrowIncentiveIds.obligationAccessStore,
6410
- import_utils19.SUI_CLOCK_OBJECT_ID
5781
+ import_utils18.SUI_CLOCK_OBJECT_ID
6411
5782
  ]
6412
5783
  );
6413
5784
  },
@@ -6425,7 +5796,7 @@ var generateBorrowIncentiveNormalMethod = ({ builder, txBlock }) => {
6425
5796
  veScaIds.treasury,
6426
5797
  veScaIds.table,
6427
5798
  veScaKey,
6428
- import_utils19.SUI_CLOCK_OBJECT_ID
5799
+ import_utils18.SUI_CLOCK_OBJECT_ID
6429
5800
  ],
6430
5801
  []
6431
5802
  );
@@ -6439,7 +5810,7 @@ var generateBorrowIncentiveNormalMethod = ({ builder, txBlock }) => {
6439
5810
  borrowIncentiveIds.incentiveAccounts,
6440
5811
  obligationKey,
6441
5812
  obligationId,
6442
- import_utils19.SUI_CLOCK_OBJECT_ID
5813
+ import_utils18.SUI_CLOCK_OBJECT_ID
6443
5814
  ]
6444
5815
  );
6445
5816
  },
@@ -6457,7 +5828,7 @@ var generateBorrowIncentiveNormalMethod = ({ builder, txBlock }) => {
6457
5828
  borrowIncentiveIds.incentiveAccounts,
6458
5829
  obligationKey,
6459
5830
  obligationId,
6460
- import_utils19.SUI_CLOCK_OBJECT_ID
5831
+ import_utils18.SUI_CLOCK_OBJECT_ID
6461
5832
  ],
6462
5833
  [rewardType]
6463
5834
  );
@@ -6471,7 +5842,7 @@ var generateBorrowIncentiveNormalMethod = ({ builder, txBlock }) => {
6471
5842
  borrowIncentiveIds.incentiveAccounts,
6472
5843
  obligation,
6473
5844
  veScaKey,
6474
- import_utils19.SUI_CLOCK_OBJECT_ID
5845
+ import_utils18.SUI_CLOCK_OBJECT_ID
6475
5846
  ]
6476
5847
  );
6477
5848
  }
@@ -6482,7 +5853,7 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
6482
5853
  stakeObligationQuick: async (obligation, obligationKey) => {
6483
5854
  const {
6484
5855
  obligationId: obligationArg,
6485
- obligationKey: obligationtKeyArg,
5856
+ obligationKey: obligationKeyArg,
6486
5857
  obligationLocked
6487
5858
  } = await requireObligationInfo2(
6488
5859
  builder,
@@ -6494,13 +5865,13 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
6494
5865
  (txn) => txn.kind === "MoveCall" && (txn.target === `${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake` || txn.target === `${builder.address.get("borrowIncentive.id")}::user::unstake`)
6495
5866
  );
6496
5867
  if (!obligationLocked || unstakeObligationBeforeStake) {
6497
- txBlock.stakeObligation(obligationArg, obligationtKeyArg);
5868
+ txBlock.stakeObligation(obligationArg, obligationKeyArg);
6498
5869
  }
6499
5870
  },
6500
5871
  stakeObligationWithVeScaQuick: async (obligation, obligationKey, veScaKey) => {
6501
5872
  const {
6502
5873
  obligationId: obligationArg,
6503
- obligationKey: obligationtKeyArg,
5874
+ obligationKey: obligationKeyArg,
6504
5875
  obligationLocked
6505
5876
  } = await requireObligationInfo2(
6506
5877
  builder,
@@ -6515,27 +5886,27 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
6515
5886
  const veSca = await requireVeSca(builder, txBlock, veScaKey);
6516
5887
  if (veSca) {
6517
5888
  const bindedObligationId = await getBindedObligationId(
6518
- builder.query,
5889
+ builder,
6519
5890
  veSca.keyId
6520
5891
  );
6521
5892
  if ((!bindedObligationId || bindedObligationId === obligationArg) && veSca.currentVeScaBalance > 0) {
6522
5893
  txBlock.stakeObligationWithVesca(
6523
5894
  obligationArg,
6524
- obligationtKeyArg,
5895
+ obligationKeyArg,
6525
5896
  veSca.keyId
6526
5897
  );
6527
5898
  } else {
6528
- txBlock.stakeObligation(obligationArg, obligationtKeyArg);
5899
+ txBlock.stakeObligation(obligationArg, obligationKeyArg);
6529
5900
  }
6530
5901
  } else {
6531
- txBlock.stakeObligation(obligationArg, obligationtKeyArg);
5902
+ txBlock.stakeObligation(obligationArg, obligationKeyArg);
6532
5903
  }
6533
5904
  }
6534
5905
  },
6535
5906
  unstakeObligationQuick: async (obligation, obligationKey) => {
6536
5907
  const {
6537
5908
  obligationId: obligationArg,
6538
- obligationKey: obligationtKeyArg,
5909
+ obligationKey: obligationKeyArg,
6539
5910
  obligationLocked
6540
5911
  } = await requireObligationInfo2(
6541
5912
  builder,
@@ -6544,14 +5915,11 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
6544
5915
  obligationKey
6545
5916
  );
6546
5917
  if (obligationLocked) {
6547
- txBlock.unstakeObligation(obligationArg, obligationtKeyArg);
5918
+ txBlock.unstakeObligation(obligationArg, obligationKeyArg);
6548
5919
  }
6549
5920
  },
6550
5921
  claimBorrowIncentiveQuick: async (coinName, rewardCoinName, obligation, obligationKey) => {
6551
- const {
6552
- obligationId: obligationArg,
6553
- obligationKey: obligationtKeyArg
6554
- } = await requireObligationInfo2(
5922
+ const { obligationId: obligationArg, obligationKey: obligationKeyArg } = await requireObligationInfo2(
6555
5923
  builder,
6556
5924
  txBlock,
6557
5925
  obligation,
@@ -6559,7 +5927,7 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
6559
5927
  );
6560
5928
  return txBlock.claimBorrowIncentive(
6561
5929
  obligationArg,
6562
- obligationtKeyArg,
5930
+ obligationKeyArg,
6563
5931
  coinName,
6564
5932
  rewardCoinName
6565
5933
  );
@@ -6642,67 +6010,225 @@ var generateReferralNormalMethod = ({
6642
6010
  burnReferralTicket: (ticket, poolCoinName) => {
6643
6011
  const coinType = builder.utils.parseCoinType(poolCoinName);
6644
6012
  return txBlock.moveCall(
6645
- `${referralIds.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,
6013
+ `${referralIds.referralPgkId}::scallop_referral_program::burn_ve_sca_referral_ticket`,
6014
+ [
6015
+ referralIds.version,
6016
+ ticket,
6017
+ referralIds.referralRevenuePool,
6018
+ import_sui_kit9.SUI_CLOCK_OBJECT_ID
6019
+ ],
6020
+ [coinType]
6021
+ );
6022
+ },
6023
+ claimReferralRevenue: (veScaKey, poolCoinName) => {
6024
+ const coinType = builder.utils.parseCoinType(poolCoinName);
6025
+ return txBlock.moveCall(
6026
+ `${referralIds.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,
6027
+ [
6028
+ referralIds.version,
6029
+ referralIds.referralRevenuePool,
6030
+ veScaKey,
6031
+ import_sui_kit9.SUI_CLOCK_OBJECT_ID
6032
+ ],
6033
+ [coinType]
6034
+ );
6035
+ }
6036
+ };
6037
+ };
6038
+ var generateReferralQuickMethod = ({
6039
+ builder,
6040
+ txBlock
6041
+ }) => {
6042
+ return {
6043
+ claimReferralRevenueQuick: async (veScaKey, coinNames = [...SUPPORT_POOLS]) => {
6044
+ const sender = requireSender(txBlock);
6045
+ const objToTransfer = [];
6046
+ for (const coinName of coinNames) {
6047
+ if (coinName === "sui") {
6048
+ const rewardCoin = txBlock.claimReferralRevenue(veScaKey, coinName);
6049
+ objToTransfer.push(rewardCoin);
6050
+ } else {
6051
+ const rewardCoin = txBlock.claimReferralRevenue(veScaKey, coinName);
6052
+ try {
6053
+ const coins = await builder.suiKit.suiInteractor.selectCoins(
6054
+ sender,
6055
+ Infinity,
6056
+ builder.utils.parseCoinType(coinName)
6057
+ );
6058
+ txBlock.mergeCoins(rewardCoin, coins.slice(0, 500));
6059
+ } catch (e) {
6060
+ } finally {
6061
+ objToTransfer.push(rewardCoin);
6062
+ }
6063
+ }
6064
+ }
6065
+ if (objToTransfer.length > 0) {
6066
+ txBlock.transferObjects(objToTransfer, sender);
6067
+ }
6068
+ }
6069
+ };
6070
+ };
6071
+ var newReferralTxBlock = (builder, initTxBlock) => {
6072
+ const txBlock = initTxBlock instanceof import_sui_kit9.TransactionBlock ? new import_sui_kit9.SuiTxBlock(initTxBlock) : initTxBlock ? initTxBlock : new import_sui_kit9.SuiTxBlock();
6073
+ const normalMethod = generateReferralNormalMethod({
6074
+ builder,
6075
+ txBlock
6076
+ });
6077
+ const normalTxBlock = new Proxy(txBlock, {
6078
+ get: (target, prop) => {
6079
+ if (prop in normalMethod) {
6080
+ return Reflect.get(normalMethod, prop);
6081
+ }
6082
+ return Reflect.get(target, prop);
6083
+ }
6084
+ });
6085
+ const quickMethod = generateReferralQuickMethod({
6086
+ builder,
6087
+ txBlock: normalTxBlock
6088
+ });
6089
+ return new Proxy(normalTxBlock, {
6090
+ get: (target, prop) => {
6091
+ if (prop in quickMethod) {
6092
+ return Reflect.get(quickMethod, prop);
6093
+ }
6094
+ return Reflect.get(target, prop);
6095
+ }
6096
+ });
6097
+ };
6098
+
6099
+ // src/builders/loyaltyProgramBuilder.ts
6100
+ var import_transactions4 = require("@mysten/sui.js/transactions");
6101
+ var import_sui_kit10 = require("@scallop-io/sui-kit");
6102
+ var generateLoyaltyProgramNormalMethod = ({ builder, txBlock }) => {
6103
+ const loyaltyProgramIds = {
6104
+ loyaltyProgramPkgId: builder.address.get("loyaltyProgram.id"),
6105
+ rewardPool: builder.address.get("loyaltyProgram.rewardPool"),
6106
+ userRewardTableId: builder.address.get(
6107
+ "loyaltyProgram.userRewardTableId"
6108
+ )
6109
+ };
6110
+ return {
6111
+ claimLoyaltyRevenue: (veScaKey) => {
6112
+ return txBlock.moveCall(
6113
+ `${loyaltyProgramIds.loyaltyProgramPkgId}::reward_pool::redeem_reward`,
6114
+ [loyaltyProgramIds.rewardPool, veScaKey]
6115
+ );
6116
+ }
6117
+ };
6118
+ };
6119
+ var generateLoyaltyProgramQuickMethod = ({
6120
+ builder,
6121
+ txBlock
6122
+ }) => {
6123
+ return {
6124
+ claimLoyaltyRevenueQuick: async (veScaKey) => {
6125
+ veScaKey = veScaKey || (await builder.query.getVeScas())[0]?.keyObject;
6126
+ const sender = requireSender(txBlock);
6127
+ if (!veScaKey)
6128
+ throw new Error(`No veScaKey found for user ${sender}`);
6129
+ const rewardCoin = txBlock.claimLoyaltyRevenue(veScaKey);
6130
+ await builder.utils.mergeSimilarCoins(
6131
+ txBlock,
6132
+ rewardCoin,
6133
+ coinIds.sca,
6134
+ requireSender(txBlock)
6135
+ );
6136
+ txBlock.transferObjects([rewardCoin], sender);
6137
+ }
6138
+ };
6139
+ };
6140
+ var newLoyaltyProgramTxBlock = (builder, initTxBlock) => {
6141
+ const txBlock = initTxBlock instanceof import_transactions4.TransactionBlock ? new import_sui_kit10.SuiTxBlock(initTxBlock) : initTxBlock ? initTxBlock : new import_sui_kit10.SuiTxBlock();
6142
+ const normalMethod = generateLoyaltyProgramNormalMethod({
6143
+ builder,
6144
+ txBlock
6145
+ });
6146
+ const normalTxBlock = new Proxy(txBlock, {
6147
+ get: (target, prop) => {
6148
+ if (prop in normalMethod) {
6149
+ return Reflect.get(normalMethod, prop);
6150
+ }
6151
+ return Reflect.get(target, prop);
6152
+ }
6153
+ });
6154
+ const quickMethod = generateLoyaltyProgramQuickMethod({
6155
+ builder,
6156
+ txBlock: normalTxBlock
6157
+ });
6158
+ return new Proxy(normalTxBlock, {
6159
+ get: (target, prop) => {
6160
+ if (prop in quickMethod) {
6161
+ return Reflect.get(quickMethod, prop);
6162
+ }
6163
+ return Reflect.get(target, prop);
6164
+ }
6165
+ });
6166
+ };
6167
+
6168
+ // src/builders/sCoinBuilder.ts
6169
+ var import_sui_kit11 = require("@scallop-io/sui-kit");
6170
+ var generateSCoinNormalMethod = ({
6171
+ builder,
6172
+ txBlock
6173
+ }) => {
6174
+ const sCoinPkgIds = {
6175
+ pkgId: builder.address.get("scoin.id")
6176
+ };
6177
+ return {
6178
+ mintSCoin: (marketCoinName, marketCoin) => {
6179
+ return txBlock.moveCall(
6180
+ `${sCoinPkgIds.pkgId}::s_coin_converter::mint_s_coin`,
6181
+ [builder.utils.getSCoinTreasury(marketCoinName), marketCoin],
6646
6182
  [
6647
- referralIds.version,
6648
- ticket,
6649
- referralIds.referralRevenuePool,
6650
- import_sui_kit9.SUI_CLOCK_OBJECT_ID
6651
- ],
6652
- [coinType]
6183
+ builder.utils.parseSCoinType(marketCoinName),
6184
+ builder.utils.parseUnderlyingSCoinType(marketCoinName)
6185
+ ]
6653
6186
  );
6654
6187
  },
6655
- claimReferralRevenue: (veScaKey, poolCoinName) => {
6656
- const coinType = builder.utils.parseCoinType(poolCoinName);
6188
+ burnSCoin: (sCoinName, sCoin) => {
6657
6189
  return txBlock.moveCall(
6658
- `${referralIds.referralPgkId}::referral_revenue_pool::claim_revenue_with_ve_sca_key`,
6190
+ `${sCoinPkgIds.pkgId}::s_coin_converter::burn_s_coin`,
6191
+ [builder.utils.getSCoinTreasury(sCoinName), sCoin],
6659
6192
  [
6660
- referralIds.version,
6661
- referralIds.referralRevenuePool,
6662
- veScaKey,
6663
- import_sui_kit9.SUI_CLOCK_OBJECT_ID
6664
- ],
6665
- [coinType]
6193
+ builder.utils.parseSCoinType(sCoinName),
6194
+ builder.utils.parseUnderlyingSCoinType(sCoinName)
6195
+ ]
6666
6196
  );
6667
6197
  }
6668
6198
  };
6669
6199
  };
6670
- var generateReferralQuickMethod = ({
6200
+ var generateSCoinQuickMethod = ({
6671
6201
  builder,
6672
6202
  txBlock
6673
6203
  }) => {
6674
6204
  return {
6675
- claimReferralRevenueQuick: async (veScaKey, coinNames = [...SUPPORT_POOLS]) => {
6205
+ mintSCoinQuick: async (marketCoinName, amount) => {
6676
6206
  const sender = requireSender(txBlock);
6677
- const objToTransfer = [];
6678
- for (const coinName of coinNames) {
6679
- if (coinName === "sui") {
6680
- const rewardCoin = txBlock.claimReferralRevenue(veScaKey, coinName);
6681
- objToTransfer.push(rewardCoin);
6682
- } else {
6683
- const rewardCoin = txBlock.claimReferralRevenue(veScaKey, coinName);
6684
- try {
6685
- const coins = await builder.suiKit.suiInteractor.selectCoins(
6686
- sender,
6687
- Infinity,
6688
- builder.utils.parseCoinType(coinName)
6689
- );
6690
- txBlock.mergeCoins(rewardCoin, coins.slice(0, 500));
6691
- } catch (e) {
6692
- } finally {
6693
- objToTransfer.push(rewardCoin);
6694
- }
6695
- }
6696
- }
6697
- if (objToTransfer.length > 0) {
6698
- txBlock.transferObjects(objToTransfer, sender);
6699
- }
6207
+ const { leftCoin, takeCoin } = await builder.selectMarketCoin(
6208
+ txBlock,
6209
+ marketCoinName,
6210
+ amount,
6211
+ sender
6212
+ );
6213
+ txBlock.transferObjects([leftCoin], sender);
6214
+ return txBlock.mintSCoin(marketCoinName, takeCoin);
6215
+ },
6216
+ burnSCoinQuick: async (sCoinName, amount) => {
6217
+ const sender = requireSender(txBlock);
6218
+ const { leftCoin, takeCoin } = await builder.selectSCoin(
6219
+ txBlock,
6220
+ sCoinName,
6221
+ amount,
6222
+ sender
6223
+ );
6224
+ txBlock.transferObjects([leftCoin], sender);
6225
+ return txBlock.burnSCoin(sCoinName, takeCoin);
6700
6226
  }
6701
6227
  };
6702
6228
  };
6703
- var newReferralTxBlock = (builder, initTxBlock) => {
6704
- const txBlock = initTxBlock instanceof import_sui_kit9.TransactionBlock ? new import_sui_kit9.SuiTxBlock(initTxBlock) : initTxBlock ? initTxBlock : new import_sui_kit9.SuiTxBlock();
6705
- const normalMethod = generateReferralNormalMethod({
6229
+ var newSCoinTxBlock = (builder, initTxBlock) => {
6230
+ const txBlock = initTxBlock instanceof import_sui_kit11.TransactionBlock ? new import_sui_kit11.SuiTxBlock(initTxBlock) : initTxBlock ? initTxBlock : new import_sui_kit11.SuiTxBlock();
6231
+ const normalMethod = generateSCoinNormalMethod({
6706
6232
  builder,
6707
6233
  txBlock
6708
6234
  });
@@ -6711,240 +6237,827 @@ var newReferralTxBlock = (builder, initTxBlock) => {
6711
6237
  if (prop in normalMethod) {
6712
6238
  return Reflect.get(normalMethod, prop);
6713
6239
  }
6714
- return Reflect.get(target, prop);
6240
+ return Reflect.get(target, prop);
6241
+ }
6242
+ });
6243
+ const quickMethod = generateSCoinQuickMethod({
6244
+ builder,
6245
+ txBlock: normalTxBlock
6246
+ });
6247
+ return new Proxy(normalTxBlock, {
6248
+ get: (target, prop) => {
6249
+ if (prop in quickMethod) {
6250
+ return Reflect.get(quickMethod, prop);
6251
+ }
6252
+ return Reflect.get(target, prop);
6253
+ }
6254
+ });
6255
+ };
6256
+
6257
+ // src/builders/index.ts
6258
+ var newScallopTxBlock = (builder, initTxBlock) => {
6259
+ const vescaTxBlock = newVeScaTxBlock(builder, initTxBlock);
6260
+ const loyaltyTxBlock = newLoyaltyProgramTxBlock(builder, vescaTxBlock);
6261
+ const borrowIncentiveTxBlock = newBorrowIncentiveTxBlock(
6262
+ builder,
6263
+ loyaltyTxBlock
6264
+ );
6265
+ const referralTxBlock = newReferralTxBlock(builder, borrowIncentiveTxBlock);
6266
+ const sCoinTxBlock = newSCoinTxBlock(builder, referralTxBlock);
6267
+ const spoolTxBlock = newSpoolTxBlock(builder, sCoinTxBlock);
6268
+ const coreTxBlock = newCoreTxBlock(builder, spoolTxBlock);
6269
+ return new Proxy(coreTxBlock, {
6270
+ get: (target, prop) => {
6271
+ if (prop in vescaTxBlock) {
6272
+ return Reflect.get(vescaTxBlock, prop);
6273
+ } else if (prop in borrowIncentiveTxBlock) {
6274
+ return Reflect.get(borrowIncentiveTxBlock, prop);
6275
+ } else if (prop in referralTxBlock) {
6276
+ return Reflect.get(referralTxBlock, prop);
6277
+ } else if (prop in spoolTxBlock) {
6278
+ return Reflect.get(spoolTxBlock, prop);
6279
+ } else if (prop in loyaltyTxBlock) {
6280
+ return Reflect.get(loyaltyTxBlock, prop);
6281
+ } else if (prop in sCoinTxBlock) {
6282
+ return Reflect.get(sCoinTxBlock, prop);
6283
+ }
6284
+ return Reflect.get(target, prop);
6285
+ }
6286
+ });
6287
+ };
6288
+
6289
+ // src/models/scallopQuery.ts
6290
+ var import_sui_kit13 = require("@scallop-io/sui-kit");
6291
+
6292
+ // src/models/scallopIndexer.ts
6293
+ var import_axios2 = __toESM(require("axios"));
6294
+ var import_sui_kit12 = require("@scallop-io/sui-kit");
6295
+ var ScallopIndexer = class {
6296
+ constructor(params, instance) {
6297
+ this.params = params;
6298
+ this.cache = instance?.cache ?? new ScallopCache(new import_sui_kit12.SuiKit({}), DEFAULT_CACHE_OPTIONS);
6299
+ this._requestClient = import_axios2.default.create({
6300
+ baseURL: SDK_API_BASE_URL,
6301
+ headers: {
6302
+ "Content-Type": "application/json",
6303
+ Accept: "application/json"
6304
+ },
6305
+ timeout: 3e4
6306
+ });
6307
+ }
6308
+ /**
6309
+ * Get market index data.
6310
+ *
6311
+ * @return Market data.
6312
+ */
6313
+ async getMarket() {
6314
+ const response = await this.cache.queryClient.fetchQuery({
6315
+ queryKey: ["market"],
6316
+ queryFn: async () => {
6317
+ return await this._requestClient.get(`/api/market`);
6318
+ }
6319
+ });
6320
+ if (response.status === 200) {
6321
+ return {
6322
+ pools: response.data.pools.reduce((marketPools, marketPool) => {
6323
+ marketPools[marketPool.coinName] = marketPool;
6324
+ return marketPools;
6325
+ }, {}),
6326
+ collaterals: response.data.collaterals.reduce(
6327
+ (marketCollaterals, marketCollateral) => {
6328
+ marketCollaterals[marketCollateral.coinName] = marketCollateral;
6329
+ return marketCollaterals;
6330
+ },
6331
+ {}
6332
+ )
6333
+ };
6334
+ } else {
6335
+ throw Error("Failed to getMarket.");
6336
+ }
6337
+ }
6338
+ /**
6339
+ * Get market pools index data.
6340
+ *
6341
+ * @return Market pools data.
6342
+ */
6343
+ async getMarketPools() {
6344
+ const response = (await this.getMarket()).pools;
6345
+ return response;
6346
+ }
6347
+ /**
6348
+ * Get market pool index data.
6349
+ *
6350
+ * @return Market pool data.
6351
+ */
6352
+ async getMarketPool(poolCoinName) {
6353
+ return (await this.getMarketPools())[poolCoinName];
6354
+ }
6355
+ /**
6356
+ * Get market collaterals index data.
6357
+ *
6358
+ * @return Market collaterals data.
6359
+ */
6360
+ async getMarketCollaterals() {
6361
+ return (await this.getMarket()).collaterals;
6362
+ }
6363
+ /**
6364
+ * Get market collateral index data.
6365
+ *
6366
+ * @return Market collateral data.
6367
+ */
6368
+ async getMarketCollateral(collateralCoinName) {
6369
+ return (await this.getMarketCollaterals())[collateralCoinName];
6370
+ }
6371
+ /**
6372
+ * Get spools index data.
6373
+ *
6374
+ * @return Spools data.
6375
+ */
6376
+ async getSpools() {
6377
+ const response = await this.cache.queryClient.fetchQuery({
6378
+ queryKey: ["spools"],
6379
+ queryFn: async () => {
6380
+ return await this._requestClient.get(`/api/spools`);
6381
+ }
6382
+ });
6383
+ if (response.status === 200) {
6384
+ return response.data.spools.reduce((spools, spool) => {
6385
+ spools[spool.marketCoinName] = spool;
6386
+ return spools;
6387
+ }, {});
6388
+ } else {
6389
+ throw Error("Failed to getSpools.");
6390
+ }
6391
+ }
6392
+ /**
6393
+ * Get spool index data.
6394
+ *
6395
+ * @return Spool data.
6396
+ */
6397
+ async getSpool(marketCoinName) {
6398
+ return (await this.getSpools())[marketCoinName];
6399
+ }
6400
+ /**
6401
+ * Get borrow incentive pools index data.
6402
+ *
6403
+ * @return Borrow incentive pools data.
6404
+ */
6405
+ async getBorrowIncentivePools() {
6406
+ const response = await this.cache.queryClient.fetchQuery({
6407
+ queryKey: ["borrowIncentivePools"],
6408
+ queryFn: async () => {
6409
+ return await this._requestClient.get(`/api/borrowIncentivePools`);
6410
+ }
6411
+ });
6412
+ if (response.status === 200) {
6413
+ return response.data.borrowIncentivePools.reduce(
6414
+ (borrowIncentivePools, borrowIncentivePool) => {
6415
+ if (Array.isArray(borrowIncentivePool.points)) {
6416
+ borrowIncentivePool.points = borrowIncentivePool.points.reduce(
6417
+ (prev, curr) => {
6418
+ prev[curr.coinName] = curr;
6419
+ return prev;
6420
+ },
6421
+ {}
6422
+ );
6423
+ }
6424
+ borrowIncentivePools[borrowIncentivePool.coinName] = borrowIncentivePool;
6425
+ return borrowIncentivePools;
6426
+ },
6427
+ {}
6428
+ );
6429
+ } else {
6430
+ throw Error("Failed to getBorrowIncentivePools.");
6715
6431
  }
6716
- });
6717
- const quickMethod = generateReferralQuickMethod({
6718
- builder,
6719
- txBlock: normalTxBlock
6720
- });
6721
- return new Proxy(normalTxBlock, {
6722
- get: (target, prop) => {
6723
- if (prop in quickMethod) {
6724
- return Reflect.get(quickMethod, prop);
6432
+ }
6433
+ /**
6434
+ * Get borrow incentive pool index data.
6435
+ *
6436
+ * @return Borrow incentive pool data.
6437
+ */
6438
+ async getBorrowIncentivePool(borrowIncentiveCoinName) {
6439
+ return (await this.getBorrowIncentivePools())[borrowIncentiveCoinName];
6440
+ }
6441
+ /**
6442
+ * Get total value locked index data.
6443
+ *
6444
+ * @return Total value locked.
6445
+ */
6446
+ async getTotalValueLocked() {
6447
+ const response = await this.cache.queryClient.fetchQuery({
6448
+ queryKey: ["totalValueLocked"],
6449
+ queryFn: async () => {
6450
+ return await this._requestClient.get(`/api/market/tvl`);
6725
6451
  }
6726
- return Reflect.get(target, prop);
6452
+ });
6453
+ if (response.status === 200) {
6454
+ return response.data;
6455
+ } else {
6456
+ throw Error("Failed to getTotalValueLocked.");
6727
6457
  }
6728
- });
6458
+ }
6729
6459
  };
6730
6460
 
6731
- // src/builders/loyaltyProgramBuilder.ts
6732
- var import_transactions4 = require("@mysten/sui.js/transactions");
6733
- var import_sui_kit10 = require("@scallop-io/sui-kit");
6734
- var generateLoyaltyProgramNormalMethod = ({ builder, txBlock }) => {
6735
- const loyaltyProgramIds = {
6736
- loyaltyProgramPkgId: builder.address.get("loyaltyProgram.id"),
6737
- rewardPool: builder.address.get("loyaltyProgram.rewardPool"),
6738
- userRewardTableId: builder.address.get(
6739
- "loyaltyProgram.userRewardTableId"
6740
- )
6741
- };
6742
- return {
6743
- claimLoyaltyRevenue: (veScaKey) => {
6744
- return txBlock.moveCall(
6745
- `${loyaltyProgramIds.loyaltyProgramPkgId}::reward_pool::redeem_reward`,
6746
- [loyaltyProgramIds.rewardPool, veScaKey]
6747
- );
6748
- }
6749
- };
6461
+ // src/queries/sCoinQuery.ts
6462
+ var import_bcs2 = require("@mysten/sui.js/bcs");
6463
+ var import_assert = __toESM(require("assert"));
6464
+ var import_bignumber7 = __toESM(require("bignumber.js"));
6465
+ var getSCoinTotalSupply = async ({
6466
+ utils
6467
+ }, sCoinName) => {
6468
+ const sCoinPkgId = utils.address.get("scoin.id");
6469
+ const args = [utils.getSCoinTreasury(sCoinName)];
6470
+ const typeArgs = [
6471
+ utils.parseSCoinType(sCoinName),
6472
+ utils.parseUnderlyingSCoinType(sCoinName)
6473
+ ];
6474
+ const queryTarget = `${sCoinPkgId}::s_coin_converter::total_supply`;
6475
+ const queryResults = await utils.cache.queryInspectTxn({
6476
+ queryTarget,
6477
+ args,
6478
+ typeArgs
6479
+ });
6480
+ const results = queryResults?.results;
6481
+ if (results && results[0].returnValues) {
6482
+ const value = Uint8Array.from(results[0].returnValues[0][0]);
6483
+ const type = results[0].returnValues[0][1];
6484
+ (0, import_assert.default)(type === "u64", "Result type is not u64");
6485
+ return (0, import_bignumber7.default)(import_bcs2.bcs.de(type, value)).shiftedBy(utils.getCoinDecimal(utils.parseCoinName(sCoinName))).toNumber();
6486
+ }
6487
+ return 0;
6750
6488
  };
6751
- var generateLoyaltyProgramQuickMethod = ({
6752
- builder,
6753
- txBlock
6754
- }) => {
6755
- return {
6756
- claimLoyaltyRevenueQuick: async (veScaKey) => {
6757
- veScaKey = veScaKey || (await builder.query.getVeScas())[0]?.keyObject;
6758
- const sender = requireSender(txBlock);
6759
- if (!veScaKey)
6760
- throw new Error(`No veScaKey found for user ${sender}`);
6761
- const rewardCoin = txBlock.claimLoyaltyRevenue(veScaKey);
6762
- await builder.utils.mergeSimilarCoins(
6763
- txBlock,
6764
- rewardCoin,
6765
- coinIds.sca,
6766
- requireSender(txBlock)
6767
- );
6768
- txBlock.transferObjects([rewardCoin], sender);
6769
- }
6770
- };
6489
+ var getSCoinAmounts = async ({
6490
+ utils
6491
+ }, sCoinNames, ownerAddress) => {
6492
+ sCoinNames = sCoinNames || [...SUPPORT_SCOIN];
6493
+ const owner = ownerAddress || utils.suiKit.currentAddress();
6494
+ const sCoins2 = {};
6495
+ await Promise.allSettled(
6496
+ sCoinNames.map(async (sCoinName) => {
6497
+ const sCoin = await getSCoinAmount({ utils }, sCoinName, owner);
6498
+ sCoins2[sCoinName] = sCoin;
6499
+ })
6500
+ );
6501
+ return sCoins2;
6771
6502
  };
6772
- var newLoyaltyProgramTxBlock = (builder, initTxBlock) => {
6773
- const txBlock = initTxBlock instanceof import_transactions4.TransactionBlock ? new import_sui_kit10.SuiTxBlock(initTxBlock) : initTxBlock ? initTxBlock : new import_sui_kit10.SuiTxBlock();
6774
- const normalMethod = generateLoyaltyProgramNormalMethod({
6775
- builder,
6776
- txBlock
6777
- });
6778
- const normalTxBlock = new Proxy(txBlock, {
6779
- get: (target, prop) => {
6780
- if (prop in normalMethod) {
6781
- return Reflect.get(normalMethod, prop);
6782
- }
6783
- return Reflect.get(target, prop);
6784
- }
6785
- });
6786
- const quickMethod = generateLoyaltyProgramQuickMethod({
6787
- builder,
6788
- txBlock: normalTxBlock
6789
- });
6790
- return new Proxy(normalTxBlock, {
6791
- get: (target, prop) => {
6792
- if (prop in quickMethod) {
6793
- return Reflect.get(quickMethod, prop);
6794
- }
6795
- return Reflect.get(target, prop);
6796
- }
6503
+ var getSCoinAmount = async ({
6504
+ utils
6505
+ }, sCoinName, ownerAddress) => {
6506
+ const owner = ownerAddress || utils.suiKit.currentAddress();
6507
+ const sCoinType = utils.parseSCoinType(sCoinName);
6508
+ const amount = await utils.cache.queryGetCoinBalance({
6509
+ owner,
6510
+ coinType: sCoinType
6797
6511
  });
6512
+ return (0, import_bignumber7.default)(amount).toNumber();
6798
6513
  };
6799
-
6800
- // src/builders/sCoinBuilder.ts
6801
- var import_sui_kit11 = require("@scallop-io/sui-kit");
6802
- var generateSCoinNormalMethod = ({
6803
- builder,
6804
- txBlock
6805
- }) => {
6806
- const sCoinPkgIds = {
6807
- pkgId: builder.address.get("scoin.id")
6808
- };
6809
- return {
6810
- mintSCoin: (marketCoinName, marketCoin) => {
6811
- return txBlock.moveCall(
6812
- `${sCoinPkgIds.pkgId}::s_coin_converter::mint_s_coin`,
6813
- [builder.utils.getSCoinTreasury(marketCoinName), marketCoin],
6814
- [
6815
- builder.utils.parseSCoinType(marketCoinName),
6816
- builder.utils.parseUnderlyingSCoinType(marketCoinName)
6817
- ]
6818
- );
6819
- },
6820
- burnSCoin: (sCoinName, sCoin) => {
6821
- return txBlock.moveCall(
6822
- `${sCoinPkgIds.pkgId}::s_coin_converter::burn_s_coin`,
6823
- [builder.utils.getSCoinTreasury(sCoinName), sCoin],
6824
- [
6825
- builder.utils.parseSCoinType(sCoinName),
6826
- builder.utils.parseUnderlyingSCoinType(sCoinName)
6827
- ]
6828
- );
6829
- }
6514
+ var isSupportStakeCoins = (value) => {
6515
+ return SUPPORT_SCOIN.includes(value);
6516
+ };
6517
+ var checkAssetParams = (fromSCoin, toSCoin) => {
6518
+ if (fromSCoin === toSCoin)
6519
+ throw new Error("fromAsset and toAsset must be different");
6520
+ if (!isSupportStakeCoins(fromSCoin))
6521
+ throw new Error("fromAsset is not supported");
6522
+ if (!isSupportStakeCoins(toSCoin)) {
6523
+ throw new Error("toAsset is not supported");
6524
+ }
6525
+ };
6526
+ var getSCoinSwapRate = async (query, fromSCoin, toSCoin, underlyingCoinPrice) => {
6527
+ checkAssetParams(fromSCoin, toSCoin);
6528
+ const fromCoinName = query.utils.parseCoinName(fromSCoin);
6529
+ const toCoinName = query.utils.parseCoinName(toSCoin);
6530
+ const marketPools = await Promise.all([
6531
+ query.getMarketPool(fromCoinName, false),
6532
+ query.getMarketPool(toCoinName, false)
6533
+ ]);
6534
+ if (marketPools.some((pool) => !pool))
6535
+ throw new Error("Failed to fetch the lendings data");
6536
+ if (marketPools.some((pool) => pool?.conversionRate === 0)) {
6537
+ throw new Error("Conversion rate cannot be zero");
6538
+ }
6539
+ const ScoinAToARate = marketPools[0].conversionRate;
6540
+ const BtoSCoinBRate = 1 / marketPools[1].conversionRate;
6541
+ const calcAtoBRate = async () => {
6542
+ const prices = await query.utils.getCoinPrices([fromCoinName, toCoinName]);
6543
+ if (!prices[fromCoinName] || !prices[toCoinName]) {
6544
+ throw new Error("Failed to fetch the coin prices");
6545
+ }
6546
+ if (prices[toCoinName] === 0) {
6547
+ throw new Error("Price of toCoin cannot be zero");
6548
+ }
6549
+ return prices[fromCoinName] / prices[toCoinName];
6830
6550
  };
6551
+ const AtoBRate = underlyingCoinPrice ?? await calcAtoBRate();
6552
+ return (0, import_bignumber7.default)(ScoinAToARate).multipliedBy(AtoBRate).multipliedBy(BtoSCoinBRate).toNumber();
6831
6553
  };
6832
- var generateSCoinQuickMethod = ({
6833
- builder,
6834
- txBlock
6835
- }) => {
6836
- return {
6837
- mintSCoinQuick: async (marketCoinName, amount) => {
6838
- const sender = requireSender(txBlock);
6839
- const { leftCoin, takeCoin } = await builder.selectMarketCoin(
6840
- txBlock,
6841
- marketCoinName,
6842
- amount,
6843
- sender
6844
- );
6845
- txBlock.transferObjects([leftCoin], sender);
6846
- return txBlock.mintSCoin(marketCoinName, takeCoin);
6847
- },
6848
- burnSCoinQuick: async (sCoinName, amount) => {
6849
- const sender = requireSender(txBlock);
6850
- const { leftCoin, takeCoin } = await builder.selectSCoin(
6851
- txBlock,
6852
- sCoinName,
6853
- amount,
6854
- sender
6554
+
6555
+ // src/models/scallopQuery.ts
6556
+ var import_utils23 = require("@mysten/sui.js/utils");
6557
+ var ScallopQuery = class {
6558
+ constructor(params, instance) {
6559
+ this.params = params;
6560
+ this.suiKit = instance?.suiKit ?? instance?.utils?.suiKit ?? new import_sui_kit13.SuiKit(params);
6561
+ if (instance?.utils) {
6562
+ this.utils = instance.utils;
6563
+ this.address = instance.utils.address;
6564
+ this.cache = this.address.cache;
6565
+ } else {
6566
+ this.cache = new ScallopCache(this.suiKit, DEFAULT_CACHE_OPTIONS);
6567
+ this.address = new ScallopAddress(
6568
+ {
6569
+ id: params?.addressesId || ADDRESSES_ID,
6570
+ network: params?.networkType
6571
+ },
6572
+ {
6573
+ cache: this.cache
6574
+ }
6855
6575
  );
6856
- txBlock.transferObjects([leftCoin], sender);
6857
- return txBlock.burnSCoin(sCoinName, takeCoin);
6858
- }
6859
- };
6860
- };
6861
- var newSCoinTxBlock = (builder, initTxBlock) => {
6862
- const txBlock = initTxBlock instanceof import_sui_kit11.TransactionBlock ? new import_sui_kit11.SuiTxBlock(initTxBlock) : initTxBlock ? initTxBlock : new import_sui_kit11.SuiTxBlock();
6863
- const normalMethod = generateSCoinNormalMethod({
6864
- builder,
6865
- txBlock
6866
- });
6867
- const normalTxBlock = new Proxy(txBlock, {
6868
- get: (target, prop) => {
6869
- if (prop in normalMethod) {
6870
- return Reflect.get(normalMethod, prop);
6871
- }
6872
- return Reflect.get(target, prop);
6576
+ this.utils = new ScallopUtils(this.params, {
6577
+ address: this.address
6578
+ });
6873
6579
  }
6874
- });
6875
- const quickMethod = generateSCoinQuickMethod({
6876
- builder,
6877
- txBlock: normalTxBlock
6878
- });
6879
- return new Proxy(normalTxBlock, {
6880
- get: (target, prop) => {
6881
- if (prop in quickMethod) {
6882
- return Reflect.get(quickMethod, prop);
6883
- }
6884
- return Reflect.get(target, prop);
6580
+ this.indexer = instance?.indexer ?? new ScallopIndexer(this.params, { cache: this.cache });
6581
+ this.walletAddress = (0, import_utils23.normalizeSuiAddress)(
6582
+ params.walletAddress || this.suiKit.currentAddress()
6583
+ );
6584
+ }
6585
+ /**
6586
+ * Request the scallop API to initialize data.
6587
+ *
6588
+ * @param force - Whether to force initialization.
6589
+ * @param address - ScallopAddress instance.
6590
+ */
6591
+ async init(force = false, address) {
6592
+ if (force || !this.address.getAddresses() || !address?.getAddresses()) {
6593
+ await this.address.read();
6594
+ } else {
6595
+ this.address = address;
6885
6596
  }
6886
- });
6887
- };
6888
-
6889
- // src/builders/index.ts
6890
- var newScallopTxBlock = (builder, initTxBlock) => {
6891
- const vescaTxBlock = newVeScaTxBlock(builder, initTxBlock);
6892
- const loyaltyTxBlock = newLoyaltyProgramTxBlock(builder, vescaTxBlock);
6893
- const borrowIncentiveTxBlock = newBorrowIncentiveTxBlock(
6894
- builder,
6895
- loyaltyTxBlock
6896
- );
6897
- const referralTxBlock = newReferralTxBlock(builder, borrowIncentiveTxBlock);
6898
- const sCoinTxBlock = newSCoinTxBlock(builder, referralTxBlock);
6899
- const spoolTxBlock = newSpoolTxBlock(builder, sCoinTxBlock);
6900
- const coreTxBlock = newCoreTxBlock(builder, spoolTxBlock);
6901
- return new Proxy(coreTxBlock, {
6902
- get: (target, prop) => {
6903
- if (prop in vescaTxBlock) {
6904
- return Reflect.get(vescaTxBlock, prop);
6905
- } else if (prop in borrowIncentiveTxBlock) {
6906
- return Reflect.get(borrowIncentiveTxBlock, prop);
6907
- } else if (prop in referralTxBlock) {
6908
- return Reflect.get(referralTxBlock, prop);
6909
- } else if (prop in spoolTxBlock) {
6910
- return Reflect.get(spoolTxBlock, prop);
6911
- } else if (prop in loyaltyTxBlock) {
6912
- return Reflect.get(loyaltyTxBlock, prop);
6913
- } else if (prop in sCoinTxBlock) {
6914
- return Reflect.get(sCoinTxBlock, prop);
6597
+ await this.utils.init(force, this.address);
6598
+ }
6599
+ /* ==================== Core Query Methods ==================== */
6600
+ /**
6601
+ * Query market data.
6602
+ * @param indexer - Whether to use indexer.
6603
+ * @return Market data.
6604
+ */
6605
+ async queryMarket(indexer = false) {
6606
+ return await queryMarket(this, indexer);
6607
+ }
6608
+ /**
6609
+ * Get market pools.
6610
+ *
6611
+ * @description
6612
+ * To obtain all market pools at once, it is recommended to use
6613
+ * the `queryMarket` method to reduce time consumption.
6614
+ *
6615
+ * @param poolCoinNames - Specific an array of support pool coin name.
6616
+ * @param indexer - Whether to use indexer.
6617
+ * @return Market pools data.
6618
+ */
6619
+ async getMarketPools(poolCoinNames, indexer = false) {
6620
+ return await getMarketPools(this, poolCoinNames, indexer);
6621
+ }
6622
+ /**
6623
+ * Get market pool
6624
+ *
6625
+ * @param poolCoinName - Specific support pool coin name.
6626
+ * @param indexer - Whether to use indexer.
6627
+ * @return Market pool data.
6628
+ */
6629
+ async getMarketPool(poolCoinName, indexer = false) {
6630
+ return await getMarketPool(this, poolCoinName, indexer);
6631
+ }
6632
+ /**
6633
+ * Get market collaterals.
6634
+ *
6635
+ * @description
6636
+ * To obtain all market collaterals at once, it is recommended to use
6637
+ * the `queryMarket` method to reduce time consumption.
6638
+ *
6639
+ * @param collateralCoinNames - Specific an array of support collateral coin name.
6640
+ * @param indexer - Whether to use indexer.
6641
+ * @return Market collaterals data.
6642
+ */
6643
+ async getMarketCollaterals(collateralCoinNames, indexer = false) {
6644
+ return await getMarketCollaterals(this, collateralCoinNames, indexer);
6645
+ }
6646
+ /**
6647
+ * Get market collateral
6648
+ *
6649
+ * @param collateralCoinName - Specific support collateral coin name.
6650
+ * @param indexer - Whether to use indexer.
6651
+ * @return Market collateral data.
6652
+ */
6653
+ async getMarketCollateral(collateralCoinName, indexer = false) {
6654
+ return await getMarketCollateral(this, collateralCoinName, indexer);
6655
+ }
6656
+ /**
6657
+ * Get obligations data.
6658
+ *
6659
+ * @param ownerAddress - The owner address.
6660
+ * @return Obligations data.
6661
+ */
6662
+ async getObligations(ownerAddress = this.walletAddress) {
6663
+ return await getObligations(this, ownerAddress);
6664
+ }
6665
+ /**
6666
+ * Query obligation data.
6667
+ *
6668
+ * @param obligationId - The obligation id.
6669
+ * @return Obligation data.
6670
+ */
6671
+ async queryObligation(obligationId) {
6672
+ return queryObligation(this, obligationId);
6673
+ }
6674
+ /**
6675
+ * Get all asset coin amounts.
6676
+ *
6677
+ * @param assetCoinNames - Specific an array of support asset coin name.
6678
+ * @param ownerAddress - The owner address.
6679
+ * @return All coin amounts.
6680
+ */
6681
+ async getCoinAmounts(assetCoinNames, ownerAddress = this.walletAddress) {
6682
+ return await getCoinAmounts(this, assetCoinNames, ownerAddress);
6683
+ }
6684
+ /**
6685
+ * Get asset coin amount.
6686
+ *
6687
+ * @param assetCoinName - Specific support asset coin name.
6688
+ * @param ownerAddress - The owner address.
6689
+ * @return Coin amount.
6690
+ */
6691
+ async getCoinAmount(assetCoinName, ownerAddress = this.walletAddress) {
6692
+ return await getCoinAmount(this, assetCoinName, ownerAddress);
6693
+ }
6694
+ /**
6695
+ * Get all market coin amounts.
6696
+ *
6697
+ * @param coinNames - Specific an array of support market coin name.
6698
+ * @param ownerAddress - The owner address.
6699
+ * @return All market market coin amounts.
6700
+ */
6701
+ async getMarketCoinAmounts(marketCoinNames, ownerAddress = this.walletAddress) {
6702
+ return await getMarketCoinAmounts(this, marketCoinNames, ownerAddress);
6703
+ }
6704
+ /**
6705
+ * Get market coin amount.
6706
+ *
6707
+ * @param coinNames - Specific support market coin name.
6708
+ * @param ownerAddress - The owner address.
6709
+ * @return Market market coin amount.
6710
+ */
6711
+ async getMarketCoinAmount(marketCoinName, ownerAddress = this.walletAddress) {
6712
+ return await getMarketCoinAmount(this, marketCoinName, ownerAddress);
6713
+ }
6714
+ /**
6715
+ * Get price from pyth fee object.
6716
+ *
6717
+ * @param assetCoinName - Specific support asset coin name.
6718
+ * @return Asset coin price.
6719
+ */
6720
+ async getPriceFromPyth(assetCoinName) {
6721
+ return await getPythPrice(this, assetCoinName);
6722
+ }
6723
+ /**
6724
+ * Get prices from pyth fee object.
6725
+ *
6726
+ * @param assetCoinNames - Array of supported asset coin names.
6727
+ * @return Array of asset coin prices.
6728
+ */
6729
+ async getPricesFromPyth(assetCoinNames) {
6730
+ return await getPythPrices(this, assetCoinNames);
6731
+ }
6732
+ /* ==================== Spool Query Methods ==================== */
6733
+ /**
6734
+ * Get spools data.
6735
+ *
6736
+ * @param stakeMarketCoinNames - Specific an array of support stake market coin name.
6737
+ * @param indexer - Whether to use indexer.
6738
+ * @return Spools data.
6739
+ */
6740
+ async getSpools(stakeMarketCoinNames, indexer = false) {
6741
+ return await getSpools(this, stakeMarketCoinNames, indexer);
6742
+ }
6743
+ /**
6744
+ * Get spool data.
6745
+ *
6746
+ * @param stakeMarketCoinName - Specific support stake market coin name.
6747
+ * @param indexer - Whether to use indexer.
6748
+ * @return Spool data.
6749
+ */
6750
+ async getSpool(stakeMarketCoinName, indexer = false) {
6751
+ return await getSpool(this, stakeMarketCoinName, indexer);
6752
+ }
6753
+ /**
6754
+ * Get stake accounts data for all stake pools (spools).
6755
+ *
6756
+ * @param ownerAddress - The owner address.
6757
+ * @return All Stake accounts data.
6758
+ */
6759
+ async getAllStakeAccounts(ownerAddress = this.walletAddress) {
6760
+ return await getStakeAccounts(this, ownerAddress);
6761
+ }
6762
+ /**
6763
+ * Get stake accounts data for specific stake pool (spool).
6764
+ *
6765
+ * @param stakeMarketCoinName - Specific support stake market coin name.
6766
+ * @param ownerAddress - The owner address.
6767
+ * @return Stake accounts data.
6768
+ */
6769
+ async getStakeAccounts(stakeMarketCoinName, ownerAddress = this.walletAddress) {
6770
+ const allStakeAccount = await this.getAllStakeAccounts(ownerAddress);
6771
+ return allStakeAccount[stakeMarketCoinName] ?? [];
6772
+ }
6773
+ /**
6774
+ * Get stake pools (spools) data.
6775
+ *
6776
+ * @description
6777
+ * For backward compatible, it is recommended to use `getSpools` method
6778
+ * to get all spools data.
6779
+ *
6780
+ * @param stakeMarketCoinNames - Specific an array of support stake market coin name.
6781
+ * @return Stake pools data.
6782
+ */
6783
+ async getStakePools(stakeMarketCoinNames = [...SUPPORT_SPOOLS]) {
6784
+ const stakePools = {};
6785
+ for (const stakeMarketCoinName of stakeMarketCoinNames) {
6786
+ const stakePool = await getStakePool(this, stakeMarketCoinName);
6787
+ if (stakePool) {
6788
+ stakePools[stakeMarketCoinName] = stakePool;
6915
6789
  }
6916
- return Reflect.get(target, prop);
6917
6790
  }
6918
- });
6791
+ return stakePools;
6792
+ }
6793
+ /**
6794
+ * Get stake pool (spool) data.
6795
+ *
6796
+ * @description
6797
+ * For backward compatible, it is recommended to use `getSpool` method
6798
+ * to get all spool data.
6799
+ *
6800
+ * @param stakeMarketCoinName - Specific support stake market coin name.
6801
+ * @return Stake pool data.
6802
+ */
6803
+ async getStakePool(stakeMarketCoinName) {
6804
+ return await getStakePool(this, stakeMarketCoinName);
6805
+ }
6806
+ /**
6807
+ * Get stake reward pools data.
6808
+ *
6809
+ * @description
6810
+ * For backward compatible, it is recommended to use `getSpools` method
6811
+ * to get all spools data.
6812
+ *
6813
+ * @param stakeMarketCoinNames - Specific an array of stake market coin name.
6814
+ * @return Stake reward pools data.
6815
+ */
6816
+ async getStakeRewardPools(stakeMarketCoinNames = [...SUPPORT_SPOOLS]) {
6817
+ const stakeRewardPools = {};
6818
+ await Promise.allSettled(
6819
+ stakeMarketCoinNames.map(async (stakeMarketCoinName) => {
6820
+ const stakeRewardPool = await getStakeRewardPool(
6821
+ this,
6822
+ stakeMarketCoinName
6823
+ );
6824
+ if (stakeRewardPool) {
6825
+ stakeRewardPools[stakeMarketCoinName] = stakeRewardPool;
6826
+ }
6827
+ })
6828
+ );
6829
+ return stakeRewardPools;
6830
+ }
6831
+ /**
6832
+ * Get stake reward pool data.
6833
+ *
6834
+ * @description
6835
+ * For backward compatible, it is recommended to use `getSpool` method
6836
+ * to get spool data.
6837
+ *
6838
+ * @param marketCoinName - Specific support stake market coin name.
6839
+ * @return Stake reward pool data.
6840
+ */
6841
+ async getStakeRewardPool(stakeMarketCoinName) {
6842
+ return await getStakeRewardPool(this, stakeMarketCoinName);
6843
+ }
6844
+ /**
6845
+ * Get borrow incentive pools data.
6846
+ *
6847
+ * @param coinNames - Specific an array of support borrow incentive coin name.
6848
+ * @param indexer - Whether to use indexer.
6849
+ * @return Borrow incentive pools data.
6850
+ */
6851
+ async getBorrowIncentivePools(coinNames, indexer = false) {
6852
+ return await queryBorrowIncentivePools(this, coinNames, indexer);
6853
+ }
6854
+ /**
6855
+ * Get borrow incentive accounts data.
6856
+ *
6857
+ * @param coinNames - Specific support borrow incentive coin name.
6858
+ * @param ownerAddress - The owner address.
6859
+ * @return Borrow incentive accounts data.
6860
+ */
6861
+ async getBorrowIncentiveAccounts(obligationId, coinNames) {
6862
+ return await queryBorrowIncentiveAccounts(this, obligationId, coinNames);
6863
+ }
6864
+ /**
6865
+ * Get user lending and spool infomation for specific pools.
6866
+ *
6867
+ * @param poolCoinNames - Specific an array of support pool coin name.
6868
+ * @param ownerAddress - The owner address.
6869
+ * @param indexer - Whether to use indexer.
6870
+ * @return All lending and spool infomation.
6871
+ */
6872
+ async getLendings(poolCoinNames, ownerAddress = this.walletAddress, indexer = false) {
6873
+ return await getLendings(this, poolCoinNames, ownerAddress, indexer);
6874
+ }
6875
+ /**
6876
+ * Get user lending and spool information for specific pool.
6877
+ *
6878
+ * @param poolCoinName - Specific support pool coin name.
6879
+ * @param ownerAddress - The owner address.
6880
+ * @param indexer - Whether to use indexer.
6881
+ * @return Lending pool data.
6882
+ */
6883
+ async getLending(poolCoinName, ownerAddress = this.walletAddress, indexer = false) {
6884
+ return await getLending(this, poolCoinName, ownerAddress, indexer);
6885
+ }
6886
+ /**
6887
+ * Get user all obligation accounts information.
6888
+ *
6889
+ * @description
6890
+ * All collateral and borrowing information in all obligation accounts owned by the user.
6891
+ *
6892
+ * @param ownerAddress - The owner address.
6893
+ * @param indexer - Whether to use indexer.
6894
+ * @return All obligation accounts information.
6895
+ */
6896
+ async getObligationAccounts(ownerAddress = this.walletAddress, indexer = false) {
6897
+ return await getObligationAccounts(this, ownerAddress, indexer);
6898
+ }
6899
+ /**
6900
+ * Get obligation account information for specific id.
6901
+ *
6902
+ * @description
6903
+ * borrowing and obligation information for specific pool.
6904
+ *
6905
+ * @param obligationId - The obligation id.
6906
+ * @param ownerAddress - The owner address.
6907
+ * @param indexer - Whether to use indexer.
6908
+ * @return Borrowing and collateral information.
6909
+ */
6910
+ async getObligationAccount(obligationId, ownerAddress = this.walletAddress, indexer = false) {
6911
+ return await getObligationAccount(
6912
+ this,
6913
+ obligationId,
6914
+ ownerAddress,
6915
+ indexer
6916
+ );
6917
+ }
6918
+ /**
6919
+ * Get total value locked.
6920
+ *
6921
+ * @param indexer - Whether to use indexer.
6922
+ * @description
6923
+ * Include total supplied value and total borrowed value.
6924
+ *
6925
+ * @return Total value locked.
6926
+ */
6927
+ async getTvl(indexer = false) {
6928
+ return await getTotalValueLocked(this, indexer);
6929
+ }
6930
+ /**
6931
+ * Get all veSca from walletAdddress
6932
+ * @param walletAddress
6933
+ * @returns array of veSca
6934
+ */
6935
+ async getVeScas(walletAddress = this.walletAddress) {
6936
+ return await getVeScas(this, walletAddress);
6937
+ }
6938
+ /**
6939
+ * Get total vesca treasury with movecall
6940
+ * @returns Promise<string | undefined>
6941
+ */
6942
+ async getVeScaTreasuryInfo() {
6943
+ return await getVeScaTreasuryInfo(this.utils);
6944
+ }
6945
+ /**
6946
+ * Return binded referrer veScaKeyId of referee walletAddress if exist
6947
+ * @param walletAddress
6948
+ * @returns veScaKeyId
6949
+ */
6950
+ async getVeScaKeyIdFromReferralBindings(walletAddress = this.walletAddress) {
6951
+ return await queryVeScaKeyIdFromReferralBindings(
6952
+ this.address,
6953
+ walletAddress
6954
+ );
6955
+ }
6956
+ /**
6957
+ * Get binded obligationId from a veScaKey if it exists.
6958
+ * @param veScaKey
6959
+ * @returns obligationId
6960
+ */
6961
+ async getBindedObligationId(veScaKey) {
6962
+ return await getBindedObligationId(this, veScaKey);
6963
+ }
6964
+ /**
6965
+ * Get binded veSCA key from a obligationId if it exists.
6966
+ * @param obligationId
6967
+ * @returns veScaKey
6968
+ */
6969
+ async getBindedVeScaKey(obligationId) {
6970
+ return await getBindedVeScaKey(this, obligationId);
6971
+ }
6972
+ /**
6973
+ * Get user's veSCA loyalty program informations
6974
+ * @param walletAddress
6975
+ * @returns Loyalty program information
6976
+ */
6977
+ async getLoyaltyProgramInfos(veScaKey) {
6978
+ return await getLoyaltyProgramInformations(this, veScaKey);
6979
+ }
6980
+ /**
6981
+ * Get total supply of sCoin
6982
+ * @param sCoinName - Supported sCoin name
6983
+ * @returns Total Supply
6984
+ */
6985
+ async getSCoinTotalSupply(sCoinName) {
6986
+ return await getSCoinTotalSupply(this, sCoinName);
6987
+ }
6988
+ /**
6989
+ * Get all sCoin amounts.
6990
+ *
6991
+ * @param sCoinNames - Specific an array of support sCoin name.
6992
+ * @param ownerAddress - The owner address.
6993
+ * @return All market sCoin amounts.
6994
+ */
6995
+ async getSCoinAmounts(sCoinNames, ownerAddress = this.walletAddress) {
6996
+ return await getSCoinAmounts(this, sCoinNames, ownerAddress);
6997
+ }
6998
+ /**
6999
+ * Get sCoin amount.
7000
+ *
7001
+ * @param coinNames - Specific support sCoin name.
7002
+ * @param ownerAddress - The owner address.
7003
+ * @return sCoin amount.
7004
+ */
7005
+ async getSCoinAmount(sCoinName, ownerAddress = this.walletAddress) {
7006
+ const parsedSCoinName = this.utils.parseSCoinName(sCoinName);
7007
+ return parsedSCoinName ? await getSCoinAmount(this, parsedSCoinName, ownerAddress) : 0;
7008
+ }
7009
+ /**
7010
+ * Get swap rate from sCoin A to sCoin B
7011
+ * @param assetCoinNames
7012
+ * @returns
7013
+ */
7014
+ async getSCoinSwapRate(fromSCoin, toSCoin) {
7015
+ return await getSCoinSwapRate(this, fromSCoin, toSCoin);
7016
+ }
7017
+ /*
7018
+ * Get flashloan fee for specified assets
7019
+ */
7020
+ async getFlashLoanFees(assetCoinNames = [...SUPPORT_POOLS]) {
7021
+ return await getFlashLoanFees(this, assetCoinNames);
7022
+ }
6919
7023
  };
6920
7024
 
6921
7025
  // src/models/scallopBuilder.ts
6922
7026
  var ScallopBuilder = class {
6923
7027
  constructor(params, instance) {
7028
+ this.suiKit = instance?.suiKit ?? new import_sui_kit14.SuiKit(params);
6924
7029
  this.params = params;
6925
- this.suiKit = instance?.suiKit ?? new import_sui_kit12.SuiKit(params);
6926
- this.cache = instance?.cache ?? new ScallopCache(DEFAULT_CACHE_OPTIONS, this.suiKit);
6927
- this.address = instance?.address ?? new ScallopAddress(
6928
- {
6929
- id: params?.addressesId || ADDRESSES_ID,
6930
- network: params?.networkType
6931
- },
6932
- this.cache
6933
- );
6934
- this.query = instance?.query ?? new ScallopQuery(params, {
6935
- suiKit: this.suiKit,
6936
- address: this.address,
6937
- cache: this.cache
6938
- });
6939
- this.utils = instance?.utils ?? new ScallopUtils(this.params, {
6940
- suiKit: this.suiKit,
6941
- address: this.address,
6942
- query: this.query,
6943
- cache: this.cache
6944
- });
6945
7030
  this.walletAddress = (0, import_utils24.normalizeSuiAddress)(
6946
7031
  params?.walletAddress || this.suiKit.currentAddress()
6947
7032
  );
7033
+ if (instance?.query) {
7034
+ this.query = instance.query;
7035
+ this.utils = this.query.utils;
7036
+ this.address = this.utils.address;
7037
+ this.cache = this.address.cache;
7038
+ } else {
7039
+ this.cache = new ScallopCache(this.suiKit, DEFAULT_CACHE_OPTIONS);
7040
+ this.address = new ScallopAddress(
7041
+ {
7042
+ id: params?.addressesId || ADDRESSES_ID,
7043
+ network: params?.networkType
7044
+ },
7045
+ {
7046
+ cache: this.cache
7047
+ }
7048
+ );
7049
+ this.utils = new ScallopUtils(this.params, {
7050
+ address: this.address
7051
+ });
7052
+ this.query = new ScallopQuery(
7053
+ {
7054
+ walletAddress: this.walletAddress
7055
+ },
7056
+ {
7057
+ utils: this.utils
7058
+ }
7059
+ );
7060
+ }
6948
7061
  this.isTestnet = params.networkType ? params.networkType === "testnet" : false;
6949
7062
  }
6950
7063
  /**
@@ -7050,36 +7163,37 @@ var ScallopBuilder = class {
7050
7163
  var ScallopClient = class {
7051
7164
  constructor(params, instance) {
7052
7165
  this.params = params;
7053
- this.suiKit = instance?.suiKit ?? new import_sui_kit13.SuiKit(params);
7054
- this.cache = instance?.cache ?? new ScallopCache(DEFAULT_CACHE_OPTIONS, this.suiKit);
7055
- this.address = instance?.address ?? new ScallopAddress(
7056
- {
7057
- id: params?.addressesId || ADDRESSES_ID,
7058
- network: params?.networkType
7059
- },
7060
- this.cache
7061
- );
7062
- this.query = instance?.query ?? new ScallopQuery(params, {
7063
- suiKit: this.suiKit,
7064
- address: this.address,
7065
- cache: this.cache
7066
- });
7067
- this.utils = instance?.utils ?? new ScallopUtils(params, {
7068
- suiKit: this.suiKit,
7069
- address: this.address,
7070
- query: this.query,
7071
- cache: this.cache
7072
- });
7073
- this.builder = instance?.builder ?? new ScallopBuilder(params, {
7074
- suiKit: this.suiKit,
7075
- address: this.address,
7076
- query: this.query,
7077
- utils: this.utils,
7078
- cache: this.cache
7079
- });
7166
+ this.suiKit = instance?.suiKit ?? instance?.builder?.suiKit ?? new import_sui_kit15.SuiKit(params);
7080
7167
  this.walletAddress = (0, import_utils25.normalizeSuiAddress)(
7081
7168
  params?.walletAddress || this.suiKit.currentAddress()
7082
7169
  );
7170
+ if (instance?.builder) {
7171
+ this.builder = instance.builder;
7172
+ this.query = this.builder.query;
7173
+ this.utils = this.query.utils;
7174
+ this.address = this.utils.address;
7175
+ this.cache = this.address.cache;
7176
+ } else {
7177
+ this.cache = new ScallopCache(this.suiKit, DEFAULT_CACHE_OPTIONS);
7178
+ this.address = new ScallopAddress(
7179
+ {
7180
+ id: params?.addressesId || ADDRESSES_ID,
7181
+ network: params?.networkType
7182
+ },
7183
+ {
7184
+ cache: this.cache
7185
+ }
7186
+ );
7187
+ this.utils = new ScallopUtils(this.params, {
7188
+ address: this.address
7189
+ });
7190
+ this.query = new ScallopQuery(this.params, {
7191
+ utils: this.utils
7192
+ });
7193
+ this.builder = new ScallopBuilder(this.params, {
7194
+ query: this.query
7195
+ });
7196
+ }
7083
7197
  }
7084
7198
  /**
7085
7199
  * Request the scallop API to initialize data.
@@ -7645,6 +7759,48 @@ var ScallopClient = class {
7645
7759
  return txBlock.txBlock;
7646
7760
  }
7647
7761
  }
7762
+ async claimAllUnlockedSca(sign = true) {
7763
+ const veScaKeys = (await this.query.getVeScas(this.walletAddress) ?? []).map(({ keyObject }) => keyObject);
7764
+ if (veScaKeys.length === 0) {
7765
+ throw new Error("No veSCA found in the wallet");
7766
+ }
7767
+ const scaCoins = [];
7768
+ const tx = this.builder.createTxBlock();
7769
+ tx.setSender(this.walletAddress);
7770
+ await Promise.all(
7771
+ veScaKeys.map(async (key) => {
7772
+ try {
7773
+ const scaCoin = await tx.redeemScaQuick(key, false);
7774
+ if (!scaCoin)
7775
+ return;
7776
+ scaCoins.push(scaCoin);
7777
+ } catch (e) {
7778
+ }
7779
+ })
7780
+ );
7781
+ if (scaCoins.length === 0) {
7782
+ throw new Error("No unlocked SCA found in the veSCA accounts");
7783
+ }
7784
+ if (scaCoins.length > 1) {
7785
+ tx.mergeCoins(scaCoins[0], scaCoins.slice(1));
7786
+ }
7787
+ await this.utils.mergeSimilarCoins(
7788
+ tx,
7789
+ scaCoins[0],
7790
+ "sca",
7791
+ this.walletAddress
7792
+ );
7793
+ if (sign) {
7794
+ return await this.suiKit.signAndSendTxn(
7795
+ tx
7796
+ );
7797
+ } else {
7798
+ return {
7799
+ tx: tx.txBlock,
7800
+ scaCoin: scaCoins[0]
7801
+ };
7802
+ }
7803
+ }
7648
7804
  async mintTestCoin(assetCoinName, amount, sign = true, receiveAddress) {
7649
7805
  const isTestnet = this.params.networkType ? this.params.networkType === "testnet" : false;
7650
7806
  if (!isTestnet) {
@@ -7671,18 +7827,18 @@ var ScallopClient = class {
7671
7827
  var Scallop = class {
7672
7828
  constructor(params, cacheOptions, tokenBucket) {
7673
7829
  this.params = params;
7674
- this.suiKit = new import_sui_kit14.SuiKit(params);
7830
+ this.suiKit = new import_sui_kit16.SuiKit(params);
7675
7831
  this.cache = new ScallopCache(
7676
- cacheOptions ?? DEFAULT_CACHE_OPTIONS,
7677
7832
  this.suiKit,
7833
+ cacheOptions ?? DEFAULT_CACHE_OPTIONS,
7678
7834
  tokenBucket ?? new TokenBucket(DEFAULT_TOKENS_PER_INTERVAL, DEFAULT_INTERVAL_IN_MS)
7679
7835
  );
7680
- this._address = new ScallopAddress(
7836
+ this.address = new ScallopAddress(
7681
7837
  {
7682
7838
  id: params?.addressesId || ADDRESSES_ID,
7683
7839
  network: params?.networkType
7684
7840
  },
7685
- this.cache
7841
+ { cache: this.cache }
7686
7842
  );
7687
7843
  }
7688
7844
  /**
@@ -7692,8 +7848,8 @@ var Scallop = class {
7692
7848
  * @return Scallop Address.
7693
7849
  */
7694
7850
  async getScallopAddress(id) {
7695
- await this._address.read(id);
7696
- return this._address;
7851
+ await this.address.read(id);
7852
+ return this.address;
7697
7853
  }
7698
7854
  /**
7699
7855
  * Create a scallop builder instance that already has initial data.
@@ -7701,12 +7857,10 @@ var Scallop = class {
7701
7857
  * @return Scallop Builder.
7702
7858
  */
7703
7859
  async createScallopBuilder() {
7704
- if (!this._address.getAddresses())
7705
- await this._address.read();
7860
+ if (!this.address.getAddresses())
7861
+ await this.address.read();
7706
7862
  const scallopBuilder = new ScallopBuilder(this.params, {
7707
- suiKit: this.suiKit,
7708
- address: this._address,
7709
- cache: this.cache
7863
+ query: await this.createScallopQuery()
7710
7864
  });
7711
7865
  return scallopBuilder;
7712
7866
  }
@@ -7717,11 +7871,11 @@ var Scallop = class {
7717
7871
  * @return Scallop Client.
7718
7872
  */
7719
7873
  async createScallopClient(walletAddress) {
7720
- if (!this._address.getAddresses())
7721
- await this._address.read();
7874
+ if (!this.address.getAddresses())
7875
+ await this.address.read();
7722
7876
  const scallopClient = new ScallopClient(
7723
7877
  { ...this.params, walletAddress },
7724
- { suiKit: this.suiKit, address: this._address, cache: this.cache }
7878
+ { builder: await this.createScallopBuilder() }
7725
7879
  );
7726
7880
  return scallopClient;
7727
7881
  }
@@ -7731,12 +7885,10 @@ var Scallop = class {
7731
7885
  * @return Scallop Query.
7732
7886
  */
7733
7887
  async createScallopQuery() {
7734
- if (!this._address.getAddresses())
7735
- await this._address.read();
7888
+ if (!this.address.getAddresses())
7889
+ await this.address.read();
7736
7890
  const scallopQuery = new ScallopQuery(this.params, {
7737
- suiKit: this.suiKit,
7738
- address: this._address,
7739
- cache: this.cache
7891
+ utils: await this.createScallopUtils()
7740
7892
  });
7741
7893
  return scallopQuery;
7742
7894
  }
@@ -7757,12 +7909,10 @@ var Scallop = class {
7757
7909
  * @return Scallop Utils.
7758
7910
  */
7759
7911
  async createScallopUtils() {
7760
- if (!this._address.getAddresses())
7761
- await this._address.read();
7912
+ if (!this.address.getAddresses())
7913
+ await this.address.read();
7762
7914
  const scallopUtils = new ScallopUtils(this.params, {
7763
- suiKit: this.suiKit,
7764
- address: this._address,
7765
- cache: this.cache
7915
+ address: this.address
7766
7916
  });
7767
7917
  return scallopUtils;
7768
7918
  }