@gearbox-protocol/sdk 15.1.0-next.5 → 15.1.0-next.7

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 (130) hide show
  1. package/dist/cjs/common-utils/utils/apy/get-single-quota-borrow-rate.js +2 -0
  2. package/dist/cjs/common-utils/utils/creditAccount/calc-health-factor.js +24 -22
  3. package/dist/cjs/common-utils/utils/creditAccount/calc-quota-borrow-rate.js +2 -0
  4. package/dist/cjs/common-utils/utils/creditAccount/get-time-to-liquidation.js +5 -4
  5. package/dist/cjs/common-utils/utils/creditAccount/liquidation-price.js +21 -11
  6. package/dist/cjs/model/index.js +1 -0
  7. package/dist/cjs/model/positions.schema.js +13 -0
  8. package/dist/cjs/preview/preview/CreditAccountState.js +14 -1
  9. package/dist/cjs/preview/preview/buildDelayedPreview.js +16 -6
  10. package/dist/cjs/preview/preview/previewAdjustCreditAccount.js +9 -2
  11. package/dist/cjs/preview/preview/previewOpenCreditAccount.js +11 -3
  12. package/dist/cjs/preview/preview/previewOperation.js +1 -1
  13. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +0 -6
  14. package/dist/cjs/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +2 -90
  15. package/dist/cjs/sdk/accounts/intents/testing/sdk-mock.js +31 -4
  16. package/dist/cjs/sdk/accounts/intents/utils/adjust-state-to-snapshot.js +18 -0
  17. package/dist/cjs/sdk/accounts/intents/utils/index.js +2 -0
  18. package/dist/cjs/sdk/accounts/liquidations/LiquidationsService.js +0 -3
  19. package/dist/cjs/sdk/index.js +21 -5
  20. package/dist/cjs/sdk/market/credit/CreditManagerV310Contract.js +1 -12
  21. package/dist/cjs/sdk/market/credit/CreditSuite.js +17 -26
  22. package/dist/cjs/sdk/market/credit/index.js +3 -0
  23. package/dist/cjs/sdk/market/credit/isStrategyCollateral.js +50 -0
  24. package/dist/cjs/sdk/market/index.js +17 -0
  25. package/dist/cjs/sdk/market/math.js +57 -44
  26. package/dist/cjs/sdk/market/oracle/PriceOracleBaseContract.js +10 -3
  27. package/dist/cjs/sdk/market/pool/PoolV310Contract.js +1 -1
  28. package/dist/cjs/sdk/opportunities/index.js +0 -13
  29. package/dist/cjs/sdk/positions/PositionsService.js +206 -1
  30. package/dist/cjs/sdk/positions/calcBorrowRate.js +43 -0
  31. package/dist/cjs/sdk/positions/calcHealthFactor.js +44 -0
  32. package/dist/cjs/sdk/positions/calcLiquidationPrice.js +23 -0
  33. package/dist/cjs/sdk/positions/calcLiquidationPriceForTarget.js +30 -0
  34. package/dist/cjs/sdk/positions/calcTimeToLiquidationMs.js +18 -0
  35. package/dist/cjs/sdk/positions/index.js +12 -1
  36. package/dist/cjs/sdk/positions/types.js +31 -0
  37. package/dist/esm/common-utils/utils/apy/get-single-quota-borrow-rate.js +2 -0
  38. package/dist/esm/common-utils/utils/creditAccount/calc-health-factor.js +24 -22
  39. package/dist/esm/common-utils/utils/creditAccount/calc-quota-borrow-rate.js +2 -0
  40. package/dist/esm/common-utils/utils/creditAccount/get-time-to-liquidation.js +5 -4
  41. package/dist/esm/common-utils/utils/creditAccount/liquidation-price.js +21 -11
  42. package/dist/esm/dev/AccountOpener.js +1 -1
  43. package/dist/esm/dev/withdrawalUtils.js +1 -1
  44. package/dist/esm/model/index.js +2 -2
  45. package/dist/esm/model/positions.schema.js +14 -2
  46. package/dist/esm/plugins/adapters/contracts/ERC4626AdapterContract.js +1 -1
  47. package/dist/esm/preview/preview/CreditAccountState.js +14 -1
  48. package/dist/esm/preview/preview/buildDelayedPreview.js +16 -6
  49. package/dist/esm/preview/preview/previewAdjustCreditAccount.js +9 -2
  50. package/dist/esm/preview/preview/previewOpenCreditAccount.js +11 -3
  51. package/dist/esm/preview/preview/previewOperation.js +1 -1
  52. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  53. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  54. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +2 -8
  55. package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +2 -90
  56. package/dist/esm/sdk/accounts/intents/testing/sdk-mock.js +31 -4
  57. package/dist/esm/sdk/accounts/intents/utils/adjust-state-to-snapshot.js +17 -0
  58. package/dist/esm/sdk/accounts/intents/utils/index.js +2 -1
  59. package/dist/esm/sdk/accounts/liquidations/LiquidationsService.js +1 -4
  60. package/dist/esm/sdk/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  61. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  62. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  63. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  64. package/dist/esm/sdk/base/TokensMeta.js +3 -3
  65. package/dist/esm/sdk/chain/detectNetwork.js +1 -1
  66. package/dist/esm/sdk/core/createAddressProvider.js +1 -1
  67. package/dist/esm/sdk/index.js +9 -2
  68. package/dist/esm/sdk/market/credit/CreditFacadeV310BaseContract.js +1 -1
  69. package/dist/esm/sdk/market/credit/CreditManagerV310Contract.js +2 -13
  70. package/dist/esm/sdk/market/credit/CreditSuite.js +18 -27
  71. package/dist/esm/sdk/market/credit/index.js +2 -1
  72. package/dist/esm/sdk/market/credit/isStrategyCollateral.js +48 -0
  73. package/dist/esm/sdk/market/index.js +3 -1
  74. package/dist/esm/sdk/market/math.js +52 -40
  75. package/dist/esm/sdk/market/oracle/PriceOracleBaseContract.js +10 -3
  76. package/dist/esm/sdk/market/pool/PoolV310Contract.js +3 -3
  77. package/dist/esm/sdk/market/zapper/IETHZapperContract.js +1 -1
  78. package/dist/esm/sdk/market/zapper/ZapperContract.js +1 -1
  79. package/dist/esm/sdk/opportunities/index.js +1 -2
  80. package/dist/esm/sdk/pools/PoolService.js +1 -1
  81. package/dist/esm/sdk/positions/PositionsService.js +206 -1
  82. package/dist/esm/sdk/positions/calcBorrowRate.js +42 -0
  83. package/dist/esm/sdk/positions/calcHealthFactor.js +43 -0
  84. package/dist/esm/sdk/positions/calcLiquidationPrice.js +22 -0
  85. package/dist/esm/sdk/positions/calcLiquidationPriceForTarget.js +29 -0
  86. package/dist/esm/sdk/positions/calcTimeToLiquidationMs.js +17 -0
  87. package/dist/esm/sdk/positions/index.js +7 -2
  88. package/dist/esm/sdk/positions/types.js +31 -1
  89. package/dist/esm/sdk/utils/viem/simulateWithPriceUpdates.js +1 -1
  90. package/dist/types/common-utils/utils/apy/get-single-quota-borrow-rate.d.ts +2 -0
  91. package/dist/types/common-utils/utils/creditAccount/calc-health-factor.d.ts +3 -0
  92. package/dist/types/common-utils/utils/creditAccount/calc-quota-borrow-rate.d.ts +2 -0
  93. package/dist/types/common-utils/utils/creditAccount/get-time-to-liquidation.d.ts +3 -0
  94. package/dist/types/common-utils/utils/creditAccount/liquidation-price.d.ts +3 -0
  95. package/dist/types/model/index.d.ts +3 -3
  96. package/dist/types/model/opportunities.d.ts +9 -9
  97. package/dist/types/model/positions.d.ts +87 -4
  98. package/dist/types/model/positions.schema.d.ts +26 -1
  99. package/dist/types/preview/preview/CreditAccountState.d.ts +6 -0
  100. package/dist/types/preview/preview/buildDelayedPreview.d.ts +5 -1
  101. package/dist/types/preview/preview/types.d.ts +4 -2
  102. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +1 -7
  103. package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressor.d.ts +3 -12
  104. package/dist/types/sdk/accounts/credit-account-compressor/index.d.ts +2 -2
  105. package/dist/types/sdk/accounts/credit-account-compressor/types.d.ts +1 -19
  106. package/dist/types/sdk/accounts/index.d.ts +2 -2
  107. package/dist/types/sdk/accounts/intents/testing/sdk-mock.d.ts +6 -0
  108. package/dist/types/sdk/accounts/intents/utils/adjust-state-to-snapshot.d.ts +13 -0
  109. package/dist/types/sdk/accounts/intents/utils/index.d.ts +2 -1
  110. package/dist/types/sdk/accounts/types.d.ts +1 -12
  111. package/dist/types/sdk/index.d.ts +10 -4
  112. package/dist/types/sdk/market/credit/CreditManagerV310Contract.d.ts +0 -4
  113. package/dist/types/sdk/market/credit/CreditSuite.d.ts +2 -16
  114. package/dist/types/sdk/market/credit/index.d.ts +2 -1
  115. package/dist/types/sdk/market/credit/isStrategyCollateral.d.ts +74 -0
  116. package/dist/types/sdk/market/credit/types.d.ts +2 -9
  117. package/dist/types/sdk/market/index.d.ts +3 -1
  118. package/dist/types/sdk/market/math.d.ts +44 -34
  119. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +4 -0
  120. package/dist/types/sdk/market/oracle/types.d.ts +8 -0
  121. package/dist/types/sdk/opportunities/index.d.ts +1 -2
  122. package/dist/types/sdk/positions/PositionsService.d.ts +31 -2
  123. package/dist/types/sdk/positions/calcBorrowRate.d.ts +40 -0
  124. package/dist/types/sdk/positions/calcHealthFactor.d.ts +45 -0
  125. package/dist/types/sdk/positions/calcLiquidationPrice.d.ts +12 -0
  126. package/dist/types/sdk/positions/calcLiquidationPriceForTarget.d.ts +43 -0
  127. package/dist/types/sdk/positions/calcTimeToLiquidationMs.d.ts +15 -0
  128. package/dist/types/sdk/positions/index.d.ts +7 -2
  129. package/dist/types/sdk/positions/types.d.ts +58 -1
  130. package/package.json +1 -1
@@ -5,6 +5,8 @@ const require_common_utils_utils_creditAccount_calc_quota_borrow_rate = require(
5
5
  /**
6
6
  * Under the hood sums up rates for all given quotas and then multiplies them by 1+feeInterest,
7
7
  * but it is expected that the ONLY quota will be passed
8
+ *
9
+ * @deprecated Use `calcBorrowRate` from `sdk/positions` instead.
8
10
  */
9
11
  function getSingleQuotaBorrowRate(props) {
10
12
  const qr = require_common_utils_utils_creditAccount_calc_quota_borrow_rate.calcQuotaBorrowRate(props);
@@ -1,10 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_sdk_utils_bigint_math = require("../../../sdk/utils/bigint-math.js");
3
- const require_sdk_constants_math = require("../../../sdk/constants/math.js");
4
- require("../../../sdk/index.js");
5
- const require_common_utils_utils_price_math = require("../price-math.js");
2
+ const require_sdk_positions_calcHealthFactor = require("../../../sdk/positions/calcHealthFactor.js");
6
3
  //#region src/common-utils/utils/creditAccount/calc-health-factor.ts
7
- const MAX_UINT16 = 65535;
8
4
  /**
9
5
  * Computes account health factor in percentage-factor units.
10
6
  *
@@ -15,25 +11,31 @@ const MAX_UINT16 = 65535;
15
11
  * @param props Credit account balances, quotas, prices, thresholds, and debt context.
16
12
  * @returns Health factor as a number in `PERCENTAGE_FACTOR` scale,
17
13
  * or `65535` when debt is zero.
14
+ *
15
+ * @deprecated Use `calcHealthFactor` from `sdk/positions` instead; this
16
+ * wrapper only maps the legacy props onto an `AccountSnapshot`.
18
17
  */
19
18
  function calcHealthFactor({ assets, quotas, quotasInfo, liquidationThresholds, underlyingToken, debt, prices, tokensList }) {
20
- if (debt === 0n) return MAX_UINT16;
21
- const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
22
- const underlyingPrice = prices[underlyingToken] || 0n;
23
- const assetMoney = assets.reduce((acc, { token: tokenAddress, balance: amount }) => {
24
- const tokenDecimals = tokensList[tokenAddress]?.decimals || 18;
25
- const lt = liquidationThresholds[tokenAddress] || 0n;
26
- const price = prices[tokenAddress] || 0n;
27
- const tokenLtMoney = require_common_utils_utils_price_math.PriceUtils.calcTotalPrice(price, amount, tokenDecimals) * lt / require_sdk_constants_math.PERCENTAGE_FACTOR;
28
- const { isActive = false } = quotasInfo?.[tokenAddress] || {};
29
- const quota = quotas[tokenAddress];
30
- const quotaBalance = isActive ? quota?.balance || 0n : 0n;
31
- const quotaMoney = require_common_utils_utils_price_math.PriceUtils.calcTotalPrice(underlyingPrice, quotaBalance, underlyingDecimals);
32
- return acc + (quota ? require_sdk_utils_bigint_math.BigIntMath.min(quotaMoney, tokenLtMoney) : tokenLtMoney);
33
- }, 0n);
34
- const borrowedMoney = require_common_utils_utils_price_math.PriceUtils.calcTotalPrice(underlyingPrice || require_sdk_constants_math.PRICE_DECIMALS, debt, underlyingDecimals);
35
- const hfInPercent = borrowedMoney > 0n ? assetMoney * require_sdk_constants_math.PERCENTAGE_FACTOR / borrowedMoney : 0n;
36
- return Number(hfInPercent);
19
+ const decimals = {};
20
+ for (const [token, meta] of Object.entries(tokensList)) decimals[token] = meta.decimals;
21
+ const lts = {};
22
+ for (const [token, lt] of Object.entries(liquidationThresholds)) lts[token] = Number(lt);
23
+ const activeQuotas = {};
24
+ for (const [token, info] of Object.entries(quotasInfo)) if (info?.isActive) activeQuotas[token] = true;
25
+ return require_sdk_positions_calcHealthFactor.calcHealthFactor({
26
+ snapshot: {
27
+ creditManager: underlyingToken,
28
+ assets,
29
+ quotas: Object.values(quotas),
30
+ totalDebt: debt,
31
+ totalValue: 0n
32
+ },
33
+ underlying: underlyingToken,
34
+ decimals,
35
+ prices,
36
+ liquidationThresholds: lts,
37
+ activeQuotas
38
+ });
37
39
  }
38
40
  //#endregion
39
41
  exports.calcHealthFactor = calcHealthFactor;
@@ -9,6 +9,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
9
9
  *
10
10
  * @param props Quota balances and per-token quota rates.
11
11
  * @returns Sum of `balance * rate` terms in percentage-factor scale.
12
+ *
13
+ * @deprecated Use `calcBorrowRate` from `sdk/positions` instead.
12
14
  */
13
15
  function calcQuotaBorrowRate({ quotas, quotaRates }) {
14
16
  return Object.values(quotas).reduce((acc, { token, balance }) => {
@@ -1,6 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_sdk_constants_math = require("../../../sdk/constants/math.js");
3
- require("../../../sdk/index.js");
2
+ const require_sdk_positions_calcTimeToLiquidationMs = require("../../../sdk/positions/calcTimeToLiquidationMs.js");
4
3
  //#region src/common-utils/utils/creditAccount/get-time-to-liquidation.ts
5
4
  /**
6
5
  * Estimates time remaining until health factor reaches liquidation level.
@@ -12,10 +11,12 @@ require("../../../sdk/index.js");
12
11
  * @param props Current health factor and `totalBorrowRate * debt` term.
13
12
  * @returns Milliseconds to liquidation as `bigint`, or `null` when already at/under
14
13
  * liquidation threshold or when borrow-rate exposure is zero.
14
+ *
15
+ * @deprecated Use `calcTimeToLiquidationMs` from `sdk/positions` instead;
16
+ * this wrapper only forwards to the new implementation.
15
17
  */
16
18
  function getTimeToLiquidation({ healthFactor, totalBorrowRate_debt }) {
17
- if (healthFactor <= 10000n || totalBorrowRate_debt === 0n) return null;
18
- return (BigInt(healthFactor) - require_sdk_constants_math.PERCENTAGE_FACTOR) * (BigInt(require_sdk_constants_math.SECONDS_PER_YEAR) * require_sdk_constants_math.PERCENTAGE_FACTOR * require_sdk_constants_math.PERCENTAGE_DECIMALS / totalBorrowRate_debt) * 1000n / require_sdk_constants_math.PERCENTAGE_FACTOR;
19
+ return require_sdk_positions_calcTimeToLiquidationMs.calcTimeToLiquidationMs(healthFactor, totalBorrowRate_debt);
19
20
  }
20
21
  //#endregion
21
22
  exports.getTimeToLiquidation = getTimeToLiquidation;
@@ -1,6 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_sdk_constants_math = require("../../../sdk/constants/math.js");
3
- require("../../../sdk/index.js");
2
+ const require_sdk_positions_calcLiquidationPriceForTarget = require("../../../sdk/positions/calcLiquidationPriceForTarget.js");
4
3
  //#region src/common-utils/utils/creditAccount/liquidation-price.ts
5
4
  /**
6
5
  * Calculates target token liquidation price for a credit account.
@@ -13,17 +12,28 @@ require("../../../sdk/index.js");
13
12
  * @param props Debt context, assets, thresholds, and token metadata.
14
13
  * @returns Target token price in `PRICE_DECIMALS` precision that corresponds
15
14
  * to liquidation boundary; returns `0n` when target balance or LT is non-positive.
15
+ *
16
+ * @deprecated Use `calcLiquidationPriceForTarget` from `sdk/positions`
17
+ * instead; this wrapper only maps the legacy props onto an `AccountSnapshot`.
16
18
  */
17
19
  function liquidationPrice({ liquidationThresholds, debt, underlyingToken, targetToken, assets, tokensList }) {
18
- const underlyingDecimals = tokensList[underlyingToken]?.decimals || 18;
19
- const { balance: underlyingBalance = 0n } = assets[underlyingToken] || {};
20
- const effectiveDebt = (debt - underlyingBalance * (liquidationThresholds[underlyingToken] || 0n) / require_sdk_constants_math.PERCENTAGE_FACTOR) * require_sdk_constants_math.WAD / 10n ** BigInt(underlyingDecimals);
21
- const targetDecimals = tokensList[targetToken]?.decimals || 18;
22
- const { balance: targetBalance = 0n } = assets[targetToken] || {};
23
- const effectiveTargetBalance = targetBalance * require_sdk_constants_math.WAD / 10n ** BigInt(targetDecimals);
24
- const lpLT = liquidationThresholds[targetToken] || 0n;
25
- if (targetBalance <= 0n || lpLT <= 0n) return 0n;
26
- return effectiveDebt * require_sdk_constants_math.PRICE_DECIMALS * require_sdk_constants_math.PERCENTAGE_FACTOR / (effectiveTargetBalance * lpLT);
20
+ const decimals = {};
21
+ for (const [token, meta] of Object.entries(tokensList)) decimals[token] = meta.decimals;
22
+ const lts = {};
23
+ for (const [token, lt] of Object.entries(liquidationThresholds)) lts[token] = Number(lt);
24
+ return require_sdk_positions_calcLiquidationPriceForTarget.calcLiquidationPriceForTarget({
25
+ snapshot: {
26
+ creditManager: underlyingToken,
27
+ assets: Object.values(assets),
28
+ quotas: [],
29
+ totalDebt: debt,
30
+ totalValue: 0n
31
+ },
32
+ targetToken,
33
+ underlying: underlyingToken,
34
+ decimals,
35
+ liquidationThresholds: lts
36
+ });
27
37
  }
28
38
  //#endregion
29
39
  exports.liquidationPrice = liquidationPrice;
@@ -24,6 +24,7 @@ exports.amountSchema = require_model_primitives_schema.amountSchema;
24
24
  exports.apyBreakdownSchema = require_model_opportunities_schema.apyBreakdownSchema;
25
25
  exports.assetTypeSchema = require_model_primitives_schema.assetTypeSchema;
26
26
  exports.booleanParamSchema = require_model_filters_schema.booleanParamSchema;
27
+ exports.borrowRateBreakdownSchema = require_model_positions_schema.borrowRateBreakdownSchema;
27
28
  exports.bpsSchema = require_model_primitives_schema.bpsSchema;
28
29
  exports.chainFailedSchema = require_model_response_schema.chainFailedSchema;
29
30
  exports.chainIdSchema = require_model_primitives_schema.chainIdSchema;
@@ -73,6 +73,15 @@ const poolPositionSchema = zod_v4.z.object({
73
73
  pnl: pnlBreakdownSchema.optional()
74
74
  });
75
75
  /**
76
+ * {@link BorrowRateBreakdown}
77
+ **/
78
+ const borrowRateBreakdownSchema = zod_v4.z.object({
79
+ total: require_model_primitives_schema.bpsSchema,
80
+ totalOnDebt: require_model_primitives_schema.bpsSchema,
81
+ base: require_model_primitives_schema.bpsSchema,
82
+ quotas: zod_v4.z.record(require_sdk_utils_zod.ZodAddress(), require_model_primitives_schema.bpsSchema)
83
+ });
84
+ /**
76
85
  * {@link StrategyPosition}
77
86
  **/
78
87
  const strategyPositionSchema = zod_v4.z.object({
@@ -88,6 +97,9 @@ const strategyPositionSchema = zod_v4.z.object({
88
97
  totalDebt: require_model_primitives_schema.tokenAmountSchema,
89
98
  totalValue: require_model_primitives_schema.tokenAmountSchema,
90
99
  healthFactor: require_model_primitives_schema.bpsSchema,
100
+ borrowRate: borrowRateBreakdownSchema.optional(),
101
+ timeToLiquidation: require_sdk_utils_zod.ZodBigInt().nullable().optional(),
102
+ liquidationPrice: require_sdk_utils_zod.ZodBigInt().nullable().optional(),
91
103
  pnl: pnlBreakdownSchema.optional(),
92
104
  collaterals: zod_v4.z.array(positionCollateralSchema)
93
105
  });
@@ -163,6 +175,7 @@ const positionKeySchema = zod_v4.z.discriminatedUnion("kind", [zod_v4.z.object({
163
175
  ...strategyPositionKeySchema.shape
164
176
  })]);
165
177
  //#endregion
178
+ exports.borrowRateBreakdownSchema = borrowRateBreakdownSchema;
166
179
  exports.pnlBreakdownSchema = pnlBreakdownSchema;
167
180
  exports.pointsProgramPnLSchema = pointsProgramPnLSchema;
168
181
  exports.pointsRewardsPnLSchema = pointsRewardsPnLSchema;
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_sdk_utils_AssetsMap = require("../../sdk/utils/AssetsMap.js");
3
- require("../../sdk/constants/math.js");
3
+ const require_sdk_constants_math = require("../../sdk/constants/math.js");
4
4
  require("../../sdk/index.js");
5
5
  let viem = require("viem");
6
6
  //#region src/preview/preview/CreditAccountState.ts
@@ -79,6 +79,19 @@ var CreditAccountState = class CreditAccountState {
79
79
  totalDebt: ca.debt + ca.accruedInterest + ca.accruedFees
80
80
  });
81
81
  }
82
+ /**
83
+ * Immutable snapshot of this projected state for `sdk.positions` metric
84
+ * methods: dust-filtered balances, all quotas, and {@link totalDebt}.
85
+ **/
86
+ toSnapshot(totalValue) {
87
+ return {
88
+ creditManager: this.creditManager,
89
+ assets: this.balances.toAssets(require_sdk_constants_math.DUST_THRESHOLD),
90
+ quotas: this.quotas.toAssets(0n),
91
+ totalDebt: this.totalDebt,
92
+ totalValue
93
+ };
94
+ }
82
95
  clone() {
83
96
  return new CreditAccountState({
84
97
  creditAccount: this.creditAccount,
@@ -26,8 +26,10 @@ let viem = require("viem");
26
26
  * @param receivedToken - Token the `CLOSE_ACCOUNT` resume withdraws to the
27
27
  * user: the unwrapped underlying (vault asset) for RWA markets, the
28
28
  * underlying itself otherwise.
29
+ * @param sdk - Market data source for the position metrics of the resulting
30
+ * state; read synchronously, no network access.
29
31
  */
30
- function buildDelayedPreview(afterInstant, before, detected, convert, receivedToken) {
32
+ function buildDelayedPreview(afterInstant, before, detected, convert, receivedToken, sdk) {
31
33
  const { request, intent } = detected;
32
34
  const post = afterInstant.clone();
33
35
  const converter = makeSafeConverter(convert);
@@ -40,7 +42,7 @@ function buildDelayedPreview(afterInstant, before, detected, convert, receivedTo
40
42
  break;
41
43
  case "WITHDRAW_COLLATERAL": applyWithdrawCollateral(post, request, intent, converter, collateralWithdrawn);
42
44
  }
43
- return buildAdjustPreview(post, before, collateralWithdrawn, converter);
45
+ return buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk);
44
46
  }
45
47
  function makeSafeConverter(convert) {
46
48
  let error;
@@ -172,8 +174,11 @@ function buildClosePreview(post, converter, receivedToken) {
172
174
  error: converter.error
173
175
  };
174
176
  }
175
- function buildAdjustPreview(post, before, collateralWithdrawn, converter) {
177
+ function buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk) {
176
178
  const totalValue = totalValueInUnderlying(post, converter.convert, require_sdk_constants_math.DUST_THRESHOLD);
179
+ const assets = post.balances.toAssets(require_sdk_constants_math.DUST_THRESHOLD);
180
+ const quotas = post.quotas.toAssets(0n);
181
+ const snap = post.toSnapshot(totalValue);
177
182
  return {
178
183
  operation: "AdjustCreditAccount",
179
184
  creditManager: post.creditManager,
@@ -183,11 +188,16 @@ function buildAdjustPreview(post, before, collateralWithdrawn, converter) {
183
188
  totalValue,
184
189
  debt: post.debt,
185
190
  debtChange: post.debt - before.debt,
186
- quotas: post.quotas.toAssets(0n),
191
+ quotas,
187
192
  quotasChange: post.quotas.difference(before.quotas).toAssets(),
188
- assets: post.balances.toAssets(require_sdk_constants_math.DUST_THRESHOLD),
193
+ assets,
189
194
  assetsChange: post.balances.difference(before.balances).toAssets(require_sdk_constants_math.DUST_THRESHOLD),
190
- error: converter.error
195
+ error: converter.error,
196
+ healthFactor: sdk.positions.healthFactor(snap),
197
+ overallApy: 0,
198
+ borrowRate: sdk.positions.borrowRate(snap),
199
+ timeToLiquidation: sdk.positions.timeToLiquidation(snap),
200
+ liquidationPrice: sdk.positions.liquidationPrice(snap)
191
201
  };
192
202
  }
193
203
  //#endregion
@@ -22,6 +22,7 @@ async function previewAdjustCreditAccount(input, operation, options) {
22
22
  const { assets: collateralAdded, error: unwrapError } = require_preview_preview_unwrapNativeCollateral.unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(require_sdk_constants_address_provider.AP_WETH_TOKEN, 0));
23
23
  error ??= unwrapError;
24
24
  const assets = account.balances.toAssets(require_sdk_constants_math.DUST_THRESHOLD);
25
+ const quotas = account.quotas.toAssets(0n);
25
26
  const assetsChange = account.balances.difference(before.balances).toAssets(require_sdk_constants_math.DUST_THRESHOLD);
26
27
  const totalValue = assets.reduce((acc, { token, balance }) => {
27
28
  try {
@@ -34,6 +35,7 @@ async function previewAdjustCreditAccount(input, operation, options) {
34
35
  return acc;
35
36
  }
36
37
  }, 0n);
38
+ const snap = account.toSnapshot(totalValue);
37
39
  return {
38
40
  operation: "AdjustCreditAccount",
39
41
  creditManager: operation.creditManager,
@@ -43,11 +45,16 @@ async function previewAdjustCreditAccount(input, operation, options) {
43
45
  totalValue,
44
46
  debt: account.debt,
45
47
  debtChange: account.debt - before.debt,
46
- quotas: account.quotas.toAssets(0n),
48
+ quotas,
47
49
  quotasChange: account.quotas.difference(before.quotas).toAssets(),
48
50
  assets,
49
51
  assetsChange,
50
- error
52
+ error,
53
+ healthFactor: sdk.positions.healthFactor(snap),
54
+ overallApy: 0,
55
+ borrowRate: sdk.positions.borrowRate(snap),
56
+ timeToLiquidation: sdk.positions.timeToLiquidation(snap),
57
+ liquidationPrice: sdk.positions.liquidationPrice(snap)
51
58
  };
52
59
  }
53
60
  //#endregion
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_sdk_constants_address_provider = require("../../sdk/constants/address-provider.js");
3
+ const require_sdk_constants_math = require("../../sdk/constants/math.js");
3
4
  require("../../sdk/index.js");
4
5
  const require_preview_preview_types = require("./types.js");
5
6
  const require_preview_preview_CreditAccountState = require("./CreditAccountState.js");
@@ -26,7 +27,9 @@ async function previewOpenCreditAccount(input, operation) {
26
27
  });
27
28
  const { assets: collateral, error: unwrapError } = require_preview_preview_unwrapNativeCollateral.unwrapNativeCollateral(state.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(require_sdk_constants_address_provider.AP_WETH_TOKEN, 0));
28
29
  error ??= unwrapError ?? priceError;
29
- const assets = account.balances.toAssets(1n);
30
+ const assets = account.balances.toAssets(require_sdk_constants_math.DUST_THRESHOLD);
31
+ const quotas = account.quotas.toAssets(0n);
32
+ const snap = account.toSnapshot(collateralValue + account.totalDebt);
30
33
  return {
31
34
  operation: operation.operation,
32
35
  creditManager: operation.creditManager,
@@ -34,9 +37,14 @@ async function previewOpenCreditAccount(input, operation) {
34
37
  collateral,
35
38
  collateralValue,
36
39
  debt: account.debt,
37
- quotas: account.quotas.toAssets(0n),
40
+ quotas,
38
41
  assets,
39
- error
42
+ error,
43
+ healthFactor: sdk.positions.healthFactor(snap),
44
+ overallApy: 0,
45
+ borrowRate: sdk.positions.borrowRate(snap),
46
+ timeToLiquidation: sdk.positions.timeToLiquidation(snap),
47
+ liquidationPrice: sdk.positions.liquidationPrice(snap)
40
48
  };
41
49
  }
42
50
  /**
@@ -70,7 +70,7 @@ async function previewMulticallOperation(input, operation, options) {
70
70
  creditManager: operation.creditManager,
71
71
  intent: delayed.intent,
72
72
  instantPreview,
73
- delayedPreview: require_preview_preview_buildDelayedPreview.buildDelayedPreview(after.account, before, delayed, convert, receivedToken)
73
+ delayedPreview: require_preview_preview_buildDelayedPreview.buildDelayedPreview(after.account, before, delayed, convert, receivedToken, sdk)
74
74
  };
75
75
  }
76
76
  //#endregion
@@ -57,12 +57,6 @@ var CreditAccountsServiceV310 = class extends require_sdk_base_SDKConstruct.SDKC
57
57
  return this.#compressor.getBorrowerCreditAccounts(borrower, options, blockNumber);
58
58
  }
59
59
  /**
60
- * {@inheritDoc ICreditAccountsService.listPositions}
61
- **/
62
- async listPositions(props) {
63
- return this.#compressor.listPositions(props);
64
- }
65
- /**
66
60
  * {@inheritDoc ICreditAccountsService.getRewards}
67
61
  **/
68
62
  async getRewards(creditAccount) {
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_sdk_utils_AddressMap = require("../../utils/AddressMap.js");
3
2
  const require_sdk_utils_AddressSet = require("../../utils/AddressSet.js");
4
3
  const require_sdk_constants_address_provider = require("../../constants/address-provider.js");
5
4
  const require_sdk_constants_addresses = require("../../constants/addresses.js");
@@ -10,11 +9,8 @@ const require_sdk_utils_hex = require("../../utils/hex.js");
10
9
  require("../../utils/index.js");
11
10
  const require_sdk_base_SDKConstruct = require("../../base/SDKConstruct.js");
12
11
  require("../../base/index.js");
13
- const require_sdk_market_math = require("../../market/math.js");
14
- const require_sdk_market_credit_dominantCollateral = require("../../market/credit/dominantCollateral.js");
15
12
  const require_sdk_utils_viem_simulateWithPriceUpdates = require("../../utils/viem/simulateWithPriceUpdates.js");
16
13
  require("../../utils/viem/index.js");
17
- require("../../market/index.js");
18
14
  const require_abi_rwa_iRWAFactory = require("../../../abi/rwa/iRWAFactory.js");
19
15
  const require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310Contract = require("./CreditAccountCompressorV310Contract.js");
20
16
  //#region src/sdk/accounts/credit-account-compressor/CreditAccountCompressor.ts
@@ -22,9 +18,8 @@ const require_sdk_accounts_credit_account_compressor_CreditAccountCompressorV310
22
18
  * Reads credit accounts of the current chain.
23
19
  *
24
20
  * Stitches the credit account compressor together with the RWA factories (for
25
- * accounts owned via an investor EOA) and with the withdrawal compressor (for
26
- * assets that are on their way out of an account), and describes the result
27
- * either as raw account data or as {@link StrategyPosition}s.
21
+ * accounts owned via an investor EOA), and describes the result as raw
22
+ * account data.
28
23
  *
29
24
  * TODO: create and deploy new compressor contract onchain to avoid all this stitching
30
25
  **/
@@ -174,89 +169,6 @@ var CreditAccountCompressor = class extends require_sdk_base_SDKConstruct.SDKCon
174
169
  return filtered.sort((a, b) => Number(a.healthFactor - b.healthFactor));
175
170
  }
176
171
  /**
177
- * Describes all credit accounts of a wallet as strategy positions.
178
- *
179
- * @param props - {@link ListStrategyPositionsProps}
180
- **/
181
- async listPositions(props) {
182
- const { owner, includeZeroDebt, blockNumber } = props;
183
- const [accounts] = await Promise.all([this.getBorrowerCreditAccounts(owner, { includeZeroDebt }, blockNumber), this.sdk.withdrawalCompressor?.loadWithdrawableAssets(void 0, blockNumber)]);
184
- const describable = accounts.filter((ca) => {
185
- if (!ca.success) this.logger?.warn(`cannot describe position of ${this.labelAddress(ca.creditAccount)}: collateral computation failed`);
186
- return ca.success;
187
- });
188
- const withdrawals = await Promise.all(describable.map((ca) => this.#accountWithdrawals(ca, blockNumber)));
189
- return describable.map((ca, i) => this.#toStrategyPosition(ca, withdrawals[i] ?? new require_sdk_utils_AddressMap.AddressMap()));
190
- }
191
- /**
192
- * Builds one strategy position from an account snapshot.
193
- *
194
- * @param withdrawals - Delayed withdrawals of the account, keyed by the
195
- * phantom token that represents them on it.
196
- **/
197
- #toStrategyPosition(ca, withdrawals) {
198
- const suite = this.sdk.marketRegister.findCreditManager(ca.creditManager);
199
- const { market } = suite;
200
- const { priceOracle } = market;
201
- const { pool } = market.pool;
202
- const token = this.sdk.tokensMeta.mustGetToken(market.unwrappedUnderlying);
203
- const totalDebtValue = ca.debt + ca.accruedInterest + ca.accruedFees;
204
- const collateral = require_sdk_market_credit_dominantCollateral.dominantCollateral(ca, market);
205
- return {
206
- kind: "strategy",
207
- chainId: this.sdk.chainId,
208
- creditManager: ca.creditManager,
209
- creditAccount: ca.creditAccount,
210
- name: collateral ? suite.strategyName(collateral) : token.symbol,
211
- targetCollateral: collateral ? this.sdk.tokensMeta.mustGetToken(collateral) : null,
212
- leverage: require_sdk_market_math.positionLeverage(totalDebtValue, ca.totalValue),
213
- borrowApy: require_sdk_market_math.borrowApyBps(pool.baseInterestRate, suite.creditManager.feeInterest),
214
- totalDebt: {
215
- token,
216
- value: totalDebtValue,
217
- valueUsd: require_sdk_market_math.usdToNumber(ca.totalDebtUSD)
218
- },
219
- totalValue: {
220
- token,
221
- value: ca.totalValue,
222
- valueUsd: require_sdk_market_math.usdToNumber(ca.totalValueUSD)
223
- },
224
- healthFactor: require_sdk_market_math.healthFactorBps(ca.healthFactor),
225
- collaterals: ca.tokens.flatMap((t) => {
226
- if ((t.mask & ca.enabledTokensMask) === 0n || t.balance <= 10n) return [];
227
- return [{
228
- collateral: priceOracle.toTokenAmount(t.token, t.balance),
229
- quota: priceOracle.toTokenAmount(market.underlying, t.quota),
230
- withdrawals: withdrawals.get(t.token) ?? []
231
- }];
232
- })
233
- };
234
- }
235
- /**
236
- * Delayed withdrawals of one account, keyed by the phantom token that
237
- * represents them on it, so that each collateral row can pick up its own.
238
- **/
239
- async #accountWithdrawals(ca, blockNumber) {
240
- const compressor = this.sdk.withdrawalCompressor;
241
- const byPhantomToken = new require_sdk_utils_AddressMap.AddressMap(void 0, "accountWithdrawals");
242
- const holdsPhantomToken = ca.tokens.some((t) => t.balance > 10n && compressor?.getWithdrawalSourceToken(t.token) !== void 0);
243
- if (!compressor || !holdsPhantomToken) return byPhantomToken;
244
- const { priceOracle } = this.sdk.marketRegister.findByCreditManager(ca.creditManager);
245
- const { claimable, pending } = await compressor.getCurrentWithdrawals(ca.creditAccount, blockNumber);
246
- const add = (w, outputs, claimableAt) => {
247
- const assets = outputs.map((o) => ({
248
- isDelayed: true,
249
- ...priceOracle.toTokenAmount(o.token, o.amount),
250
- redeemer: w.redeemer,
251
- claimableAt: claimableAt === void 0 ? void 0 : Number(claimableAt)
252
- }));
253
- byPhantomToken.upsert(w.withdrawalPhantomToken, [...byPhantomToken.get(w.withdrawalPhantomToken) ?? [], ...assets]);
254
- };
255
- for (const w of claimable) add(w, w.outputs);
256
- for (const w of pending) add(w, w.expectedOutputs, w.claimableAt);
257
- return byPhantomToken;
258
- }
259
- /**
260
172
  * Credit account compressor contract of the current chain.
261
173
  *
262
174
  * Resolved on every access, because the address provider is only populated
@@ -84,11 +84,37 @@ function buildMockSdk(args) {
84
84
  quotaIncreaseFee: 0n,
85
85
  ...q
86
86
  })) };
87
- const liquidationThresholds = { entries: () => Object.entries(args.liquidationThresholds) };
87
+ const quotaOf = (token) => args.quotas[token.toLowerCase()] ?? args.quotas[token];
88
+ const liquidationThresholds = {
89
+ entries: () => Object.entries(args.liquidationThresholds),
90
+ get: (token) => args.liquidationThresholds[token.toLowerCase()] ?? args.liquidationThresholds[token]
91
+ };
88
92
  const market = {
89
- priceOracle: { convert },
93
+ priceOracle: {
94
+ convert,
95
+ convertToUSD: (token, amount) => {
96
+ const from = token.toLowerCase();
97
+ const price = args.prices[from] ?? args.prices[token];
98
+ if (price === void 0) throw new Error(`mock priceOracle: missing price for ${from}`);
99
+ return amount * price / 10n ** BigInt(decimalsOf(from));
100
+ },
101
+ safeConvertToUSD: (token, amount) => {
102
+ const from = token.toLowerCase();
103
+ const price = args.prices[from] ?? args.prices[token];
104
+ if (price === void 0) return null;
105
+ return amount * price / 10n ** BigInt(decimalsOf(from));
106
+ }
107
+ },
90
108
  pool: {
91
- pqk: { quotas },
109
+ pqk: {
110
+ quotas,
111
+ quotaRate: (token) => Number(quotaOf(token)?.rate ?? 0n),
112
+ hasActiveQuota: (token) => {
113
+ const q = quotaOf(token);
114
+ return !!q?.isActive && q.limit > 0n;
115
+ }
116
+ },
117
+ pool: { baseInterestRate: args.baseInterestRate ?? 0n },
92
118
  underlying: args.underlying
93
119
  }
94
120
  };
@@ -96,7 +122,8 @@ function buildMockSdk(args) {
96
122
  creditManager: {
97
123
  address: args.creditManager,
98
124
  liquidationThresholds,
99
- collateralTokens: []
125
+ collateralTokens: [],
126
+ feeInterest: args.feeInterest ?? 0
100
127
  },
101
128
  creditFacade: {
102
129
  address: args.creditFacade,
@@ -0,0 +1,18 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/sdk/accounts/intents/utils/adjust-state-to-snapshot.ts
3
+ /**
4
+ * Maps an intents {@link AdjustState} onto the {@link AccountSnapshot} that
5
+ * position-metric functions take. `accountDebt` is treated as total debt
6
+ * (principal plus accrued interest and fees).
7
+ **/
8
+ function adjustStateToSnapshot(creditManager, state) {
9
+ return {
10
+ creditManager,
11
+ assets: state.assets,
12
+ quotas: Object.values(state.quotas),
13
+ totalDebt: state.accountDebt,
14
+ totalValue: state.totalValue
15
+ };
16
+ }
17
+ //#endregion
18
+ exports.adjustStateToSnapshot = adjustStateToSnapshot;
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_accounts_intents_utils_adjust_state_to_snapshot = require("./adjust-state-to-snapshot.js");
2
3
  const require_sdk_accounts_intents_utils_assemble_operation_calls = require("./assemble-operation-calls.js");
3
4
  const require_sdk_accounts_intents_utils_borrowed_amount_plus_interest_and_fees = require("./borrowed-amount-plus-interest-and-fees.js");
4
5
  const require_sdk_accounts_intents_utils_common = require("./common.js");
@@ -7,6 +8,7 @@ const require_sdk_accounts_intents_utils_quotas_for_update = require("./quotas-f
7
8
  const require_sdk_accounts_intents_utils_simulate_assets = require("./simulate-assets.js");
8
9
  const require_sdk_accounts_intents_utils_simulate_adjust_state = require("./simulate-adjust-state.js");
9
10
  const require_sdk_accounts_intents_utils_with_quota_update = require("./with-quota-update.js");
11
+ exports.adjustStateToSnapshot = require_sdk_accounts_intents_utils_adjust_state_to_snapshot.adjustStateToSnapshot;
10
12
  exports.assembleOperationCalls = require_sdk_accounts_intents_utils_assemble_operation_calls.assembleOperationCalls;
11
13
  exports.calcBorrowedAmountPlusInterestAndFees = require_sdk_accounts_intents_utils_borrowed_amount_plus_interest_and_fees.calcBorrowedAmountPlusInterestAndFees;
12
14
  exports.convertAmount = require_sdk_accounts_intents_utils_convert_amount.convertAmount;
@@ -33,7 +33,6 @@ var LiquidationsService = class extends require_sdk_base_SDKConstruct.SDKConstru
33
33
  * Accounts whose collateral computation failed are excluded.
34
34
  **/
35
35
  async getLiquidatableAccounts(props) {
36
- await this.sdk.withdrawalCompressor?.loadWithdrawableAssets(void 0, props?.blockNumber);
37
36
  const unhealthy = await this.sdk.accounts.getCreditAccounts({
38
37
  maxHealthFactor: require_sdk_constants_math.WAD - 1n,
39
38
  includeZeroDebt: false
@@ -60,7 +59,6 @@ var LiquidationsService = class extends require_sdk_base_SDKConstruct.SDKConstru
60
59
  const ca = await this.#getCreditAccountData(creditAccount, blockNumber);
61
60
  const suite = this.sdk.marketRegister.findCreditManager(ca.creditManager);
62
61
  const { priceOracle } = suite.market;
63
- await this.sdk.withdrawalCompressor?.loadWithdrawableAssets(void 0, blockNumber);
64
62
  const account = this.#buildAccount(ca, suite);
65
63
  const data = await this.#getLiquidationData(ca, liquidator, ignoreReservePrices, blockNumber);
66
64
  return {
@@ -97,7 +95,6 @@ var LiquidationsService = class extends require_sdk_base_SDKConstruct.SDKConstru
97
95
  async getLiquidationPositions(props) {
98
96
  const compressor = this.sdk.withdrawalCompressor;
99
97
  if (!compressor) return [];
100
- await compressor.loadWithdrawableAssets(void 0, props.blockNumber);
101
98
  const phantomTokens = new require_sdk_utils_AddressSet.AddressSet(compressor.getWithdrawableAssets().map((a) => a.withdrawalPhantomToken));
102
99
  const { claimable, pending } = await compressor.getExternalAccountCurrentWithdrawals({
103
100
  account: props.liquidator,