@gearbox-protocol/sdk 16.0.0-next.27 → 16.0.0-next.29

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 (75) 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/intents/open-strategy.js +5 -18
  4. package/dist/cjs/onchain/accounts/intents/realize.js +77 -49
  5. package/dist/cjs/onchain/accounts/intents/testing/market.js +1 -0
  6. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +28 -5
  7. package/dist/cjs/onchain/index.js +6 -0
  8. package/dist/cjs/onchain/market/credit/creditOperationMarket.js +32 -0
  9. package/dist/cjs/onchain/market/credit/index.js +3 -0
  10. package/dist/cjs/onchain/market/index.js +5 -0
  11. package/dist/cjs/onchain/market/oracle/collateralPriceInUnderlying.js +27 -0
  12. package/dist/cjs/onchain/market/oracle/index.js +2 -0
  13. package/dist/cjs/onchain/positions/PositionsService.js +94 -0
  14. package/dist/cjs/onchain/positions/calcLiquidationPrice.js +14 -4
  15. package/dist/cjs/onchain/positions/index.js +1 -0
  16. package/dist/cjs/preview/index.js +6 -6
  17. package/dist/cjs/preview/preview/{buildDelayedPreview.js → buildDelayedStrategyVerify.js} +8 -27
  18. package/dist/cjs/preview/preview/index.js +6 -6
  19. package/dist/cjs/preview/preview/{previewAdjustCreditAccount.js → previewAdjustStrategyVerify.js} +6 -24
  20. package/dist/cjs/preview/preview/{previewCloseOrRepayCreditAccount.js → previewExitOrRepayStrategyVerify.js} +6 -7
  21. package/dist/cjs/preview/preview/{previewPoolOperation.js → previewLpVerify.js} +3 -3
  22. package/dist/cjs/preview/preview/{previewOpenCreditAccount.js → previewOpenStrategyVerify.js} +6 -26
  23. package/dist/cjs/preview/preview/previewOperation.js +13 -12
  24. package/dist/cjs/preview/validate/checkOperation.js +13 -9
  25. package/dist/esm/model/index.js +2 -2
  26. package/dist/esm/model/previews.js +23 -1
  27. package/dist/esm/onchain/accounts/intents/open-strategy.js +5 -18
  28. package/dist/esm/onchain/accounts/intents/realize.js +77 -49
  29. package/dist/esm/onchain/accounts/intents/testing/market.js +1 -0
  30. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +27 -6
  31. package/dist/esm/onchain/index.js +4 -2
  32. package/dist/esm/onchain/market/credit/creditOperationMarket.js +30 -0
  33. package/dist/esm/onchain/market/credit/index.js +2 -1
  34. package/dist/esm/onchain/market/index.js +3 -1
  35. package/dist/esm/onchain/market/oracle/collateralPriceInUnderlying.js +26 -0
  36. package/dist/esm/onchain/market/oracle/index.js +2 -1
  37. package/dist/esm/onchain/positions/PositionsService.js +95 -1
  38. package/dist/esm/onchain/positions/calcLiquidationPrice.js +14 -5
  39. package/dist/esm/onchain/positions/index.js +2 -2
  40. package/dist/esm/preview/index.js +4 -4
  41. package/dist/esm/preview/preview/{buildDelayedPreview.js → buildDelayedStrategyVerify.js} +9 -28
  42. package/dist/esm/preview/preview/index.js +4 -4
  43. package/dist/esm/preview/preview/{previewAdjustCreditAccount.js → previewAdjustStrategyVerify.js} +7 -25
  44. package/dist/esm/preview/preview/{previewCloseOrRepayCreditAccount.js → previewExitOrRepayStrategyVerify.js} +6 -7
  45. package/dist/esm/preview/preview/{previewPoolOperation.js → previewLpVerify.js} +3 -3
  46. package/dist/esm/preview/preview/{previewOpenCreditAccount.js → previewOpenStrategyVerify.js} +7 -27
  47. package/dist/esm/preview/preview/previewOperation.js +13 -12
  48. package/dist/esm/preview/validate/checkOperation.js +13 -9
  49. package/dist/types/model/index.d.ts +2 -2
  50. package/dist/types/model/previews.d.ts +222 -97
  51. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +13 -7
  52. package/dist/types/onchain/accounts/intents/testing/market.d.ts +1 -0
  53. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +18 -0
  54. package/dist/types/onchain/accounts/intents/types.d.ts +12 -0
  55. package/dist/types/onchain/index.d.ts +4 -2
  56. package/dist/types/onchain/market/credit/creditOperationMarket.d.ts +23 -0
  57. package/dist/types/onchain/market/credit/index.d.ts +2 -1
  58. package/dist/types/onchain/market/index.d.ts +3 -1
  59. package/dist/types/onchain/market/oracle/collateralPriceInUnderlying.d.ts +19 -0
  60. package/dist/types/onchain/market/oracle/index.d.ts +2 -1
  61. package/dist/types/onchain/positions/PositionsService.d.ts +38 -0
  62. package/dist/types/onchain/positions/calcLiquidationPrice.d.ts +10 -1
  63. package/dist/types/onchain/positions/index.d.ts +2 -2
  64. package/dist/types/preview/index.d.ts +5 -5
  65. package/dist/types/preview/preview/{buildDelayedPreview.d.ts → buildDelayedStrategyVerify.d.ts} +4 -4
  66. package/dist/types/preview/preview/index.d.ts +4 -4
  67. package/dist/types/preview/preview/{previewAdjustCreditAccount.d.ts → previewAdjustStrategyVerify.d.ts} +4 -4
  68. package/dist/types/preview/preview/{previewCloseOrRepayCreditAccount.d.ts → previewExitOrRepayStrategyVerify.d.ts} +4 -4
  69. package/dist/types/preview/preview/previewLpVerify.d.ts +11 -0
  70. package/dist/types/preview/preview/previewOpenStrategyVerify.d.ts +12 -0
  71. package/dist/types/preview/validate/checkOperation.d.ts +12 -4
  72. package/dist/types/preview/validate/index.d.ts +2 -2
  73. package/package.json +1 -1
  74. package/dist/types/preview/preview/previewOpenCreditAccount.d.ts +0 -12
  75. package/dist/types/preview/preview/previewPoolOperation.d.ts +0 -11
@@ -15,8 +15,8 @@ import { matchesOpportunityFilter, opportunityId, poolOpportunityId, strategyOpp
15
15
  import { apyBreakdownSchema, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pointRewardsSchema, pointsProgramSchema, poolOpportunityDetailSchema, poolOpportunityKeySchema, poolOpportunitySchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, rewardsSchema, strategyOpportunityDetailSchema, strategyOpportunityKeySchema, strategyOpportunitySchema, tokenRewardsSchema } from "./opportunities.schema.js";
16
16
  import { STRATEGY_POSITION_COLLATERAL_ERROR, liquidationPositionId, matchesPositionFilter, poolPositionId, positionId, strategyPositionId } from "./positions.js";
17
17
  import { borrowRateBreakdownSchema, pnlBreakdownSchema, pointsProgramPnLSchema, pointsRewardsPnLSchema, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, rewardsPnLSchema, strategyPositionKeySchema, strategyPositionSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema } from "./positions.schema.js";
18
- import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL } from "./previews.js";
18
+ import { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, asEstimated } from "./previews.js";
19
19
  import "./primitives.js";
20
20
  import "./response.js";
21
21
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
22
- export { CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, FILTER_ALL, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, amountSchema, apyBreakdownSchema, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
22
+ export { CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, FILTER_ALL, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, amountSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema };
@@ -32,5 +32,27 @@ const ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL = 1005;
32
32
  const ERROR_INVALID_TRANSACTION_VALUE = 1006;
33
33
  /** A token in the preview could not be priced by the oracle */
34
34
  const ERROR_UNPRICEABLE_TOKEN = 2001;
35
+ /**
36
+ * Renames a projection's routed fields, for a caller that built one from floor
37
+ * balances.
38
+ *
39
+ * Lives beside the type so the two cannot drift: a field added to
40
+ * {@link RoutedField} fails to compile until it is renamed here too.
41
+ **/
42
+ function asEstimated(p) {
43
+ const { totalValue, netValue, assets, healthFactor, safeHealthFactor, borrowRate, timeToLiquidation, liquidationPrice, leverage, ...settled } = p;
44
+ return {
45
+ ...settled,
46
+ estTotalValue: totalValue,
47
+ estNetValue: netValue,
48
+ estAssets: assets,
49
+ estHealthFactor: healthFactor,
50
+ estSafeHealthFactor: safeHealthFactor,
51
+ estBorrowRate: borrowRate,
52
+ estTimeToLiquidation: timeToLiquidation,
53
+ estLiquidationPrice: liquidationPrice,
54
+ estLeverage: leverage
55
+ };
56
+ }
35
57
  //#endregion
36
- export { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL };
58
+ export { ERROR_ADAPTER_CALL_OUTSIDE_BRACKET, ERROR_INVALID_TRANSACTION_VALUE, ERROR_MALFORMED_BRACKET, ERROR_NON_ADAPTER_CALL_IN_BRACKET, ERROR_UNPREVIEWABLE_ADAPTER_CALL, ERROR_UNPRICEABLE_TOKEN, ERROR_UNSUPPORTED_OUT_OF_BRACKET_CALL, asEstimated };
@@ -1,4 +1,3 @@
1
- import { calcPositionLeverage } from "../../market/math.js";
2
1
  import { IntentPreviewError } from "../../validation/refusal.js";
3
2
  import { assertCanBorrow, assertCollateralised, assertGrowthAllowed, assertMarketOperable, assertQuotaHeadroom } from "./guards.js";
4
3
  import { assertDebtInBand, assertLeverageAtLeastOne, debtForLeverage } from "./math.js";
@@ -85,34 +84,22 @@ async function previewOpenStrategy(props) {
85
84
  totalDebt: debt,
86
85
  totalValue: margin + debt
87
86
  };
88
- const projectedPool = { availableLiquidityChange: -debt };
89
- const metrics = {
90
- healthFactor: sdk.positions.healthFactor(snapshot),
91
- safeHealthFactor: sdk.positions.healthFactor(snapshot, { safePrices: true }),
92
- borrowRate: sdk.positions.borrowRate(snapshot, projectedPool),
93
- timeToLiquidation: sdk.positions.timeToLiquidation(snapshot, projectedPool),
94
- liquidationPrice: sdk.positions.liquidationPrice(snapshot)
95
- };
96
- assertCollateralised(metrics.healthFactor, false);
87
+ const { assets: _assets, quotas: _quotas, ...projection } = sdk.positions.projection(snapshot, { availableLiquidityChange: -debt });
88
+ assertCollateralised(projection.healthFactor, false);
97
89
  const priceImpact = await collectPriceImpact(leg.probe ? [leg.probe] : [], {
98
90
  totalValue: margin + debt,
99
91
  netValue: margin,
100
92
  toUnderlying: (from, amount) => convert(from, underlying, amount)
101
93
  });
102
94
  return {
103
- creditManager,
104
- name: suite.name,
105
- totalDebt: market.toUnderlyingAmount(debt),
106
- netValue: market.toUnderlyingAmount(margin),
107
- totalValue: market.toUnderlyingAmount(margin + debt),
108
- leverage: calcPositionLeverage(margin + debt, debt),
95
+ ...projection,
96
+ currentPrice: sdk.positions.currentPrice(snapshot),
109
97
  priceImpact,
110
98
  averageAssets: averageAssets.map(priced),
111
99
  minAssets: minAssets.map(priced),
112
100
  averageQuota,
113
101
  minQuota,
114
- calls: [...leg.calls],
115
- ...metrics
102
+ calls: [...leg.calls]
116
103
  };
117
104
  }
118
105
  /** Collateral plus the borrowed underlying, folded into one balance per token. */
@@ -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,29 @@ 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
- })),
328
+ ...projection,
301
329
  priceImpact,
302
- ...metrics
330
+ currentPrice: sdk.positions.currentPrice(snapshot)
303
331
  };
304
332
  return {
305
333
  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,
@@ -13,6 +13,17 @@ import { vi } from "vitest";
13
13
  * from their inputs, so `result.calls` pins down which ops reached the
14
14
  * assembler and in which order.
15
15
  */
16
+ /** Market configurator the mock market is governed by — the curator's address. */
17
+ const MOCK_MARKET_CONFIGURATOR = "0x00000000000000000000000000000000000c0f16";
18
+ /**
19
+ * Liquidation fees of the mock suite: a 3% premium (the manager reports its
20
+ * complement) on top of a 1.5% protocol fee, so the discount a screen shows is
21
+ * 450bps.
22
+ */
23
+ const MOCK_LIQUIDATION_FEES = {
24
+ feeLiquidation: 150,
25
+ liquidationDiscount: 9700
26
+ };
16
27
  /** Recognizable router call embedded in routed leg results. */
17
28
  const MOCK_ROUTER_CALL = {
18
29
  target: "0x9999999999999999999999999999999999999999",
@@ -155,6 +166,8 @@ function buildMockSdk(args) {
155
166
  };
156
167
  const market = {
157
168
  toUnderlyingAmount,
169
+ /** {@inheritDoc MarketSuite.underlying} */
170
+ underlying: args.underlying,
158
171
  priceOracle: {
159
172
  convert,
160
173
  safeConvert,
@@ -204,6 +217,8 @@ function buildMockSdk(args) {
204
217
  const expirationDate = args.expirationDate ?? 0;
205
218
  const creditManagerSuite = {
206
219
  name: "TestCreditManager",
220
+ marketConfigurator: { address: MOCK_MARKET_CONFIGURATOR },
221
+ liquidationFees: () => MOCK_LIQUIDATION_FEES,
207
222
  creditManager: {
208
223
  address: args.creditManager,
209
224
  liquidationThresholds,
@@ -238,10 +253,12 @@ function buildMockSdk(args) {
238
253
  };
239
254
  /** Linear unless the case says otherwise — see `routeQuote`. */
240
255
  const quote = args.routeQuote ?? ((amount) => amount);
256
+ /** Slippage-free unless the case says otherwise — see `routeFloor`. */
257
+ const floor = args.routeFloor ?? ((amount) => amount);
241
258
  const router = {
242
259
  findOneTokenPath: vi.fn(async ({ amount, tokenIn, tokenOut }) => ({
243
260
  amount: quote(amount),
244
- minAmount: quote(amount),
261
+ minAmount: floor(quote(amount)),
245
262
  calls: routeCalls(tokenIn, tokenOut)
246
263
  })),
247
264
  findManyToOnePath: vi.fn(async ({ expectedBalances, leftoverBalances, target }) => {
@@ -249,7 +266,7 @@ function buildMockSdk(args) {
249
266
  const tokenIn = expectedBalances[0]?.token ?? target;
250
267
  return {
251
268
  amount: quote(spent),
252
- minAmount: quote(spent),
269
+ minAmount: floor(quote(spent)),
253
270
  calls: routeCalls(tokenIn, target)
254
271
  };
255
272
  }),
@@ -270,11 +287,15 @@ function buildMockSdk(args) {
270
287
  amount += convert(token, targetLc, spend);
271
288
  }
272
289
  balances[targetLc] = (balances[targetLc] ?? 0n) + amount;
290
+ const untouched = (balances[targetLc] ?? 0n) - amount;
273
291
  return {
274
292
  amount,
275
- minAmount: amount,
293
+ minAmount: floor(amount),
276
294
  balances,
277
- minBalances: { ...balances },
295
+ minBalances: {
296
+ ...balances,
297
+ [targetLc]: untouched + floor(amount)
298
+ },
278
299
  calls: [MOCK_ROUTER_CALL]
279
300
  };
280
301
  }),
@@ -284,7 +305,7 @@ function buildMockSdk(args) {
284
305
  const amount = sold.reduce((acc, a) => acc + convert(a.token, underlying, a.balance), 0n);
285
306
  return {
286
307
  amount,
287
- minAmount: amount,
308
+ minAmount: floor(amount),
288
309
  underlyingBalance: amount,
289
310
  calls: sold.length === 0 ? [] : [MOCK_CLOSE_CALL]
290
311
  };
@@ -380,4 +401,4 @@ function payloadOf(slice) {
380
401
  };
381
402
  }
382
403
  //#endregion
383
- export { CA_OP_CALLS, MOCK_CLAIM_CALL, MOCK_CLOSE_CALL, MOCK_REQUEST_CALL, MOCK_ROUTER_CALL, MOCK_RWA_UNWRAP_CALL, MOCK_RWA_WRAP_CALL, buildMockSdk };
404
+ export { CA_OP_CALLS, MOCK_CLAIM_CALL, MOCK_CLOSE_CALL, MOCK_LIQUIDATION_FEES, MOCK_MARKET_CONFIGURATOR, MOCK_REQUEST_CALL, MOCK_ROUTER_CALL, MOCK_RWA_UNWRAP_CALL, MOCK_RWA_WRAP_CALL, buildMockSdk };
@@ -138,6 +138,7 @@ import { CreditManagerV310Contract } from "./market/credit/CreditManagerV310Cont
138
138
  import { strategyName } from "./market/strategyName.js";
139
139
  import { dominantCollateral, isStrategyCollateral, pickStrategyTargetCollateral } from "./market/credit/collateralUtils.js";
140
140
  import { CreditSuite } from "./market/credit/CreditSuite.js";
141
+ import { creditOperationMarket, totalLiquidationDiscount } from "./market/credit/creditOperationMarket.js";
141
142
  import { expectedBalanceDeltas } from "./market/credit/expectedBalanceDeltas.js";
142
143
  import { simulateMulticall } from "./utils/viem/simulateMulticall.js";
143
144
  import { SimulateWithPriceUpdatesError, getSimulateWithPriceUpdatesError, simulateWithPriceUpdates } from "./utils/viem/simulateWithPriceUpdates.js";
@@ -145,6 +146,7 @@ import { executeDelegatedMulticalls } from "./utils/viem/executeDelegatedMultica
145
146
  import { estimateRawTxGas, sendRawTx } from "./utils/viem/sendRawTx.js";
146
147
  import { watchBlocksAsync } from "./utils/viem/watchBlocksAsync.js";
147
148
  import "./utils/viem/index.js";
149
+ import { collateralPriceInUnderlying } from "./market/oracle/collateralPriceInUnderlying.js";
148
150
  import { isUpdatablePriceFeed } from "./market/pricefeeds/isUpdatablePriceFeed.js";
149
151
  import { PriceFeedRef } from "./market/pricefeeds/PriceFeedRef.js";
150
152
  import { AbstractPriceFeedContract, PartialPriceFeedInitError } from "./market/pricefeeds/AbstractPriceFeed.js";
@@ -230,7 +232,7 @@ import "./pools/index.js";
230
232
  import { calcBorrowRate } from "./positions/calcBorrowRate.js";
231
233
  import { calcHealthFactor } from "./positions/calcHealthFactor.js";
232
234
  import { calcLiquidationPriceForTarget } from "./positions/calcLiquidationPriceForTarget.js";
233
- import { calcLiquidationPrice } from "./positions/calcLiquidationPrice.js";
235
+ import { calcLiquidationPrice, soleNonUnderlyingCollateral } from "./positions/calcLiquidationPrice.js";
234
236
  import { calcTimeToLiquidationMs } from "./positions/calcTimeToLiquidationMs.js";
235
237
  import { MultichainPositionsService } from "./positions/MultichainPositionsService.js";
236
238
  import { accountSnapshotFromCreditAccountData } from "./positions/types.js";
@@ -245,4 +247,4 @@ import { MultichainSDK } from "./MultichainSDK.js";
245
247
  import { attachOptionsSchema, onchainSDKOptionsSchema } from "./options.js";
246
248
  import "./types/index.js";
247
249
  import "./validation/index.js";
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 };
250
+ 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, collateralPriceInUnderlying, collectTraces, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, creditOperationMarket, 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, soleNonUnderlyingCollateral, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toShares, toSharesUp, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, totalLiquidationDiscount, usdToNumber, watchBlocksAsync };
@@ -0,0 +1,30 @@
1
+ import { PERCENTAGE_FACTOR } from "../../constants/math.js";
2
+ //#region src/onchain/market/credit/creditOperationMarket.ts
3
+ /**
4
+ * What a liquidation takes off an account, in basis points: the premium the
5
+ * liquidator keeps plus the protocol's own fee, with the suite's expiration
6
+ * already resolved.
7
+ *
8
+ * Not {@link LiquidationFees.liquidationDiscount}, which is the complement of
9
+ * the premium alone (`100% - liquidationPremium`) and says what share of the
10
+ * seized collateral repays the debt.
11
+ **/
12
+ function totalLiquidationDiscount(suite) {
13
+ const { feeLiquidation, liquidationDiscount } = suite.liquidationFees();
14
+ return Number(PERCENTAGE_FACTOR) - liquidationDiscount + feeLiquidation;
15
+ }
16
+ /**
17
+ * The market half of every credit operation result, read off the suite that
18
+ * serves it. Spread into a preview or a projection so the four fields are
19
+ * filled in one place and cannot drift apart between the two halves of the SDK.
20
+ **/
21
+ function creditOperationMarket(suite) {
22
+ return {
23
+ creditManager: suite.creditManager.address,
24
+ name: suite.name,
25
+ curator: suite.marketConfigurator.address,
26
+ liquidationDiscount: totalLiquidationDiscount(suite)
27
+ };
28
+ }
29
+ //#endregion
30
+ export { creditOperationMarket, totalLiquidationDiscount };
@@ -4,6 +4,7 @@ import { CreditFacadeV310Contract } from "./CreditFacadeV310Contract.js";
4
4
  import { CreditManagerV310Contract } from "./CreditManagerV310Contract.js";
5
5
  import { dominantCollateral, isStrategyCollateral, pickStrategyTargetCollateral } from "./collateralUtils.js";
6
6
  import { CreditSuite } from "./CreditSuite.js";
7
+ import { creditOperationMarket, totalLiquidationDiscount } from "./creditOperationMarket.js";
7
8
  import { expectedBalanceDeltas } from "./expectedBalanceDeltas.js";
8
9
  import "./types.js";
9
- export { CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, abi as creditFacadeV310Abi, dominantCollateral, expectedBalanceDeltas, isStrategyCollateral, pickStrategyTargetCollateral };
10
+ export { CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, abi as creditFacadeV310Abi, creditOperationMarket, dominantCollateral, expectedBalanceDeltas, isStrategyCollateral, pickStrategyTargetCollateral, totalLiquidationDiscount };
@@ -92,8 +92,10 @@ import { CreditManagerV310Contract } from "./credit/CreditManagerV310Contract.js
92
92
  import { strategyName } from "./strategyName.js";
93
93
  import { dominantCollateral, isStrategyCollateral, pickStrategyTargetCollateral } from "./credit/collateralUtils.js";
94
94
  import { CreditSuite } from "./credit/CreditSuite.js";
95
+ import { creditOperationMarket, totalLiquidationDiscount } from "./credit/creditOperationMarket.js";
95
96
  import { expectedBalanceDeltas } from "./credit/expectedBalanceDeltas.js";
96
97
  import "./credit/index.js";
98
+ import { collateralPriceInUnderlying } from "./oracle/collateralPriceInUnderlying.js";
97
99
  import { isUpdatablePriceFeed } from "./pricefeeds/isUpdatablePriceFeed.js";
98
100
  import { PriceFeedRef } from "./pricefeeds/PriceFeedRef.js";
99
101
  import { AbstractPriceFeedContract, PartialPriceFeedInitError } from "./pricefeeds/AbstractPriceFeed.js";
@@ -144,4 +146,4 @@ import { RWARegistry } from "./rwa/RWARegistry.js";
144
146
  import { RWA_FACTORY_TYPES, isRWAFactory } from "./rwa/types.js";
145
147
  import "./rwa/index.js";
146
148
  import "./types.js";
147
- export { AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AccountMigratorAdapterContract, AdapterType, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BoundedPriceFeedContract, CamelotV3AdapterContract, CompositePriceFeedContract, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LidoV1AdapterContract, LinearInterestRateModelContract, MAX_LEVERAGE_BUFFER_BPS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, PARTIAL_LIQUIDATION_BUFFER_BPS, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PoolSuite, PoolV310Contract, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RedstonePriceFeedContract, SECURITIZE_REGISTER_VAULT_TYPES, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, StakingRewardsAdapterContract, TraderJoePoolVersion, TraderJoeRouterAdapterContract, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UnsupportedZapperFunctionError, UpshiftVaultAdapterContract, VelodromeV2RouterAdapterContract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, bpsToRay, calcBorrowApy, calcEffectiveBorrowApy, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcUtilization, calcUtilizationRaw, classifyCurveOperation, createAdapter, createPriceOracle, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, dominantCollateral, erc4626ReferralAdapterAbi, expectedBalanceDeltas, fetchRedstonePayloads, fnSigToName, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getRawPriceUpdates, hasAdapterDeployParamsAbi, healthFactorBps, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, 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, isLPPriceFeed, isRWAFactory, isStrategyCollateral, isUpdatablePriceFeed, iwstETHAbi, iwstEthv1AdapterAbi, lidoV1_WETHGatewayAbi, mellowDvvAdapterAbi, minSeizedAmount, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parsePosNegAmount, pickStrategyTargetCollateral, rayToBps, rewardsFromTransfers, strategyName, swapFromTransfers, toNetTransfers, usdToNumber };
149
+ export { AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AccountMigratorAdapterContract, AdapterType, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BoundedPriceFeedContract, CamelotV3AdapterContract, CompositePriceFeedContract, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LidoV1AdapterContract, LinearInterestRateModelContract, MAX_LEVERAGE_BUFFER_BPS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, PARTIAL_LIQUIDATION_BUFFER_BPS, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PoolSuite, PoolV310Contract, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RedstonePriceFeedContract, SECURITIZE_REGISTER_VAULT_TYPES, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, StakingRewardsAdapterContract, TraderJoePoolVersion, TraderJoeRouterAdapterContract, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UnsupportedZapperFunctionError, UpshiftVaultAdapterContract, VelodromeV2RouterAdapterContract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, bpsToRay, calcBorrowApy, calcEffectiveBorrowApy, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcUtilization, calcUtilizationRaw, classifyCurveOperation, collateralPriceInUnderlying, createAdapter, createPriceOracle, createZapper, abi as creditFacadeV310Abi, creditOperationMarket, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, dominantCollateral, erc4626ReferralAdapterAbi, expectedBalanceDeltas, fetchRedstonePayloads, fnSigToName, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getRawPriceUpdates, hasAdapterDeployParamsAbi, healthFactorBps, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, 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, isLPPriceFeed, isRWAFactory, isStrategyCollateral, isUpdatablePriceFeed, iwstETHAbi, iwstEthv1AdapterAbi, lidoV1_WETHGatewayAbi, mellowDvvAdapterAbi, minSeizedAmount, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parsePosNegAmount, pickStrategyTargetCollateral, rayToBps, rewardsFromTransfers, strategyName, swapFromTransfers, toNetTransfers, totalLiquidationDiscount, usdToNumber };
@@ -0,0 +1,26 @@
1
+ import { PRICE_DECIMALS } from "../../constants/math.js";
2
+ //#region src/onchain/market/oracle/collateralPriceInUnderlying.ts
3
+ /**
4
+ * What one unit of `collateral` costs in `underlying` right now, in the
5
+ * oracle's 8-decimal (`PRICE_DECIMALS`) fixed point — the scale and the
6
+ * denomination `calcLiquidationPrice` answers in, so the two figures are read
7
+ * as a pair.
8
+ *
9
+ * Both sides come from the oracle's **main** feeds: this is the price the
10
+ * market quotes, not the conservative one a hand-over is weighed at.
11
+ *
12
+ * `null` when the oracle cannot answer for either token, or prices the
13
+ * underlying at zero — a screen shows a gap rather than a number derived from
14
+ * a missing feed.
15
+ **/
16
+ function collateralPriceInUnderlying(oracle, collateral, underlying) {
17
+ try {
18
+ const underlyingPrice = oracle.mainPrice(underlying);
19
+ if (underlyingPrice <= 0n) return null;
20
+ return oracle.mainPrice(collateral) * PRICE_DECIMALS / underlyingPrice;
21
+ } catch {
22
+ return null;
23
+ }
24
+ }
25
+ //#endregion
26
+ export { collateralPriceInUnderlying };
@@ -1,4 +1,5 @@
1
+ import { collateralPriceInUnderlying } from "./collateralPriceInUnderlying.js";
1
2
  import { PriceOracleV310Contract } from "./PriceOracleV310Contract.js";
2
3
  import { createPriceOracle } from "./createPriceOracle.js";
3
4
  import "./types.js";
4
- export { PriceOracleV310Contract, createPriceOracle };
5
+ export { PriceOracleV310Contract, collateralPriceInUnderlying, createPriceOracle };