@gearbox-protocol/sdk 16.0.0-next.26 → 16.0.0-next.28

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 (71) hide show
  1. package/dist/cjs/model/index.js +1 -0
  2. package/dist/cjs/model/previews.js +23 -0
  3. package/dist/cjs/onchain/accounts/index.js +2 -0
  4. package/dist/cjs/onchain/accounts/intents/index.js +2 -0
  5. package/dist/cjs/onchain/accounts/intents/open-strategy.js +4 -18
  6. package/dist/cjs/onchain/accounts/intents/realize.js +77 -50
  7. package/dist/cjs/onchain/accounts/intents/testing/market.js +1 -0
  8. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +13 -5
  9. package/dist/cjs/onchain/index.js +2 -0
  10. package/dist/cjs/onchain/positions/PositionsService.js +79 -0
  11. package/dist/cjs/preview/index.js +6 -6
  12. package/dist/cjs/preview/preview/{buildDelayedPreview.js → buildDelayedStrategyVerify.js} +6 -25
  13. package/dist/cjs/preview/preview/index.js +6 -6
  14. package/dist/cjs/preview/preview/{previewAdjustCreditAccount.js → previewAdjustStrategyVerify.js} +6 -24
  15. package/dist/cjs/preview/preview/{previewCloseOrRepayCreditAccount.js → previewExitOrRepayStrategyVerify.js} +3 -3
  16. package/dist/cjs/preview/preview/{previewPoolOperation.js → previewLpVerify.js} +3 -3
  17. package/dist/cjs/preview/preview/{previewOpenCreditAccount.js → previewOpenStrategyVerify.js} +6 -26
  18. package/dist/cjs/preview/preview/previewOperation.js +10 -10
  19. package/dist/cjs/preview/validate/checkOperation.js +13 -9
  20. package/dist/cjs/rewards/rewards/api.js +15 -7
  21. package/dist/cjs/sdk/prepare/PrepareApi.js +7 -0
  22. package/dist/cjs/sdk/prepare/withdrawable-collaterals.js +23 -0
  23. package/dist/esm/model/index.js +2 -2
  24. package/dist/esm/model/previews.js +23 -1
  25. package/dist/esm/onchain/accounts/index.js +2 -1
  26. package/dist/esm/onchain/accounts/intents/index.js +2 -1
  27. package/dist/esm/onchain/accounts/intents/open-strategy.js +4 -18
  28. package/dist/esm/onchain/accounts/intents/realize.js +77 -50
  29. package/dist/esm/onchain/accounts/intents/testing/market.js +1 -0
  30. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +13 -5
  31. package/dist/esm/onchain/index.js +2 -1
  32. package/dist/esm/onchain/positions/PositionsService.js +79 -0
  33. package/dist/esm/preview/index.js +4 -4
  34. package/dist/esm/preview/preview/{buildDelayedPreview.js → buildDelayedStrategyVerify.js} +7 -26
  35. package/dist/esm/preview/preview/index.js +4 -4
  36. package/dist/esm/preview/preview/{previewAdjustCreditAccount.js → previewAdjustStrategyVerify.js} +7 -25
  37. package/dist/esm/preview/preview/{previewCloseOrRepayCreditAccount.js → previewExitOrRepayStrategyVerify.js} +3 -3
  38. package/dist/esm/preview/preview/{previewPoolOperation.js → previewLpVerify.js} +3 -3
  39. package/dist/esm/preview/preview/{previewOpenCreditAccount.js → previewOpenStrategyVerify.js} +7 -27
  40. package/dist/esm/preview/preview/previewOperation.js +10 -10
  41. package/dist/esm/preview/validate/checkOperation.js +13 -9
  42. package/dist/esm/rewards/rewards/api.js +16 -8
  43. package/dist/esm/sdk/prepare/PrepareApi.js +7 -0
  44. package/dist/esm/sdk/prepare/withdrawable-collaterals.js +22 -0
  45. package/dist/types/model/index.d.ts +2 -2
  46. package/dist/types/model/previews.d.ts +202 -76
  47. package/dist/types/onchain/accounts/index.d.ts +2 -1
  48. package/dist/types/onchain/accounts/intents/index.d.ts +2 -1
  49. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +1 -7
  50. package/dist/types/onchain/accounts/intents/testing/market.d.ts +1 -0
  51. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +7 -0
  52. package/dist/types/onchain/accounts/intents/utils/index.d.ts +1 -1
  53. package/dist/types/onchain/index.d.ts +2 -1
  54. package/dist/types/onchain/positions/PositionsService.d.ts +30 -0
  55. package/dist/types/preview/index.d.ts +5 -5
  56. package/dist/types/preview/preview/{buildDelayedPreview.d.ts → buildDelayedStrategyVerify.d.ts} +4 -4
  57. package/dist/types/preview/preview/index.d.ts +4 -4
  58. package/dist/types/preview/preview/{previewAdjustCreditAccount.d.ts → previewAdjustStrategyVerify.d.ts} +4 -4
  59. package/dist/types/preview/preview/{previewCloseOrRepayCreditAccount.d.ts → previewExitOrRepayStrategyVerify.d.ts} +4 -4
  60. package/dist/types/preview/preview/previewLpVerify.d.ts +11 -0
  61. package/dist/types/preview/preview/previewOpenStrategyVerify.d.ts +12 -0
  62. package/dist/types/preview/validate/checkOperation.d.ts +12 -4
  63. package/dist/types/preview/validate/index.d.ts +2 -2
  64. package/dist/types/rewards/rewards/api.d.ts +12 -6
  65. package/dist/types/rewards/rewards/merkl-api.d.ts +6 -0
  66. package/dist/types/sdk/prepare/PrepareApi.d.ts +5 -0
  67. package/dist/types/sdk/prepare/types.d.ts +18 -1
  68. package/dist/types/sdk/prepare/withdrawable-collaterals.d.ts +11 -0
  69. package/package.json +1 -1
  70. package/dist/types/preview/preview/previewOpenCreditAccount.d.ts +0 -12
  71. package/dist/types/preview/preview/previewPoolOperation.d.ts +0 -11
@@ -1,4 +1,3 @@
1
- import { calcPositionLeverage } from "../../market/math.js";
2
1
  import { IntentPreviewError } from "../../validation/refusal.js";
3
2
  import { toToken, toTokenAmount } from "../../validation/token.js";
4
3
  import { eq, toTargetDecimals } from "./utils/common.js";
@@ -32,16 +31,36 @@ async function realize(steps, props) {
32
31
  const market = sdk.marketRegister.findByCreditManager(creditAccount.creditManager);
33
32
  const price = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount) ?? 0n;
34
33
  const suite = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
35
- const ledger = new OperationLedger({
34
+ const start = {
36
35
  initialAssets: creditAccount.tokens,
37
36
  underlying,
38
37
  debt: creditAccount.totalDebt,
39
38
  convert: price
40
- });
39
+ };
40
+ /**
41
+ * The floor: every routed leg counted at the amount it guarantees. This is
42
+ * what the calls are built from — a repayment may only spend underlying the
43
+ * route promises to have raised — and what the guards are answered on, since
44
+ * a floor that does not clear the facade's bar is a transaction that can
45
+ * revert.
46
+ */
47
+ const ledger = new OperationLedger(start);
48
+ /**
49
+ * The same walk with every routed leg counted at the amount the pathfinder
50
+ * expects to return. Nothing is built from it: it is where the position
51
+ * actually lands, so it is what the reported state is read off.
52
+ */
53
+ const expected = new OperationLedger(start);
41
54
  const operations = [];
42
- const push = (op) => {
55
+ /**
56
+ * @param asExpected - The operation as the expected branch sees it, for the
57
+ * legs where the two differ. Defaults to the operation itself, which is the
58
+ * case for everything whose amount the calldata fixes.
59
+ */
60
+ const push = (op, asExpected = op) => {
43
61
  operations.push(op);
44
62
  ledger.apply(op);
63
+ expected.apply(asExpected);
45
64
  };
46
65
  /** One per routed leg, each already awaiting its quote; folded after the guards. */
47
66
  const probes = [];
@@ -137,13 +156,17 @@ async function realize(steps, props) {
137
156
  keep: held - amount
138
157
  });
139
158
  if (leg.probe) probes.push(leg.probe);
140
- push(buildSwapOperation({
159
+ const swap = buildSwapOperation({
141
160
  tokenIn: step.from,
142
161
  amountIn: amount,
143
162
  tokenOut: step.to,
144
163
  amountOut: leg.minAmount,
145
164
  calls: leg.calls
146
- }));
165
+ });
166
+ push(swap, {
167
+ ...swap,
168
+ amountOut: leg.amount
169
+ });
147
170
  raised = leg.minAmount;
148
171
  break;
149
172
  }
@@ -154,12 +177,22 @@ async function realize(steps, props) {
154
177
  if (balances.length > 0) {
155
178
  const leg = await paths.closeAll({ balances });
156
179
  if (leg.probe) probes.push(leg.probe);
157
- if (leg.calls.length > 0 || leg.minAmount > 0n) push(buildCloseSwapOperation({
158
- from: balances,
159
- tokenOut: underlying,
160
- amountOut: leg.minAmount,
161
- calls: leg.calls
162
- }));
180
+ if (leg.calls.length > 0 || leg.minAmount > 0n) {
181
+ const sale = buildCloseSwapOperation({
182
+ from: balances,
183
+ tokenOut: underlying,
184
+ amountOut: leg.minAmount,
185
+ calls: leg.calls
186
+ });
187
+ push(sale, {
188
+ ...sale,
189
+ from: balances.map((a) => ({
190
+ token: a.token,
191
+ balance: expected.balanceOf(a.token)
192
+ })),
193
+ amountOut: leg.amount
194
+ });
195
+ }
163
196
  }
164
197
  raised = ledger.balanceOf(underlying);
165
198
  break;
@@ -225,24 +258,32 @@ async function realize(steps, props) {
225
258
  creditAccount,
226
259
  sdk
227
260
  }));
228
- for (const { token, balance } of ledger.snapshot().assets) push(buildWithdrawCollateralOperation({
229
- token,
230
- amount: balance,
231
- to: step.to,
232
- all: true,
233
- creditAccount,
234
- sdk
235
- }));
261
+ for (const { token, balance } of ledger.snapshot().assets) {
262
+ const payout = buildWithdrawCollateralOperation({
263
+ token,
264
+ amount: balance,
265
+ to: step.to,
266
+ all: true,
267
+ creditAccount,
268
+ sdk
269
+ });
270
+ push(payout, {
271
+ ...payout,
272
+ amount: expected.balanceOf(token)
273
+ });
274
+ }
236
275
  break;
237
276
  }
238
277
  }
239
- const { assets, totalValue, debt } = ledger.snapshot();
278
+ const floor = ledger.snapshot();
279
+ const { assets, debt } = floor;
280
+ const projected = expected.snapshot();
240
281
  assertGrowthAllowed({
241
282
  sdk,
242
283
  suite,
243
284
  market,
244
285
  before: creditAccount.tokens,
245
- after: assets
286
+ after: projected.assets
246
287
  });
247
288
  const quotas = cleared ?? getQuotasForUpdate({
248
289
  assetsBefore: creditAccount.tokens,
@@ -264,42 +305,28 @@ async function realize(steps, props) {
264
305
  }));
265
306
  }
266
307
  const quotasAfter = quotasAfterUpdate(creditAccount.tokens, quotas.desiredQuota);
308
+ const quoted = Object.values(quotasAfter);
267
309
  const snapshot = {
268
310
  creditManager: creditAccount.creditManager,
269
- assets,
270
- quotas: Object.values(quotasAfter),
311
+ assets: projected.assets,
312
+ quotas: quoted,
271
313
  totalDebt: debt,
272
- totalValue
273
- };
274
- const projectedPool = { availableLiquidityChange: creditAccount.totalDebt - debt };
275
- const metrics = {
276
- healthFactor: sdk.positions.healthFactor(snapshot),
277
- safeHealthFactor: paysOut ? sdk.positions.healthFactor(snapshot, { safePrices: true }) : void 0,
278
- borrowRate: sdk.positions.borrowRate(snapshot, projectedPool),
279
- timeToLiquidation: sdk.positions.timeToLiquidation(snapshot, projectedPool),
280
- liquidationPrice: sdk.positions.liquidationPrice(snapshot)
314
+ totalValue: projected.totalValue
281
315
  };
282
- assertCollateralised(paysOut ? sdk.positions.healthFactor(snapshot, { safePrices: true }) : metrics.healthFactor, paysOut);
316
+ const projection = sdk.positions.projection(snapshot, { availableLiquidityChange: creditAccount.totalDebt - debt });
317
+ assertCollateralised(sdk.positions.healthFactor({
318
+ ...snapshot,
319
+ assets,
320
+ totalValue: floor.totalValue
321
+ }, { safePrices: paysOut }), paysOut);
283
322
  const priceImpact = await collectPriceImpact(probes, {
284
- totalValue,
285
- netValue: totalValue - debt,
323
+ totalValue: projected.totalValue,
324
+ netValue: projected.totalValue - debt,
286
325
  toUnderlying: (from, amount) => price(from, underlying, amount)
287
326
  });
288
- const oracle = market.priceOracle;
289
327
  const state = {
290
- creditManager: creditAccount.creditManager,
291
- name: suite.name,
292
- totalValue: market.toUnderlyingAmount(totalValue),
293
- totalDebt: market.toUnderlyingAmount(debt),
294
- netValue: market.toUnderlyingAmount(totalValue - debt),
295
- leverage: calcPositionLeverage(totalValue, debt),
296
- assets: assets.map((a) => oracle.toTokenAmount(a.token, a.balance)),
297
- quotas: Object.values(quotasAfter).map((q) => ({
298
- token: sdk.tokensMeta.mustGetToken(q.token),
299
- ...oracle.toAmount(underlying, q.balance)
300
- })),
301
- priceImpact,
302
- ...metrics
328
+ ...projection,
329
+ priceImpact
303
330
  };
304
331
  return {
305
332
  operations,
@@ -96,6 +96,7 @@ function buildMarketSdk(extras) {
96
96
  creditFacade: CREDIT_FACADE,
97
97
  underlying: UND,
98
98
  routeQuote: extras?.routeQuote,
99
+ routeFloor: extras?.routeFloor,
99
100
  rwaAssets: extras?.rwaAssets,
100
101
  phantoms: extras?.phantoms,
101
102
  creditAccounts: extras?.creditAccounts,
@@ -155,6 +155,8 @@ function buildMockSdk(args) {
155
155
  };
156
156
  const market = {
157
157
  toUnderlyingAmount,
158
+ /** {@inheritDoc MarketSuite.underlying} */
159
+ underlying: args.underlying,
158
160
  priceOracle: {
159
161
  convert,
160
162
  safeConvert,
@@ -238,10 +240,12 @@ function buildMockSdk(args) {
238
240
  };
239
241
  /** Linear unless the case says otherwise — see `routeQuote`. */
240
242
  const quote = args.routeQuote ?? ((amount) => amount);
243
+ /** Slippage-free unless the case says otherwise — see `routeFloor`. */
244
+ const floor = args.routeFloor ?? ((amount) => amount);
241
245
  const router = {
242
246
  findOneTokenPath: vi.fn(async ({ amount, tokenIn, tokenOut }) => ({
243
247
  amount: quote(amount),
244
- minAmount: quote(amount),
248
+ minAmount: floor(quote(amount)),
245
249
  calls: routeCalls(tokenIn, tokenOut)
246
250
  })),
247
251
  findManyToOnePath: vi.fn(async ({ expectedBalances, leftoverBalances, target }) => {
@@ -249,7 +253,7 @@ function buildMockSdk(args) {
249
253
  const tokenIn = expectedBalances[0]?.token ?? target;
250
254
  return {
251
255
  amount: quote(spent),
252
- minAmount: quote(spent),
256
+ minAmount: floor(quote(spent)),
253
257
  calls: routeCalls(tokenIn, target)
254
258
  };
255
259
  }),
@@ -270,11 +274,15 @@ function buildMockSdk(args) {
270
274
  amount += convert(token, targetLc, spend);
271
275
  }
272
276
  balances[targetLc] = (balances[targetLc] ?? 0n) + amount;
277
+ const untouched = (balances[targetLc] ?? 0n) - amount;
273
278
  return {
274
279
  amount,
275
- minAmount: amount,
280
+ minAmount: floor(amount),
276
281
  balances,
277
- minBalances: { ...balances },
282
+ minBalances: {
283
+ ...balances,
284
+ [targetLc]: untouched + floor(amount)
285
+ },
278
286
  calls: [MOCK_ROUTER_CALL]
279
287
  };
280
288
  }),
@@ -284,7 +292,7 @@ function buildMockSdk(args) {
284
292
  const amount = sold.reduce((acc, a) => acc + convert(a.token, underlying, a.balance), 0n);
285
293
  return {
286
294
  amount,
287
- minAmount: amount,
295
+ minAmount: floor(amount),
288
296
  underlyingBalance: amount,
289
297
  calls: sold.length === 0 ? [] : [MOCK_CLOSE_CALL]
290
298
  };
@@ -196,6 +196,7 @@ import { CreditAccountsServiceV310 } from "./accounts/CreditAccountsServiceV310.
196
196
  import { MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, isMalformedPreviewError } from "./validation/checks.js";
197
197
  import { IntentPreviewError, raise, refuse } from "./validation/refusal.js";
198
198
  import { toToken, toTokenAmount } from "./validation/token.js";
199
+ import { isPhantomToken } from "./accounts/intents/utils/pick-token.js";
199
200
  import { borrowable } from "./accounts/intents/guards.js";
200
201
  import { fetchCreditAccountSlice, toCreditAccountSlice } from "./accounts/intents/utils/credit-account-slice.js";
201
202
  import { calcDefaultQuota, calcQuotaUpdate, calcRecommendedQuota, roundUpQuota } from "./accounts/quota-utils.js";
@@ -244,4 +245,4 @@ import { MultichainSDK } from "./MultichainSDK.js";
244
245
  import { attachOptionsSchema, onchainSDKOptionsSchema } from "./options.js";
245
246
  import "./types/index.js";
246
247
  import "./validation/index.js";
247
- 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, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, IntentPreviewError, InvalidDelayedIntentError, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, 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, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, 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, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UnsupportedZapperFunctionError, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, borrowable, botPermissionsToString, bpsToRay, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, childLogger, classifyCurveOperation, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, fetchRedstonePayloads, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isDust, isLPPriceFeed, isMalformedPreviewError, isPublicNetwork, isRWAFactory, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, mellowDvvAdapterAbi, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parsePosNegAmount, percentFmt, pickStrategyTargetCollateral, raise, rayToBps, rayToNumber, refuse, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toShares, toSharesUp, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
248
+ 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, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, EXECUTE_BYTES_SELECTOR, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, IntentPreviewError, InvalidDelayedIntentError, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, 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, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, 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, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UnsupportedZapperFunctionError, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, borrowable, botPermissionsToString, bpsToRay, bytes32ToString, calcBorrowApy, calcBorrowRate, calcDefaultQuota, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcQuotaUpdate, calcRecommendedQuota, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, childLogger, classifyCurveOperation, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, fetchRedstonePayloads, filterDust, filterDustUSD, findCallTo, findCallWithInput, findCuratorMarketConfigurator, findExecuteBytes, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isDust, isLPPriceFeed, isMalformedPreviewError, isPhantomToken, isPublicNetwork, isRWAFactory, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, mellowDvvAdapterAbi, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parsePosNegAmount, percentFmt, pickStrategyTargetCollateral, raise, rayToBps, rayToNumber, refuse, resolveProtocolCall, retry, rewardsFromTransfers, roundUpQuota, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toShares, toSharesUp, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
@@ -163,6 +163,85 @@ var PositionsService = class extends SDKConstruct {
163
163
  });
164
164
  }
165
165
  /**
166
+ * Every derived number of an account state at once — the whole
167
+ * {@link AccountMetrics} half of a projection.
168
+ *
169
+ * This is what both halves of the SDK fill their answers from: `prepare`, for
170
+ * a state it walked an intent into, and `preview`, for one it replayed out of
171
+ * calldata. One snapshot in, one set of metrics out, so the two descriptions
172
+ * of the same operation cannot disagree because one of them grew its own
173
+ * formula.
174
+ *
175
+ * Identical to the four methods above field for field, and cheaper than
176
+ * calling them one by one: the market data is collected once, and the health
177
+ * factor and borrow rate the time to liquidation decays at are the very ones
178
+ * reported beside it.
179
+ **/
180
+ metrics(snapshot, options) {
181
+ const data = this.#marketData(snapshot);
182
+ const factor = (safePrices) => calcHealthFactor({
183
+ snapshot,
184
+ underlying: data.underlying,
185
+ decimals: data.decimals,
186
+ prices: data.prices,
187
+ reservePrices: data.reservePrices,
188
+ safePrices,
189
+ liquidationThresholds: data.liquidationThresholds,
190
+ activeQuotas: data.activeQuotas
191
+ });
192
+ const healthFactor = factor(false);
193
+ const borrowRate = calcBorrowRate({
194
+ snapshot,
195
+ baseInterestRate: this.#baseInterestRate(snapshot, data, options),
196
+ feeInterest: data.feeInterest,
197
+ quotaRates: data.quotaRates,
198
+ resolveToken: (address) => this.sdk.tokensMeta.mustGetToken(address)
199
+ });
200
+ return {
201
+ healthFactor,
202
+ safeHealthFactor: factor(true),
203
+ borrowRate,
204
+ timeToLiquidation: calcTimeToLiquidationMs(healthFactor, BigInt(borrowRate.totalOnDebt)),
205
+ liquidationPrice: calcLiquidationPrice({
206
+ snapshot,
207
+ underlying: data.underlying,
208
+ decimals: data.decimals,
209
+ liquidationThresholds: data.liquidationThresholds
210
+ }),
211
+ leverage: calcPositionLeverage(snapshot.totalValue, snapshot.totalDebt)
212
+ };
213
+ }
214
+ /**
215
+ * A projected account state as both halves of the SDK report it: the holdings
216
+ * priced and named, and the metrics of {@link PositionsService.metrics}.
217
+ *
218
+ * The snapshot is taken at its word — what it lists is what comes back, so a
219
+ * caller that drops dust before the walk reports an account without it, and
220
+ * one that keeps wei reports them. That is the whole of the policy left to
221
+ * the caller; everything downstream of the balances is decided here.
222
+ *
223
+ * @param options - The operation's effect on the pool, for the rate the
224
+ * metrics are quoted at, see {@link ProjectedPoolOptions}.
225
+ **/
226
+ projection(snapshot, options) {
227
+ const { creditManager, totalValue, totalDebt } = snapshot;
228
+ const market = this.sdk.marketRegister.findByCreditManager(creditManager);
229
+ const { priceOracle } = market;
230
+ return {
231
+ creditManager,
232
+ name: this.sdk.marketRegister.findCreditManager(creditManager).name,
233
+ totalValue: market.toUnderlyingAmount(totalValue),
234
+ totalDebt: market.toUnderlyingAmount(totalDebt),
235
+ netValue: market.toUnderlyingAmount(totalValue - totalDebt),
236
+ assets: snapshot.assets.map((a) => priceOracle.toTokenAmount(a.token, a.balance)),
237
+ quotas: snapshot.quotas.map((q) => ({
238
+ token: this.sdk.tokensMeta.mustGetToken(q.token),
239
+ ...priceOracle.toAmount(market.underlying, q.balance)
240
+ })),
241
+ ...this.metrics(snapshot, options)
242
+ };
243
+ }
244
+ /**
166
245
  * Builds one strategy position from an account snapshot.
167
246
  *
168
247
  * @param withdrawals - Delayed withdrawals of the account, keyed by the
@@ -19,7 +19,7 @@ import { BalancePrerequisite } from "./prerequisites/BalancePrerequisite.js";
19
19
  import { RWAOpenRequirementsPrerequisite } from "./prerequisites/RWAOpenRequirementsPrerequisite.js";
20
20
  import { checkPrerequisites } from "./prerequisites/checkPrerequisites.js";
21
21
  import "./prerequisites/index.js";
22
- import { buildDelayedPreview } from "./preview/buildDelayedPreview.js";
22
+ import { buildDelayedStrategyVerify } from "./preview/buildDelayedStrategyVerify.js";
23
23
  import { CreditAccountState } from "./preview/CreditAccountState.js";
24
24
  import { classifyCloseOrRepay, isCloseOrRepay } from "./preview/detectCloseOrRepay.js";
25
25
  import { detectDelayedClaim, resolveDelayedClaimIntent } from "./preview/detectDelayedClaim.js";
@@ -27,12 +27,12 @@ import { detectDelayedOperation } from "./preview/detectDelayedOperation.js";
27
27
  import { UnsupportedOperationError } from "./preview/errors.js";
28
28
  import { makeReplayState, replayInnerOperations } from "./preview/replayInnerOperations.js";
29
29
  import { replayMulticall } from "./preview/replayMulticall.js";
30
- import { previewAdjustCreditAccount } from "./preview/previewAdjustCreditAccount.js";
31
- import { previewCloseOrRepayCreditAccount } from "./preview/previewCloseOrRepayCreditAccount.js";
30
+ import { previewAdjustStrategyVerify } from "./preview/previewAdjustStrategyVerify.js";
31
+ import { previewExitOrRepayStrategyVerify } from "./preview/previewExitOrRepayStrategyVerify.js";
32
32
  import { previewOperation } from "./preview/previewOperation.js";
33
33
  import "./preview/index.js";
34
34
  import "./types.js";
35
35
  import { checkOperation, collateralIssue, marketIssues, quotaCountIssue } from "./validate/checkOperation.js";
36
36
  import { checkSimulation } from "./validate/checkSimulation.js";
37
37
  import "./validate/index.js";
38
- export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, IntentPreviewError, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedPreview, checkOperation, checkPrerequisites, checkSimulation, classifyCloseOrRepay, classifyInnerOperations, collateralIssue, detectDelayedClaim, detectDelayedOperation, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, marketIssues, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, quotaCountIssue, raise, refuse, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
38
+ export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, IntentPreviewError, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedStrategyVerify, checkOperation, checkPrerequisites, checkSimulation, classifyCloseOrRepay, classifyInnerOperations, collateralIssue, detectDelayedClaim, detectDelayedOperation, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, marketIssues, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustStrategyVerify, previewExitOrRepayStrategyVerify, previewOperation, quotaCountIssue, raise, refuse, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
@@ -1,12 +1,11 @@
1
1
  import { AssetsMap } from "../../onchain/utils/AssetsMap.js";
2
2
  import { BigIntMath } from "../../onchain/utils/bigint-math.js";
3
3
  import { DUST_THRESHOLD } from "../../onchain/constants/math.js";
4
- import { calcPositionLeverage } from "../../onchain/market/math.js";
5
- import { ERROR_UNPRICEABLE_TOKEN } from "../../model/previews.js";
4
+ import { ERROR_UNPRICEABLE_TOKEN, asEstimated } from "../../model/previews.js";
6
5
  import "../../model/index.js";
7
6
  import "../../onchain/index.js";
8
7
  import { isAddressEqual } from "viem";
9
- //#region src/preview/preview/buildDelayedPreview.ts
8
+ //#region src/preview/preview/buildDelayedStrategyVerify.ts
10
9
  /**
11
10
  * Builds the best-effort preview of the account state after the detected
12
11
  * delayed withdrawal is claimed and its intent (if any) is resumed:
@@ -29,7 +28,7 @@ import { isAddressEqual } from "viem";
29
28
  * @param sdk - Market data source for the position metrics of the resulting
30
29
  * state; read synchronously, no network access.
31
30
  */
32
- function buildDelayedPreview(afterInstant, before, detected, convert, receivedToken, sdk) {
31
+ function buildDelayedStrategyVerify(afterInstant, before, detected, convert, receivedToken, sdk) {
33
32
  const { request, intent } = detected;
34
33
  const post = afterInstant.clone();
35
34
  const converter = makeSafeConverter(convert);
@@ -174,41 +173,23 @@ function buildClosePreview(post, converter, receivedToken, sdk) {
174
173
  };
175
174
  }
176
175
  function buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk) {
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
+ const snap = post.toSnapshot(totalValueInUnderlying(post, converter.convert, DUST_THRESHOLD));
181
177
  const market = sdk.marketRegister.findByCreditManager(post.creditManager);
182
178
  const oracle = market.priceOracle;
183
179
  return {
184
180
  operation: "AdjustCreditAccount",
185
- creditManager: post.creditManager,
186
- name: sdk.marketRegister.findCreditManager(post.creditManager).name,
181
+ ...asEstimated(sdk.positions.projection(snap, { availableLiquidityChange: before.totalDebt - post.totalDebt })),
187
182
  creditAccount: post.creditAccount,
188
183
  collateralAdded: [],
189
184
  collateralWithdrawn: collateralWithdrawn.toAssets().map((a) => oracle.toTokenAmount(a.token, a.balance)),
190
- totalValue: market.toUnderlyingAmount(totalValue),
191
- totalDebt: market.toUnderlyingAmount(post.totalDebt),
192
- netValue: market.toUnderlyingAmount(totalValue - post.totalDebt),
193
185
  totalDebtChange: market.toUnderlyingAmount(post.totalDebt - before.totalDebt),
194
- quotas: quotas.map((q) => ({
195
- token: sdk.tokensMeta.mustGetToken(q.token),
196
- ...oracle.toAmount(market.underlying, q.balance)
197
- })),
198
186
  quotasChange: post.quotas.difference(before.quotas).toAssets().map((q) => ({
199
187
  token: sdk.tokensMeta.mustGetToken(q.token),
200
188
  ...oracle.toAmount(market.underlying, q.balance)
201
189
  })),
202
- assets: assets.map((a) => oracle.toTokenAmount(a.token, a.balance)),
203
190
  assetsChange: post.balances.difference(before.balances).toAssets(DUST_THRESHOLD).map((a) => oracle.toTokenAmount(a.token, a.balance)),
204
- error: converter.error,
205
- healthFactor: sdk.positions.healthFactor(snap),
206
- safeHealthFactor: sdk.positions.healthFactor(snap, { safePrices: true }),
207
- borrowRate: sdk.positions.borrowRate(snap, { availableLiquidityChange: before.totalDebt - post.totalDebt }),
208
- timeToLiquidation: sdk.positions.timeToLiquidation(snap, { availableLiquidityChange: before.totalDebt - post.totalDebt }),
209
- liquidationPrice: sdk.positions.liquidationPrice(snap),
210
- leverage: calcPositionLeverage(totalValue, post.totalDebt)
191
+ error: converter.error
211
192
  };
212
193
  }
213
194
  //#endregion
214
- export { buildDelayedPreview };
195
+ export { buildDelayedStrategyVerify };
@@ -1,4 +1,4 @@
1
- import { buildDelayedPreview } from "./buildDelayedPreview.js";
1
+ import { buildDelayedStrategyVerify } from "./buildDelayedStrategyVerify.js";
2
2
  import { CreditAccountState } from "./CreditAccountState.js";
3
3
  import { classifyCloseOrRepay, isCloseOrRepay } from "./detectCloseOrRepay.js";
4
4
  import { detectDelayedClaim, resolveDelayedClaimIntent } from "./detectDelayedClaim.js";
@@ -6,7 +6,7 @@ import { detectDelayedOperation } from "./detectDelayedOperation.js";
6
6
  import { UnsupportedOperationError } from "./errors.js";
7
7
  import { makeReplayState, replayInnerOperations } from "./replayInnerOperations.js";
8
8
  import { replayMulticall } from "./replayMulticall.js";
9
- import { previewAdjustCreditAccount } from "./previewAdjustCreditAccount.js";
10
- import { previewCloseOrRepayCreditAccount } from "./previewCloseOrRepayCreditAccount.js";
9
+ import { previewAdjustStrategyVerify } from "./previewAdjustStrategyVerify.js";
10
+ import { previewExitOrRepayStrategyVerify } from "./previewExitOrRepayStrategyVerify.js";
11
11
  import { previewOperation } from "./previewOperation.js";
12
- export { CreditAccountState, UnsupportedOperationError, buildDelayedPreview, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, isCloseOrRepay, makeReplayState, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
12
+ export { CreditAccountState, UnsupportedOperationError, buildDelayedStrategyVerify, classifyCloseOrRepay, detectDelayedClaim, detectDelayedOperation, isCloseOrRepay, makeReplayState, previewAdjustStrategyVerify, previewExitOrRepayStrategyVerify, previewOperation, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
@@ -1,12 +1,11 @@
1
1
  import { AP_WETH_TOKEN } from "../../onchain/constants/address-provider.js";
2
2
  import { DUST_THRESHOLD } from "../../onchain/constants/math.js";
3
- import { calcPositionLeverage } from "../../onchain/market/math.js";
4
- import { ERROR_UNPRICEABLE_TOKEN } from "../../model/previews.js";
3
+ import { ERROR_UNPRICEABLE_TOKEN, asEstimated } from "../../model/previews.js";
5
4
  import "../../model/index.js";
6
5
  import "../../onchain/index.js";
7
6
  import { replayMulticall } from "./replayMulticall.js";
8
7
  import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
9
- //#region src/preview/preview/previewAdjustCreditAccount.ts
8
+ //#region src/preview/preview/previewAdjustStrategyVerify.ts
10
9
  /**
11
10
  * Previews a `multicall`/`botMulticall` operation on an existing credit
12
11
  * account: threads the multicall through {@link replayMulticall} over the
@@ -14,7 +13,7 @@ import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
14
13
  * minimal guaranteed post-state alongside the changes relative to the
15
14
  * pre-state.
16
15
  */
17
- async function previewAdjustCreditAccount(input, operation, options) {
16
+ async function previewAdjustStrategyVerify(input, operation, options) {
18
17
  const { sdk, value = 0n } = input;
19
18
  const market = sdk.marketRegister.findByCreditManager(operation.creditManager);
20
19
  const oracle = market.priceOracle;
@@ -23,10 +22,8 @@ async function previewAdjustCreditAccount(input, operation, options) {
23
22
  let error = replayError;
24
23
  const { assets: collateralAdded, error: unwrapError } = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
25
24
  error ??= unwrapError;
26
- const assets = account.balances.toAssets(DUST_THRESHOLD);
27
- const quotas = account.quotas.toAssets(0n);
28
25
  const assetsChange = account.balances.difference(before.balances).toAssets(DUST_THRESHOLD);
29
- const totalValue = assets.reduce((acc, { token, balance }) => {
26
+ const totalValue = account.balances.toAssets(DUST_THRESHOLD).reduce((acc, { token, balance }) => {
30
27
  try {
31
28
  return acc + oracle.convert(token, market.underlying, balance);
32
29
  } catch {
@@ -40,33 +37,18 @@ async function previewAdjustCreditAccount(input, operation, options) {
40
37
  const snap = account.toSnapshot(totalValue);
41
38
  return {
42
39
  operation: "AdjustCreditAccount",
43
- creditManager: operation.creditManager,
44
- name: sdk.marketRegister.findCreditManager(operation.creditManager).name,
40
+ ...asEstimated(sdk.positions.projection(snap, { availableLiquidityChange: before.totalDebt - account.totalDebt })),
45
41
  creditAccount: operation.creditAccount,
46
42
  collateralAdded: collateralAdded.map((a) => oracle.toTokenAmount(a.token, a.balance)),
47
43
  collateralWithdrawn: after.collateralWithdrawn.toAssets().map((a) => oracle.toTokenAmount(a.token, a.balance)),
48
- totalValue: market.toUnderlyingAmount(totalValue),
49
- totalDebt: market.toUnderlyingAmount(account.totalDebt),
50
- netValue: market.toUnderlyingAmount(totalValue - account.totalDebt),
51
44
  totalDebtChange: market.toUnderlyingAmount(account.totalDebt - before.totalDebt),
52
- quotas: quotas.map((q) => ({
53
- token: sdk.tokensMeta.mustGetToken(q.token),
54
- ...oracle.toAmount(market.underlying, q.balance)
55
- })),
56
45
  quotasChange: account.quotas.difference(before.quotas).toAssets().map((q) => ({
57
46
  token: sdk.tokensMeta.mustGetToken(q.token),
58
47
  ...oracle.toAmount(market.underlying, q.balance)
59
48
  })),
60
- assets: assets.map((a) => oracle.toTokenAmount(a.token, a.balance)),
61
49
  assetsChange: assetsChange.map((a) => oracle.toTokenAmount(a.token, a.balance)),
62
- error,
63
- healthFactor: sdk.positions.healthFactor(snap),
64
- safeHealthFactor: sdk.positions.healthFactor(snap, { safePrices: true }),
65
- borrowRate: sdk.positions.borrowRate(snap, { availableLiquidityChange: before.totalDebt - account.totalDebt }),
66
- timeToLiquidation: sdk.positions.timeToLiquidation(snap, { availableLiquidityChange: before.totalDebt - account.totalDebt }),
67
- liquidationPrice: sdk.positions.liquidationPrice(snap),
68
- leverage: calcPositionLeverage(totalValue, account.totalDebt)
50
+ error
69
51
  };
70
52
  }
71
53
  //#endregion
72
- export { previewAdjustCreditAccount };
54
+ export { previewAdjustStrategyVerify };
@@ -4,8 +4,8 @@ import "../../onchain/index.js";
4
4
  import { classifyCloseOrRepay } from "./detectCloseOrRepay.js";
5
5
  import { replayMulticall } from "./replayMulticall.js";
6
6
  import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
7
- //#region src/preview/preview/previewCloseOrRepayCreditAccount.ts
8
- async function previewCloseOrRepayCreditAccount(input, operation, permanent, options) {
7
+ //#region src/preview/preview/previewExitOrRepayStrategyVerify.ts
8
+ async function previewExitOrRepayStrategyVerify(input, operation, permanent, options) {
9
9
  const { sdk } = input;
10
10
  const market = sdk.marketRegister.findByCreditManager(operation.creditManager);
11
11
  const exitTokens = [market.underlying];
@@ -62,4 +62,4 @@ function previewRepayCreditAccount(input, operation, permanent, replay) {
62
62
  };
63
63
  }
64
64
  //#endregion
65
- export { previewCloseOrRepayCreditAccount };
65
+ export { previewExitOrRepayStrategyVerify };
@@ -1,7 +1,7 @@
1
1
  import { simulatePoolOperation } from "../simulate/simulatePoolOperation.js";
2
2
  import "../simulate/index.js";
3
- //#region src/preview/preview/previewPoolOperation.ts
4
- async function previewPoolOperation(input, operation, options) {
3
+ //#region src/preview/preview/previewLpVerify.ts
4
+ async function previewLpVerify(input, operation, options) {
5
5
  const { sdk, to, calldata } = input;
6
6
  const { tokenIn, tokenOut } = operation;
7
7
  const market = sdk.marketRegister.findByPool(operation.pool);
@@ -21,4 +21,4 @@ async function previewPoolOperation(input, operation, options) {
21
21
  };
22
22
  }
23
23
  //#endregion
24
- export { previewPoolOperation };
24
+ export { previewLpVerify };