@gearbox-protocol/sdk 16.0.0-next.22 → 16.0.0-next.24

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 (83) hide show
  1. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +2 -2
  2. package/dist/cjs/onchain/accounts/intents/open-strategy.js +9 -4
  3. package/dist/cjs/onchain/accounts/intents/realize.js +13 -6
  4. package/dist/cjs/onchain/accounts/intents/tail.js +3 -2
  5. package/dist/cjs/onchain/accounts/intents/testing/market.js +1 -1
  6. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +19 -1
  7. package/dist/cjs/onchain/accounts/intents/tests/add-collateral.fixtures.js +4 -4
  8. package/dist/cjs/onchain/accounts/intents/tests/adjust-leverage.fixtures.js +15 -15
  9. package/dist/cjs/onchain/accounts/intents/tests/deposit.fixtures.js +13 -13
  10. package/dist/cjs/onchain/accounts/intents/tests/finish-decrease-leverage.fixtures.js +2 -2
  11. package/dist/cjs/onchain/accounts/intents/tests/finish-withdraw.fixtures.js +2 -2
  12. package/dist/cjs/onchain/accounts/intents/tests/withdraw-asset.fixtures.js +4 -4
  13. package/dist/cjs/onchain/accounts/intents/tests/withdraw.fixtures.js +7 -7
  14. package/dist/cjs/onchain/accounts/intents/utils/adjust-state-to-snapshot.js +8 -5
  15. package/dist/cjs/onchain/accounts/intents/utils/common.js +2 -2
  16. package/dist/cjs/onchain/accounts/intents/utils/credit-account-slice.js +4 -4
  17. package/dist/cjs/onchain/accounts/intents/view.js +2 -2
  18. package/dist/cjs/onchain/market/MarketSuite.js +15 -0
  19. package/dist/cjs/onchain/market/math.js +6 -2
  20. package/dist/cjs/onchain/pools/PoolService.js +25 -29
  21. package/dist/cjs/preview/index.js +3 -1
  22. package/dist/cjs/preview/preview/buildDelayedPreview.js +5 -4
  23. package/dist/cjs/preview/preview/previewAdjustCreditAccount.js +4 -3
  24. package/dist/cjs/preview/preview/previewCloseOrRepayCreditAccount.js +1 -1
  25. package/dist/cjs/preview/preview/previewOpenCreditAccount.js +7 -7
  26. package/dist/cjs/preview/validate/checkOperation.js +47 -37
  27. package/dist/cjs/preview/validate/checkSimulation.js +5 -18
  28. package/dist/cjs/preview/validate/index.js +3 -1
  29. package/dist/cjs/sdk/execute/ExecuteApi.js +9 -6
  30. package/dist/cjs/sdk/prepare/PrepareApi.js +4 -1
  31. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +2 -2
  32. package/dist/esm/onchain/accounts/intents/open-strategy.js +9 -4
  33. package/dist/esm/onchain/accounts/intents/realize.js +13 -6
  34. package/dist/esm/onchain/accounts/intents/tail.js +3 -2
  35. package/dist/esm/onchain/accounts/intents/testing/market.js +1 -1
  36. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +19 -1
  37. package/dist/esm/onchain/accounts/intents/tests/add-collateral.fixtures.js +4 -4
  38. package/dist/esm/onchain/accounts/intents/tests/adjust-leverage.fixtures.js +15 -15
  39. package/dist/esm/onchain/accounts/intents/tests/deposit.fixtures.js +13 -13
  40. package/dist/esm/onchain/accounts/intents/tests/finish-decrease-leverage.fixtures.js +2 -2
  41. package/dist/esm/onchain/accounts/intents/tests/finish-withdraw.fixtures.js +2 -2
  42. package/dist/esm/onchain/accounts/intents/tests/withdraw-asset.fixtures.js +4 -4
  43. package/dist/esm/onchain/accounts/intents/tests/withdraw.fixtures.js +7 -7
  44. package/dist/esm/onchain/accounts/intents/utils/adjust-state-to-snapshot.js +8 -5
  45. package/dist/esm/onchain/accounts/intents/utils/common.js +2 -2
  46. package/dist/esm/onchain/accounts/intents/utils/credit-account-slice.js +4 -4
  47. package/dist/esm/onchain/accounts/intents/view.js +2 -2
  48. package/dist/esm/onchain/market/MarketSuite.js +15 -0
  49. package/dist/esm/onchain/market/math.js +6 -2
  50. package/dist/esm/onchain/pools/PoolService.js +25 -29
  51. package/dist/esm/preview/index.js +2 -2
  52. package/dist/esm/preview/preview/buildDelayedPreview.js +5 -4
  53. package/dist/esm/preview/preview/previewAdjustCreditAccount.js +4 -3
  54. package/dist/esm/preview/preview/previewCloseOrRepayCreditAccount.js +1 -1
  55. package/dist/esm/preview/preview/previewOpenCreditAccount.js +7 -7
  56. package/dist/esm/preview/validate/checkOperation.js +45 -37
  57. package/dist/esm/preview/validate/checkSimulation.js +7 -20
  58. package/dist/esm/preview/validate/index.js +2 -2
  59. package/dist/esm/sdk/execute/ExecuteApi.js +9 -6
  60. package/dist/esm/sdk/prepare/PrepareApi.js +4 -1
  61. package/dist/types/model/index.d.ts +2 -2
  62. package/dist/types/model/previews.d.ts +71 -125
  63. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +13 -29
  64. package/dist/types/onchain/accounts/intents/testing/expect.d.ts +6 -2
  65. package/dist/types/onchain/accounts/intents/testing/market.d.ts +1 -1
  66. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +1 -1
  67. package/dist/types/onchain/accounts/intents/tests/add-collateral.fixtures.d.ts +1 -1
  68. package/dist/types/onchain/accounts/intents/tests/adjust-leverage.fixtures.d.ts +2 -2
  69. package/dist/types/onchain/accounts/intents/tests/deposit.fixtures.d.ts +2 -2
  70. package/dist/types/onchain/accounts/intents/tests/withdraw-asset.fixtures.d.ts +1 -1
  71. package/dist/types/onchain/accounts/intents/tests/withdraw.fixtures.d.ts +2 -2
  72. package/dist/types/onchain/accounts/intents/types.d.ts +8 -59
  73. package/dist/types/onchain/accounts/intents/utils/adjust-state-to-snapshot.d.ts +2 -2
  74. package/dist/types/onchain/accounts/intents/utils/credit-account-slice.d.ts +3 -3
  75. package/dist/types/onchain/market/MarketSuite.d.ts +13 -1
  76. package/dist/types/onchain/market/math.d.ts +5 -1
  77. package/dist/types/onchain/pools/types.d.ts +6 -4
  78. package/dist/types/preview/index.d.ts +2 -2
  79. package/dist/types/preview/preview/buildDelayedPreview.d.ts +1 -1
  80. package/dist/types/preview/validate/checkOperation.d.ts +24 -7
  81. package/dist/types/preview/validate/checkSimulation.d.ts +0 -2
  82. package/dist/types/preview/validate/index.d.ts +2 -2
  83. package/package.json +1 -1
@@ -30,7 +30,7 @@ function checkOperation(input, options = {}) {
30
30
  case "RWAOpenCreditAccount":
31
31
  case "AdjustCreditAccount": return creditIssues(sdk, preview, options);
32
32
  case "CloseCreditAccount":
33
- case "RepayCreditAccount": return marketIssues(sdk, preview.creditManager);
33
+ case "RepayCreditAccount": return marketIssues(sdk.marketRegister.findCreditManager(preview.creditManager));
34
34
  }
35
35
  }
36
36
  function poolIssues(sdk, preview, options, isDeposit) {
@@ -49,8 +49,8 @@ function poolIssues(sdk, preview, options, isDeposit) {
49
49
  })) || fundingIssue(options, [preview.tokenIn]);
50
50
  }
51
51
  /** What the market itself refuses, whatever the operation does. */
52
- function marketIssues(sdk, creditManager) {
53
- const suite = sdk.marketRegister.findCreditManager(creditManager);
52
+ function marketIssues(suite) {
53
+ const creditManager = suite.creditManager.address;
54
54
  return checkCreditManagerPaused({
55
55
  isPaused: suite.isPaused,
56
56
  creditManager
@@ -65,29 +65,42 @@ function creditIssues(sdk, preview, options) {
65
65
  const market = suite.market;
66
66
  const underlying = toToken(sdk, market.pool.underlying);
67
67
  const isOpening = preview.operation === "OpenCreditAccount" || preview.operation === "RWAOpenCreditAccount";
68
- return marketIssues(sdk, preview.creditManager) || checkDebtInBand({
69
- debt: preview.debt,
68
+ return marketIssues(suite) || checkDebtInBand({
69
+ debt: preview.totalDebt.value,
70
70
  minDebt: suite.creditFacade.minDebt,
71
71
  maxDebt: suite.creditFacade.maxDebt,
72
72
  underlying,
73
73
  allowZero: !isOpening
74
- }) || borrowIssue(suite, preview, underlying) || forbiddenIssue(suite, preview) || checkQuotaCount({
75
- count: preview.quotas.filter((q) => q.value > 0n).length,
74
+ }) || borrowIssue(suite, preview, underlying) || forbiddenIssue(suite, preview) || quotaCountIssue(suite, preview) || quotaIssue(market, preview, underlying) || collateralIssue(preview, options) || fundingIssue(options, preview.collateralAdded);
75
+ }
76
+ /**
77
+ * A bar that reads nothing but the projected account, so a parsed transaction
78
+ * and a simulated one are held to it by the same code.
79
+ *
80
+ * These stay separate functions rather than one block because the order the
81
+ * checks run in is the answer: `checkOperation` interleaves the checks that
82
+ * need an operation's *delta* between them, and the caller acts on the first
83
+ * issue reported.
84
+ */
85
+ function quotaCountIssue(suite, projection) {
86
+ return checkQuotaCount({
87
+ count: projection.quotas.filter((q) => q.value > 0n).length,
76
88
  max: suite.creditManager.maxEnabledTokens
77
- }) || quotaIssue(market, preview, underlying) || (preview.debt === 0n ? null : collateralIssue(preview, options)) || fundingIssue(options, collateralOf(preview));
89
+ });
78
90
  }
79
91
  /**
80
92
  * What the transaction draws, against what the market can lend right now.
81
93
  *
82
94
  * Only a draw is weighed: repaying, or leaving the debt alone, can never exceed
83
- * a ceiling. Opening borrows the whole debt; adjusting borrows `debtChange`.
95
+ * a ceiling. Opening borrows the whole debt; adjusting borrows
96
+ * `totalDebtChange`.
84
97
  *
85
98
  * The engine holds every simulation to this already (`assertCanBorrow`), so
86
99
  * this is here for the transactions it never saw — a pasted calldata reaches
87
100
  * the confirm screen with nothing else standing between it and a revert.
88
101
  */
89
102
  function borrowIssue(suite, preview, underlying) {
90
- const drawn = preview.operation === "AdjustCreditAccount" ? preview.debtChange : preview.debt;
103
+ const drawn = preview.operation === "AdjustCreditAccount" ? preview.totalDebtChange.value : preview.totalDebt.value;
91
104
  if (drawn <= 0n) return null;
92
105
  const { limit, binding } = borrowable(suite);
93
106
  return checkBorrowLimit({
@@ -97,12 +110,27 @@ function borrowIssue(suite, preview, underlying) {
97
110
  underlying
98
111
  });
99
112
  }
100
- /** The account against whichever bars the caller holds it to. */
101
- function collateralIssue(preview, options) {
102
- return collateralIssuesOf({
103
- healthFactor: preview.healthFactor,
104
- safeHealthFactor: preview.safeHealthFactor
105
- }, options);
113
+ /**
114
+ * The account against whichever bars the caller holds it to.
115
+ *
116
+ * A loan-free account is nothing to weigh: the health factor reports its
117
+ * zero-debt sentinel and no bar applies.
118
+ *
119
+ * {@inheritDoc quotaCountIssue}
120
+ */
121
+ function collateralIssue(projection, options) {
122
+ const { minHealthFactor, minSafeHealthFactor, currentHealthFactor } = options;
123
+ if (projection.totalDebt.value === 0n) return null;
124
+ return (minHealthFactor === void 0 ? null : checkCollateralised({
125
+ healthFactor: projection.healthFactor,
126
+ required: minHealthFactor,
127
+ safePrices: false,
128
+ improvesFrom: currentHealthFactor
129
+ })) || (minSafeHealthFactor === void 0 || projection.safeHealthFactor === void 0 ? null : checkCollateralised({
130
+ healthFactor: projection.safeHealthFactor,
131
+ required: minSafeHealthFactor,
132
+ safePrices: true
133
+ }));
106
134
  }
107
135
  /** The wallet's side of the operation, against the balances it was given. */
108
136
  function fundingIssue(options, puts) {
@@ -118,12 +146,6 @@ function fundingIssue(options, puts) {
118
146
  }
119
147
  return null;
120
148
  }
121
- /** What the wallet puts in, which is what its balances have to cover. */
122
- function collateralOf(preview) {
123
- if ("collateral" in preview) return preview.collateral;
124
- if ("collateralAdded" in preview) return preview.collateralAdded;
125
- return [];
126
- }
127
149
  function forbiddenIssue(suite, preview) {
128
150
  const obtained = preview.operation === "AdjustCreditAccount" ? preview.assetsChange : preview.assets;
129
151
  const forbidden = suite.forbiddenTokens;
@@ -153,19 +175,5 @@ function quotaIssue(market, preview, underlying) {
153
175
  }
154
176
  return null;
155
177
  }
156
- /** The two collateral bars, shared by the preview and the simulation paths. */
157
- function collateralIssuesOf(factors, options) {
158
- const { minHealthFactor, minSafeHealthFactor, currentHealthFactor } = options;
159
- return (minHealthFactor === void 0 ? null : checkCollateralised({
160
- healthFactor: factors.healthFactor,
161
- required: minHealthFactor,
162
- safePrices: false,
163
- improvesFrom: currentHealthFactor
164
- })) || (minSafeHealthFactor === void 0 || factors.safeHealthFactor === void 0 ? null : checkCollateralised({
165
- healthFactor: factors.safeHealthFactor,
166
- required: minSafeHealthFactor,
167
- safePrices: true
168
- }));
169
- }
170
178
  //#endregion
171
- export { checkOperation, collateralIssuesOf };
179
+ export { checkOperation, collateralIssue, marketIssues, quotaCountIssue };
@@ -1,7 +1,7 @@
1
- import { checkCreditManagerPaused, checkDebtInBand, checkMarketExpired, checkQuotaCount } from "../../onchain/validation/checks.js";
1
+ import { checkDebtInBand } from "../../onchain/validation/checks.js";
2
2
  import { toToken } from "../../onchain/validation/token.js";
3
3
  import "../../onchain/index.js";
4
- import { collateralIssuesOf } from "./checkOperation.js";
4
+ import { collateralIssue, marketIssues, quotaCountIssue } from "./checkOperation.js";
5
5
  //#region src/preview/validate/checkSimulation.ts
6
6
  /**
7
7
  * Whether a simulated operation clears the caller's own bars.
@@ -24,28 +24,15 @@ import { collateralIssuesOf } from "./checkOperation.js";
24
24
  * came back `ok` has already passed them.
25
25
  */
26
26
  function checkSimulation(input, options = {}) {
27
- const { sdk, state, creditManager } = input;
28
- const suite = sdk.marketRegister.findCreditManager(creditManager);
29
- return checkCreditManagerPaused({
30
- isPaused: suite.isPaused,
31
- creditManager
32
- }) || checkMarketExpired({
33
- isExpired: suite.isExpired,
34
- creditManager,
35
- expirationDate: suite.creditFacade.expirationDate
36
- }) || checkDebtInBand({
37
- debt: state.accountDebt,
27
+ const { sdk, state } = input;
28
+ const suite = sdk.marketRegister.findCreditManager(state.creditManager);
29
+ return marketIssues(suite) || checkDebtInBand({
30
+ debt: state.totalDebt.value,
38
31
  minDebt: suite.creditFacade.minDebt,
39
32
  maxDebt: suite.creditFacade.maxDebt,
40
33
  underlying: toToken(sdk, suite.market.pool.underlying),
41
34
  allowZero: true
42
- }) || checkQuotaCount({
43
- count: Object.values(state.quotas).filter((q) => q.balance > 0n).length,
44
- max: suite.creditManager.maxEnabledTokens
45
- }) || (state.accountDebt === 0n ? null : collateralIssuesOf({
46
- healthFactor: state.healthFactor,
47
- safeHealthFactor: state.safeHealthFactor
48
- }, options));
35
+ }) || quotaCountIssue(suite, state) || collateralIssue(state, options);
49
36
  }
50
37
  //#endregion
51
38
  export { checkSimulation };
@@ -1,3 +1,3 @@
1
- import { checkOperation, collateralIssuesOf } from "./checkOperation.js";
1
+ import { checkOperation, collateralIssue, marketIssues, quotaCountIssue } from "./checkOperation.js";
2
2
  import { checkSimulation } from "./checkSimulation.js";
3
- export { checkOperation, checkSimulation, collateralIssuesOf };
3
+ export { checkOperation, checkSimulation, collateralIssue, marketIssues, quotaCountIssue };
@@ -24,21 +24,24 @@ function poolTx(sdk, request) {
24
24
  const { pool, wallet, sim } = request;
25
25
  const { tokenIn, tokenOut } = sim.preview;
26
26
  if (request.op === "deposit") {
27
- const meta = sdk.pools.getDepositMetadata(pool, tokenIn.token, tokenOut.token);
27
+ const meta = sdk.pools.getDepositMetadata(pool, tokenIn.token.address, tokenOut.token.address);
28
28
  const result = sdk.pools.addLiquidity({
29
29
  pool,
30
30
  wallet,
31
- collateral: tokenIn,
31
+ collateral: {
32
+ token: tokenIn.token.address,
33
+ balance: tokenIn.value
34
+ },
32
35
  meta
33
36
  });
34
- if (!result) throw new Error(`pool ${pool} takes no deposit transaction for ${tokenIn.token} (${meta.type})`);
37
+ if (!result) throw new Error(`pool ${pool} takes no deposit transaction for ${tokenIn.token.address} (${meta.type})`);
35
38
  return result.tx;
36
39
  }
37
- const meta = sdk.pools.getWithdrawalMetadata(pool, tokenIn.token, tokenOut.token);
40
+ const meta = sdk.pools.getWithdrawalMetadata(pool, tokenIn.token.address, tokenOut.token.address);
38
41
  return sdk.pools.removeLiquidity({
39
42
  pool,
40
43
  wallet,
41
- amount: request.op === "withdraw" ? tokenOut.balance : tokenIn.balance,
44
+ amount: request.op === "withdraw" ? tokenOut.value : tokenIn.value,
42
45
  permit: void 0,
43
46
  meta,
44
47
  mode: request.op === "withdraw" ? "withdraw" : "redeem"
@@ -52,7 +55,7 @@ async function openTx(sdk, request) {
52
55
  to: wallet,
53
56
  collateral,
54
57
  ethAmount,
55
- debt: preview.debt,
58
+ debt: preview.totalDebt.value,
56
59
  calls: preview.calls,
57
60
  averageQuota: preview.averageQuota,
58
61
  minQuota: preview.minQuota,
@@ -65,7 +65,10 @@ var PrepareApi = class extends MultichainConstruct {
65
65
  tokenOut
66
66
  });
67
67
  const call = pools.addLiquidity({
68
- collateral: preview.tokenIn,
68
+ collateral: {
69
+ token: preview.tokenIn.token.address,
70
+ balance: preview.tokenIn.value
71
+ },
69
72
  pool: pool.pool,
70
73
  wallet: params.wallet,
71
74
  meta: pools.getDepositMetadata(pool.pool, tokenIn, tokenOut)
@@ -15,8 +15,8 @@ import { Notice, NoticeKind, NoticeSubject } from "./notices.js";
15
15
  import { noticeKindSchema, noticeSchema } from "./notices.schema.js";
16
16
  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";
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 { AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, 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, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview } from "./previews.js";
18
+ import { AccountProjection, AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, 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, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview } from "./previews.js";
19
19
  import { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema, underlyingTokenSchema } from "./primitives.schema.js";
20
20
  import { ChainFailed, ChainMetadata, ChainScoped, ChainSucceeded, DataResponse, DataSource, ResponseMetadata } from "./response.js";
21
21
  import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
22
- export { AdjustCreditAccountPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CloseCreditAccountPreview, CompareTag, CompareTolerance, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedCreditAccountOperationPreview, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedWithdrawCollateralIntent, 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, FilterAll, Filterable, GridSampling, InstantOperationPreview, InstantReceivedAsset, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationPreview, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionRef, Position, PositionChartMetric, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayCreditAccountPreview, ResponseMetadata, Rewards, RewardsPnL, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, 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 { AccountProjection, AdjustCreditAccountPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CloseCreditAccountPreview, CompareTag, CompareTolerance, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedCreditAccountOperationPreview, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedWithdrawCollateralIntent, 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, FilterAll, Filterable, GridSampling, InstantOperationPreview, InstantReceivedAsset, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, Notice, NoticeKind, NoticeSubject, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationPreview, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionRef, Position, PositionChartMetric, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionTransaction, PositionTransactionKind, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayCreditAccountPreview, ResponseMetadata, Rewards, RewardsPnL, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, 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 };
@@ -137,8 +137,26 @@ interface PoolOperationPreview {
137
137
  */
138
138
  error?: OperationPreviewError;
139
139
  }
140
- interface OpenCreditAccountPreview {
141
- operation: "OpenCreditAccount" | "RWAOpenCreditAccount";
140
+ /**
141
+ * A credit account as an operation leaves it, answered by both halves of the
142
+ * SDK: `prepare`, which walks a request forward into the calls that realise it,
143
+ * and `preview`, which decodes calls that already exist and replays them back.
144
+ *
145
+ * `totalDebt`, `totalValue`, `leverage` and `healthFactor` mean here exactly
146
+ * what they mean on a {@link StrategyPosition}, down to the token an amount
147
+ * names — an RWA market reports USDC, not the dcUSDC wrapper the pool holds.
148
+ **/
149
+ interface AccountProjection {
150
+ /**
151
+ * Credit manager the account belongs to. Carried on the projection itself so
152
+ * a caller weighing one — `checkSimulation` among them — needs nothing beside
153
+ * it to find the market.
154
+ */
155
+ creditManager: Address;
156
+ /**
157
+ * Human-readable credit manager name.
158
+ */
159
+ name: string;
142
160
  /**
143
161
  * Health factor in basis points: below `10000` the account is liquidatable.
144
162
  *
@@ -150,12 +168,14 @@ interface OpenCreditAccountPreview {
150
168
  * token's main and reserve oracle feeds, which is what the credit manager
151
169
  * switches to for a call that hands funds over.
152
170
  *
153
- * Always reported, so a caller that needs the stricter reading does not have
154
- * to recompute it; whether to hold the account to it is the caller's call.
171
+ * Absent only where the walk had no reason to weigh it: the intents engine
172
+ * computes it for an operation that hands funds over, which is the one the
173
+ * credit manager holds to safe prices on-chain. Both preview builders and
174
+ * `openNewStrategy` always report it.
155
175
  *
156
176
  * @example `11800` where `healthFactor` is `12500`
157
177
  **/
158
- safeHealthFactor: Bps;
178
+ safeHealthFactor?: Bps;
159
179
  /**
160
180
  * Cost of the debt, broken down by source.
161
181
  **/
@@ -178,18 +198,40 @@ interface OpenCreditAccountPreview {
178
198
  **/
179
199
  leverage: Leverage;
180
200
  /**
181
- * Credit manager the account is opened in
182
- */
183
- creditManager: Address;
201
+ * Everything the account holds, denominated in the market's underlying.
202
+ **/
203
+ totalValue: TokenAmount;
184
204
  /**
185
- * Human-readable credit manager name
186
- */
187
- name: string;
205
+ * What it would take to settle the loan: principal plus accrued interest and
206
+ * fees, in the market's underlying.
207
+ **/
208
+ totalDebt: TokenAmount;
209
+ /**
210
+ * Own funds in the position: `totalValue` less `totalDebt`, in the market's
211
+ * underlying. The read model leaves a strategy caller to subtract these two
212
+ * itself; a projection reports the figure so an "own funds" row reads the
213
+ * same on every screen that shows one.
214
+ **/
215
+ netValue: TokenAmount;
216
+ /**
217
+ * What the account holds, token by token.
218
+ **/
219
+ assets: TokenAmount[];
220
+ /**
221
+ * Quota bought for each collateral, denominated in the market's underlying
222
+ * rather than in the collateral token — the same convention as
223
+ * {@link PositionCollateral.quota}. A token the account leaves unquoted is
224
+ * absent rather than present at zero.
225
+ **/
226
+ quotas: TokenAmount[];
227
+ }
228
+ interface OpenCreditAccountPreview extends AccountProjection {
229
+ operation: "OpenCreditAccount" | "RWAOpenCreditAccount";
188
230
  /**
189
- * Target token of strategy: the first quoted token, with its balance taken
190
- * from `assets`. Undefined when nothing is quoted.
231
+ * Collateral token this position is a strategy in: the first quoted token,
232
+ * with its balance taken from `assets`. Undefined when nothing is quoted.
191
233
  */
192
- target?: TokenAmount;
234
+ targetCollateral?: TokenAmount;
193
235
  /**
194
236
  * Tokens that were added as collateral during account opening.
195
237
  *
@@ -197,89 +239,16 @@ interface OpenCreditAccountPreview {
197
239
  * `NATIVE_ADDRESS` entry, with the wrapped native token amount reduced
198
240
  * accordingly (omitted entirely when it reaches zero).
199
241
  */
200
- collateral: TokenAmount[];
201
- /**
202
- * Sum of collateral tokens in underlying
203
- */
204
- collateralValue: bigint;
205
- /**
206
- * Total account value after opening: collateral plus borrowed amount, in
207
- * underlying.
208
- */
209
- totalValue: bigint;
210
- /**
211
- * Borrowed amount in underlying
212
- */
213
- debt: bigint;
214
- /**
215
- * WARNING: unlike every other `TokenAmount` in this model, `value` is
216
- * denominated in the market underlying, NOT in `token`. `token` only
217
- * identifies which collateral the quota applies to; `valueUsd` prices the
218
- * underlying amount.
219
- *
220
- * Desired quotas
221
- */
222
- quotas: TokenAmount[];
223
- /**
224
- * Minimum amount of assets on credit account after it's opened,
225
- * as estimated by router
226
- */
227
- assets: TokenAmount[];
242
+ collateralAdded: TokenAmount[];
228
243
  /**
229
244
  * Set when preview encountered non-fatal errors, all fields are
230
- * still computed best-effort, but derived fields (`assets`, `target`,
231
- * `collateralValue`) may be unreliable in that case.
245
+ * still computed best-effort, but derived fields (`assets`,
246
+ * `targetCollateral`, `netValue`) may be unreliable in that case.
232
247
  */
233
248
  error?: OperationPreviewError;
234
249
  }
235
- interface AdjustCreditAccountPreview {
250
+ interface AdjustCreditAccountPreview extends AccountProjection {
236
251
  operation: "AdjustCreditAccount";
237
- /**
238
- * Health factor in basis points: below `10000` the account is liquidatable.
239
- *
240
- * @example `12500` for a health factor of 1.25
241
- **/
242
- healthFactor: Bps;
243
- /**
244
- * The same factor with collateral valued at safe prices — the lower of each
245
- * token's main and reserve oracle feeds, which is what the credit manager
246
- * switches to for a call that hands funds over.
247
- *
248
- * Always reported, so a caller that needs the stricter reading does not have
249
- * to recompute it; whether to hold the account to it is the caller's call.
250
- *
251
- * @example `11800` where `healthFactor` is `12500`
252
- **/
253
- safeHealthFactor: Bps;
254
- /**
255
- * Cost of the debt, broken down by source.
256
- **/
257
- borrowRate: BorrowRateBreakdown;
258
- /**
259
- * Estimated milliseconds until the health factor decays to `10000` under
260
- * the current borrow rate, or `null` when the debt carries no rate (or the
261
- * account is already liquidatable).
262
- **/
263
- timeToLiquidation: bigint | null;
264
- /**
265
- * Price of the single non-underlying collateral at which the account
266
- * becomes liquidatable, in the oracle's 8-decimal fixed point, or `null`
267
- * when the account holds zero or several non-underlying assets.
268
- **/
269
- liquidationPrice: bigint | null;
270
- /**
271
- * Total-value leverage: `totalValue / (totalValue − totalDebt)`. `1` =
272
- * unleveraged; `0` if underwater.
273
- **/
274
- leverage: Leverage;
275
- /**
276
- * Credit manager the account is opened in
277
- */
278
- creditManager: Address;
279
- /**
280
- * Human-readable credit manager name
281
- */
282
- name: string;
283
252
  /**
284
253
  * Credit account that is being adjusted
285
254
  */
@@ -296,45 +265,18 @@ interface AdjustCreditAccountPreview {
296
265
  * Tokens that were withdrawn as collateral during account adjustment.
297
266
  */
298
267
  collateralWithdrawn: TokenAmount[];
299
- /**
300
- * Sum of collateral tokens in underlying
301
- */
302
- totalValue: bigint;
303
- /**
304
- * What the account owes in underlying once the operation lands: principal
305
- * plus accrued interest and fees, which is the amount it would take to
306
- * settle the loan — the same quantity `prepare` projects as `accountDebt`.
307
- */
308
- debt: bigint;
309
268
  /**
310
269
  * Debt after minus debt before. A repayment settles interest and fees
311
270
  * before principal, so this is the payment itself rather than the part of
312
271
  * it the principal happened to absorb.
313
272
  */
314
- debtChange: bigint;
273
+ totalDebtChange: TokenAmount;
315
274
  /**
316
- * WARNING: unlike every other `TokenAmount` in this model, `value` is
317
- * denominated in the market underlying, NOT in `token`. `token` only
318
- * identifies which collateral the quota applies to; `valueUsd` prices the
319
- * underlying amount.
320
- *
321
- * Desired quotas
322
- */
323
- quotas: TokenAmount[];
324
- /**
325
- * WARNING: unlike every other `TokenAmount` in this model, `value` is
326
- * denominated in the market underlying, NOT in `token`. `token` only
327
- * identifies which collateral the quota applies to; `valueUsd` prices the
328
- * underlying amount.
329
- *
330
- * Quotas after minus quotas before
275
+ * Quotas after minus quotas before. Denominated in the market's underlying
276
+ * like {@link AccountProjection.quotas}, so `token` names the collateral the
277
+ * quota applies to rather than the amount's own unit.
331
278
  */
332
279
  quotasChange: TokenAmount[];
333
- /**
334
- * Minimum amount of assets on credit account after the operation,
335
- * as estimated by router
336
- */
337
- assets: TokenAmount[];
338
280
  /**
339
281
  * Assets after minus assets before
340
282
  */
@@ -425,9 +367,13 @@ interface RepayCreditAccountPreview {
425
367
  */
426
368
  collateralWithdrawn: TokenAmount[];
427
369
  /**
428
- * Total debt repaid: principal + accrued interest + fees, in underlying
370
+ * Total debt repaid: principal + accrued interest + fees, in underlying.
371
+ *
372
+ * The same quantity an {@link AdjustCreditAccountPreview} reports as
373
+ * `totalDebtChange`, with the sign a repayment screen reads: positive for
374
+ * what the wallet parted with.
429
375
  */
430
- debtRepaid: bigint;
376
+ debtRepaid: TokenAmount;
431
377
  /**
432
378
  * Intent of the delayed withdrawal this transaction claims; set when the
433
379
  * multicall claims a delayed withdrawal
@@ -490,4 +436,4 @@ interface DelayedCreditAccountOperationPreview {
490
436
  */
491
437
  type OperationPreview = PoolOperationPreview | OpenCreditAccountPreview | AdjustCreditAccountPreview | CloseCreditAccountPreview | RepayCreditAccountPreview | DelayedCreditAccountOperationPreview;
492
438
  //#endregion
493
- export { AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, 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, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview };
439
+ export { AccountProjection, AdjustCreditAccountPreview, CloseCreditAccountPreview, DelayedCreditAccountOperationPreview, 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, InstantOperationPreview, OpenCreditAccountPreview, OperationPreview, OperationPreviewError, PoolOperationPreview, PoolOperationType, PreviewOperationInput, PreviewOperationOptions, RepayCreditAccountPreview };
@@ -1,5 +1,5 @@
1
1
  import { Bps, TokenAmount } from "../../../model/primitives.js";
2
- import { BorrowRateBreakdown } from "../../../model/positions.js";
2
+ import { AccountProjection } from "../../../model/previews.js";
3
3
  import "../../../model/index.js";
4
4
  import { Asset } from "../../base/types.js";
5
5
  import { MultiCall } from "../../types/transactions.js";
@@ -32,42 +32,26 @@ interface OpenStrategyProps {
32
32
  * hands back expected and floor balances from a single call, and `openCA` wants
33
33
  * both `minQuota` and `averageQuota`, so there is nothing to gain by dropping one.
34
34
  */
35
- interface OpenStrategyPreview {
35
+ interface OpenStrategyPreview extends Omit<AccountProjection, "assets" | "quotas"> {
36
36
  /**
37
- * Health factor in basis points: below `10000` the account is liquidatable.
38
- *
39
- * @example `12500` for a health factor of 1.25
40
- **/
41
- healthFactor: Bps;
42
- /**
43
- * Cost of the debt, broken down by source.
44
- **/
45
- borrowRate: BorrowRateBreakdown;
46
- /**
47
- * Estimated milliseconds until the health factor decays to `10000` under
48
- * the current borrow rate, or `null` when the debt carries no rate (or the
49
- * account is already liquidatable).
37
+ * The same factor with collateral valued at safe prices, which is what the
38
+ * credit manager weighs an opening at on-chain. Always reported here: an
39
+ * opening always hands the pool's funds over.
50
40
  **/
51
- timeToLiquidation: bigint | null;
52
- /**
53
- * Price of the single non-underlying collateral at which the account
54
- * becomes liquidatable, in the oracle's 8-decimal fixed point, or `null`
55
- * when the account holds zero or several non-underlying assets.
56
- **/
57
- liquidationPrice: bigint | null;
58
- /** Debt drawn, in underlying. */
59
- debt: bigint;
60
- /** Collateral supplied, valued in underlying. */
61
- collateral: bigint;
62
- /** Position size — collateral plus debt, in underlying. */
63
- totalValue: bigint;
41
+ safeHealthFactor: Bps;
64
42
  /** What the routed leg lost to market depth; `undefined` if not measured. */
65
43
  priceImpact: PathLossRate | undefined;
66
44
  /** Expected post-open balances. */
67
45
  averageAssets: TokenAmount[];
68
46
  /** Floor post-open balances after slippage. */
69
47
  minAssets: TokenAmount[];
70
- /** Quotas to buy against `averageAssets`; feeds `openCA.averageQuota`. */
48
+ /**
49
+ * Quotas to buy against `averageAssets`; feeds `openCA.averageQuota`.
50
+ *
51
+ * Bare pairs rather than priced amounts, like `calls` below: these three are
52
+ * transport for the transaction, handed to `openCA` untouched, and are the
53
+ * only fields here a caller is not meant to display.
54
+ **/
71
55
  averageQuota: Asset[];
72
56
  /** Quotas to buy against `minAssets`; feeds `openCA.minQuota`. */
73
57
  minQuota: Asset[];
@@ -34,7 +34,7 @@ declare function expectCallsArrayExact(calls: MultiCall[], expected: MultiCall[]
34
34
  */
35
35
  declare function expectAdjustPreview(result: IntentPreviewResult | DelayedStartResult, args: {
36
36
  totalValue: bigint;
37
- accountDebt: bigint;
37
+ totalDebt: bigint;
38
38
  expectedOps: ExpectedFlowOp[];
39
39
  expectedCalls?: MultiCall[];
40
40
  }): OperationState;
@@ -42,7 +42,11 @@ declare function expectAdjustPreview(result: IntentPreviewResult | DelayedStartR
42
42
  declare function expectPreviewError(result: IntentPreviewResult | DelayedStartResult, reason: Extract<IntentPreviewResult, {
43
43
  ok: false;
44
44
  }>["reason"]): void;
45
- /** What a priced holdings list says the account holds of `token`. */
45
+ /**
46
+ * What a priced list — holdings or quotas — says the account stands at for
47
+ * `token`. A quota is denominated in the market underlying, so this reads the
48
+ * quota bought *for* `token`, not an amount of it.
49
+ */
46
50
  declare function assetBalance(assets: Array<TokenAmount>, token: Address): bigint;
47
51
  //#endregion
48
52
  export { ExpectedFlowOp };
@@ -86,7 +86,7 @@ declare function valueInUnd(amount: bigint, token: Address, overrides?: {
86
86
  declare function caToken(token: Address, balance: bigint, quota?: bigint): CreditAccountSlice["tokens"][number];
87
87
  /** Bare CA slice on the fixture market. */
88
88
  declare function buildFixtureCreditAccount(args: {
89
- accountDebt: bigint;
89
+ totalDebt: bigint;
90
90
  tokens: CreditAccountSlice["tokens"];
91
91
  }): CreditAccountSlice;
92
92
  //#endregion
@@ -111,7 +111,7 @@ interface BuildMockSdkArgs {
111
111
  /**
112
112
  * Accounts `accounts.getCreditAccountData` knows, keyed by address. What the
113
113
  * prepare layer reads on its own instead of taking a slice from the caller;
114
- * `accountDebt` lands as the principal with no interest or fees accrued.
114
+ * `totalDebt` lands as the principal with no interest or fees accrued.
115
115
  */
116
116
  creditAccounts?: CreditAccountSlice[];
117
117
  /**
@@ -21,7 +21,7 @@ interface AddCollateralCase {
21
21
  intent: AddCollateralIntent;
22
22
  /** Balances already on the account. */
23
23
  tokens: ReturnType<typeof caToken>[];
24
- accountDebt: bigint;
24
+ totalDebt: bigint;
25
25
  /** Expected TVL in UND after the operation. */
26
26
  totalValue: bigint;
27
27
  ops: ExpectedFlowOp[];