@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
@@ -31,7 +31,7 @@ const case_position_token = {
31
31
  amount: ADD_ANY
32
32
  },
33
33
  tokens: [caToken(UND, BASE_UND)],
34
- accountDebt: DEBT,
34
+ totalDebt: DEBT,
35
35
  totalValue: BASE_UND + valueInUnd(ADD_ANY, ANY),
36
36
  ops: [{
37
37
  type: "addCollateral",
@@ -56,7 +56,7 @@ const case_underlying = {
56
56
  amount: ADD_UND
57
57
  },
58
58
  tokens: [caToken(ANY, ADD_ANY, QUOTA_ANY)],
59
- accountDebt: DEBT,
59
+ totalDebt: DEBT,
60
60
  totalValue: valueInUnd(ADD_ANY, ANY) + ADD_UND,
61
61
  ops: [{
62
62
  type: "addCollateral",
@@ -73,7 +73,7 @@ const case_rwa_asset = {
73
73
  amount: ADD_RWA
74
74
  },
75
75
  tokens: [caToken(UND, BASE_UND)],
76
- accountDebt: DEBT,
76
+ totalDebt: DEBT,
77
77
  totalValue: BASE_UND + valueInUnd(ADD_RWA, RWA_ASSET),
78
78
  ops: [{
79
79
  type: "addCollateral",
@@ -98,7 +98,7 @@ function buildAddCollateralProps(c, sdk) {
98
98
  return {
99
99
  intent: c.intent,
100
100
  creditAccount: buildFixtureCreditAccount({
101
- accountDebt: c.accountDebt,
101
+ totalDebt: c.totalDebt,
102
102
  tokens: c.tokens
103
103
  }),
104
104
  sdk,
@@ -36,9 +36,9 @@ const case_increase = {
36
36
  token: POS
37
37
  },
38
38
  tokens: [caToken(POS, TVL_2X, QUOTA_1000)],
39
- accountDebt: DEBT_2X,
39
+ totalDebt: DEBT_2X,
40
40
  totalValue: TVL_3X,
41
- accountDebtAfter: DEBT_3X,
41
+ totalDebtAfter: DEBT_3X,
42
42
  ops: [
43
43
  {
44
44
  type: "increaseDebt",
@@ -72,9 +72,9 @@ const case_increase_underlying = {
72
72
  token: UND
73
73
  },
74
74
  tokens: [caToken(UND, TVL_2X)],
75
- accountDebt: DEBT_2X,
75
+ totalDebt: DEBT_2X,
76
76
  totalValue: TVL_3X,
77
- accountDebtAfter: DEBT_3X,
77
+ totalDebtAfter: DEBT_3X,
78
78
  ops: [{
79
79
  type: "increaseDebt",
80
80
  amount: STEP
@@ -88,9 +88,9 @@ const case_increase_rwa = {
88
88
  token: RWA_ASSET
89
89
  },
90
90
  tokens: [caToken(RWA_ASSET, TVL_2X, QUOTA_1000)],
91
- accountDebt: DEBT_2X,
91
+ totalDebt: DEBT_2X,
92
92
  totalValue: TVL_3X,
93
- accountDebtAfter: DEBT_3X,
93
+ totalDebtAfter: DEBT_3X,
94
94
  ops: [
95
95
  {
96
96
  type: "increaseDebt",
@@ -123,9 +123,9 @@ const case_decrease = {
123
123
  token: POS
124
124
  },
125
125
  tokens: [caToken(POS, TVL_3X, QUOTA_1500)],
126
- accountDebt: DEBT_3X,
126
+ totalDebt: DEBT_3X,
127
127
  totalValue: TVL_2X,
128
- accountDebtAfter: DEBT_2X,
128
+ totalDebtAfter: DEBT_2X,
129
129
  ops: [
130
130
  {
131
131
  type: "swap",
@@ -159,9 +159,9 @@ const case_decrease_from_idle_underlying = {
159
159
  token: POS
160
160
  },
161
161
  tokens: [caToken(POS, TVL_2X, QUOTA_1000), caToken(UND, STEP)],
162
- accountDebt: DEBT_3X,
162
+ totalDebt: DEBT_3X,
163
163
  totalValue: TVL_2X,
164
- accountDebtAfter: DEBT_2X,
164
+ totalDebtAfter: DEBT_2X,
165
165
  ops: [{
166
166
  type: "decreaseDebt",
167
167
  amount: STEP
@@ -175,9 +175,9 @@ const case_decrease_rwa = {
175
175
  token: RWA_ASSET
176
176
  },
177
177
  tokens: [caToken(RWA_ASSET, TVL_3X, QUOTA_1500)],
178
- accountDebt: DEBT_3X,
178
+ totalDebt: DEBT_3X,
179
179
  totalValue: TVL_2X,
180
- accountDebtAfter: DEBT_2X,
180
+ totalDebtAfter: DEBT_2X,
181
181
  ops: [
182
182
  {
183
183
  type: "wrapRwaCollateral",
@@ -210,9 +210,9 @@ const case_noop = {
210
210
  token: POS
211
211
  },
212
212
  tokens: [caToken(POS, TVL_2X, QUOTA_1000)],
213
- accountDebt: DEBT_2X,
213
+ totalDebt: DEBT_2X,
214
214
  totalValue: TVL_2X,
215
- accountDebtAfter: DEBT_2X,
215
+ totalDebtAfter: DEBT_2X,
216
216
  ops: []
217
217
  };
218
218
  function buildAdjustLeverageSdk(c) {
@@ -222,7 +222,7 @@ function buildAdjustLeverageProps(c, sdk) {
222
222
  return {
223
223
  intent: c.intent,
224
224
  creditAccount: buildFixtureCreditAccount({
225
- accountDebt: c.accountDebt,
225
+ totalDebt: c.totalDebt,
226
226
  tokens: c.tokens
227
227
  }),
228
228
  sdk,
@@ -31,9 +31,9 @@ const case_fixed_leverage = {
31
31
  positionToken: POS
32
32
  },
33
33
  tokens: [caToken(POS, P1000, QUOTA_1000)],
34
- accountDebt: DEBT_START,
34
+ totalDebt: DEBT_START,
35
35
  totalValue: P2000,
36
- accountDebtAfter: P1000,
36
+ totalDebtAfter: P1000,
37
37
  ops: [
38
38
  {
39
39
  type: "addCollateral",
@@ -75,9 +75,9 @@ const case_target_leverage = {
75
75
  targetLeverage: LEV_3X
76
76
  },
77
77
  tokens: [caToken(POS, P1000, QUOTA_1000)],
78
- accountDebt: DEBT_START,
78
+ totalDebt: DEBT_START,
79
79
  totalValue: P3000,
80
- accountDebtAfter: P2000,
80
+ totalDebtAfter: P2000,
81
81
  ops: [
82
82
  {
83
83
  type: "addCollateral",
@@ -118,9 +118,9 @@ const case_position_is_underlying = {
118
118
  positionToken: UND
119
119
  },
120
120
  tokens: [caToken(UND, P1000)],
121
- accountDebt: DEBT_START,
121
+ totalDebt: DEBT_START,
122
122
  totalValue: P2000,
123
- accountDebtAfter: P1000,
123
+ totalDebtAfter: P1000,
124
124
  ops: [{
125
125
  type: "addCollateral",
126
126
  token: UND,
@@ -140,9 +140,9 @@ const case_rwa_collateral = {
140
140
  positionToken: POS
141
141
  },
142
142
  tokens: [caToken(POS, P1000, QUOTA_1000)],
143
- accountDebt: DEBT_START,
143
+ totalDebt: DEBT_START,
144
144
  totalValue: P2000,
145
- accountDebtAfter: P1000,
145
+ totalDebtAfter: P1000,
146
146
  ops: [
147
147
  {
148
148
  type: "addCollateral",
@@ -194,9 +194,9 @@ const case_rwa_position = {
194
194
  positionToken: RWA_ASSET
195
195
  },
196
196
  tokens: [caToken(RWA_ASSET, P1000, QUOTA_1000)],
197
- accountDebt: DEBT_START,
197
+ totalDebt: DEBT_START,
198
198
  totalValue: P2000,
199
- accountDebtAfter: P1000,
199
+ totalDebtAfter: P1000,
200
200
  ops: [
201
201
  {
202
202
  type: "addCollateral",
@@ -249,9 +249,9 @@ const case_native_coin = {
249
249
  value: NATIVE_VALUE
250
250
  },
251
251
  tokens: [caToken(POS, M32_BALANCE, quotaOf(M32_BALANCE))],
252
- accountDebt: M32_DEBT,
252
+ totalDebt: M32_DEBT,
253
253
  totalValue: 1500000000n,
254
- accountDebtAfter: 1200000000n,
254
+ totalDebtAfter: 1200000000n,
255
255
  ops: [
256
256
  {
257
257
  type: "addCollateral",
@@ -293,7 +293,7 @@ function buildDepositProps(c, sdk) {
293
293
  return {
294
294
  intent: c.intent,
295
295
  creditAccount: buildFixtureCreditAccount({
296
- accountDebt: c.accountDebt,
296
+ totalDebt: c.totalDebt,
297
297
  tokens: c.tokens
298
298
  }),
299
299
  sdk,
@@ -49,7 +49,7 @@ function buildDecreaseTailProps(args) {
49
49
  underlying: UND,
50
50
  enabledTokensMask: 0n,
51
51
  totalDebtUSD: 0n,
52
- accountDebt: DECREASE_PRE_D,
52
+ totalDebt: DECREASE_PRE_D,
53
53
  tokens: args.tokens ?? [{
54
54
  token: "0xb1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1b1",
55
55
  balance: args.claimedAmount,
@@ -180,7 +180,7 @@ function buildMatrixDecreaseTailProps(c) {
180
180
  underlying: UND,
181
181
  enabledTokensMask: 0n,
182
182
  totalDebtUSD: 0n,
183
- accountDebt: M7_DEBT,
183
+ totalDebt: M7_DEBT,
184
184
  tokens: [{
185
185
  token: POS,
186
186
  balance: M7_POS_LEFT,
@@ -63,7 +63,7 @@ function buildWithdrawFinishProps(args) {
63
63
  underlying: UND,
64
64
  enabledTokensMask: 0n,
65
65
  totalDebtUSD: 0n,
66
- accountDebt: WITHDRAW_PRE_D,
66
+ totalDebt: WITHDRAW_PRE_D,
67
67
  tokens: args.tokens ?? [
68
68
  {
69
69
  token: "0x1111111111111111111111111111111111111111",
@@ -308,7 +308,7 @@ function buildMatrixWithdrawTailProps(c) {
308
308
  underlying: UND,
309
309
  enabledTokensMask: 0n,
310
310
  totalDebtUSD: 0n,
311
- accountDebt: M4_DEBT,
311
+ totalDebt: M4_DEBT,
312
312
  tokens: [{
313
313
  token: POS,
314
314
  balance: M4_SPEND,
@@ -35,7 +35,7 @@ const case_any_token = {
35
35
  to: WALLET
36
36
  },
37
37
  tokens: [caToken(UND, HELD_UND), caToken(ANY, HELD_ANY, QUOTA_ANY_BEFORE)],
38
- accountDebt: DEBT,
38
+ totalDebt: DEBT,
39
39
  totalValue: HELD_UND + valueInUnd(HELD_ANY - OUT_ANY, ANY),
40
40
  ops: [{
41
41
  type: "withdrawCollateral",
@@ -61,7 +61,7 @@ const case_underlying = {
61
61
  to: WALLET
62
62
  },
63
63
  tokens: [caToken(UND, HELD_UND)],
64
- accountDebt: DEBT,
64
+ totalDebt: DEBT,
65
65
  totalValue: HELD_UND - OUT_UND,
66
66
  ops: [{
67
67
  type: "withdrawCollateral",
@@ -82,7 +82,7 @@ const case_rwa_underlying = {
82
82
  to: WALLET
83
83
  },
84
84
  tokens: [caToken(UND, HELD_UND)],
85
- accountDebt: DEBT,
85
+ totalDebt: DEBT,
86
86
  totalValue: HELD_UND - OUT_UND,
87
87
  ops: [{
88
88
  type: "unwrapRwaCollateral",
@@ -105,7 +105,7 @@ function buildWithdrawAssetProps(c, sdk) {
105
105
  return {
106
106
  intent: c.intent,
107
107
  creditAccount: buildFixtureCreditAccount({
108
- accountDebt: c.accountDebt,
108
+ totalDebt: c.totalDebt,
109
109
  tokens: c.tokens
110
110
  }),
111
111
  sdk,
@@ -26,9 +26,9 @@ const QUOTA_AFTER = quotaOf(TVL_AFTER);
26
26
  /** Quota ops carry signed deltas. */
27
27
  const QUOTA_DELTA = QUOTA_AFTER - QUOTA_BEFORE;
28
28
  const base = {
29
- accountDebt: DEBT_BEFORE,
29
+ totalDebt: DEBT_BEFORE,
30
30
  totalValue: TVL_AFTER,
31
- accountDebtAfter: DEBT_AFTER
31
+ totalDebtAfter: DEBT_AFTER
32
32
  };
33
33
  /** Row 1 — S = U, T = U: repay, then hand over the underlying. */
34
34
  const case_und_und = {
@@ -290,9 +290,9 @@ const case_matrix_4_1 = {
290
290
  sourceToken: POS
291
291
  },
292
292
  tokens: [caToken(POS, M4_BALANCE, quotaOf(M4_BALANCE))],
293
- accountDebt: M4_DEBT,
293
+ totalDebt: M4_DEBT,
294
294
  totalValue: M4_SPEND,
295
- accountDebtAfter: M4_DD,
295
+ totalDebtAfter: M4_DD,
296
296
  ops: [
297
297
  {
298
298
  type: "swap",
@@ -341,9 +341,9 @@ const case_matrix_4_2 = {
341
341
  sourceToken: POS
342
342
  },
343
343
  tokens: [caToken(POS, M4_BALANCE, quotaOf(M4_BALANCE))],
344
- accountDebt: M4_DEBT,
344
+ totalDebt: M4_DEBT,
345
345
  totalValue: M4_SPEND,
346
- accountDebtAfter: M4_DD,
346
+ totalDebtAfter: M4_DD,
347
347
  ops: [
348
348
  {
349
349
  type: "swap",
@@ -390,7 +390,7 @@ function buildWithdrawProps(c, sdk) {
390
390
  return {
391
391
  intent: c.intent,
392
392
  creditAccount: buildFixtureCreditAccount({
393
- accountDebt: c.accountDebt,
393
+ totalDebt: c.totalDebt,
394
394
  tokens: c.tokens
395
395
  }),
396
396
  sdk,
@@ -1,8 +1,8 @@
1
1
  //#region src/onchain/accounts/intents/utils/adjust-state-to-snapshot.ts
2
2
  /**
3
3
  * Maps an intents {@link OperationState} onto the {@link AccountSnapshot} that
4
- * position-metric functions take. `accountDebt` is treated as total debt
5
- * (principal plus accrued interest and fees).
4
+ * position-metric functions take: the state prices what it reports, a snapshot
5
+ * only names it.
6
6
  **/
7
7
  function adjustStateToSnapshot(creditManager, state) {
8
8
  return {
@@ -11,9 +11,12 @@ function adjustStateToSnapshot(creditManager, state) {
11
11
  token: a.token.address,
12
12
  balance: a.value
13
13
  })),
14
- quotas: Object.values(state.quotas),
15
- totalDebt: state.accountDebt,
16
- totalValue: state.totalValue
14
+ quotas: state.quotas.map((q) => ({
15
+ token: q.token.address,
16
+ balance: q.value
17
+ })),
18
+ totalDebt: state.totalDebt.value,
19
+ totalValue: state.totalValue.value
17
20
  };
18
21
  }
19
22
  //#endregion
@@ -14,7 +14,7 @@ function toTargetDecimals(fromAmount, fromToken, toToken, sdk) {
14
14
  * with balance from the projection (0n when absent), new tokens get quota 0n.
15
15
  */
16
16
  function toRouterCaSlice(creditAccount, expectedBalances = []) {
17
- const { accountDebt, underlying, creditFacade, creditManager, creditAccount: creditAccountAddress, tokens: _, ...restCA } = creditAccount;
17
+ const { totalDebt, underlying, creditFacade, creditManager, creditAccount: creditAccountAddress, tokens: _, ...restCA } = creditAccount;
18
18
  const expected = new AddressMap([]);
19
19
  for (const asset of expectedBalances ?? []) expected.upsert(asset.token, (expected.get(asset.token) ?? 0n) + asset.balance);
20
20
  const tokens = creditAccount.tokens.map((t) => {
@@ -32,7 +32,7 @@ function toRouterCaSlice(creditAccount, expectedBalances = []) {
32
32
  creditAccount: creditAccountAddress.toLowerCase(),
33
33
  creditFacade: creditFacade.toLowerCase(),
34
34
  creditManager: creditManager.toLowerCase(),
35
- debt: creditAccount.accountDebt,
35
+ debt: creditAccount.totalDebt,
36
36
  tokens
37
37
  };
38
38
  }
@@ -3,9 +3,9 @@ import { calcBorrowedAmountPlusInterestAndFees } from "./borrowed-amount-plus-in
3
3
  /**
4
4
  * Narrows full account data down to the slice the intent engine operates on.
5
5
  *
6
- * `accountDebt` is the total repayable debt (principal + accrued interest +
7
- * accrued fees) rather than the principal, because every debt-touching intent
8
- * settles the full outstanding amount.
6
+ * `totalDebt` is the total repayable debt (principal + accrued interest +
7
+ * accrued fees) rather than `CreditAccountData.debt`'s principal, because every
8
+ * debt-touching intent settles the full outstanding amount.
9
9
  *
10
10
  * Addresses are lowercased so that `eq` comparisons and `AddressMap` lookups
11
11
  * behave consistently everywhere downstream.
@@ -18,7 +18,7 @@ function toCreditAccountSlice(ca) {
18
18
  underlying: ca.underlying.toLowerCase(),
19
19
  enabledTokensMask: ca.enabledTokensMask,
20
20
  totalDebtUSD: ca.totalDebtUSD,
21
- accountDebt: calcBorrowedAmountPlusInterestAndFees(ca),
21
+ totalDebt: calcBorrowedAmountPlusInterestAndFees(ca),
22
22
  tokens: ca.tokens.map((t) => ({
23
23
  ...t,
24
24
  token: t.token.toLowerCase()
@@ -19,8 +19,8 @@ function accountView(creditAccount, sdk) {
19
19
  underlying,
20
20
  sdk,
21
21
  rwaAsset: sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset,
22
- debt: creditAccount.accountDebt,
23
- collateral: totalValue - creditAccount.accountDebt,
22
+ debt: creditAccount.totalDebt,
23
+ collateral: totalValue - creditAccount.totalDebt,
24
24
  band: {
25
25
  minDebt: creditFacade.minDebt,
26
26
  maxDebt: creditFacade.maxDebt
@@ -127,6 +127,21 @@ var MarketSuite = class extends SDKConstruct {
127
127
  };
128
128
  }
129
129
  /**
130
+ * Prices a figure already denominated in this market's underlying — a debt,
131
+ * a TVL, a payout — as the read model reports one.
132
+ *
133
+ * The token it names is {@link underlyingToken}, so an amount coming out of a
134
+ * preview or a simulation carries the same identity as the one on a
135
+ * `StrategyPosition`: USDC on an RWA market, not the dcUSDC wrapper the pool
136
+ * actually holds. The two convert one-for-one, so the figure is exact either
137
+ * way; only the label differs, and a caller showing both side by side must
138
+ * not see two.
139
+ **/
140
+ toUnderlyingAmount = (value) => ({
141
+ token: this.underlyingToken,
142
+ ...this.priceOracle.toAmount(this.underlying, value)
143
+ });
144
+ /**
130
145
  * Display name of this market's pool, e.g. `"USDC Pool"`.
131
146
  */
132
147
  get poolName() {
@@ -42,16 +42,20 @@ const USD_DUST_THRESHOLD = 1000n;
42
42
  /**
43
43
  * Converts a USD value in the oracle's 8-decimal fixed point to a float.
44
44
  *
45
- * Values below {@link USD_DUST_THRESHOLD} report as `0`.
45
+ * Values whose magnitude is below {@link USD_DUST_THRESHOLD} report as `0`.
46
+ * The threshold is weighed on the magnitude because the deltas the model
47
+ * carries — a debt repaid, a balance sold — are negative, and dust is dust in
48
+ * either direction.
46
49
  *
47
50
  * @example
48
51
  * ```ts
49
52
  * // usd: $1500.50 in 8-decimal fixed point
50
53
  * usdToNumber(150_050_000_000n) // 1500.5
54
+ * usdToNumber(-150_050_000_000n) // -1500.5
51
55
  * ```
52
56
  **/
53
57
  function usdToNumber(usd) {
54
- return usd < USD_DUST_THRESHOLD ? 0 : Number(usd) / Number(PRICE_DECIMALS);
58
+ return (usd < 0n ? -usd : usd) < USD_DUST_THRESHOLD ? 0 : Number(usd) / Number(PRICE_DECIMALS);
55
59
  }
56
60
  /**
57
61
  * Share of capital currently borrowed, in basis points. Returns `0` when there
@@ -20,6 +20,14 @@ import "../market/index.js";
20
20
  */
21
21
  const LIQUIDITY_SAFETY_NUM = 99999n;
22
22
  const LIQUIDITY_SAFETY_DENOM = 100000n;
23
+ /**
24
+ * What the pool can actually pay out right now, shaved by a hair so a
25
+ * withdrawal sized against it does not fail on rounding.
26
+ **/
27
+ function payoutCeiling(market) {
28
+ const { pool } = market;
29
+ return market.priceOracle.toAmount(pool.underlying, pool.pool.availableLiquidity * LIQUIDITY_SAFETY_NUM / LIQUIDITY_SAFETY_DENOM);
30
+ }
23
31
  var PoolService = class extends SDKConstruct {
24
32
  /**
25
33
  * {@inheritDoc IPoolsService.getDepositTokensIn}
@@ -125,7 +133,9 @@ var PoolService = class extends SDKConstruct {
125
133
  */
126
134
  simulateDeposit(props) {
127
135
  const { pool: poolAddr, amount } = props;
128
- const { pool } = this.sdk.marketRegister.findByPool(poolAddr);
136
+ const market = this.sdk.marketRegister.findByPool(poolAddr);
137
+ const { pool } = market;
138
+ const { toTokenAmount } = market.priceOracle;
129
139
  const tokenIn = props.tokenIn ?? pool.underlying;
130
140
  const tokenOut = this.#resolveTokenOut(props.tokenOut, () => this.getDepositTokensOut(poolAddr, tokenIn), {
131
141
  poolAddr,
@@ -134,14 +144,8 @@ var PoolService = class extends SDKConstruct {
134
144
  });
135
145
  const { zapper } = this.getDepositMetadata(poolAddr, tokenIn, tokenOut);
136
146
  return {
137
- tokenIn: {
138
- token: tokenIn,
139
- balance: amount
140
- },
141
- tokenOut: {
142
- token: tokenOut,
143
- balance: toShares(pool.pool, amount)
144
- },
147
+ tokenIn: toTokenAmount(tokenIn, amount),
148
+ tokenOut: toTokenAmount(tokenOut, toShares(pool.pool, amount)),
145
149
  zapper: zapper?.baseParams.addr
146
150
  };
147
151
  }
@@ -150,7 +154,9 @@ var PoolService = class extends SDKConstruct {
150
154
  */
151
155
  simulateWithdraw(props) {
152
156
  const { pool: poolAddr, amount } = props;
153
- const { pool } = this.sdk.marketRegister.findByPool(poolAddr);
157
+ const market = this.sdk.marketRegister.findByPool(poolAddr);
158
+ const { pool } = market;
159
+ const { toTokenAmount } = market.priceOracle;
154
160
  const tokenIn = props.tokenIn ?? poolAddr;
155
161
  const tokenOut = this.#resolveTokenOut(props.tokenOut, () => this.getWithdrawalTokensOut(poolAddr, tokenIn), {
156
162
  poolAddr,
@@ -159,16 +165,10 @@ var PoolService = class extends SDKConstruct {
159
165
  });
160
166
  const { zapper } = this.getWithdrawalMetadata(poolAddr, tokenIn, tokenOut);
161
167
  return {
162
- tokenIn: {
163
- token: tokenIn,
164
- balance: toSharesUp(pool.pool, amount)
165
- },
166
- tokenOut: {
167
- token: tokenOut,
168
- balance: amount
169
- },
168
+ tokenIn: toTokenAmount(tokenIn, toSharesUp(pool.pool, amount)),
169
+ tokenOut: toTokenAmount(tokenOut, amount),
170
170
  zapper: zapper?.baseParams.addr,
171
- availableLiquidity: pool.pool.availableLiquidity * LIQUIDITY_SAFETY_NUM / LIQUIDITY_SAFETY_DENOM
171
+ availableLiquidity: payoutCeiling(market)
172
172
  };
173
173
  }
174
174
  /**
@@ -176,7 +176,9 @@ var PoolService = class extends SDKConstruct {
176
176
  */
177
177
  simulateRedeem(props) {
178
178
  const { pool: poolAddr, amount } = props;
179
- const { pool } = this.sdk.marketRegister.findByPool(poolAddr);
179
+ const market = this.sdk.marketRegister.findByPool(poolAddr);
180
+ const { pool } = market;
181
+ const { toTokenAmount } = market.priceOracle;
180
182
  const tokenIn = props.tokenIn ?? poolAddr;
181
183
  const tokenOut = this.#resolveTokenOut(props.tokenOut, () => this.getWithdrawalTokensOut(poolAddr, tokenIn), {
182
184
  poolAddr,
@@ -185,16 +187,10 @@ var PoolService = class extends SDKConstruct {
185
187
  });
186
188
  const { zapper } = this.getWithdrawalMetadata(poolAddr, tokenIn, tokenOut);
187
189
  return {
188
- tokenIn: {
189
- token: tokenIn,
190
- balance: amount
191
- },
192
- tokenOut: {
193
- token: tokenOut,
194
- balance: toAssets(pool.pool, amount)
195
- },
190
+ tokenIn: toTokenAmount(tokenIn, amount),
191
+ tokenOut: toTokenAmount(tokenOut, toAssets(pool.pool, amount)),
196
192
  zapper: zapper?.baseParams.addr,
197
- availableLiquidity: pool.pool.availableLiquidity * LIQUIDITY_SAFETY_NUM / LIQUIDITY_SAFETY_DENOM
193
+ availableLiquidity: payoutCeiling(market)
198
194
  };
199
195
  }
200
196
  /**
@@ -32,7 +32,7 @@ import { previewCloseOrRepayCreditAccount } from "./preview/previewCloseOrRepayC
32
32
  import { previewOperation } from "./preview/previewOperation.js";
33
33
  import "./preview/index.js";
34
34
  import "./types.js";
35
- import { checkOperation, collateralIssuesOf } from "./validate/checkOperation.js";
35
+ import { checkOperation, collateralIssue, marketIssues, quotaCountIssue } from "./validate/checkOperation.js";
36
36
  import { checkSimulation } from "./validate/checkSimulation.js";
37
37
  import "./validate/index.js";
38
- export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, IntentPreviewError, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedPreview, checkOperation, checkPrerequisites, checkSimulation, classifyCloseOrRepay, classifyInnerOperations, collateralIssuesOf, detectDelayedClaim, detectDelayedOperation, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, raise, refuse, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
38
+ export { AllowancePrerequisite, BalancePrerequisite, CreditAccountState, IntentPreviewError, Prerequisite, RWAOpenRequirementsPrerequisite, TransferAlignmentError, UnexpectedFacadeEventOrderError, UnknownAdapterError, UnknownFacadeCallError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, WithdrawCollateralAlignmentError, buildDelayedPreview, checkOperation, checkPrerequisites, checkSimulation, classifyCloseOrRepay, classifyInnerOperations, collateralIssue, detectDelayedClaim, detectDelayedOperation, extractAdapterCallTraces, extractTransfers, findFacadeCalls, isCloseOrRepay, isPoolOperation, isRWAOperation, makeReplayState, marketIssues, parseFacadeOperationCalldata, parseOperationCalldata, parsePoolOperationCalldata, parseRWAFactoryOperationCalldata, previewAdjustCreditAccount, previewCloseOrRepayCreditAccount, previewOperation, quotaCountIssue, raise, refuse, replayInnerOperations, replayMulticall, resolveDelayedClaimIntent };
@@ -17,7 +17,7 @@ import { isAddressEqual } from "viem";
17
17
  * nothing and set a non-fatal `ERROR_UNPRICEABLE_TOKEN` error on the
18
18
  * preview.
19
19
  *
20
- * The changes (e.g. `debtChange`) are reported relative to the account
20
+ * The changes (e.g. `totalDebtChange`) are reported relative to the account
21
21
  * state before the whole transaction.
22
22
  *
23
23
  * @param afterInstant - Account state after the instant part of the
@@ -187,9 +187,10 @@ function buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk) {
187
187
  creditAccount: post.creditAccount,
188
188
  collateralAdded: [],
189
189
  collateralWithdrawn: collateralWithdrawn.toAssets().map((a) => oracle.toTokenAmount(a.token, a.balance)),
190
- totalValue,
191
- debt: post.totalDebt,
192
- debtChange: post.totalDebt - before.totalDebt,
190
+ totalValue: market.toUnderlyingAmount(totalValue),
191
+ totalDebt: market.toUnderlyingAmount(post.totalDebt),
192
+ netValue: market.toUnderlyingAmount(totalValue - post.totalDebt),
193
+ totalDebtChange: market.toUnderlyingAmount(post.totalDebt - before.totalDebt),
193
194
  quotas: quotas.map((q) => ({
194
195
  token: sdk.tokensMeta.mustGetToken(q.token),
195
196
  ...oracle.toAmount(market.underlying, q.balance)
@@ -45,9 +45,10 @@ async function previewAdjustCreditAccount(input, operation, options) {
45
45
  creditAccount: operation.creditAccount,
46
46
  collateralAdded: collateralAdded.map((a) => oracle.toTokenAmount(a.token, a.balance)),
47
47
  collateralWithdrawn: after.collateralWithdrawn.toAssets().map((a) => oracle.toTokenAmount(a.token, a.balance)),
48
- totalValue,
49
- debt: account.totalDebt,
50
- debtChange: account.totalDebt - before.totalDebt,
48
+ totalValue: market.toUnderlyingAmount(totalValue),
49
+ totalDebt: market.toUnderlyingAmount(account.totalDebt),
50
+ netValue: market.toUnderlyingAmount(totalValue - account.totalDebt),
51
+ totalDebtChange: market.toUnderlyingAmount(account.totalDebt - before.totalDebt),
51
52
  quotas: quotas.map((q) => ({
52
53
  token: sdk.tokensMeta.mustGetToken(q.token),
53
54
  ...oracle.toAmount(market.underlying, q.balance)
@@ -56,7 +56,7 @@ function previewRepayCreditAccount(input, operation, permanent, replay) {
56
56
  name: sdk.marketRegister.findCreditManager(operation.creditManager).name,
57
57
  creditAccount: operation.creditAccount,
58
58
  collateralAdded: collateralAdded.map((a) => market.priceOracle.toTokenAmount(a.token, a.balance)),
59
- debtRepaid: before.totalDebt - after.account.totalDebt,
59
+ debtRepaid: market.toUnderlyingAmount(before.totalDebt - after.account.totalDebt),
60
60
  collateralWithdrawn: after.collateralWithdrawn.toAssets().map((a) => market.priceOracle.toTokenAmount(a.token, a.balance)),
61
61
  error
62
62
  };
@@ -16,7 +16,7 @@ async function previewOpenCreditAccount(input, operation) {
16
16
  let error = await replayInnerOperations(sdk, operation.multicall, state);
17
17
  const account = state.account;
18
18
  let priceError;
19
- const collateralValue = state.collateralAdded.sum((token, balance) => {
19
+ const netValue = state.collateralAdded.sum((token, balance) => {
20
20
  try {
21
21
  return oracle.convert(token, market.underlying, balance);
22
22
  } catch {
@@ -31,18 +31,18 @@ async function previewOpenCreditAccount(input, operation) {
31
31
  error ??= unwrapError ?? priceError;
32
32
  const assets = account.balances.toAssets(DUST_THRESHOLD);
33
33
  const quotas = account.quotas.toAssets(0n);
34
- const totalValue = collateralValue + account.totalDebt;
34
+ const totalValue = netValue + account.totalDebt;
35
35
  const snap = account.toSnapshot(totalValue);
36
36
  const targetAsset = inferTargetAsset(operation.multicall, account.balances);
37
37
  return {
38
38
  operation: operation.operation,
39
39
  creditManager: operation.creditManager,
40
40
  name: sdk.marketRegister.findCreditManager(operation.creditManager).name,
41
- target: targetAsset ? oracle.toTokenAmount(targetAsset.token, targetAsset.balance) : void 0,
42
- collateral: collateral.map((a) => oracle.toTokenAmount(a.token, a.balance)),
43
- collateralValue,
44
- totalValue,
45
- debt: account.debt,
41
+ targetCollateral: targetAsset ? oracle.toTokenAmount(targetAsset.token, targetAsset.balance) : void 0,
42
+ collateralAdded: collateral.map((a) => oracle.toTokenAmount(a.token, a.balance)),
43
+ netValue: market.toUnderlyingAmount(netValue),
44
+ totalValue: market.toUnderlyingAmount(totalValue),
45
+ totalDebt: market.toUnderlyingAmount(account.totalDebt),
46
46
  quotas: quotas.map((q) => ({
47
47
  token: sdk.tokensMeta.mustGetToken(q.token),
48
48
  ...oracle.toAmount(market.underlying, q.balance)