@scallop-io/sui-scallop-sdk 0.44.18 → 0.44.20

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 (56) hide show
  1. package/dist/builders/borrowIncentiveBuilder.d.ts +7 -0
  2. package/dist/builders/vescaBuilder.d.ts +24 -0
  3. package/dist/constants/common.d.ts +7 -4
  4. package/dist/constants/index.d.ts +1 -0
  5. package/dist/constants/vesca.d.ts +5 -0
  6. package/dist/index.js +888 -255
  7. package/dist/index.js.map +1 -1
  8. package/dist/index.mjs +877 -248
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/models/scallopClient.d.ts +7 -7
  11. package/dist/models/scallopUtils.d.ts +16 -14
  12. package/dist/queries/index.d.ts +1 -0
  13. package/dist/queries/vescaQuery.d.ts +28 -0
  14. package/dist/types/address.d.ts +9 -0
  15. package/dist/types/builder/borrowIncentive.d.ts +9 -6
  16. package/dist/types/builder/index.d.ts +3 -1
  17. package/dist/types/builder/vesca.d.ts +33 -0
  18. package/dist/types/constant/enum.d.ts +1 -1
  19. package/dist/types/query/borrowIncentive.d.ts +65 -60
  20. package/dist/types/query/index.d.ts +1 -0
  21. package/dist/types/query/portfolio.d.ts +12 -6
  22. package/dist/types/query/vesca.d.ts +7 -0
  23. package/dist/types/utils.d.ts +1 -2
  24. package/dist/utils/builder.d.ts +6 -0
  25. package/dist/utils/query.d.ts +4 -10
  26. package/dist/utils/util.d.ts +7 -0
  27. package/package.json +1 -1
  28. package/src/builders/borrowIncentiveBuilder.ts +174 -25
  29. package/src/builders/index.ts +6 -2
  30. package/src/builders/vescaBuilder.ts +392 -0
  31. package/src/constants/common.ts +19 -6
  32. package/src/constants/enum.ts +9 -3
  33. package/src/constants/index.ts +1 -0
  34. package/src/constants/vesca.ts +7 -0
  35. package/src/models/scallopAddress.ts +9 -1
  36. package/src/models/scallopClient.ts +29 -20
  37. package/src/models/scallopUtils.ts +45 -0
  38. package/src/queries/borrowIncentiveQuery.ts +93 -83
  39. package/src/queries/coreQuery.ts +19 -20
  40. package/src/queries/index.ts +1 -0
  41. package/src/queries/portfolioQuery.ts +79 -41
  42. package/src/queries/spoolQuery.ts +1 -1
  43. package/src/queries/vescaQuery.ts +124 -0
  44. package/src/types/address.ts +9 -0
  45. package/src/types/builder/borrowIncentive.ts +22 -5
  46. package/src/types/builder/index.ts +4 -1
  47. package/src/types/builder/vesca.ts +73 -0
  48. package/src/types/constant/enum.ts +1 -1
  49. package/src/types/query/borrowIncentive.ts +195 -74
  50. package/src/types/query/index.ts +1 -0
  51. package/src/types/query/portfolio.ts +17 -6
  52. package/src/types/query/vesca.ts +7 -0
  53. package/src/types/utils.ts +1 -1
  54. package/src/utils/builder.ts +141 -0
  55. package/src/utils/query.ts +226 -130
  56. package/src/utils/util.ts +34 -1
package/dist/index.mjs CHANGED
@@ -1,9 +1,12 @@
1
1
  // src/constants/common.ts
2
2
  var API_BASE_URL = "https://sui.api.scallop.io";
3
3
  var SDK_API_BASE_URL = "https://sdk.api.scallop.io";
4
- var ADDRESSES_ID = "6462a088a7ace142bb6d7e9b";
5
- var PROTOCOL_OBJECT_ID = "0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";
6
- var BORROW_FEE_PROTOCOL_ID = "0xc38f849e81cfe46d4e4320f508ea7dda42934a329d5a6571bb4c3cb6ea63f5da";
4
+ var IS_VE_SCA_TEST = false;
5
+ var ADDRESSES_ID = IS_VE_SCA_TEST ? "65fb07c39c845425d71d7b18" : "6601955b8b0024600a917079";
6
+ var PROTOCOL_OBJECT_ID = IS_VE_SCA_TEST ? "0xc9f859f98ca352a11b97a038c4b4162bee437b8df8caa047990fe9cb03d4f778" : "0xefe8b36d5b2e43728cc323298626b83177803521d195cfb11e15b910e892fddf";
7
+ var BORROW_FEE_PROTOCOL_ID = IS_VE_SCA_TEST ? "0xc9f859f98ca352a11b97a038c4b4162bee437b8df8caa047990fe9cb03d4f778" : "0xc38f849e81cfe46d4e4320f508ea7dda42934a329d5a6571bb4c3cb6ea63f5da";
8
+ var SCA_COIN_TYPE = IS_VE_SCA_TEST ? `0x6cd813061a3adf3602b76545f076205f0c8e7ec1d3b1eab9a1da7992c18c0524::sca::SCA` : "0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6::sca::SCA";
9
+ var OLD_BORROW_INCENTIVE_PROTOCOL_ID = "0xc63072e7f5f4983a2efaf5bdba1480d5e7d74d57948e1c7cc436f8e22cbeb410";
7
10
  var SUPPORT_POOLS = [
8
11
  "eth",
9
12
  "btc",
@@ -42,7 +45,7 @@ var SUPPORT_SPOOLS = [
42
45
  ];
43
46
  var SUPPORT_SPOOLS_REWARDS = ["sui"];
44
47
  var SUPPORT_BORROW_INCENTIVE_POOLS = ["sui", "usdc", "usdt"];
45
- var SUPPORT_BORROW_INCENTIVE_REWARDS = ["sui"];
48
+ var SUPPORT_BORROW_INCENTIVE_REWARDS = ["sui", "sca"];
46
49
  var SUPPORT_ORACLES = ["supra", "switchboard", "pyth"];
47
50
  var SUPPORT_PACKAGES = [
48
51
  "coinDecimalsRegistry",
@@ -82,7 +85,8 @@ var coinDecimals = {
82
85
  scetus: 9,
83
86
  safsui: 9,
84
87
  shasui: 9,
85
- svsui: 9
88
+ svsui: 9,
89
+ sca: 9
86
90
  };
87
91
  var assetCoins = {
88
92
  eth: "eth",
@@ -95,7 +99,8 @@ var assetCoins = {
95
99
  cetus: "cetus",
96
100
  afsui: "afsui",
97
101
  hasui: "hasui",
98
- vsui: "vsui"
102
+ vsui: "vsui",
103
+ sca: "sca"
99
104
  };
100
105
  var marketCoins = {
101
106
  seth: "seth",
@@ -131,9 +136,9 @@ var spoolRewardCoins = {
131
136
  svsui: "sui"
132
137
  };
133
138
  var borrowIncentiveRewardCoins = {
134
- sui: "sui",
135
- usdc: "sui",
136
- usdt: "sui"
139
+ sui: ["sui", "sca"],
140
+ usdc: ["sui", "sca"],
141
+ usdt: ["sui", "sca"]
137
142
  };
138
143
  var coinIds = {
139
144
  sui: "0x0000000000000000000000000000000000000000000000000000000000000002",
@@ -146,7 +151,8 @@ var coinIds = {
146
151
  cetus: "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b",
147
152
  afsui: "0xf325ce1300e8dac124071d3152c5c5ee6174914f8bc2161e88329cf579246efc",
148
153
  hasui: "0xbde4ba4c2e274a60ce15c1cfff9e5c42e41654ac8b6d906a57efa4bd3c29f47d",
149
- vsui: "0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"
154
+ vsui: "0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55",
155
+ sca: IS_VE_SCA_TEST ? "0x6cd813061a3adf3602b76545f076205f0c8e7ec1d3b1eab9a1da7992c18c0524" : "0x7016aae72cfc67f2fadf55769c0a7dd54291a583b63051a5ed71081cce836ac6"
150
156
  };
151
157
  var wormholeCoinIds = {
152
158
  eth: "0xaf8cd5edc19c4512f4259f0bee101a40d41ebed738ade5874359610ef8eeced5",
@@ -160,6 +166,13 @@ var voloCoinIds = {
160
166
  vsui: "0x549e8b69270defbfafd4f94e17ec44cdbdd99820b33bda2278dea3b9a32d3f55"
161
167
  };
162
168
 
169
+ // src/constants/vesca.ts
170
+ var UNLOCK_ROUND_DURATION = 60 * 60 * 24;
171
+ var MAX_LOCK_ROUNDS = 1460;
172
+ var MAX_LOCK_DURATION = MAX_LOCK_ROUNDS * UNLOCK_ROUND_DURATION;
173
+ var MIN_INITIAL_LOCK_AMOUNT = 1e10;
174
+ var MIN_TOP_UP_AMOUNT = 1e9;
175
+
163
176
  // src/models/scallop.ts
164
177
  import { SuiKit as SuiKit5 } from "@scallop-io/sui-kit";
165
178
 
@@ -388,8 +401,17 @@ var EMPTY_ADDRESSES = {
388
401
  adminCap: "",
389
402
  object: "",
390
403
  query: "",
404
+ config: "",
391
405
  incentivePools: "",
392
406
  incentiveAccounts: ""
407
+ },
408
+ vesca: {
409
+ id: "",
410
+ adminCap: "",
411
+ tableId: "",
412
+ table: "",
413
+ treasury: "",
414
+ config: ""
393
415
  }
394
416
  };
395
417
  var ScallopAddress = class {
@@ -717,10 +739,96 @@ var requireSender = (txBlock) => {
717
739
  }
718
740
  return sender;
719
741
  };
742
+ var checkLockSca = (scaAmountOrCoin, lockPeriodInDays, newUnlockAtInSecondTimestamp, prevUnlockAtInSecondTimestamp) => {
743
+ const isInitialLock = !prevUnlockAtInSecondTimestamp;
744
+ const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1e3 <= (/* @__PURE__ */ new Date()).getTime();
745
+ if (isInitialLock || isLockExpired) {
746
+ if (scaAmountOrCoin !== void 0 && lockPeriodInDays !== void 0) {
747
+ if (lockPeriodInDays <= 0) {
748
+ throw new Error("Lock period must be greater than 0");
749
+ }
750
+ if (typeof scaAmountOrCoin === "number" && scaAmountOrCoin < MIN_INITIAL_LOCK_AMOUNT) {
751
+ throw new Error(
752
+ `Minimum lock amount for ${isLockExpired ? "renewing expired veSca" : "initial lock"} is 10 SCA`
753
+ );
754
+ }
755
+ const extendLockPeriodInSecond = lockPeriodInDays * UNLOCK_ROUND_DURATION;
756
+ if (extendLockPeriodInSecond > MAX_LOCK_DURATION) {
757
+ throw new Error(
758
+ `Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS} days)`
759
+ );
760
+ }
761
+ } else {
762
+ throw new Error(
763
+ `SCA amount and lock period is required for ${isLockExpired ? "renewing expired veSca" : "initial lock"}`
764
+ );
765
+ }
766
+ } else {
767
+ checkVesca(prevUnlockAtInSecondTimestamp);
768
+ if (typeof scaAmountOrCoin === "number" && scaAmountOrCoin < MIN_TOP_UP_AMOUNT) {
769
+ throw new Error("Minimum top up amount is 1 SCA");
770
+ }
771
+ if (!!newUnlockAtInSecondTimestamp && !!prevUnlockAtInSecondTimestamp) {
772
+ const totalLockDuration = newUnlockAtInSecondTimestamp - prevUnlockAtInSecondTimestamp;
773
+ if (totalLockDuration > MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {
774
+ throw new Error(
775
+ `Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`
776
+ );
777
+ }
778
+ }
779
+ }
780
+ };
781
+ var checkExtendLockPeriod = (lockPeriodInDays, newUnlockAtInSecondTimestamp, prevUnlockAtInSecondTimestamp) => {
782
+ checkVesca(prevUnlockAtInSecondTimestamp);
783
+ if (lockPeriodInDays <= 0) {
784
+ throw new Error("Lock period must be greater than 0");
785
+ }
786
+ const isInitialLock = !prevUnlockAtInSecondTimestamp;
787
+ const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1e3 <= (/* @__PURE__ */ new Date()).getTime();
788
+ if (isLockExpired) {
789
+ throw new Error("veSca is expired, use renewExpiredVeScaQuick instead");
790
+ }
791
+ if (prevUnlockAtInSecondTimestamp) {
792
+ const totalLockDuration = newUnlockAtInSecondTimestamp - prevUnlockAtInSecondTimestamp;
793
+ if (totalLockDuration > MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {
794
+ throw new Error(
795
+ `Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`
796
+ );
797
+ }
798
+ }
799
+ };
800
+ var checkExtendLockAmount = (scaAmount, prevUnlockAtInSecondTimestamp) => {
801
+ checkVesca(prevUnlockAtInSecondTimestamp);
802
+ if (scaAmount < MIN_TOP_UP_AMOUNT) {
803
+ throw new Error("Minimum top up amount is 1 SCA");
804
+ }
805
+ const isInitialLock = !prevUnlockAtInSecondTimestamp;
806
+ const isLockExpired = !isInitialLock && prevUnlockAtInSecondTimestamp * 1e3 <= (/* @__PURE__ */ new Date()).getTime();
807
+ if (isLockExpired) {
808
+ throw new Error("veSca is expired, use renewExpiredVeScaQuick instead");
809
+ }
810
+ };
811
+ var checkRenewExpiredVeSca = (scaAmount, lockPeriodInDays, prevUnlockAtInSecondTimestamp) => {
812
+ checkVesca(prevUnlockAtInSecondTimestamp);
813
+ if (scaAmount < MIN_INITIAL_LOCK_AMOUNT) {
814
+ throw new Error("Minimum lock amount for renewing expired vesca 10 SCA");
815
+ }
816
+ const extendLockPeriodInSecond = lockPeriodInDays * UNLOCK_ROUND_DURATION;
817
+ if (extendLockPeriodInSecond >= MAX_LOCK_DURATION - UNLOCK_ROUND_DURATION) {
818
+ throw new Error(
819
+ `Maximum lock period is ~4 years (${MAX_LOCK_ROUNDS - 1} days)`
820
+ );
821
+ }
822
+ };
823
+ var checkVesca = (prevUnlockAtInSecondTimestamp) => {
824
+ if (prevUnlockAtInSecondTimestamp === void 0) {
825
+ throw new Error("veSca not found");
826
+ }
827
+ };
720
828
 
721
829
  // src/utils/query.ts
722
830
  import BigNumber from "bignumber.js";
723
- import { normalizeStructTag } from "@mysten/sui.js/utils";
831
+ import { normalizeStructTag, parseStructTag } from "@mysten/sui.js/utils";
724
832
  var parseOriginMarketPoolData = (originMarketPoolData) => {
725
833
  return {
726
834
  coinType: normalizeStructTag(originMarketPoolData.type.name),
@@ -954,119 +1062,120 @@ var calculateSpoolRewardPoolData = (parsedSpoolData, parsedSpoolRewardPoolData,
954
1062
  rewardPerSec: rewardPerSec.toNumber()
955
1063
  };
956
1064
  };
1065
+ var parseOriginBorrowIncentivesPoolPointData = (originBorrowIncentivePoolPointData) => {
1066
+ return {
1067
+ pointType: normalizeStructTag(
1068
+ originBorrowIncentivePoolPointData.point_type.name
1069
+ ),
1070
+ distributedPointPerPeriod: Number(
1071
+ originBorrowIncentivePoolPointData.distributed_point_per_period
1072
+ ),
1073
+ period: Number(originBorrowIncentivePoolPointData.point_distribution_time),
1074
+ distributedPoint: Number(
1075
+ originBorrowIncentivePoolPointData.distributed_point
1076
+ ),
1077
+ points: Number(originBorrowIncentivePoolPointData.points),
1078
+ index: Number(originBorrowIncentivePoolPointData.index),
1079
+ baseWeight: Number(originBorrowIncentivePoolPointData.base_weight),
1080
+ weightedAmount: Number(originBorrowIncentivePoolPointData.weighted_amount),
1081
+ lastUpdate: Number(originBorrowIncentivePoolPointData.last_update)
1082
+ };
1083
+ };
957
1084
  var parseOriginBorrowIncentivePoolData = (originBorrowIncentivePoolData) => {
958
1085
  return {
959
1086
  poolType: normalizeStructTag(originBorrowIncentivePoolData.pool_type.name),
960
- maxPoint: Number(originBorrowIncentivePoolData.max_distributed_point),
961
- distributedPoint: Number(originBorrowIncentivePoolData.distributed_point),
962
- pointPerPeriod: Number(
963
- originBorrowIncentivePoolData.distributed_point_per_period
964
- ),
965
- period: Number(originBorrowIncentivePoolData.point_distribution_time),
966
- maxStake: Number(originBorrowIncentivePoolData.max_stakes),
1087
+ minStakes: Number(originBorrowIncentivePoolData.min_stakes),
1088
+ maxStakes: Number(originBorrowIncentivePoolData.max_stakes),
967
1089
  staked: Number(originBorrowIncentivePoolData.stakes),
968
- index: Number(originBorrowIncentivePoolData.index),
969
1090
  createdAt: Number(originBorrowIncentivePoolData.created_at),
970
- lastUpdate: Number(originBorrowIncentivePoolData.last_update)
1091
+ poolPoints: originBorrowIncentivePoolData.points.reduce(
1092
+ (acc, point) => {
1093
+ const parsed = parseOriginBorrowIncentivesPoolPointData(point);
1094
+ const name = parseStructTag(
1095
+ parsed.pointType
1096
+ ).name.toLowerCase();
1097
+ acc[name] = parsed;
1098
+ return acc;
1099
+ },
1100
+ {}
1101
+ )
971
1102
  };
972
1103
  };
973
- var calculateBorrowIncentivePoolData = (parsedBorrowIncentivePoolData, borrowIncentiveCoinPrice, borrowIncentiveCoinDecimal) => {
1104
+ var calculateBorrowIncentivePoolPointData = (pasredBorrowIncentinvePoolData, parsedBorrowIncentivePoolPointData, rewardCoinPrice, rewardCoinDecimal, poolCoinPrice, poolCoinDecimal) => {
974
1105
  const baseIndexRate = 1e9;
975
1106
  const distributedPointPerSec = BigNumber(
976
- parsedBorrowIncentivePoolData.pointPerPeriod
977
- ).dividedBy(parsedBorrowIncentivePoolData.period);
978
- const pointPerSec = BigNumber(
979
- parsedBorrowIncentivePoolData.pointPerPeriod
980
- ).dividedBy(parsedBorrowIncentivePoolData.period);
981
- const remainingPeriod = BigNumber(parsedBorrowIncentivePoolData.maxPoint).minus(parsedBorrowIncentivePoolData.distributedPoint).dividedBy(pointPerSec);
982
- const startDate = parsedBorrowIncentivePoolData.createdAt;
983
- const endDate = remainingPeriod.plus(parsedBorrowIncentivePoolData.lastUpdate).integerValue().toNumber();
1107
+ parsedBorrowIncentivePoolPointData.distributedPointPerPeriod
1108
+ ).dividedBy(parsedBorrowIncentivePoolPointData.period);
984
1109
  const timeDelta = BigNumber(
985
- Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3) - parsedBorrowIncentivePoolData.lastUpdate
986
- ).dividedBy(parsedBorrowIncentivePoolData.period).toFixed(0);
987
- const remainingPoints = BigNumber(
988
- parsedBorrowIncentivePoolData.maxPoint
989
- ).minus(parsedBorrowIncentivePoolData.distributedPoint);
1110
+ Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3) - parsedBorrowIncentivePoolPointData.lastUpdate
1111
+ ).dividedBy(parsedBorrowIncentivePoolPointData.period).toFixed(0);
990
1112
  const accumulatedPoints = BigNumber.minimum(
991
1113
  BigNumber(timeDelta).multipliedBy(
992
- parsedBorrowIncentivePoolData.pointPerPeriod
1114
+ parsedBorrowIncentivePoolPointData.distributedPointPerPeriod
993
1115
  ),
994
- remainingPoints
1116
+ BigNumber(parsedBorrowIncentivePoolPointData.points)
995
1117
  );
996
- const currentPointIndex = BigNumber(parsedBorrowIncentivePoolData.index).plus(
997
- accumulatedPoints.dividedBy(parsedBorrowIncentivePoolData.staked).isFinite() ? BigNumber(baseIndexRate).multipliedBy(accumulatedPoints).dividedBy(parsedBorrowIncentivePoolData.staked) : 0
1118
+ const currentPointIndex = BigNumber(
1119
+ parsedBorrowIncentivePoolPointData.index
1120
+ ).plus(
1121
+ accumulatedPoints.dividedBy(parsedBorrowIncentivePoolPointData.weightedAmount).isFinite() ? BigNumber(baseIndexRate).multipliedBy(accumulatedPoints).dividedBy(parsedBorrowIncentivePoolPointData.weightedAmount) : 0
998
1122
  );
999
1123
  const currentTotalDistributedPoint = BigNumber(
1000
- parsedBorrowIncentivePoolData.distributedPoint
1124
+ parsedBorrowIncentivePoolPointData.distributedPoint
1001
1125
  ).plus(accumulatedPoints);
1002
- const stakedAmount = BigNumber(parsedBorrowIncentivePoolData.staked);
1003
- const stakedCoin = stakedAmount.shiftedBy(-1 * borrowIncentiveCoinDecimal);
1004
- const stakedValue = stakedCoin.multipliedBy(borrowIncentiveCoinPrice);
1126
+ const stakedAmount = BigNumber(pasredBorrowIncentinvePoolData.staked);
1127
+ const stakedCoin = stakedAmount.shiftedBy(-1 * poolCoinDecimal);
1128
+ const stakedValue = stakedCoin.multipliedBy(poolCoinPrice);
1129
+ const baseWeight = BigNumber(parsedBorrowIncentivePoolPointData.baseWeight);
1130
+ const weightedStakedAmount = BigNumber(
1131
+ parsedBorrowIncentivePoolPointData.weightedAmount
1132
+ );
1133
+ const weightedStakedCoin = weightedStakedAmount.shiftedBy(
1134
+ -1 * poolCoinDecimal
1135
+ );
1136
+ const weightedStakedValue = weightedStakedCoin.multipliedBy(poolCoinPrice);
1137
+ const rateYearFactor = 365 * 24 * 60 * 60;
1138
+ const rewardPerSec = BigNumber(distributedPointPerSec).shiftedBy(
1139
+ -1 * rewardCoinDecimal
1140
+ );
1141
+ const rewardValueForYear = BigNumber(rewardPerSec).multipliedBy(rateYearFactor).multipliedBy(rewardCoinPrice);
1142
+ const weightScale = BigNumber("1000000000000");
1143
+ const rewardRate = rewardValueForYear.multipliedBy(
1144
+ BigNumber(parsedBorrowIncentivePoolPointData.baseWeight).dividedBy(
1145
+ weightScale
1146
+ )
1147
+ ).dividedBy(weightedStakedValue).isFinite() ? rewardValueForYear.multipliedBy(
1148
+ BigNumber(parsedBorrowIncentivePoolPointData.baseWeight).dividedBy(
1149
+ weightScale
1150
+ )
1151
+ ).dividedBy(weightedStakedValue).toNumber() : Infinity;
1005
1152
  return {
1006
1153
  distributedPointPerSec: distributedPointPerSec.toNumber(),
1007
1154
  accumulatedPoints: accumulatedPoints.toNumber(),
1008
1155
  currentPointIndex: currentPointIndex.toNumber(),
1009
1156
  currentTotalDistributedPoint: currentTotalDistributedPoint.toNumber(),
1010
- startDate: new Date(startDate * 1e3),
1011
- endDate: new Date(endDate * 1e3),
1012
1157
  stakedAmount: stakedAmount.toNumber(),
1013
1158
  stakedCoin: stakedCoin.toNumber(),
1014
- stakedValue: stakedValue.toNumber()
1159
+ stakedValue: stakedValue.toNumber(),
1160
+ baseWeight: baseWeight.toNumber(),
1161
+ weightedStakedAmount: weightedStakedAmount.toNumber(),
1162
+ weightedStakedCoin: weightedStakedCoin.toNumber(),
1163
+ weightedStakedValue: weightedStakedValue.toNumber(),
1164
+ rewardApr: rewardRate,
1165
+ rewardPerSec: rewardPerSec.toNumber()
1015
1166
  };
1016
1167
  };
1017
- var parseOriginBorrowIncentiveRewardPoolData = (originBorrowIncentiveRewardPoolData) => {
1168
+ var parseOriginBorrowIncentiveAccountPoolPointData = (originBorrowIncentiveAccountPoolPointData) => {
1018
1169
  return {
1019
- rewardType: normalizeStructTag(
1020
- originBorrowIncentiveRewardPoolData.reward_type.name
1021
- ),
1022
- claimedRewards: Number(originBorrowIncentiveRewardPoolData.claimed_rewards),
1023
- exchangeRateNumerator: Number(
1024
- originBorrowIncentiveRewardPoolData.exchange_rate_numerator
1170
+ pointType: normalizeStructTag(
1171
+ originBorrowIncentiveAccountPoolPointData.point_type.name
1025
1172
  ),
1026
- exchangeRateDenominator: Number(
1027
- originBorrowIncentiveRewardPoolData.exchange_rate_denominator
1173
+ weightedAmount: Number(
1174
+ originBorrowIncentiveAccountPoolPointData.weighted_amount
1028
1175
  ),
1029
- remainingRewards: Number(
1030
- originBorrowIncentiveRewardPoolData.remaining_reward
1031
- )
1032
- };
1033
- };
1034
- var calculateBorrowIncentiveRewardPoolData = (parsedBorrowIncentivePoolData, parsedBorrowIncentiveRewardPoolData, calculatedBorrowIncentivePoolData, rewardCoinPrice, rewardCoinDecimal) => {
1035
- const rateYearFactor = 365 * 24 * 60 * 60;
1036
- const rewardPerSec = BigNumber(
1037
- calculatedBorrowIncentivePoolData.distributedPointPerSec
1038
- ).multipliedBy(parsedBorrowIncentiveRewardPoolData.exchangeRateNumerator).dividedBy(parsedBorrowIncentiveRewardPoolData.exchangeRateDenominator);
1039
- const totalRewardAmount = BigNumber(parsedBorrowIncentivePoolData.maxPoint).multipliedBy(parsedBorrowIncentiveRewardPoolData.exchangeRateNumerator).dividedBy(parsedBorrowIncentiveRewardPoolData.exchangeRateDenominator);
1040
- const totalRewardCoin = totalRewardAmount.shiftedBy(-1 * rewardCoinDecimal);
1041
- const totalRewardValue = totalRewardCoin.multipliedBy(rewardCoinPrice);
1042
- const remaindRewardAmount = BigNumber(
1043
- parsedBorrowIncentiveRewardPoolData.remainingRewards
1044
- );
1045
- const remaindRewardCoin = remaindRewardAmount.shiftedBy(
1046
- -1 * rewardCoinDecimal
1047
- );
1048
- const remaindRewardValue = remaindRewardCoin.multipliedBy(rewardCoinPrice);
1049
- const claimedRewardAmount = BigNumber(
1050
- parsedBorrowIncentiveRewardPoolData.claimedRewards
1051
- );
1052
- const claimedRewardCoin = claimedRewardAmount.shiftedBy(
1053
- -1 * rewardCoinDecimal
1054
- );
1055
- const claimedRewardValue = claimedRewardCoin.multipliedBy(rewardCoinPrice);
1056
- const rewardValueForYear = BigNumber(rewardPerSec).shiftedBy(-1 * rewardCoinDecimal).multipliedBy(rateYearFactor).multipliedBy(rewardCoinPrice);
1057
- const rewardRate = rewardValueForYear.dividedBy(calculatedBorrowIncentivePoolData.stakedValue).isFinite() ? rewardValueForYear.dividedBy(calculatedBorrowIncentivePoolData.stakedValue).toNumber() : Infinity;
1058
- return {
1059
- rewardApr: rewardRate,
1060
- totalRewardAmount: totalRewardAmount.toNumber(),
1061
- totalRewardCoin: totalRewardCoin.toNumber(),
1062
- totalRewardValue: totalRewardValue.toNumber(),
1063
- remaindRewardAmount: remaindRewardAmount.toNumber(),
1064
- remaindRewardCoin: remaindRewardCoin.toNumber(),
1065
- remaindRewardValue: remaindRewardValue.toNumber(),
1066
- claimedRewardAmount: claimedRewardAmount.toNumber(),
1067
- claimedRewardCoin: claimedRewardCoin.toNumber(),
1068
- claimedRewardValue: claimedRewardValue.toNumber(),
1069
- rewardPerSec: rewardPerSec.toNumber()
1176
+ points: Number(originBorrowIncentiveAccountPoolPointData.points),
1177
+ totalPoints: Number(originBorrowIncentiveAccountPoolPointData.total_points),
1178
+ index: Number(originBorrowIncentiveAccountPoolPointData.index)
1070
1179
  };
1071
1180
  };
1072
1181
  var parseOriginBorrowIncentiveAccountData = (originBorrowIncentiveAccountData) => {
@@ -1074,10 +1183,18 @@ var parseOriginBorrowIncentiveAccountData = (originBorrowIncentiveAccountData) =
1074
1183
  poolType: normalizeStructTag(
1075
1184
  originBorrowIncentiveAccountData.pool_type.name
1076
1185
  ),
1077
- amount: Number(originBorrowIncentiveAccountData.amount),
1078
- index: Number(originBorrowIncentiveAccountData.index),
1079
- points: Number(originBorrowIncentiveAccountData.points),
1080
- totalPoints: Number(originBorrowIncentiveAccountData.total_points)
1186
+ debtAmount: Number(originBorrowIncentiveAccountData.debt_amount),
1187
+ pointList: originBorrowIncentiveAccountData.points_list.reduce(
1188
+ (acc, point) => {
1189
+ const parsed = parseOriginBorrowIncentiveAccountPoolPointData(point);
1190
+ const name = parseStructTag(
1191
+ parsed.pointType
1192
+ ).name.toLowerCase();
1193
+ acc[name] = parsed;
1194
+ return acc;
1195
+ },
1196
+ {}
1197
+ )
1081
1198
  };
1082
1199
  };
1083
1200
  var minBigNumber = (...args) => {
@@ -1105,7 +1222,8 @@ var isMarketCoin = (coinName) => {
1105
1222
  .../* @__PURE__ */ new Set([
1106
1223
  ...SUPPORT_POOLS,
1107
1224
  ...SUPPORT_COLLATERALS,
1108
- ...SUPPORT_SPOOLS_REWARDS
1225
+ ...SUPPORT_SPOOLS_REWARDS,
1226
+ ...SUPPORT_BORROW_INCENTIVE_REWARDS
1109
1227
  ])
1110
1228
  ].includes(assetCoinName);
1111
1229
  };
@@ -1123,7 +1241,12 @@ var parseAssetSymbol = (coinName) => {
1123
1241
  };
1124
1242
  var parseDataFromPythPriceFeed = (feed, address) => {
1125
1243
  const assetCoinNames = [
1126
- .../* @__PURE__ */ new Set([...SUPPORT_POOLS, ...SUPPORT_COLLATERALS])
1244
+ .../* @__PURE__ */ new Set([
1245
+ ...SUPPORT_POOLS,
1246
+ ...SUPPORT_COLLATERALS,
1247
+ ...SUPPORT_SPOOLS_REWARDS,
1248
+ ...SUPPORT_BORROW_INCENTIVE_REWARDS
1249
+ ])
1127
1250
  ];
1128
1251
  const assetCoinName = assetCoinNames.find((assetCoinName2) => {
1129
1252
  return address.get(`core.coins.${assetCoinName2}.oracle.pyth.feed`) === feed.id;
@@ -1139,6 +1262,19 @@ var parseDataFromPythPriceFeed = (feed, address) => {
1139
1262
  throw new Error("Invalid feed id");
1140
1263
  }
1141
1264
  };
1265
+ var findClosestUnlockRound = (unlockAtInSecondTimestamp) => {
1266
+ const unlockDate = new Date(unlockAtInSecondTimestamp * 1e3);
1267
+ const closestTwelveAM = new Date(unlockAtInSecondTimestamp * 1e3);
1268
+ closestTwelveAM.setUTCHours(0, 0, 0, 0);
1269
+ if (unlockDate.getUTCHours() >= 0) {
1270
+ closestTwelveAM.setUTCDate(closestTwelveAM.getUTCDate() + 1);
1271
+ }
1272
+ const now = (/* @__PURE__ */ new Date()).getTime();
1273
+ if (closestTwelveAM.getTime() - now > MAX_LOCK_DURATION * 1e3) {
1274
+ closestTwelveAM.setUTCDate(closestTwelveAM.getUTCDate() - 1);
1275
+ }
1276
+ return Math.floor(closestTwelveAM.getTime() / 1e3);
1277
+ };
1142
1278
 
1143
1279
  // src/queries/coreQuery.ts
1144
1280
  var queryMarket = async (query, indexer = false) => {
@@ -1327,7 +1463,7 @@ var getMarketPool = async (query, poolCoinName, indexer = false, marketObject, c
1327
1463
  const fields = marketObject.content.fields;
1328
1464
  const coinType = query.utils.parseCoinType(poolCoinName);
1329
1465
  const balanceSheetParentId = fields.vault.fields.balance_sheets.fields.table.fields.id.id;
1330
- const balanceSheetDdynamicFieldObjectResponse = await query.suiKit.client().getDynamicFieldObject({
1466
+ const balanceSheetDynamicFieldObjectResponse = await query.suiKit.client().getDynamicFieldObject({
1331
1467
  parentId: balanceSheetParentId,
1332
1468
  name: {
1333
1469
  type: "0x1::type_name::TypeName",
@@ -1336,9 +1472,9 @@ var getMarketPool = async (query, poolCoinName, indexer = false, marketObject, c
1336
1472
  }
1337
1473
  }
1338
1474
  });
1339
- const balanceSheetDdynamicFieldObject = balanceSheetDdynamicFieldObjectResponse.data;
1340
- if (balanceSheetDdynamicFieldObject && balanceSheetDdynamicFieldObject.content && "fields" in balanceSheetDdynamicFieldObject.content) {
1341
- const dynamicFields = balanceSheetDdynamicFieldObject.content.fields;
1475
+ const balanceSheetDynamicFieldObject = balanceSheetDynamicFieldObjectResponse.data;
1476
+ if (balanceSheetDynamicFieldObject && balanceSheetDynamicFieldObject.content && "fields" in balanceSheetDynamicFieldObject.content) {
1477
+ const dynamicFields = balanceSheetDynamicFieldObject.content.fields;
1342
1478
  balanceSheet = dynamicFields.value.fields;
1343
1479
  }
1344
1480
  const borrowIndexParentId = fields.borrow_dynamics.fields.table.fields.id.id;
@@ -1498,7 +1634,7 @@ var getMarketCollateral = async (query, collateralCoinName, indexer = false, mar
1498
1634
  const fields = marketObject.content.fields;
1499
1635
  const coinType = query.utils.parseCoinType(collateralCoinName);
1500
1636
  const riskModelParentId = fields.risk_models.fields.table.fields.id.id;
1501
- const riskModelDdynamicFieldObjectResponse = await query.suiKit.client().getDynamicFieldObject({
1637
+ const riskModelDynamicFieldObjectResponse = await query.suiKit.client().getDynamicFieldObject({
1502
1638
  parentId: riskModelParentId,
1503
1639
  name: {
1504
1640
  type: "0x1::type_name::TypeName",
@@ -1507,9 +1643,9 @@ var getMarketCollateral = async (query, collateralCoinName, indexer = false, mar
1507
1643
  }
1508
1644
  }
1509
1645
  });
1510
- const riskModelDdynamicFieldObject = riskModelDdynamicFieldObjectResponse.data;
1511
- if (riskModelDdynamicFieldObject && riskModelDdynamicFieldObject.content && "fields" in riskModelDdynamicFieldObject.content) {
1512
- const dynamicFields = riskModelDdynamicFieldObject.content.fields;
1646
+ const riskModelDynamicFieldObject = riskModelDynamicFieldObjectResponse.data;
1647
+ if (riskModelDynamicFieldObject && riskModelDynamicFieldObject.content && "fields" in riskModelDynamicFieldObject.content) {
1648
+ const dynamicFields = riskModelDynamicFieldObject.content.fields;
1513
1649
  riskModel = dynamicFields.value.fields;
1514
1650
  }
1515
1651
  const collateralStatParentId = fields.collateral_stats.fields.table.fields.id.id;
@@ -2179,71 +2315,70 @@ var queryBorrowIncentivePools = async (query, borrowIncentiveCoinNames, indexer
2179
2315
  const incentivePoolsId = query.address.get("borrowIncentive.incentivePools");
2180
2316
  const txBlock = new SuiKitTxBlock2();
2181
2317
  const queryTarget = `${queryPkgId}::incentive_pools_query::incentive_pools_data`;
2182
- txBlock.moveCall(queryTarget, [incentivePoolsId], ["0x2::sui::SUI"]);
2318
+ txBlock.moveCall(queryTarget, [incentivePoolsId]);
2183
2319
  const queryResult = await query.suiKit.inspectTxn(txBlock);
2184
2320
  const borrowIncentivePoolsQueryData = queryResult.events[0].parsedJson;
2185
- const parsedBorrowIncentiveRewardPoolData = parseOriginBorrowIncentiveRewardPoolData(
2186
- borrowIncentivePoolsQueryData.reward_pool
2187
- );
2188
- const rewardCoinType = parsedBorrowIncentiveRewardPoolData.rewardType;
2189
- const rewardCoinName = query.utils.parseCoinNameFromType(rewardCoinType);
2190
- const coinPrices = await query.utils.getCoinPrices(
2191
- [.../* @__PURE__ */ new Set([...borrowIncentiveCoinNames, rewardCoinName])]
2192
- );
2193
2321
  const borrowIncentivePools = {};
2194
2322
  if (indexer) {
2195
- const borrowIncentivePoolsIndexer = await query.indexer.getBorrowIncentivePools();
2196
- for (const borrowIncentivePool of Object.values(
2197
- borrowIncentivePoolsIndexer
2198
- )) {
2199
- if (!borrowIncentiveCoinNames.includes(borrowIncentivePool.coinName))
2200
- continue;
2201
- borrowIncentivePool.coinPrice = coinPrices[borrowIncentivePool.coinName] || borrowIncentivePool.coinPrice;
2202
- borrowIncentivePool.rewardCoinPrice = coinPrices[rewardCoinName] || borrowIncentivePool.rewardCoinPrice;
2203
- borrowIncentivePools[borrowIncentivePool.coinName] = borrowIncentivePool;
2204
- }
2205
- return borrowIncentivePools;
2206
2323
  }
2207
2324
  for (const pool of borrowIncentivePoolsQueryData.incentive_pools) {
2208
- const coinType = normalizeStructTag4(pool.pool_type.name);
2209
- const coinName = query.utils.parseCoinNameFromType(coinType);
2210
- const rewardCoinName2 = query.utils.parseCoinNameFromType(rewardCoinType);
2211
- if (!borrowIncentiveCoinNames.includes(coinName)) {
2212
- continue;
2213
- }
2325
+ const borrowIncentivePoolPoints = {};
2214
2326
  const parsedBorrowIncentivePoolData = parseOriginBorrowIncentivePoolData(pool);
2215
- const coinPrice = coinPrices?.[coinName] ?? 0;
2216
- const coinDecimal = query.utils.getCoinDecimal(coinName);
2217
- const calculatedBorrowIncentivePoolData = calculateBorrowIncentivePoolData(
2218
- parsedBorrowIncentivePoolData,
2219
- coinPrice,
2220
- coinDecimal
2327
+ const coinPrices = await query.utils.getCoinPrices(
2328
+ [
2329
+ .../* @__PURE__ */ new Set([
2330
+ ...borrowIncentiveCoinNames,
2331
+ ...SUPPORT_BORROW_INCENTIVE_REWARDS
2332
+ ])
2333
+ ]
2221
2334
  );
2222
- const rewardCoinPrice = coinPrices?.[rewardCoinName2] ?? 0;
2223
- const rewardCoinDecimal = query.utils.getCoinDecimal(rewardCoinName2);
2224
- const calculatedBorrowIncentiveRewardPoolData = calculateBorrowIncentiveRewardPoolData(
2225
- parsedBorrowIncentivePoolData,
2226
- parsedBorrowIncentiveRewardPoolData,
2227
- calculatedBorrowIncentivePoolData,
2228
- rewardCoinPrice,
2229
- rewardCoinDecimal
2335
+ const poolCoinType = normalizeStructTag4(pool.pool_type.name);
2336
+ const poolCoinName = query.utils.parseCoinNameFromType(
2337
+ poolCoinType
2230
2338
  );
2231
- borrowIncentivePools[coinName] = {
2232
- coinName,
2233
- symbol: query.utils.parseSymbol(coinName),
2234
- coinType,
2235
- rewardCoinType,
2236
- coinDecimal,
2237
- rewardCoinDecimal,
2238
- coinPrice,
2239
- rewardCoinPrice,
2240
- maxPoint: parsedBorrowIncentivePoolData.maxPoint,
2241
- distributedPoint: parsedBorrowIncentivePoolData.distributedPoint,
2242
- maxStake: parsedBorrowIncentivePoolData.maxStake,
2243
- ...calculatedBorrowIncentivePoolData,
2244
- exchangeRateNumerator: parsedBorrowIncentiveRewardPoolData.exchangeRateNumerator,
2245
- exchangeRateDenominator: parsedBorrowIncentiveRewardPoolData.exchangeRateDenominator,
2246
- ...calculatedBorrowIncentiveRewardPoolData
2339
+ const poolCoinPrice = coinPrices?.[poolCoinName] ?? 0;
2340
+ const poolCoinDecimal = query.utils.getCoinDecimal(poolCoinName);
2341
+ if (!borrowIncentiveCoinNames.includes(poolCoinName)) {
2342
+ continue;
2343
+ }
2344
+ for (const [coinName, poolPoint] of Object.entries(
2345
+ parsedBorrowIncentivePoolData.poolPoints
2346
+ )) {
2347
+ const rewardCoinType = normalizeStructTag4(poolPoint.pointType);
2348
+ const rewardCoinName = query.utils.parseCoinNameFromType(
2349
+ rewardCoinType
2350
+ );
2351
+ const rewardCoinPrice = coinPrices?.[rewardCoinName] ?? 0;
2352
+ const rewardCoinDecimal = query.utils.getCoinDecimal(rewardCoinName);
2353
+ const symbol = query.utils.parseSymbol(rewardCoinName);
2354
+ const coinDecimal = query.utils.getCoinDecimal(rewardCoinName);
2355
+ const calculatedPoolPoint = calculateBorrowIncentivePoolPointData(
2356
+ parsedBorrowIncentivePoolData,
2357
+ poolPoint,
2358
+ rewardCoinPrice,
2359
+ rewardCoinDecimal,
2360
+ poolCoinPrice,
2361
+ poolCoinDecimal
2362
+ );
2363
+ borrowIncentivePoolPoints[coinName] = {
2364
+ symbol,
2365
+ coinName: rewardCoinName,
2366
+ coinType: rewardCoinType,
2367
+ coinDecimal,
2368
+ coinPrice: rewardCoinPrice,
2369
+ points: poolPoint.points,
2370
+ distributedPoint: poolPoint.distributedPoint,
2371
+ weightedAmount: poolPoint.weightedAmount,
2372
+ ...calculatedPoolPoint
2373
+ };
2374
+ }
2375
+ borrowIncentivePools[poolCoinName] = {
2376
+ coinName: poolCoinName,
2377
+ symbol: query.utils.parseSymbol(poolCoinName),
2378
+ coinType: poolCoinType,
2379
+ coinDecimal: poolCoinDecimal,
2380
+ coinPrice: poolCoinPrice,
2381
+ points: borrowIncentivePoolPoints
2247
2382
  };
2248
2383
  }
2249
2384
  return borrowIncentivePools;
@@ -2262,19 +2397,13 @@ var queryBorrowIncentiveAccounts = async (query, obligationId, borrowIncentiveCo
2262
2397
  const queryResult = await query.suiKit.inspectTxn(txBlock);
2263
2398
  const borrowIncentiveAccountsQueryData = queryResult.events[0].parsedJson;
2264
2399
  const borrowIncentiveAccounts = Object.values(
2265
- borrowIncentiveAccountsQueryData.incentive_states
2400
+ borrowIncentiveAccountsQueryData.pool_records
2266
2401
  ).reduce((accounts, accountData) => {
2267
2402
  const parsedBorrowIncentiveAccount = parseOriginBorrowIncentiveAccountData(accountData);
2268
2403
  const poolType = parsedBorrowIncentiveAccount.poolType;
2269
2404
  const coinName = query.utils.parseCoinNameFromType(poolType);
2270
2405
  if (borrowIncentiveCoinNames && borrowIncentiveCoinNames.includes(coinName)) {
2271
- accounts[coinName] = {
2272
- poolType,
2273
- amount: parsedBorrowIncentiveAccount.amount,
2274
- points: parsedBorrowIncentiveAccount.points,
2275
- totalPoints: parsedBorrowIncentiveAccount.totalPoints,
2276
- index: parsedBorrowIncentiveAccount.index
2277
- };
2406
+ accounts[coinName] = parsedBorrowIncentiveAccount;
2278
2407
  }
2279
2408
  return accounts;
2280
2409
  }, {});
@@ -2494,9 +2623,8 @@ var getObligationAccounts = async (query, ownerAddress, indexer = false) => {
2494
2623
  };
2495
2624
  var getObligationAccount = async (query, obligationId, ownerAddress, indexer = false, market, coinPrices, coinAmounts) => {
2496
2625
  market = market || await query.queryMarket(indexer);
2497
- const assetCoinNames = [
2626
+ const collateralAssetCoinNames = [
2498
2627
  .../* @__PURE__ */ new Set([
2499
- ...Object.values(market.pools).map((pool) => pool.coinName),
2500
2628
  ...Object.values(market.collaterals).map(
2501
2629
  (collateral) => collateral.coinName
2502
2630
  )
@@ -2508,8 +2636,8 @@ var getObligationAccount = async (query, obligationId, ownerAddress, indexer = f
2508
2636
  indexer
2509
2637
  );
2510
2638
  const borrowIncentiveAccounts = await query.getBorrowIncentiveAccounts(obligationId);
2511
- coinPrices = coinPrices || await query.utils.getCoinPrices(assetCoinNames);
2512
- coinAmounts = coinAmounts || await query.getCoinAmounts(assetCoinNames, ownerAddress);
2639
+ coinPrices = coinPrices || await query.utils.getCoinPrices(collateralAssetCoinNames);
2640
+ coinAmounts = coinAmounts || await query.getCoinAmounts(collateralAssetCoinNames, ownerAddress);
2513
2641
  const collaterals = {};
2514
2642
  const debts = {};
2515
2643
  const borrowIncentives = {};
@@ -2520,7 +2648,7 @@ var getObligationAccount = async (query, obligationId, ownerAddress, indexer = f
2520
2648
  let totalBorrowedPools = 0;
2521
2649
  let totalBorrowedValue = BigNumber3(0);
2522
2650
  let totalBorrowedValueWithWeight = BigNumber3(0);
2523
- for (const assetCoinName of assetCoinNames) {
2651
+ for (const assetCoinName of collateralAssetCoinNames) {
2524
2652
  const collateral = obligationQuery.collaterals.find((collateral2) => {
2525
2653
  const collateralCoinName = query.utils.parseCoinNameFromType(
2526
2654
  collateral2.type.name
@@ -2577,7 +2705,10 @@ var getObligationAccount = async (query, obligationId, ownerAddress, indexer = f
2577
2705
  };
2578
2706
  }
2579
2707
  }
2580
- for (const assetCoinName of assetCoinNames) {
2708
+ const borrowAssetCoinNames = [
2709
+ .../* @__PURE__ */ new Set([...Object.values(market.pools).map((pool) => pool.coinName)])
2710
+ ];
2711
+ for (const assetCoinName of borrowAssetCoinNames) {
2581
2712
  const debt = obligationQuery.debts.find((debt2) => {
2582
2713
  const poolCoinName = query.utils.parseCoinNameFromType(
2583
2714
  debt2.type.name
@@ -2636,34 +2767,51 @@ var getObligationAccount = async (query, obligationId, ownerAddress, indexer = f
2636
2767
  )) {
2637
2768
  const coinName = poolCoinName;
2638
2769
  const borrowIncentivePool = borrowIncentivePools[coinName];
2639
- let availableClaimAmount = BigNumber3(0);
2640
- let availableClaimCoin = BigNumber3(0);
2641
2770
  if (borrowIncentivePool) {
2642
- const accountBorrowedAmount = BigNumber3(borrowIncentiveAccount.amount);
2643
- const baseIndexRate = 1e9;
2644
- const increasedPointRate = borrowIncentivePool.currentPointIndex ? BigNumber3(
2645
- borrowIncentivePool.currentPointIndex - borrowIncentiveAccount.index
2646
- ).dividedBy(baseIndexRate) : 1;
2647
- availableClaimAmount = availableClaimAmount.plus(
2648
- accountBorrowedAmount.multipliedBy(increasedPointRate).plus(borrowIncentiveAccount.points).multipliedBy(borrowIncentivePool.exchangeRateNumerator).dividedBy(borrowIncentivePool.exchangeRateDenominator)
2649
- );
2650
- availableClaimCoin = availableClaimAmount.shiftedBy(
2651
- -1 * borrowIncentivePool.rewardCoinDecimal
2652
- );
2653
- if (availableClaimAmount.isGreaterThan(0)) {
2654
- borrowIncentives[coinName] = {
2655
- coinName: borrowIncentivePool.coinName,
2656
- coinType: borrowIncentivePool.coinType,
2657
- rewardCoinType: borrowIncentivePool.rewardCoinType,
2658
- symbol: borrowIncentivePool.symbol,
2659
- coinDecimal: borrowIncentivePool.coinDecimal,
2660
- rewardCoinDecimal: borrowIncentivePool.rewardCoinDecimal,
2661
- coinPrice: borrowIncentivePool.coinPrice,
2662
- rewardCoinPrice: borrowIncentivePool.rewardCoinPrice,
2663
- availableClaimAmount: availableClaimAmount.toNumber(),
2664
- availableClaimCoin: availableClaimCoin.toNumber()
2665
- };
2771
+ const rewards = [];
2772
+ for (const rewardCoinName of SUPPORT_BORROW_INCENTIVE_REWARDS) {
2773
+ const accountPoint = borrowIncentiveAccount.pointList[rewardCoinName];
2774
+ const poolPoint = borrowIncentivePool.points[rewardCoinName];
2775
+ if (accountPoint && poolPoint) {
2776
+ let availableClaimAmount = BigNumber3(0);
2777
+ let availableClaimCoin = BigNumber3(0);
2778
+ const accountBorrowedAmount = BigNumber3(accountPoint.weightedAmount);
2779
+ const baseIndexRate = 1e9;
2780
+ const increasedPointRate = poolPoint.currentPointIndex ? BigNumber3(
2781
+ poolPoint.currentPointIndex - accountPoint.index
2782
+ ).dividedBy(baseIndexRate) : 1;
2783
+ availableClaimAmount = availableClaimAmount.plus(
2784
+ accountBorrowedAmount.multipliedBy(increasedPointRate).plus(accountPoint.points)
2785
+ );
2786
+ availableClaimCoin = availableClaimAmount.shiftedBy(
2787
+ -1 * poolPoint.coinDecimal
2788
+ );
2789
+ const weightScale = BigNumber3("1000000000000");
2790
+ const boostValue = BigNumber3(accountPoint.weightedAmount).div(
2791
+ BigNumber3(borrowIncentiveAccount.debtAmount).multipliedBy(poolPoint.baseWeight).dividedBy(weightScale)
2792
+ ).toNumber();
2793
+ if (availableClaimAmount.isGreaterThan(0)) {
2794
+ rewards.push({
2795
+ coinName: poolPoint.coinName,
2796
+ coinType: poolPoint.coinType,
2797
+ symbol: poolPoint.symbol,
2798
+ coinDecimal: poolPoint.coinDecimal,
2799
+ coinPrice: poolPoint.coinPrice,
2800
+ availableClaimAmount: availableClaimAmount.toNumber(),
2801
+ availableClaimCoin: availableClaimCoin.toNumber(),
2802
+ boostValue
2803
+ });
2804
+ }
2805
+ }
2666
2806
  }
2807
+ borrowIncentives[coinName] = {
2808
+ coinName: borrowIncentivePool.coinName,
2809
+ coinType: borrowIncentivePool.coinType,
2810
+ symbol: borrowIncentivePool.symbol,
2811
+ coinDecimal: borrowIncentivePool.coinDecimal,
2812
+ coinPrice: borrowIncentivePool.coinPrice,
2813
+ rewards
2814
+ };
2667
2815
  }
2668
2816
  }
2669
2817
  let riskLevel = totalRequiredCollateralValue.isZero() ? BigNumber3(0) : totalBorrowedValueWithWeight.dividedBy(totalRequiredCollateralValue);
@@ -2791,6 +2939,70 @@ var getTotalValueLocked = async (query, indexer = false) => {
2791
2939
  return tvl;
2792
2940
  };
2793
2941
 
2942
+ // src/queries/vescaQuery.ts
2943
+ import BigNumber4 from "bignumber.js";
2944
+ var getVescaKeys = async (query, ownerAddress) => {
2945
+ const owner = ownerAddress || query.suiKit.currentAddress();
2946
+ const veScaPkgId = IS_VE_SCA_TEST ? "0xb220d034bdf335d77ae5bfbf6daf059c2cc7a1f719b12bfed75d1736fac038c8" : query.address.get("vesca.id");
2947
+ const veScaKeyType = `${veScaPkgId}::ve_sca::VeScaKey`;
2948
+ const keyObjectsResponse = [];
2949
+ let hasNextPage = false;
2950
+ let nextCursor = null;
2951
+ do {
2952
+ const paginatedKeyObjectsResponse = await query.suiKit.client().getOwnedObjects({
2953
+ owner,
2954
+ filter: {
2955
+ StructType: veScaKeyType
2956
+ },
2957
+ cursor: nextCursor
2958
+ });
2959
+ keyObjectsResponse.push(...paginatedKeyObjectsResponse.data);
2960
+ if (paginatedKeyObjectsResponse.hasNextPage && paginatedKeyObjectsResponse.nextCursor) {
2961
+ hasNextPage = true;
2962
+ nextCursor = paginatedKeyObjectsResponse.nextCursor;
2963
+ } else {
2964
+ hasNextPage = false;
2965
+ }
2966
+ } while (hasNextPage);
2967
+ const keyObjectDatas = keyObjectsResponse.map((objResponse) => objResponse.data).filter((data) => !!data);
2968
+ return keyObjectDatas;
2969
+ };
2970
+ var getVeScas = async (query, ownerAddress) => {
2971
+ const keyObjectDatas = await getVescaKeys(query, ownerAddress);
2972
+ const keyObjectId = keyObjectDatas.map((data) => data.objectId);
2973
+ const veScas = [];
2974
+ for (const keyId of keyObjectId) {
2975
+ const veSca = await getVeSca(query, keyId);
2976
+ if (veSca)
2977
+ veScas.push(veSca);
2978
+ }
2979
+ return veScas;
2980
+ };
2981
+ var getVeSca = async (query, veScaKeyId, ownerAddress) => {
2982
+ const tableId = IS_VE_SCA_TEST ? "0xc607241e4a679fe376d1170b2fbe07b64917bfe69100d4825241cda20039d4bd" : query.address.get(`vesca.tableId`);
2983
+ veScaKeyId = veScaKeyId || (await getVescaKeys(query, ownerAddress))[0].objectId;
2984
+ let vesca = void 0;
2985
+ const veScaDynamicFieldObjectResponse = await query.suiKit.client().getDynamicFieldObject({
2986
+ parentId: tableId,
2987
+ name: {
2988
+ type: "0x2::object::ID",
2989
+ value: veScaKeyId
2990
+ }
2991
+ });
2992
+ const veScaDynamicFieldObject = veScaDynamicFieldObjectResponse.data;
2993
+ if (veScaDynamicFieldObject && veScaDynamicFieldObject.content && veScaDynamicFieldObject.content.dataType === "moveObject" && "fields" in veScaDynamicFieldObject.content) {
2994
+ const dynamicFields = veScaDynamicFieldObject.content.fields.value.fields;
2995
+ vesca = {
2996
+ id: veScaDynamicFieldObject.objectId,
2997
+ keyId: veScaKeyId,
2998
+ lockedScaAmount: BigNumber4(dynamicFields.locked_sca_amount).toNumber(),
2999
+ lockedScaCoin: BigNumber4(dynamicFields.locked_sca_amount).shiftedBy(-9).toNumber(),
3000
+ unlockAt: BigNumber4(dynamicFields.unlock_at).toNumber()
3001
+ };
3002
+ }
3003
+ return vesca;
3004
+ };
3005
+
2794
3006
  // src/models/scallopIndexer.ts
2795
3007
  import axios2 from "axios";
2796
3008
  var ScallopIndexer = class {
@@ -3633,6 +3845,38 @@ var ScallopUtils = class {
3633
3845
  parseApyToApr(apy, compoundFrequency = 365) {
3634
3846
  return ((1 + apy) ** (1 / compoundFrequency) - 1) * compoundFrequency;
3635
3847
  }
3848
+ /**
3849
+ * Give extend lock period to get unlock at in seconds timestamp.
3850
+ *
3851
+ * @description
3852
+ * - When the user without remaining unlock period, If the extended unlock day is not specified,
3853
+ * the unlock period will be increased by one day by default.
3854
+ * - When the given extended day plus the user's remaining unlock period exceeds the maximum
3855
+ * unlock period, the maximum unlock period is used as unlock period.
3856
+ *
3857
+ * @param extendLockPeriodInDay The extend lock period in day.
3858
+ * @param unlockAtInSecondTimestamp The unlock timestamp from veSca object.
3859
+ * @return New unlock at in seconds timestamp.
3860
+ */
3861
+ getUnlockAt(extendLockPeriodInDay, unlockAtInSecondTimestamp) {
3862
+ const now = Math.floor((/* @__PURE__ */ new Date()).getTime() / 1e3);
3863
+ const remainingLockPeriod = unlockAtInSecondTimestamp ? Math.max(unlockAtInSecondTimestamp - now, 0) : 0;
3864
+ let newUnlockAtInSecondTimestamp = 0;
3865
+ if (remainingLockPeriod === 0) {
3866
+ const lockPeriod = (extendLockPeriodInDay ?? 1) * UNLOCK_ROUND_DURATION;
3867
+ newUnlockAtInSecondTimestamp = Math.min(
3868
+ now + lockPeriod,
3869
+ now + MAX_LOCK_DURATION
3870
+ );
3871
+ } else {
3872
+ const lockPeriod = Math.min(
3873
+ extendLockPeriodInDay ? extendLockPeriodInDay * UNLOCK_ROUND_DURATION + remainingLockPeriod : remainingLockPeriod,
3874
+ MAX_LOCK_DURATION
3875
+ );
3876
+ newUnlockAtInSecondTimestamp = now + lockPeriod;
3877
+ }
3878
+ return findClosestUnlockRound(newUnlockAtInSecondTimestamp);
3879
+ }
3636
3880
  };
3637
3881
 
3638
3882
  // src/models/scallopBuilder.ts
@@ -4293,9 +4537,282 @@ var newSpoolTxBlock = (builder, initTxBlock) => {
4293
4537
  };
4294
4538
 
4295
4539
  // src/builders/borrowIncentiveBuilder.ts
4296
- import { TransactionBlock as TransactionBlock3 } from "@mysten/sui.js/transactions";
4297
- import { SUI_CLOCK_OBJECT_ID as SUI_CLOCK_OBJECT_ID4 } from "@mysten/sui.js/utils";
4298
- import { SuiTxBlock as SuiKitTxBlock5 } from "@scallop-io/sui-kit";
4540
+ import { TransactionBlock as TransactionBlock4 } from "@mysten/sui.js/transactions";
4541
+ import { SUI_CLOCK_OBJECT_ID as SUI_CLOCK_OBJECT_ID5 } from "@mysten/sui.js/utils";
4542
+ import { SuiTxBlock as SuiKitTxBlock6 } from "@scallop-io/sui-kit";
4543
+
4544
+ // src/builders/vescaBuilder.ts
4545
+ import {
4546
+ SUI_CLOCK_OBJECT_ID as SUI_CLOCK_OBJECT_ID4,
4547
+ TransactionBlock as TransactionBlock3,
4548
+ SuiTxBlock as SuiKitTxBlock5
4549
+ } from "@scallop-io/sui-kit";
4550
+ var requireVeSca = async (...params) => {
4551
+ const [builder, txBlock, veScaKey] = params;
4552
+ if (params.length === 3 && veScaKey && typeof veScaKey === "string") {
4553
+ const veSca = await getVeSca(builder.query, veScaKey);
4554
+ if (!veSca) {
4555
+ return void 0;
4556
+ }
4557
+ return veSca;
4558
+ }
4559
+ const sender = requireSender(txBlock);
4560
+ const veScas = await getVeScas(builder.query, sender);
4561
+ if (veScas.length === 0) {
4562
+ return void 0;
4563
+ }
4564
+ return veScas[0];
4565
+ };
4566
+ var generateNormalVeScaMethod = ({
4567
+ builder,
4568
+ txBlock
4569
+ }) => {
4570
+ const veScaIds = {
4571
+ pkgId: builder.address.get("vesca.id"),
4572
+ table: builder.address.get("vesca.table"),
4573
+ treasury: builder.address.get("vesca.treasury"),
4574
+ config: builder.address.get("vesca.config")
4575
+ };
4576
+ return {
4577
+ lockSca: (scaCoin, unlockAtInSecondTimestamp) => {
4578
+ return txBlock.moveCall(
4579
+ `${veScaIds.pkgId}::ve_sca::mint_ve_sca_key`,
4580
+ [
4581
+ veScaIds.config,
4582
+ veScaIds.table,
4583
+ veScaIds.treasury,
4584
+ scaCoin,
4585
+ unlockAtInSecondTimestamp,
4586
+ SUI_CLOCK_OBJECT_ID4
4587
+ ],
4588
+ []
4589
+ );
4590
+ },
4591
+ extendLockPeriod: (veScaKey, newUnlockAtInSecondTimestamp) => {
4592
+ txBlock.moveCall(
4593
+ `${veScaIds.pkgId}::ve_sca::extend_lock_period`,
4594
+ [
4595
+ veScaIds.config,
4596
+ veScaKey,
4597
+ veScaIds.table,
4598
+ veScaIds.treasury,
4599
+ newUnlockAtInSecondTimestamp,
4600
+ SUI_CLOCK_OBJECT_ID4
4601
+ ],
4602
+ []
4603
+ );
4604
+ },
4605
+ extendLockAmount: (veScaKey, scaCoin) => {
4606
+ txBlock.moveCall(
4607
+ `${veScaIds.pkgId}::ve_sca::lock_more_sca`,
4608
+ [
4609
+ veScaIds.config,
4610
+ veScaKey,
4611
+ veScaIds.table,
4612
+ veScaIds.treasury,
4613
+ scaCoin,
4614
+ SUI_CLOCK_OBJECT_ID4
4615
+ ],
4616
+ []
4617
+ );
4618
+ },
4619
+ renewExpiredVeSca: (veScaKey, scaCoin, newUnlockAtInSecondTimestamp) => {
4620
+ txBlock.moveCall(
4621
+ `${veScaIds.pkgId}::ve_sca::renew_expired_ve_sca`,
4622
+ [
4623
+ veScaIds.config,
4624
+ veScaKey,
4625
+ veScaIds.table,
4626
+ veScaIds.treasury,
4627
+ scaCoin,
4628
+ newUnlockAtInSecondTimestamp,
4629
+ SUI_CLOCK_OBJECT_ID4
4630
+ ],
4631
+ []
4632
+ );
4633
+ },
4634
+ redeemSca: (veScaKey) => {
4635
+ return txBlock.moveCall(
4636
+ `${veScaIds.pkgId}::ve_sca::redeem`,
4637
+ [
4638
+ veScaIds.config,
4639
+ veScaKey,
4640
+ veScaIds.table,
4641
+ veScaIds.treasury,
4642
+ SUI_CLOCK_OBJECT_ID4
4643
+ ],
4644
+ []
4645
+ );
4646
+ }
4647
+ };
4648
+ };
4649
+ var generateQuickVeScaMethod = ({
4650
+ builder,
4651
+ txBlock
4652
+ }) => {
4653
+ return {
4654
+ lockScaQuick: async (amountOrCoin, lockPeriodInDays, autoCheck = true) => {
4655
+ const sender = requireSender(txBlock);
4656
+ const veSca = await requireVeSca(builder, txBlock);
4657
+ let scaCoin = void 0;
4658
+ const transferObjects = [];
4659
+ if (amountOrCoin !== void 0 && typeof amountOrCoin === "number") {
4660
+ const coins = await builder.utils.selectCoinIds(
4661
+ amountOrCoin,
4662
+ SCA_COIN_TYPE,
4663
+ sender
4664
+ );
4665
+ const [takeCoin, leftCoin] = txBlock.takeAmountFromCoins(
4666
+ coins,
4667
+ amountOrCoin
4668
+ );
4669
+ scaCoin = takeCoin;
4670
+ transferObjects.push(leftCoin);
4671
+ } else {
4672
+ scaCoin = amountOrCoin;
4673
+ }
4674
+ const newUnlockAt = builder.utils.getUnlockAt(
4675
+ lockPeriodInDays,
4676
+ veSca?.unlockAt
4677
+ );
4678
+ if (autoCheck)
4679
+ checkLockSca(
4680
+ amountOrCoin,
4681
+ lockPeriodInDays,
4682
+ newUnlockAt,
4683
+ veSca?.unlockAt
4684
+ );
4685
+ console.log(
4686
+ new Date(newUnlockAt * 1e3).toLocaleString("en-CA", {
4687
+ hour12: true
4688
+ })
4689
+ );
4690
+ const isInitialLock = !veSca?.unlockAt;
4691
+ const isLockExpired = !isInitialLock && veSca.unlockAt * 1e3 <= (/* @__PURE__ */ new Date()).getTime();
4692
+ if (isInitialLock || isLockExpired) {
4693
+ if (scaCoin) {
4694
+ if (isInitialLock) {
4695
+ const veScaKey = txBlock.lockSca(scaCoin, newUnlockAt);
4696
+ transferObjects.push(veScaKey);
4697
+ } else {
4698
+ if (veSca.lockedScaAmount !== 0) {
4699
+ const unlockedSca = txBlock.redeemSca(veSca.keyId);
4700
+ transferObjects.push(unlockedSca);
4701
+ }
4702
+ txBlock.renewExpiredVeSca(veSca.keyId, scaCoin, newUnlockAt);
4703
+ }
4704
+ }
4705
+ } else {
4706
+ if (!!scaCoin && !!lockPeriodInDays) {
4707
+ txBlock.extendLockPeriod(veSca.keyId, newUnlockAt);
4708
+ txBlock.extendLockAmount(veSca.keyId, scaCoin);
4709
+ } else if (lockPeriodInDays) {
4710
+ txBlock.extendLockPeriod(veSca.keyId, newUnlockAt);
4711
+ } else if (scaCoin) {
4712
+ txBlock.extendLockAmount(veSca.keyId, scaCoin);
4713
+ }
4714
+ }
4715
+ if (transferObjects.length > 0) {
4716
+ txBlock.transferObjects(transferObjects, sender);
4717
+ }
4718
+ },
4719
+ extendLockPeriodQuick: async (lockPeriodInDays, veScaKey, autoCheck = true) => {
4720
+ const veSca = await requireVeSca(builder, txBlock, veScaKey);
4721
+ const newUnlockAt = builder.utils.getUnlockAt(lockPeriodInDays);
4722
+ if (autoCheck)
4723
+ checkExtendLockPeriod(lockPeriodInDays, newUnlockAt, veSca?.unlockAt);
4724
+ if (veSca) {
4725
+ txBlock.extendLockPeriod(veSca.keyId, newUnlockAt);
4726
+ }
4727
+ },
4728
+ extendLockAmountQuick: async (scaAmount, veScaKey, autoCheck = true) => {
4729
+ const sender = requireSender(txBlock);
4730
+ const veSca = await requireVeSca(builder, txBlock, veScaKey);
4731
+ if (autoCheck)
4732
+ checkExtendLockAmount(scaAmount, veSca?.unlockAt);
4733
+ if (veSca) {
4734
+ const scaCoins = await builder.utils.selectCoinIds(
4735
+ scaAmount,
4736
+ SCA_COIN_TYPE,
4737
+ sender
4738
+ );
4739
+ const [takeCoin, leftCoin] = txBlock.takeAmountFromCoins(
4740
+ scaCoins,
4741
+ scaAmount
4742
+ );
4743
+ txBlock.extendLockAmount(veSca.keyId, takeCoin);
4744
+ txBlock.transferObjects([leftCoin], sender);
4745
+ }
4746
+ },
4747
+ renewExpiredVeScaQuick: async (scaAmount, lockPeriodInDays, veScaKey, autoCheck = true) => {
4748
+ const sender = requireSender(txBlock);
4749
+ const veSca = await requireVeSca(builder, txBlock, veScaKey);
4750
+ const newUnlockAt = builder.utils.getUnlockAt(
4751
+ lockPeriodInDays,
4752
+ veSca?.unlockAt
4753
+ );
4754
+ if (autoCheck)
4755
+ checkRenewExpiredVeSca(scaAmount, lockPeriodInDays, veSca?.unlockAt);
4756
+ if (veSca) {
4757
+ const transferObjects = [];
4758
+ if (veSca.lockedScaAmount !== 0) {
4759
+ const unlockedSca = txBlock.redeemSca(veSca.keyId);
4760
+ transferObjects.push(unlockedSca);
4761
+ }
4762
+ const scaCoins = await builder.utils.selectCoinIds(
4763
+ scaAmount,
4764
+ SCA_COIN_TYPE,
4765
+ sender
4766
+ );
4767
+ const [takeCoin, leftCoin] = txBlock.takeAmountFromCoins(
4768
+ scaCoins,
4769
+ scaAmount
4770
+ );
4771
+ transferObjects.push(leftCoin);
4772
+ txBlock.renewExpiredVeSca(veSca.keyId, takeCoin, newUnlockAt);
4773
+ txBlock.transferObjects(transferObjects, sender);
4774
+ }
4775
+ },
4776
+ redeemScaQuick: async (veScaKey) => {
4777
+ const sender = requireSender(txBlock);
4778
+ const veSca = await requireVeSca(builder, txBlock, veScaKey);
4779
+ checkVesca(veSca?.unlockAt);
4780
+ if (veSca) {
4781
+ const sca = txBlock.redeemSca(veSca.keyId);
4782
+ txBlock.transferObjects([sca], sender);
4783
+ }
4784
+ }
4785
+ };
4786
+ };
4787
+ var newVeScaTxBlock = (builder, initTxBlock) => {
4788
+ const txBlock = initTxBlock instanceof TransactionBlock3 ? new SuiKitTxBlock5(initTxBlock) : initTxBlock ? initTxBlock : new SuiKitTxBlock5();
4789
+ const normalMethod = generateNormalVeScaMethod({
4790
+ builder,
4791
+ txBlock
4792
+ });
4793
+ const normalTxBlock = new Proxy(txBlock, {
4794
+ get: (target, prop) => {
4795
+ if (prop in normalMethod) {
4796
+ return Reflect.get(normalMethod, prop);
4797
+ }
4798
+ return Reflect.get(target, prop);
4799
+ }
4800
+ });
4801
+ const quickMethod = generateQuickVeScaMethod({
4802
+ builder,
4803
+ txBlock: normalTxBlock
4804
+ });
4805
+ return new Proxy(normalTxBlock, {
4806
+ get: (target, prop) => {
4807
+ if (prop in quickMethod) {
4808
+ return Reflect.get(quickMethod, prop);
4809
+ }
4810
+ return Reflect.get(target, prop);
4811
+ }
4812
+ });
4813
+ };
4814
+
4815
+ // src/builders/borrowIncentiveBuilder.ts
4299
4816
  var requireObligationInfo2 = async (...params) => {
4300
4817
  const [builder, txBlock, obligationId, obligationKey] = params;
4301
4818
  if (params.length === 4 && obligationId && obligationKey && typeof obligationId === "string") {
@@ -4316,59 +4833,115 @@ var requireObligationInfo2 = async (...params) => {
4316
4833
  obligationLocked: obligations[0].locked
4317
4834
  };
4318
4835
  };
4836
+ var getBindedObligationId = async (builder, veScaKey) => {
4837
+ const borrowIncentivePkgId = builder.address.get("borrowIncentive.id");
4838
+ const incentivePoolsId = builder.address.get(
4839
+ "borrowIncentive.incentivePools"
4840
+ );
4841
+ const veScaPkgId = IS_VE_SCA_TEST ? "0xb220d034bdf335d77ae5bfbf6daf059c2cc7a1f719b12bfed75d1736fac038c8" : builder.address.get("vesca.id");
4842
+ const client = builder.suiKit.client();
4843
+ const incentivePoolsResponse = await client.getObject({
4844
+ id: incentivePoolsId,
4845
+ options: {
4846
+ showContent: true
4847
+ }
4848
+ });
4849
+ if (incentivePoolsResponse.data?.content?.dataType !== "moveObject")
4850
+ return false;
4851
+ const incentivePoolFields = incentivePoolsResponse.data.content.fields;
4852
+ const veScaBindTableId = incentivePoolFields.ve_sca_bind.fields.id.id;
4853
+ const keyType = `${borrowIncentivePkgId}::typed_id::TypedID<${veScaPkgId}::ve_sca::VeScaKey>`;
4854
+ const veScaBindTableResponse = await client.getDynamicFieldObject({
4855
+ parentId: veScaBindTableId,
4856
+ name: {
4857
+ type: keyType,
4858
+ value: veScaKey
4859
+ }
4860
+ });
4861
+ if (veScaBindTableResponse.data?.content?.dataType !== "moveObject")
4862
+ return false;
4863
+ const veScaBindTableFields = veScaBindTableResponse.data.content.fields;
4864
+ const obligationId = veScaBindTableFields.value.fields.id;
4865
+ return obligationId;
4866
+ };
4319
4867
  var generateBorrowIncentiveNormalMethod = ({ builder, txBlock }) => {
4320
4868
  const borrowIncentiveIds = {
4321
- borrowIncentivePkg: builder.address.get("borrowIncentive.id"),
4869
+ borrowIncentivePkg: IS_VE_SCA_TEST ? "0x4d5a7cefa4147b4ace0ca845b20437d6ac0d32e5f2f855171f745472c2576246" : builder.address.get("borrowIncentive.id"),
4322
4870
  query: builder.address.get("borrowIncentive.query"),
4871
+ config: builder.address.get("borrowIncentive.config"),
4323
4872
  incentivePools: builder.address.get("borrowIncentive.incentivePools"),
4324
4873
  incentiveAccounts: builder.address.get(
4325
4874
  "borrowIncentive.incentiveAccounts"
4326
4875
  ),
4327
4876
  obligationAccessStore: builder.address.get("core.obligationAccessStore")
4328
4877
  };
4878
+ const veScaIds = {
4879
+ table: builder.address.get("vesca.table"),
4880
+ treasury: builder.address.get("vesca.treasury"),
4881
+ config: builder.address.get("vesca.config")
4882
+ };
4329
4883
  return {
4330
- stakeObligation: (obligationId, obligaionKey) => {
4331
- const rewardCoinName = "sui";
4332
- const rewardType = builder.utils.parseCoinType(rewardCoinName);
4884
+ stakeObligation: (obligationId, obligationKey) => {
4333
4885
  txBlock.moveCall(
4334
4886
  `${borrowIncentiveIds.borrowIncentivePkg}::user::stake`,
4335
4887
  [
4888
+ borrowIncentiveIds.config,
4336
4889
  borrowIncentiveIds.incentivePools,
4337
4890
  borrowIncentiveIds.incentiveAccounts,
4338
- obligaionKey,
4891
+ obligationKey,
4339
4892
  obligationId,
4340
4893
  borrowIncentiveIds.obligationAccessStore,
4341
- SUI_CLOCK_OBJECT_ID4
4894
+ SUI_CLOCK_OBJECT_ID5
4895
+ ]
4896
+ );
4897
+ },
4898
+ stakeObligationWithVesca: (obligationId, obligationKey, veScaKey) => {
4899
+ txBlock.moveCall(
4900
+ `${borrowIncentiveIds.borrowIncentivePkg}::user::stake_with_ve_sca`,
4901
+ [
4902
+ borrowIncentiveIds.config,
4903
+ borrowIncentiveIds.incentivePools,
4904
+ borrowIncentiveIds.incentiveAccounts,
4905
+ obligationKey,
4906
+ obligationId,
4907
+ borrowIncentiveIds.obligationAccessStore,
4908
+ veScaIds.config,
4909
+ veScaIds.treasury,
4910
+ veScaIds.table,
4911
+ veScaKey,
4912
+ SUI_CLOCK_OBJECT_ID5
4342
4913
  ],
4343
- [rewardType]
4914
+ []
4344
4915
  );
4345
4916
  },
4346
- unstakeObligation: (obligationId, obligaionKey) => {
4347
- const rewardCoinName = "sui";
4348
- const rewardType = builder.utils.parseCoinType(rewardCoinName);
4917
+ unstakeObligation: (obligationId, obligationKey) => {
4349
4918
  txBlock.moveCall(
4350
4919
  `${borrowIncentiveIds.borrowIncentivePkg}::user::unstake`,
4351
4920
  [
4921
+ borrowIncentiveIds.config,
4352
4922
  borrowIncentiveIds.incentivePools,
4353
4923
  borrowIncentiveIds.incentiveAccounts,
4354
- obligaionKey,
4924
+ obligationKey,
4355
4925
  obligationId,
4356
- SUI_CLOCK_OBJECT_ID4
4357
- ],
4358
- [rewardType]
4926
+ SUI_CLOCK_OBJECT_ID5
4927
+ ]
4359
4928
  );
4360
4929
  },
4361
- claimBorrowIncentive: (obligationId, obligaionKey, coinName) => {
4362
- const rewardCoinName = borrowIncentiveRewardCoins[coinName];
4930
+ claimBorrowIncentive: (obligationId, obligationKey, coinName, rewardCoinName) => {
4931
+ const rewardCoinNames = borrowIncentiveRewardCoins[coinName];
4932
+ if (rewardCoinNames.includes(rewardCoinName) === false) {
4933
+ throw new Error(`Invalid reward coin name ${rewardCoinName}`);
4934
+ }
4363
4935
  const rewardType = builder.utils.parseCoinType(rewardCoinName);
4364
4936
  return txBlock.moveCall(
4365
4937
  `${borrowIncentiveIds.borrowIncentivePkg}::user::redeem_rewards`,
4366
4938
  [
4939
+ borrowIncentiveIds.config,
4367
4940
  borrowIncentiveIds.incentivePools,
4368
4941
  borrowIncentiveIds.incentiveAccounts,
4369
- obligaionKey,
4942
+ obligationKey,
4370
4943
  obligationId,
4371
- SUI_CLOCK_OBJECT_ID4
4944
+ SUI_CLOCK_OBJECT_ID5
4372
4945
  ],
4373
4946
  [rewardType]
4374
4947
  );
@@ -4389,12 +4962,51 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
4389
4962
  obligationKey
4390
4963
  );
4391
4964
  const unstakeObligationBeforeStake = !!txBlock.txBlock.blockData.transactions.find(
4392
- (txn) => txn.kind === "MoveCall" && txn.target === `${builder.address.get("borrowIncentive.id")}::user::unstake`
4965
+ (txn) => txn.kind === "MoveCall" && (txn.target === `${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake` || txn.target === (IS_VE_SCA_TEST ? `${"0x4d5a7cefa4147b4ace0ca845b20437d6ac0d32e5f2f855171f745472c2576246"}::user::unstake` : `${builder.address.get(
4966
+ "borrowIncentive.id"
4967
+ )}::user::unstake`))
4393
4968
  );
4394
4969
  if (!obligationLocked || unstakeObligationBeforeStake) {
4395
4970
  txBlock.stakeObligation(obligationArg, obligationtKeyArg);
4396
4971
  }
4397
4972
  },
4973
+ stakeObligationWithVeScaQuick: async (obligation, obligationKey, veScaKey) => {
4974
+ const {
4975
+ obligationId: obligationArg,
4976
+ obligationKey: obligationtKeyArg,
4977
+ obligationLocked
4978
+ } = await requireObligationInfo2(
4979
+ builder,
4980
+ txBlock,
4981
+ obligation,
4982
+ obligationKey
4983
+ );
4984
+ const unstakeObligationBeforeStake = !!txBlock.txBlock.blockData.transactions.find(
4985
+ (txn) => txn.kind === "MoveCall" && (txn.target === `${OLD_BORROW_INCENTIVE_PROTOCOL_ID}::user::unstake` || txn.target === (IS_VE_SCA_TEST ? `${"0x4d5a7cefa4147b4ace0ca845b20437d6ac0d32e5f2f855171f745472c2576246"}::user::unstake` : `${builder.address.get(
4986
+ "borrowIncentive.id"
4987
+ )}::user::unstake`))
4988
+ );
4989
+ if (!obligationLocked || unstakeObligationBeforeStake) {
4990
+ const veSca = await requireVeSca(builder, txBlock, veScaKey);
4991
+ if (veSca) {
4992
+ const bindedObligationId = await getBindedObligationId(
4993
+ builder,
4994
+ veSca.keyId
4995
+ );
4996
+ if (!bindedObligationId || bindedObligationId === obligationArg) {
4997
+ txBlock.stakeObligationWithVesca(
4998
+ obligationArg,
4999
+ obligationtKeyArg,
5000
+ veSca.keyId
5001
+ );
5002
+ } else {
5003
+ txBlock.stakeObligation(obligationArg, obligationtKeyArg);
5004
+ }
5005
+ } else {
5006
+ txBlock.stakeObligation(obligationArg, obligationtKeyArg);
5007
+ }
5008
+ }
5009
+ },
4398
5010
  unstakeObligationQuick: async (obligation, obligationKey) => {
4399
5011
  const {
4400
5012
  obligationId: obligationArg,
@@ -4410,7 +5022,7 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
4410
5022
  txBlock.unstakeObligation(obligationArg, obligationtKeyArg);
4411
5023
  }
4412
5024
  },
4413
- claimBorrowIncentiveQuick: async (coinName, obligation, obligationKey) => {
5025
+ claimBorrowIncentiveQuick: async (coinName, rewardCoinName, obligation, obligationKey) => {
4414
5026
  const {
4415
5027
  obligationId: obligationArg,
4416
5028
  obligationKey: obligationtKeyArg
@@ -4423,13 +5035,14 @@ var generateBorrowIncentiveQuickMethod = ({ builder, txBlock }) => {
4423
5035
  return txBlock.claimBorrowIncentive(
4424
5036
  obligationArg,
4425
5037
  obligationtKeyArg,
4426
- coinName
5038
+ coinName,
5039
+ rewardCoinName
4427
5040
  );
4428
5041
  }
4429
5042
  };
4430
5043
  };
4431
5044
  var newBorrowIncentiveTxBlock = (builder, initTxBlock) => {
4432
- const txBlock = initTxBlock instanceof TransactionBlock3 ? new SuiKitTxBlock5(initTxBlock) : initTxBlock ? initTxBlock : new SuiKitTxBlock5();
5045
+ const txBlock = initTxBlock instanceof TransactionBlock4 ? new SuiKitTxBlock6(initTxBlock) : initTxBlock ? initTxBlock : new SuiKitTxBlock6();
4433
5046
  const normalMethod = generateBorrowIncentiveNormalMethod({
4434
5047
  builder,
4435
5048
  txBlock
@@ -4458,15 +5071,18 @@ var newBorrowIncentiveTxBlock = (builder, initTxBlock) => {
4458
5071
 
4459
5072
  // src/builders/index.ts
4460
5073
  var newScallopTxBlock = (builder, initTxBlock) => {
5074
+ const vescaTxBlock = newVeScaTxBlock(builder, initTxBlock);
4461
5075
  const borrowIncentiveTxBlock = newBorrowIncentiveTxBlock(
4462
5076
  builder,
4463
- initTxBlock
5077
+ vescaTxBlock
4464
5078
  );
4465
5079
  const spoolTxBlock = newSpoolTxBlock(builder, borrowIncentiveTxBlock);
4466
5080
  const coreTxBlock = newCoreTxBlock(builder, spoolTxBlock);
4467
5081
  return new Proxy(coreTxBlock, {
4468
5082
  get: (target, prop) => {
4469
- if (prop in borrowIncentiveTxBlock) {
5083
+ if (prop in vescaTxBlock) {
5084
+ return Reflect.get(vescaTxBlock, prop);
5085
+ } else if (prop in borrowIncentiveTxBlock) {
4470
5086
  return Reflect.get(borrowIncentiveTxBlock, prop);
4471
5087
  } else if (prop in spoolTxBlock) {
4472
5088
  return Reflect.get(spoolTxBlock, prop);
@@ -4966,7 +5582,7 @@ var ScallopClient = class {
4966
5582
  const coins = [];
4967
5583
  for (const stakeMarketCoin of stakeMarketCoins2) {
4968
5584
  const stakeCoinName = this.utils.parseCoinName(stakeMarketCoinName);
4969
- const coin = await txBlock.withdraw(stakeMarketCoin, stakeCoinName);
5585
+ const coin = txBlock.withdraw(stakeMarketCoin, stakeCoinName);
4970
5586
  coins.push(coin);
4971
5587
  }
4972
5588
  txBlock.transferObjects(coins, sender);
@@ -4999,17 +5615,17 @@ var ScallopClient = class {
4999
5615
  /**
5000
5616
  * stake obligaion.
5001
5617
  *
5002
- * @param obligaionId - The obligation account object.
5003
- * @param obligaionKeyId - The obligation key account object.
5618
+ * @param obligationId - The obligation account object.
5619
+ * @param obligationKeyId - The obligation key account object.
5004
5620
  * @param sign - Decide to directly sign the transaction or return the transaction block.
5005
5621
  * @param walletAddress - The wallet address of the owner.
5006
5622
  * @return Transaction block response or transaction block
5007
5623
  */
5008
- async stakeObligation(obligaionId, obligaionKeyId, sign = true, walletAddress) {
5624
+ async stakeObligation(obligationId, obligationKeyId, sign = true, walletAddress) {
5009
5625
  const txBlock = this.builder.createTxBlock();
5010
5626
  const sender = walletAddress || this.walletAddress;
5011
5627
  txBlock.setSender(sender);
5012
- await txBlock.stakeObligationQuick(obligaionId, obligaionKeyId);
5628
+ await txBlock.stakeObligationQuick(obligationId, obligationKeyId);
5013
5629
  if (sign) {
5014
5630
  return await this.suiKit.signAndSendTxn(
5015
5631
  txBlock
@@ -5021,17 +5637,17 @@ var ScallopClient = class {
5021
5637
  /**
5022
5638
  * unstake obligaion.
5023
5639
  *
5024
- * @param obligaionId - The obligation account object.
5025
- * @param obligaionKeyId - The obligation key account object.
5640
+ * @param obligationId - The obligation account object.
5641
+ * @param obligationKeyId - The obligation key account object.
5026
5642
  * @param sign - Decide to directly sign the transaction or return the transaction block.
5027
5643
  * @param walletAddress - The wallet address of the owner.
5028
5644
  * @return Transaction block response or transaction block
5029
5645
  */
5030
- async unstakeObligation(obligaionId, obligaionKeyId, sign = true, walletAddress) {
5646
+ async unstakeObligation(obligationId, obligationKeyId, sign = true, walletAddress) {
5031
5647
  const txBlock = this.builder.createTxBlock();
5032
5648
  const sender = walletAddress || this.walletAddress;
5033
5649
  txBlock.setSender(sender);
5034
- await txBlock.unstakeObligationQuick(obligaionId, obligaionKeyId);
5650
+ await txBlock.unstakeObligationQuick(obligationId, obligationKeyId);
5035
5651
  if (sign) {
5036
5652
  return await this.suiKit.signAndSendTxn(
5037
5653
  txBlock
@@ -5050,16 +5666,21 @@ var ScallopClient = class {
5050
5666
  * @param walletAddress - The wallet address of the owner.
5051
5667
  * @return Transaction block response or transaction block
5052
5668
  */
5053
- async claimBorrowIncentive(coinName, obligaionId, obligaionKeyId, sign = true, walletAddress) {
5669
+ async claimBorrowIncentive(coinName, obligationId, obligationKeyId, sign = true, walletAddress) {
5054
5670
  const txBlock = this.builder.createTxBlock();
5055
5671
  const sender = walletAddress || this.walletAddress;
5056
5672
  txBlock.setSender(sender);
5057
- const rewardCoin = await txBlock.claimBorrowIncentiveQuick(
5058
- coinName,
5059
- obligaionId,
5060
- obligaionKeyId
5061
- );
5062
- txBlock.transferObjects([rewardCoin], sender);
5673
+ const rewardCoins = [];
5674
+ for (const rewardCoinName of SUPPORT_BORROW_INCENTIVE_REWARDS) {
5675
+ const rewardCoin = await txBlock.claimBorrowIncentiveQuick(
5676
+ coinName,
5677
+ rewardCoinName,
5678
+ obligationId,
5679
+ obligationKeyId
5680
+ );
5681
+ rewardCoins.push(rewardCoin);
5682
+ }
5683
+ txBlock.transferObjects(rewardCoins, sender);
5063
5684
  if (sign) {
5064
5685
  return await this.suiKit.signAndSendTxn(
5065
5686
  txBlock
@@ -5181,7 +5802,14 @@ export {
5181
5802
  ADDRESSES_ID,
5182
5803
  API_BASE_URL,
5183
5804
  BORROW_FEE_PROTOCOL_ID,
5805
+ IS_VE_SCA_TEST,
5806
+ MAX_LOCK_DURATION,
5807
+ MAX_LOCK_ROUNDS,
5808
+ MIN_INITIAL_LOCK_AMOUNT,
5809
+ MIN_TOP_UP_AMOUNT,
5810
+ OLD_BORROW_INCENTIVE_PROTOCOL_ID,
5184
5811
  PROTOCOL_OBJECT_ID,
5812
+ SCA_COIN_TYPE,
5185
5813
  SDK_API_BASE_URL,
5186
5814
  SUPPORT_BORROW_INCENTIVE_POOLS,
5187
5815
  SUPPORT_BORROW_INCENTIVE_REWARDS,
@@ -5198,6 +5826,7 @@ export {
5198
5826
  ScallopIndexer,
5199
5827
  ScallopQuery,
5200
5828
  ScallopUtils,
5829
+ UNLOCK_ROUND_DURATION,
5201
5830
  assetCoins,
5202
5831
  borrowIncentiveRewardCoins,
5203
5832
  coinDecimals,