@gearbox-protocol/sdk 15.1.0-next.6 → 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 (106) 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 +12 -0
  20. package/dist/cjs/sdk/market/oracle/PriceOracleBaseContract.js +10 -3
  21. package/dist/cjs/sdk/positions/PositionsService.js +206 -1
  22. package/dist/cjs/sdk/positions/calcBorrowRate.js +43 -0
  23. package/dist/cjs/sdk/positions/calcHealthFactor.js +44 -0
  24. package/dist/cjs/sdk/positions/calcLiquidationPrice.js +23 -0
  25. package/dist/cjs/sdk/positions/calcLiquidationPriceForTarget.js +30 -0
  26. package/dist/cjs/sdk/positions/calcTimeToLiquidationMs.js +18 -0
  27. package/dist/cjs/sdk/positions/index.js +12 -1
  28. package/dist/cjs/sdk/positions/types.js +31 -0
  29. package/dist/esm/common-utils/utils/apy/get-single-quota-borrow-rate.js +2 -0
  30. package/dist/esm/common-utils/utils/creditAccount/calc-health-factor.js +24 -22
  31. package/dist/esm/common-utils/utils/creditAccount/calc-quota-borrow-rate.js +2 -0
  32. package/dist/esm/common-utils/utils/creditAccount/get-time-to-liquidation.js +5 -4
  33. package/dist/esm/common-utils/utils/creditAccount/liquidation-price.js +21 -11
  34. package/dist/esm/dev/AccountOpener.js +1 -1
  35. package/dist/esm/dev/withdrawalUtils.js +1 -1
  36. package/dist/esm/model/index.js +2 -2
  37. package/dist/esm/model/positions.schema.js +14 -2
  38. package/dist/esm/plugins/adapters/contracts/ERC4626AdapterContract.js +1 -1
  39. package/dist/esm/preview/preview/CreditAccountState.js +14 -1
  40. package/dist/esm/preview/preview/buildDelayedPreview.js +16 -6
  41. package/dist/esm/preview/preview/previewAdjustCreditAccount.js +9 -2
  42. package/dist/esm/preview/preview/previewOpenCreditAccount.js +11 -3
  43. package/dist/esm/preview/preview/previewOperation.js +1 -1
  44. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  45. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  46. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +2 -8
  47. package/dist/esm/sdk/accounts/credit-account-compressor/CreditAccountCompressor.js +2 -90
  48. package/dist/esm/sdk/accounts/intents/testing/sdk-mock.js +31 -4
  49. package/dist/esm/sdk/accounts/intents/utils/adjust-state-to-snapshot.js +17 -0
  50. package/dist/esm/sdk/accounts/intents/utils/index.js +2 -1
  51. package/dist/esm/sdk/accounts/liquidations/LiquidationsService.js +1 -4
  52. package/dist/esm/sdk/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  53. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  54. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  55. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  56. package/dist/esm/sdk/base/TokensMeta.js +3 -3
  57. package/dist/esm/sdk/chain/detectNetwork.js +1 -1
  58. package/dist/esm/sdk/core/createAddressProvider.js +1 -1
  59. package/dist/esm/sdk/index.js +7 -1
  60. package/dist/esm/sdk/market/credit/CreditFacadeV310BaseContract.js +1 -1
  61. package/dist/esm/sdk/market/oracle/PriceOracleBaseContract.js +10 -3
  62. package/dist/esm/sdk/market/pool/PoolV310Contract.js +1 -1
  63. package/dist/esm/sdk/market/zapper/IETHZapperContract.js +1 -1
  64. package/dist/esm/sdk/market/zapper/ZapperContract.js +1 -1
  65. package/dist/esm/sdk/pools/PoolService.js +1 -1
  66. package/dist/esm/sdk/positions/PositionsService.js +206 -1
  67. package/dist/esm/sdk/positions/calcBorrowRate.js +42 -0
  68. package/dist/esm/sdk/positions/calcHealthFactor.js +43 -0
  69. package/dist/esm/sdk/positions/calcLiquidationPrice.js +22 -0
  70. package/dist/esm/sdk/positions/calcLiquidationPriceForTarget.js +29 -0
  71. package/dist/esm/sdk/positions/calcTimeToLiquidationMs.js +17 -0
  72. package/dist/esm/sdk/positions/index.js +7 -2
  73. package/dist/esm/sdk/positions/types.js +31 -1
  74. package/dist/esm/sdk/utils/viem/simulateWithPriceUpdates.js +1 -1
  75. package/dist/types/common-utils/utils/apy/get-single-quota-borrow-rate.d.ts +2 -0
  76. package/dist/types/common-utils/utils/creditAccount/calc-health-factor.d.ts +3 -0
  77. package/dist/types/common-utils/utils/creditAccount/calc-quota-borrow-rate.d.ts +2 -0
  78. package/dist/types/common-utils/utils/creditAccount/get-time-to-liquidation.d.ts +3 -0
  79. package/dist/types/common-utils/utils/creditAccount/liquidation-price.d.ts +3 -0
  80. package/dist/types/model/index.d.ts +3 -3
  81. package/dist/types/model/positions.d.ts +84 -1
  82. package/dist/types/model/positions.schema.d.ts +26 -1
  83. package/dist/types/preview/preview/CreditAccountState.d.ts +6 -0
  84. package/dist/types/preview/preview/buildDelayedPreview.d.ts +5 -1
  85. package/dist/types/preview/preview/types.d.ts +4 -2
  86. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +1 -7
  87. package/dist/types/sdk/accounts/credit-account-compressor/CreditAccountCompressor.d.ts +3 -12
  88. package/dist/types/sdk/accounts/credit-account-compressor/index.d.ts +2 -2
  89. package/dist/types/sdk/accounts/credit-account-compressor/types.d.ts +1 -19
  90. package/dist/types/sdk/accounts/index.d.ts +2 -2
  91. package/dist/types/sdk/accounts/intents/testing/sdk-mock.d.ts +6 -0
  92. package/dist/types/sdk/accounts/intents/utils/adjust-state-to-snapshot.d.ts +13 -0
  93. package/dist/types/sdk/accounts/intents/utils/index.d.ts +2 -1
  94. package/dist/types/sdk/accounts/types.d.ts +1 -12
  95. package/dist/types/sdk/index.d.ts +8 -3
  96. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +4 -0
  97. package/dist/types/sdk/market/oracle/types.d.ts +8 -0
  98. package/dist/types/sdk/positions/PositionsService.d.ts +31 -2
  99. package/dist/types/sdk/positions/calcBorrowRate.d.ts +40 -0
  100. package/dist/types/sdk/positions/calcHealthFactor.d.ts +45 -0
  101. package/dist/types/sdk/positions/calcLiquidationPrice.d.ts +12 -0
  102. package/dist/types/sdk/positions/calcLiquidationPriceForTarget.d.ts +43 -0
  103. package/dist/types/sdk/positions/calcTimeToLiquidationMs.d.ts +15 -0
  104. package/dist/types/sdk/positions/index.d.ts +7 -2
  105. package/dist/types/sdk/positions/types.d.ts +58 -1
  106. package/package.json +1 -1
@@ -6,7 +6,7 @@ import { POOL_HISTORY_METRICS, POOL_POSITION_HISTORY_METRICS, STRATEGY_HISTORY_M
6
6
  import { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema } from "./primitives.schema.js";
7
7
  import { apyBreakdownSchema, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pointRewardsSchema, pointsProgramSchema, poolOpportunityDetailSchema, poolOpportunityKeySchema, poolOpportunitySchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, rewardsSchema, strategyOpportunityDetailSchema, strategyOpportunityKeySchema, strategyOpportunitySchema, tokenRewardsSchema } from "./opportunities.schema.js";
8
8
  import { delayedReceivedAssetSchema, instantReceivedAssetSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionSchema, receivedAssetSchema } from "./liquidations.schema.js";
9
- import { pnlBreakdownSchema, pointsProgramPnLSchema, pointsRewardsPnLSchema, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionKeySchema, positionKindSchema, positionSchema, rewardsPnLSchema, strategyPositionKeySchema, strategyPositionSchema, tokenRewardsPnLSchema } from "./positions.schema.js";
9
+ import { borrowRateBreakdownSchema, pnlBreakdownSchema, pointsProgramPnLSchema, pointsRewardsPnLSchema, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionKeySchema, positionKindSchema, positionSchema, rewardsPnLSchema, strategyPositionKeySchema, strategyPositionSchema, tokenRewardsPnLSchema } from "./positions.schema.js";
10
10
  import { historyChartMetadataSchema, historyMetricSchema, historyPointSchema, historyRangeSchema, historySeriesSchema, opportunityHistoryQuerySchema, poolHistoryMetricSchema, poolPositionHistoryMetricSchema, positionHistoryMetricSchema, positionHistoryQuerySchema, strategyHistoryMetricSchema, strategyPositionHistoryMetricSchema } from "./history.schema.js";
11
11
  import { matchesLiquidatableAccountFilter } from "./liquidations.js";
12
12
  import { matchesOpportunityFilter, opportunityId, poolOpportunityId, strategyOpportunityId } from "./opportunities.js";
@@ -14,4 +14,4 @@ import { liquidationPositionId, matchesPositionFilter, poolPositionId, positionI
14
14
  import "./primitives.js";
15
15
  import "./response.js";
16
16
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
17
- export { FILTER_ALL, POOL_HISTORY_METRICS, POOL_POSITION_HISTORY_METRICS, STRATEGY_HISTORY_METRICS, STRATEGY_POSITION_HISTORY_METRICS, amountSchema, apyBreakdownSchema, assetTypeSchema, booleanParamSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, historyChartMetadataSchema, historyMetricSchema, historyPointSchema, historyRangeSchema, historySeriesSchema, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityHistoryQuerySchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolHistoryMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionHistoryMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionHistoryMetricSchema, positionHistoryQuerySchema, positionId, positionKeySchema, positionKindSchema, positionSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyHistoryMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionHistoryMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, txCallSchema };
17
+ export { FILTER_ALL, POOL_HISTORY_METRICS, POOL_POSITION_HISTORY_METRICS, STRATEGY_HISTORY_METRICS, STRATEGY_POSITION_HISTORY_METRICS, amountSchema, apyBreakdownSchema, assetTypeSchema, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, historyChartMetadataSchema, historyMetricSchema, historyPointSchema, historyRangeSchema, historySeriesSchema, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityHistoryQuerySchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolHistoryMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionHistoryMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionHistoryMetricSchema, positionHistoryQuerySchema, positionId, positionKeySchema, positionKindSchema, positionSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyHistoryMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionHistoryMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, txCallSchema };
@@ -1,4 +1,4 @@
1
- import { ZodAddress } from "../sdk/utils/zod.js";
1
+ import { ZodAddress, ZodBigInt } from "../sdk/utils/zod.js";
2
2
  import { isFilterSet } from "./filters.js";
3
3
  import { booleanParamSchema, encodeFlag, filterable } from "./filters.schema.js";
4
4
  import { assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, tokenAmountSchema, tokenSchema } from "./primitives.schema.js";
@@ -72,6 +72,15 @@ const poolPositionSchema = z.object({
72
72
  pnl: pnlBreakdownSchema.optional()
73
73
  });
74
74
  /**
75
+ * {@link BorrowRateBreakdown}
76
+ **/
77
+ const borrowRateBreakdownSchema = z.object({
78
+ total: bpsSchema,
79
+ totalOnDebt: bpsSchema,
80
+ base: bpsSchema,
81
+ quotas: z.record(ZodAddress(), bpsSchema)
82
+ });
83
+ /**
75
84
  * {@link StrategyPosition}
76
85
  **/
77
86
  const strategyPositionSchema = z.object({
@@ -87,6 +96,9 @@ const strategyPositionSchema = z.object({
87
96
  totalDebt: tokenAmountSchema,
88
97
  totalValue: tokenAmountSchema,
89
98
  healthFactor: bpsSchema,
99
+ borrowRate: borrowRateBreakdownSchema.optional(),
100
+ timeToLiquidation: ZodBigInt().nullable().optional(),
101
+ liquidationPrice: ZodBigInt().nullable().optional(),
90
102
  pnl: pnlBreakdownSchema.optional(),
91
103
  collaterals: z.array(positionCollateralSchema)
92
104
  });
@@ -162,4 +174,4 @@ const positionKeySchema = z.discriminatedUnion("kind", [z.object({
162
174
  ...strategyPositionKeySchema.shape
163
175
  })]);
164
176
  //#endregion
165
- export { pnlBreakdownSchema, pointsProgramPnLSchema, pointsRewardsPnLSchema, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionKeySchema, positionKindSchema, positionSchema, rewardsPnLSchema, strategyPositionKeySchema, strategyPositionSchema, tokenRewardsPnLSchema };
177
+ export { borrowRateBreakdownSchema, pnlBreakdownSchema, pointsProgramPnLSchema, pointsRewardsPnLSchema, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionKeySchema, positionKindSchema, positionSchema, rewardsPnLSchema, strategyPositionKeySchema, strategyPositionSchema, tokenRewardsPnLSchema };
@@ -1,5 +1,5 @@
1
- import { ierc4626AdapterAbi } from "../../../abi/ierc4626Adapter.js";
2
1
  import { MissingSerializedParamsError } from "../../../sdk/base/errors.js";
2
+ import { ierc4626AdapterAbi } from "../../../abi/ierc4626Adapter.js";
3
3
  import "../../../sdk/index.js";
4
4
  import { fnSigToName, swapFromTransfers } from "../transferHelpers.js";
5
5
  import { AbstractAdapterContract } from "./AbstractAdapter.js";
@@ -1,5 +1,5 @@
1
1
  import { AssetsMap } from "../../sdk/utils/AssetsMap.js";
2
- import "../../sdk/constants/math.js";
2
+ import { DUST_THRESHOLD } from "../../sdk/constants/math.js";
3
3
  import "../../sdk/index.js";
4
4
  import { zeroAddress } from "viem";
5
5
  //#region src/preview/preview/CreditAccountState.ts
@@ -78,6 +78,19 @@ var CreditAccountState = class CreditAccountState {
78
78
  totalDebt: ca.debt + ca.accruedInterest + ca.accruedFees
79
79
  });
80
80
  }
81
+ /**
82
+ * Immutable snapshot of this projected state for `sdk.positions` metric
83
+ * methods: dust-filtered balances, all quotas, and {@link totalDebt}.
84
+ **/
85
+ toSnapshot(totalValue) {
86
+ return {
87
+ creditManager: this.creditManager,
88
+ assets: this.balances.toAssets(DUST_THRESHOLD),
89
+ quotas: this.quotas.toAssets(0n),
90
+ totalDebt: this.totalDebt,
91
+ totalValue
92
+ };
93
+ }
81
94
  clone() {
82
95
  return new CreditAccountState({
83
96
  creditAccount: this.creditAccount,
@@ -25,8 +25,10 @@ import { isAddressEqual } from "viem";
25
25
  * @param receivedToken - Token the `CLOSE_ACCOUNT` resume withdraws to the
26
26
  * user: the unwrapped underlying (vault asset) for RWA markets, the
27
27
  * underlying itself otherwise.
28
+ * @param sdk - Market data source for the position metrics of the resulting
29
+ * state; read synchronously, no network access.
28
30
  */
29
- function buildDelayedPreview(afterInstant, before, detected, convert, receivedToken) {
31
+ function buildDelayedPreview(afterInstant, before, detected, convert, receivedToken, sdk) {
30
32
  const { request, intent } = detected;
31
33
  const post = afterInstant.clone();
32
34
  const converter = makeSafeConverter(convert);
@@ -39,7 +41,7 @@ function buildDelayedPreview(afterInstant, before, detected, convert, receivedTo
39
41
  break;
40
42
  case "WITHDRAW_COLLATERAL": applyWithdrawCollateral(post, request, intent, converter, collateralWithdrawn);
41
43
  }
42
- return buildAdjustPreview(post, before, collateralWithdrawn, converter);
44
+ return buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk);
43
45
  }
44
46
  function makeSafeConverter(convert) {
45
47
  let error;
@@ -171,8 +173,11 @@ function buildClosePreview(post, converter, receivedToken) {
171
173
  error: converter.error
172
174
  };
173
175
  }
174
- function buildAdjustPreview(post, before, collateralWithdrawn, converter) {
176
+ function buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk) {
175
177
  const totalValue = totalValueInUnderlying(post, converter.convert, DUST_THRESHOLD);
178
+ const assets = post.balances.toAssets(DUST_THRESHOLD);
179
+ const quotas = post.quotas.toAssets(0n);
180
+ const snap = post.toSnapshot(totalValue);
176
181
  return {
177
182
  operation: "AdjustCreditAccount",
178
183
  creditManager: post.creditManager,
@@ -182,11 +187,16 @@ function buildAdjustPreview(post, before, collateralWithdrawn, converter) {
182
187
  totalValue,
183
188
  debt: post.debt,
184
189
  debtChange: post.debt - before.debt,
185
- quotas: post.quotas.toAssets(0n),
190
+ quotas,
186
191
  quotasChange: post.quotas.difference(before.quotas).toAssets(),
187
- assets: post.balances.toAssets(DUST_THRESHOLD),
192
+ assets,
188
193
  assetsChange: post.balances.difference(before.balances).toAssets(DUST_THRESHOLD),
189
- error: converter.error
194
+ error: converter.error,
195
+ healthFactor: sdk.positions.healthFactor(snap),
196
+ overallApy: 0,
197
+ borrowRate: sdk.positions.borrowRate(snap),
198
+ timeToLiquidation: sdk.positions.timeToLiquidation(snap),
199
+ liquidationPrice: sdk.positions.liquidationPrice(snap)
190
200
  };
191
201
  }
192
202
  //#endregion
@@ -21,6 +21,7 @@ async function previewAdjustCreditAccount(input, operation, options) {
21
21
  const { assets: collateralAdded, error: unwrapError } = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
22
22
  error ??= unwrapError;
23
23
  const assets = account.balances.toAssets(DUST_THRESHOLD);
24
+ const quotas = account.quotas.toAssets(0n);
24
25
  const assetsChange = account.balances.difference(before.balances).toAssets(DUST_THRESHOLD);
25
26
  const totalValue = assets.reduce((acc, { token, balance }) => {
26
27
  try {
@@ -33,6 +34,7 @@ async function previewAdjustCreditAccount(input, operation, options) {
33
34
  return acc;
34
35
  }
35
36
  }, 0n);
37
+ const snap = account.toSnapshot(totalValue);
36
38
  return {
37
39
  operation: "AdjustCreditAccount",
38
40
  creditManager: operation.creditManager,
@@ -42,11 +44,16 @@ async function previewAdjustCreditAccount(input, operation, options) {
42
44
  totalValue,
43
45
  debt: account.debt,
44
46
  debtChange: account.debt - before.debt,
45
- quotas: account.quotas.toAssets(0n),
47
+ quotas,
46
48
  quotasChange: account.quotas.difference(before.quotas).toAssets(),
47
49
  assets,
48
50
  assetsChange,
49
- error
51
+ error,
52
+ healthFactor: sdk.positions.healthFactor(snap),
53
+ overallApy: 0,
54
+ borrowRate: sdk.positions.borrowRate(snap),
55
+ timeToLiquidation: sdk.positions.timeToLiquidation(snap),
56
+ liquidationPrice: sdk.positions.liquidationPrice(snap)
50
57
  };
51
58
  }
52
59
  //#endregion
@@ -1,4 +1,5 @@
1
1
  import { AP_WETH_TOKEN } from "../../sdk/constants/address-provider.js";
2
+ import { DUST_THRESHOLD } from "../../sdk/constants/math.js";
2
3
  import "../../sdk/index.js";
3
4
  import { ERROR_UNPRICEABLE_TOKEN } from "./types.js";
4
5
  import { CreditAccountState } from "./CreditAccountState.js";
@@ -25,7 +26,9 @@ async function previewOpenCreditAccount(input, operation) {
25
26
  });
26
27
  const { assets: collateral, error: unwrapError } = unwrapNativeCollateral(state.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
27
28
  error ??= unwrapError ?? priceError;
28
- const assets = account.balances.toAssets(1n);
29
+ const assets = account.balances.toAssets(DUST_THRESHOLD);
30
+ const quotas = account.quotas.toAssets(0n);
31
+ const snap = account.toSnapshot(collateralValue + account.totalDebt);
29
32
  return {
30
33
  operation: operation.operation,
31
34
  creditManager: operation.creditManager,
@@ -33,9 +36,14 @@ async function previewOpenCreditAccount(input, operation) {
33
36
  collateral,
34
37
  collateralValue,
35
38
  debt: account.debt,
36
- quotas: account.quotas.toAssets(0n),
39
+ quotas,
37
40
  assets,
38
- error
41
+ error,
42
+ healthFactor: sdk.positions.healthFactor(snap),
43
+ overallApy: 0,
44
+ borrowRate: sdk.positions.borrowRate(snap),
45
+ timeToLiquidation: sdk.positions.timeToLiquidation(snap),
46
+ liquidationPrice: sdk.positions.liquidationPrice(snap)
39
47
  };
40
48
  }
41
49
  /**
@@ -69,7 +69,7 @@ async function previewMulticallOperation(input, operation, options) {
69
69
  creditManager: operation.creditManager,
70
70
  intent: delayed.intent,
71
71
  instantPreview,
72
- delayedPreview: buildDelayedPreview(after.account, before, delayed, convert, receivedToken)
72
+ delayedPreview: buildDelayedPreview(after.account, before, delayed, convert, receivedToken, sdk)
73
73
  };
74
74
  }
75
75
  //#endregion
@@ -1,5 +1,5 @@
1
- import { iZapperAbi } from "../../abi/iZapper.js";
2
1
  import { iPoolV310Abi } from "../../abi/310/generated.js";
2
+ import { iZapperAbi } from "../../abi/iZapper.js";
3
3
  import { asPreviewSimulationError } from "./errors.js";
4
4
  //#region src/preview/simulate/simulatePoolOperation.ts
5
5
  function previewRead(operation) {
@@ -1,6 +1,6 @@
1
- import { ierc20Abi } from "../../abi/iERC20.js";
2
1
  import { iCreditFacadeV310Abi } from "../../abi/310/generated.js";
3
2
  import { AddressMap } from "../../sdk/utils/AddressMap.js";
3
+ import { ierc20Abi } from "../../abi/iERC20.js";
4
4
  import "../../sdk/index.js";
5
5
  import { UnexpectedFacadeEventOrderError } from "./errors.js";
6
6
  import { getAddress, isAddressEqual, parseEventLogs } from "viem";
@@ -1,5 +1,3 @@
1
- import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
2
- import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
3
1
  import { AP_REWARDS_COMPRESSOR } from "../constants/address-provider.js";
4
2
  import { ADDRESS_0X0 } from "../constants/addresses.js";
5
3
  import { MAX_UINT256 } from "../constants/math.js";
@@ -10,6 +8,8 @@ import "../base/index.js";
10
8
  import { AccountBotsService } from "./bots/AccountBotsService.js";
11
9
  import "./bots/index.js";
12
10
  import { rewardsCompressorAbi } from "../../abi/compressors/rewardsCompressor.js";
11
+ import { iBaseRewardPoolAbi } from "../../abi/iBaseRewardPool.js";
12
+ import { ierc4626AdapterAbi } from "../../abi/ierc4626Adapter.js";
13
13
  import { expectedBalanceDeltas } from "../market/credit/expectedBalanceDeltas.js";
14
14
  import "../market/index.js";
15
15
  import { CreditAccountCompressor } from "./credit-account-compressor/CreditAccountCompressor.js";
@@ -56,12 +56,6 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
56
56
  return this.#compressor.getBorrowerCreditAccounts(borrower, options, blockNumber);
57
57
  }
58
58
  /**
59
- * {@inheritDoc ICreditAccountsService.listPositions}
60
- **/
61
- async listPositions(props) {
62
- return this.#compressor.listPositions(props);
63
- }
64
- /**
65
59
  * {@inheritDoc ICreditAccountsService.getRewards}
66
60
  **/
67
61
  async getRewards(creditAccount) {
@@ -1,4 +1,3 @@
1
- import { AddressMap } from "../../utils/AddressMap.js";
2
1
  import { AddressSet } from "../../utils/AddressSet.js";
3
2
  import { AP_CREDIT_ACCOUNT_COMPRESSOR } from "../../constants/address-provider.js";
4
3
  import { ADDRESS_0X0 } from "../../constants/addresses.js";
@@ -9,11 +8,8 @@ import { hexEq } from "../../utils/hex.js";
9
8
  import "../../utils/index.js";
10
9
  import { SDKConstruct } from "../../base/SDKConstruct.js";
11
10
  import "../../base/index.js";
12
- import { calcBorrowApy, calcPositionLeverage, healthFactorBps, usdToNumber } from "../../market/math.js";
13
- import { dominantCollateral } from "../../market/credit/dominantCollateral.js";
14
11
  import { simulateWithPriceUpdates } from "../../utils/viem/simulateWithPriceUpdates.js";
15
12
  import "../../utils/viem/index.js";
16
- import "../../market/index.js";
17
13
  import { iRWAFactoryAbi } from "../../../abi/rwa/iRWAFactory.js";
18
14
  import { CreditAccountCompressorV310Contract } from "./CreditAccountCompressorV310Contract.js";
19
15
  //#region src/sdk/accounts/credit-account-compressor/CreditAccountCompressor.ts
@@ -21,9 +17,8 @@ import { CreditAccountCompressorV310Contract } from "./CreditAccountCompressorV3
21
17
  * Reads credit accounts of the current chain.
22
18
  *
23
19
  * Stitches the credit account compressor together with the RWA factories (for
24
- * accounts owned via an investor EOA) and with the withdrawal compressor (for
25
- * assets that are on their way out of an account), and describes the result
26
- * either as raw account data or as {@link StrategyPosition}s.
20
+ * accounts owned via an investor EOA), and describes the result as raw
21
+ * account data.
27
22
  *
28
23
  * TODO: create and deploy new compressor contract onchain to avoid all this stitching
29
24
  **/
@@ -173,89 +168,6 @@ var CreditAccountCompressor = class extends SDKConstruct {
173
168
  return filtered.sort((a, b) => Number(a.healthFactor - b.healthFactor));
174
169
  }
175
170
  /**
176
- * Describes all credit accounts of a wallet as strategy positions.
177
- *
178
- * @param props - {@link ListStrategyPositionsProps}
179
- **/
180
- async listPositions(props) {
181
- const { owner, includeZeroDebt, blockNumber } = props;
182
- const [accounts] = await Promise.all([this.getBorrowerCreditAccounts(owner, { includeZeroDebt }, blockNumber), this.sdk.withdrawalCompressor?.loadWithdrawableAssets(void 0, blockNumber)]);
183
- const describable = accounts.filter((ca) => {
184
- if (!ca.success) this.logger?.warn(`cannot describe position of ${this.labelAddress(ca.creditAccount)}: collateral computation failed`);
185
- return ca.success;
186
- });
187
- const withdrawals = await Promise.all(describable.map((ca) => this.#accountWithdrawals(ca, blockNumber)));
188
- return describable.map((ca, i) => this.#toStrategyPosition(ca, withdrawals[i] ?? new AddressMap()));
189
- }
190
- /**
191
- * Builds one strategy position from an account snapshot.
192
- *
193
- * @param withdrawals - Delayed withdrawals of the account, keyed by the
194
- * phantom token that represents them on it.
195
- **/
196
- #toStrategyPosition(ca, withdrawals) {
197
- const suite = this.sdk.marketRegister.findCreditManager(ca.creditManager);
198
- const { market } = suite;
199
- const { priceOracle } = market;
200
- const { pool } = market.pool;
201
- const token = this.sdk.tokensMeta.mustGetToken(market.unwrappedUnderlying);
202
- const totalDebtValue = ca.debt + ca.accruedInterest + ca.accruedFees;
203
- const collateral = dominantCollateral(ca, market);
204
- return {
205
- kind: "strategy",
206
- chainId: this.sdk.chainId,
207
- creditManager: ca.creditManager,
208
- creditAccount: ca.creditAccount,
209
- name: collateral ? suite.strategyName(collateral) : token.symbol,
210
- targetCollateral: collateral ? this.sdk.tokensMeta.mustGetToken(collateral) : null,
211
- leverage: calcPositionLeverage(ca.totalValue, totalDebtValue),
212
- borrowApy: calcBorrowApy(pool.baseInterestRate, suite.creditManager.feeInterest),
213
- totalDebt: {
214
- token,
215
- value: totalDebtValue,
216
- valueUsd: usdToNumber(ca.totalDebtUSD)
217
- },
218
- totalValue: {
219
- token,
220
- value: ca.totalValue,
221
- valueUsd: usdToNumber(ca.totalValueUSD)
222
- },
223
- healthFactor: healthFactorBps(ca.healthFactor),
224
- collaterals: ca.tokens.flatMap((t) => {
225
- if ((t.mask & ca.enabledTokensMask) === 0n || t.balance <= 10n) return [];
226
- return [{
227
- collateral: priceOracle.toTokenAmount(t.token, t.balance),
228
- quota: priceOracle.toTokenAmount(market.underlying, t.quota),
229
- withdrawals: withdrawals.get(t.token) ?? []
230
- }];
231
- })
232
- };
233
- }
234
- /**
235
- * Delayed withdrawals of one account, keyed by the phantom token that
236
- * represents them on it, so that each collateral row can pick up its own.
237
- **/
238
- async #accountWithdrawals(ca, blockNumber) {
239
- const compressor = this.sdk.withdrawalCompressor;
240
- const byPhantomToken = new AddressMap(void 0, "accountWithdrawals");
241
- const holdsPhantomToken = ca.tokens.some((t) => t.balance > 10n && compressor?.getWithdrawalSourceToken(t.token) !== void 0);
242
- if (!compressor || !holdsPhantomToken) return byPhantomToken;
243
- const { priceOracle } = this.sdk.marketRegister.findByCreditManager(ca.creditManager);
244
- const { claimable, pending } = await compressor.getCurrentWithdrawals(ca.creditAccount, blockNumber);
245
- const add = (w, outputs, claimableAt) => {
246
- const assets = outputs.map((o) => ({
247
- isDelayed: true,
248
- ...priceOracle.toTokenAmount(o.token, o.amount),
249
- redeemer: w.redeemer,
250
- claimableAt: claimableAt === void 0 ? void 0 : Number(claimableAt)
251
- }));
252
- byPhantomToken.upsert(w.withdrawalPhantomToken, [...byPhantomToken.get(w.withdrawalPhantomToken) ?? [], ...assets]);
253
- };
254
- for (const w of claimable) add(w, w.outputs);
255
- for (const w of pending) add(w, w.expectedOutputs, w.claimableAt);
256
- return byPhantomToken;
257
- }
258
- /**
259
171
  * Credit account compressor contract of the current chain.
260
172
  *
261
173
  * Resolved on every access, because the address provider is only populated
@@ -83,11 +83,37 @@ function buildMockSdk(args) {
83
83
  quotaIncreaseFee: 0n,
84
84
  ...q
85
85
  })) };
86
- const liquidationThresholds = { entries: () => Object.entries(args.liquidationThresholds) };
86
+ const quotaOf = (token) => args.quotas[token.toLowerCase()] ?? args.quotas[token];
87
+ const liquidationThresholds = {
88
+ entries: () => Object.entries(args.liquidationThresholds),
89
+ get: (token) => args.liquidationThresholds[token.toLowerCase()] ?? args.liquidationThresholds[token]
90
+ };
87
91
  const market = {
88
- priceOracle: { convert },
92
+ priceOracle: {
93
+ convert,
94
+ convertToUSD: (token, amount) => {
95
+ const from = token.toLowerCase();
96
+ const price = args.prices[from] ?? args.prices[token];
97
+ if (price === void 0) throw new Error(`mock priceOracle: missing price for ${from}`);
98
+ return amount * price / 10n ** BigInt(decimalsOf(from));
99
+ },
100
+ safeConvertToUSD: (token, amount) => {
101
+ const from = token.toLowerCase();
102
+ const price = args.prices[from] ?? args.prices[token];
103
+ if (price === void 0) return null;
104
+ return amount * price / 10n ** BigInt(decimalsOf(from));
105
+ }
106
+ },
89
107
  pool: {
90
- pqk: { quotas },
108
+ pqk: {
109
+ quotas,
110
+ quotaRate: (token) => Number(quotaOf(token)?.rate ?? 0n),
111
+ hasActiveQuota: (token) => {
112
+ const q = quotaOf(token);
113
+ return !!q?.isActive && q.limit > 0n;
114
+ }
115
+ },
116
+ pool: { baseInterestRate: args.baseInterestRate ?? 0n },
91
117
  underlying: args.underlying
92
118
  }
93
119
  };
@@ -95,7 +121,8 @@ function buildMockSdk(args) {
95
121
  creditManager: {
96
122
  address: args.creditManager,
97
123
  liquidationThresholds,
98
- collateralTokens: []
124
+ collateralTokens: [],
125
+ feeInterest: args.feeInterest ?? 0
99
126
  },
100
127
  creditFacade: {
101
128
  address: args.creditFacade,
@@ -0,0 +1,17 @@
1
+ //#region src/sdk/accounts/intents/utils/adjust-state-to-snapshot.ts
2
+ /**
3
+ * Maps an intents {@link AdjustState} onto the {@link AccountSnapshot} that
4
+ * position-metric functions take. `accountDebt` is treated as total debt
5
+ * (principal plus accrued interest and fees).
6
+ **/
7
+ function adjustStateToSnapshot(creditManager, state) {
8
+ return {
9
+ creditManager,
10
+ assets: state.assets,
11
+ quotas: Object.values(state.quotas),
12
+ totalDebt: state.accountDebt,
13
+ totalValue: state.totalValue
14
+ };
15
+ }
16
+ //#endregion
17
+ export { adjustStateToSnapshot };
@@ -1,3 +1,4 @@
1
+ import { adjustStateToSnapshot } from "./adjust-state-to-snapshot.js";
1
2
  import { assembleOperationCalls } from "./assemble-operation-calls.js";
2
3
  import { calcBorrowedAmountPlusInterestAndFees } from "./borrowed-amount-plus-interest-and-fees.js";
3
4
  import { eq, toRouterCaSlice, toTargetDecimals } from "./common.js";
@@ -6,4 +7,4 @@ import { getQuotasForUpdate } from "./quotas-for-update.js";
6
7
  import { simulateOperationAssets } from "./simulate-assets.js";
7
8
  import { simulateState } from "./simulate-adjust-state.js";
8
9
  import { getOperationsWithQuotaUpdate } from "./with-quota-update.js";
9
- export { assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, convertAmount, eq, getOperationsWithQuotaUpdate, getQuotasForUpdate, simulateOperationAssets, simulateState, toRouterCaSlice, toTargetDecimals };
10
+ export { adjustStateToSnapshot, assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, convertAmount, eq, getOperationsWithQuotaUpdate, getQuotasForUpdate, simulateOperationAssets, simulateState, toRouterCaSlice, toTargetDecimals };
@@ -1,4 +1,3 @@
1
- import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
2
1
  import { AddressSet } from "../../utils/AddressSet.js";
3
2
  import { bytes32ToString } from "../../utils/bytes32ToString.js";
4
3
  import { ADDRESS_0X0 } from "../../constants/addresses.js";
@@ -20,6 +19,7 @@ import { SecuritizeLiquidatorContract } from "../../market/rwa/securitize/Securi
20
19
  import "../../market/rwa/securitize/index.js";
21
20
  import "../../market/index.js";
22
21
  import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./constants.js";
22
+ import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
23
23
  //#region src/sdk/accounts/liquidations/LiquidationsService.ts
24
24
  /**
25
25
  * Service for discovering liquidatable credit accounts and previewing manual
@@ -32,7 +32,6 @@ var LiquidationsService = class extends SDKConstruct {
32
32
  * Accounts whose collateral computation failed are excluded.
33
33
  **/
34
34
  async getLiquidatableAccounts(props) {
35
- await this.sdk.withdrawalCompressor?.loadWithdrawableAssets(void 0, props?.blockNumber);
36
35
  const unhealthy = await this.sdk.accounts.getCreditAccounts({
37
36
  maxHealthFactor: WAD - 1n,
38
37
  includeZeroDebt: false
@@ -59,7 +58,6 @@ var LiquidationsService = class extends SDKConstruct {
59
58
  const ca = await this.#getCreditAccountData(creditAccount, blockNumber);
60
59
  const suite = this.sdk.marketRegister.findCreditManager(ca.creditManager);
61
60
  const { priceOracle } = suite.market;
62
- await this.sdk.withdrawalCompressor?.loadWithdrawableAssets(void 0, blockNumber);
63
61
  const account = this.#buildAccount(ca, suite);
64
62
  const data = await this.#getLiquidationData(ca, liquidator, ignoreReservePrices, blockNumber);
65
63
  return {
@@ -96,7 +94,6 @@ var LiquidationsService = class extends SDKConstruct {
96
94
  async getLiquidationPositions(props) {
97
95
  const compressor = this.sdk.withdrawalCompressor;
98
96
  if (!compressor) return [];
99
- await compressor.loadWithdrawableAssets(void 0, props.blockNumber);
100
97
  const phantomTokens = new AddressSet(compressor.getWithdrawableAssets().map((a) => a.withdrawalPhantomToken));
101
98
  const { claimable, pending } = await compressor.getExternalAccountCurrentWithdrawals({
102
99
  account: props.liquidator,
@@ -1,7 +1,7 @@
1
- import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
2
1
  import { BaseContract } from "../../base/BaseContract.js";
3
2
  import "../../base/index.js";
4
3
  import { decodeDelayedIntent } from "./intent-codec.js";
4
+ import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
5
5
  import { InvalidDelayedIntentError } from "./errors.js";
6
6
  //#region src/sdk/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.ts
7
7
  const abi = iRedemptionLoggerV310Abi;
@@ -1,5 +1,5 @@
1
- import { iWithdrawalCompressorV310Abi } from "../../../abi/IWithdrawalCompressorV310.js";
2
1
  import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
+ import { iWithdrawalCompressorV310Abi } from "../../../abi/IWithdrawalCompressorV310.js";
3
3
  //#region src/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.ts
4
4
  const abi = iWithdrawalCompressorV310Abi;
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { iWithdrawalCompressorV311Abi } from "../../../abi/IWithdrawalCompressorV311.js";
2
1
  import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
2
+ import { iWithdrawalCompressorV311Abi } from "../../../abi/IWithdrawalCompressorV311.js";
3
3
  //#region src/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.ts
4
4
  const abi = iWithdrawalCompressorV311Abi;
5
5
  /**
@@ -1,6 +1,6 @@
1
- import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
2
1
  import { encodeDelayedIntent } from "./intent-codec.js";
3
2
  import { AbstractWithdrawalCompressorContract, iCreditAccountAbi, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal } from "./AbstractWithdrawalCompressorContract.js";
3
+ import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
4
4
  import { toWithdrawalStatus } from "./types.js";
5
5
  //#region src/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.ts
6
6
  const abi = iWithdrawalCompressorV313Abi;
@@ -1,12 +1,12 @@
1
- import { iExpirableAbi } from "../../abi/iExpirable.js";
2
- import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
3
- import { iVersionAbi } from "../../abi/iVersion.js";
4
1
  import { AddressMap } from "../utils/AddressMap.js";
5
2
  import { AddressSet } from "../utils/AddressSet.js";
6
3
  import { bytes32ToString } from "../utils/bytes32ToString.js";
7
4
  import { getAssetType } from "../chain/chains.js";
8
5
  import { formatBN } from "../utils/formatter.js";
9
6
  import "../utils/index.js";
7
+ import { iExpirableAbi } from "../../abi/iExpirable.js";
8
+ import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
9
+ import { iVersionAbi } from "../../abi/iVersion.js";
10
10
  import { executeMulticallBatches } from "../utils/viem/executeMulticallBatches.js";
11
11
  //#region src/sdk/base/TokensMeta.ts
12
12
  /**
@@ -1,5 +1,5 @@
1
- import { ierc20Abi } from "../../abi/iERC20.js";
2
1
  import { chains } from "./chains.js";
2
+ import { ierc20Abi } from "../../abi/iERC20.js";
3
3
  //#region src/sdk/chain/detectNetwork.ts
4
4
  /**
5
5
  * Detects the network type from the given client.
@@ -1,8 +1,8 @@
1
- import { iVersionAbi } from "../../abi/iVersion.js";
2
1
  import { AP_MARKET_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR } from "../constants/address-provider.js";
3
2
  import { isV310 } from "../constants/versions.js";
4
3
  import "../constants/index.js";
5
4
  import { hexEq } from "../utils/hex.js";
5
+ import { iVersionAbi } from "../../abi/iVersion.js";
6
6
  import { AddressProviderV310Contract } from "./AddressProviderV310Contract.js";
7
7
  //#region src/sdk/core/createAddressProvider.ts
8
8
  const OVERRIDE_ADDRESSES = { Mainnet: {
@@ -138,7 +138,13 @@ import { PluginStateVersionError } from "./plugins/errors.js";
138
138
  import "./plugins/index.js";
139
139
  import { PoolService } from "./pools/PoolService.js";
140
140
  import "./pools/index.js";
141
+ import { calcBorrowRate } from "./positions/calcBorrowRate.js";
142
+ import { calcHealthFactor } from "./positions/calcHealthFactor.js";
143
+ import { calcLiquidationPriceForTarget } from "./positions/calcLiquidationPriceForTarget.js";
144
+ import { calcLiquidationPrice } from "./positions/calcLiquidationPrice.js";
145
+ import { calcTimeToLiquidationMs } from "./positions/calcTimeToLiquidationMs.js";
141
146
  import { MultichainPositionsService } from "./positions/MultichainPositionsService.js";
147
+ import { accountSnapshotFromCreditAccountData } from "./positions/types.js";
142
148
  import { PositionsService } from "./positions/PositionsService.js";
143
149
  import "./positions/index.js";
144
150
  import { assetsMap } from "./router/helpers.js";
@@ -149,4 +155,4 @@ import { OnchainSDK, STATE_VERSION } from "./OnchainSDK.js";
149
155
  import { MultichainSDK } from "./MultichainSDK.js";
150
156
  import { attachOptionsSchema, onchainSDKOptionsSchema } from "./options.js";
151
157
  import "./types/index.js";
152
- export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, Erc4626PriceFeedContract, ExternalPriceFeedContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InvalidDelayedIntentError, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowLRTPriceFeedContract, MidasLiquidatorContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendleTWAPPTPriceFeed, PeripheryCompressorV310Contract, PlaceholderAdapterContract, PlaceholderContract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SECURITIZE_REGISTER_VAULT_TYPES, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeRWAFactory, SimulateWithPriceUpdatesError, SimulationError, TokensMeta, TypedObjectUtils, UnsupportedZapperFunctionError, VERSION_RANGE_310, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, assetsMap, attachOptionsSchema, botPermissionsToString, bytes32ToString, calcAdditionalBorrowApy, calcBorrowApy, calcMaxLeverage, calcPositionLeverage, calcUtilization, chains, childLogger, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchRedstonePayloads, filterDust, filterDustUSD, findCuratorMarketConfigurator, fmtBinaryMask, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, healthFactorBps, hexEq, hydrateAddressProvider, iCreditAccountAbi, isDust, isLPPriceFeed, isPublicNetwork, isRWAFactory, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, json_parse, json_stringify, minSeizedAmount, mustGetDominantCollateral, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, percentFmt, primaryInstantOutput, rayToBps, rayToNumber, retry, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
158
+ export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, Erc4626PriceFeedContract, ExternalPriceFeedContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InvalidDelayedIntentError, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowLRTPriceFeedContract, MidasLiquidatorContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendleTWAPPTPriceFeed, PeripheryCompressorV310Contract, PlaceholderAdapterContract, PlaceholderContract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SECURITIZE_REGISTER_VAULT_TYPES, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeRWAFactory, SimulateWithPriceUpdatesError, SimulationError, TokensMeta, TypedObjectUtils, UnsupportedZapperFunctionError, VERSION_RANGE_310, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, assetsMap, attachOptionsSchema, botPermissionsToString, bytes32ToString, calcAdditionalBorrowApy, calcBorrowApy, calcBorrowRate, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcPositionLeverage, calcTimeToLiquidationMs, calcUtilization, chains, childLogger, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchRedstonePayloads, filterDust, filterDustUSD, findCuratorMarketConfigurator, fmtBinaryMask, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, healthFactorBps, hexEq, hydrateAddressProvider, iCreditAccountAbi, isDust, isLPPriceFeed, isPublicNetwork, isRWAFactory, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, json_parse, json_stringify, minSeizedAmount, mustGetDominantCollateral, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, percentFmt, primaryInstantOutput, rayToBps, rayToNumber, retry, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal, toSignificant, toWithdrawalStatus, usdToNumber, watchBlocksAsync };