@gearbox-protocol/sdk 16.4.0-next.1 → 16.4.0-next.10

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 (115) hide show
  1. package/dist/cjs/dev/index.js +3 -2
  2. package/dist/cjs/dev/kycUtils.js +18 -35
  3. package/dist/cjs/dev/midasUtils.js +80 -16
  4. package/dist/cjs/dev/securitizeUtils.js +14 -10
  5. package/dist/cjs/dev/withdrawalUtils.js +3 -6
  6. package/dist/cjs/model/errors/index.js +1 -0
  7. package/dist/cjs/model/errors/operation-errors.js +9 -0
  8. package/dist/cjs/model/index.js +1 -0
  9. package/dist/cjs/onchain/accounts/CreditAccountsServiceV310.js +0 -1
  10. package/dist/cjs/onchain/accounts/intents/borrow.js +139 -0
  11. package/dist/cjs/onchain/accounts/intents/{collateral-money.js → collateral-valuation.js} +7 -7
  12. package/dist/cjs/onchain/accounts/intents/index.js +86 -2
  13. package/dist/cjs/onchain/accounts/intents/leverage-band.js +2 -12
  14. package/dist/cjs/onchain/accounts/intents/maxBorrow.js +89 -0
  15. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +14 -14
  16. package/dist/cjs/onchain/accounts/intents/open-strategy.js +6 -45
  17. package/dist/cjs/onchain/accounts/intents/realize.js +44 -0
  18. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  19. package/dist/cjs/onchain/accounts/intents/utils/common.js +19 -0
  20. package/dist/cjs/onchain/accounts/intents/utils/credit-account-slice.js +21 -0
  21. package/dist/cjs/onchain/accounts/intents/utils/index.js +2 -0
  22. package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +3 -3
  23. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +8 -8
  24. package/dist/cjs/onchain/core/createAddressProvider.js +2 -5
  25. package/dist/cjs/onchain/index.js +4 -0
  26. package/dist/cjs/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  27. package/dist/cjs/onchain/positions/calcHealthFactor.js +3 -3
  28. package/dist/cjs/onchain/preview/index.js +2 -0
  29. package/dist/cjs/onchain/preview/preview/index.js +2 -0
  30. package/dist/cjs/onchain/preview/preview/midasGreenlistsAccount.js +17 -0
  31. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +5 -2
  32. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +2 -1
  33. package/dist/cjs/onchain/validation/bundles/checkMidasAccountGreenlist.js +44 -0
  34. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +15 -5
  35. package/dist/cjs/onchain/validation/bundles/index.js +2 -0
  36. package/dist/cjs/onchain/validation/index.js +2 -0
  37. package/dist/cjs/sdk/execute/ExecuteApi.js +65 -5
  38. package/dist/cjs/sdk/prepare/PrepareApi.js +86 -12
  39. package/dist/esm/dev/index.js +3 -3
  40. package/dist/esm/dev/kycUtils.js +17 -33
  41. package/dist/esm/dev/midasUtils.js +80 -18
  42. package/dist/esm/dev/securitizeUtils.js +15 -11
  43. package/dist/esm/dev/withdrawalUtils.js +3 -6
  44. package/dist/esm/model/errors/index.js +2 -2
  45. package/dist/esm/model/errors/operation-errors.js +9 -1
  46. package/dist/esm/model/index.js +2 -2
  47. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +0 -1
  48. package/dist/esm/onchain/accounts/intents/borrow.js +137 -0
  49. package/dist/esm/onchain/accounts/intents/{collateral-money.js → collateral-valuation.js} +7 -7
  50. package/dist/esm/onchain/accounts/intents/index.js +86 -2
  51. package/dist/esm/onchain/accounts/intents/leverage-band.js +2 -12
  52. package/dist/esm/onchain/accounts/intents/maxBorrow.js +87 -0
  53. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +14 -14
  54. package/dist/esm/onchain/accounts/intents/open-strategy.js +6 -45
  55. package/dist/esm/onchain/accounts/intents/realize.js +44 -0
  56. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  57. package/dist/esm/onchain/accounts/intents/utils/common.js +19 -1
  58. package/dist/esm/onchain/accounts/intents/utils/credit-account-slice.js +21 -1
  59. package/dist/esm/onchain/accounts/intents/utils/index.js +3 -3
  60. package/dist/esm/onchain/accounts/intents/utils/price-impact.js +3 -3
  61. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +8 -8
  62. package/dist/esm/onchain/core/createAddressProvider.js +2 -5
  63. package/dist/esm/onchain/index.js +3 -1
  64. package/dist/esm/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +11 -3
  65. package/dist/esm/onchain/positions/calcHealthFactor.js +3 -3
  66. package/dist/esm/onchain/preview/index.js +2 -1
  67. package/dist/esm/onchain/preview/preview/index.js +2 -1
  68. package/dist/esm/onchain/preview/preview/midasGreenlistsAccount.js +16 -0
  69. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +5 -2
  70. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +2 -1
  71. package/dist/esm/onchain/validation/bundles/checkMidasAccountGreenlist.js +43 -0
  72. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +15 -5
  73. package/dist/esm/onchain/validation/bundles/index.js +2 -1
  74. package/dist/esm/onchain/validation/index.js +2 -1
  75. package/dist/esm/sdk/execute/ExecuteApi.js +65 -5
  76. package/dist/esm/sdk/prepare/PrepareApi.js +86 -12
  77. package/dist/types/dev/index.d.ts +3 -3
  78. package/dist/types/dev/kycUtils.d.ts +1 -5
  79. package/dist/types/dev/midasUtils.d.ts +15 -4
  80. package/dist/types/model/errors/index.d.ts +2 -2
  81. package/dist/types/model/errors/operation-errors.d.ts +14 -1
  82. package/dist/types/model/index.d.ts +2 -2
  83. package/dist/types/model/previews.d.ts +17 -2
  84. package/dist/types/onchain/accounts/index.d.ts +4 -3
  85. package/dist/types/onchain/accounts/intents/borrow.d.ts +141 -0
  86. package/dist/types/onchain/accounts/intents/{collateral-money.d.ts → collateral-valuation.d.ts} +8 -8
  87. package/dist/types/onchain/accounts/intents/index.d.ts +81 -2
  88. package/dist/types/onchain/accounts/intents/maxBorrow.d.ts +54 -0
  89. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -3
  90. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -17
  91. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +2 -0
  92. package/dist/types/onchain/accounts/intents/tests/open-strategy.fixtures.d.ts +2 -2
  93. package/dist/types/onchain/accounts/intents/types.d.ts +15 -1
  94. package/dist/types/onchain/accounts/intents/utils/common.d.ts +15 -1
  95. package/dist/types/onchain/accounts/intents/utils/credit-account-slice.d.ts +14 -1
  96. package/dist/types/onchain/accounts/intents/utils/index.d.ts +3 -3
  97. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +1 -1
  98. package/dist/types/onchain/index.d.ts +7 -4
  99. package/dist/types/onchain/market/adapters/contracts/MidasGatewayAdapterContract.d.ts +8 -2
  100. package/dist/types/onchain/preview/index.d.ts +2 -1
  101. package/dist/types/onchain/preview/preview/index.d.ts +2 -1
  102. package/dist/types/onchain/preview/preview/midasGreenlistsAccount.d.ts +13 -0
  103. package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +2 -2
  104. package/dist/types/onchain/validation/bundles/checkMidasAccountGreenlist.d.ts +22 -0
  105. package/dist/types/onchain/validation/bundles/checkRWAOpening.d.ts +6 -4
  106. package/dist/types/onchain/validation/bundles/index.d.ts +3 -2
  107. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +2 -2
  108. package/dist/types/onchain/validation/index.d.ts +3 -2
  109. package/dist/types/sdk/execute/index.d.ts +2 -2
  110. package/dist/types/sdk/execute/types.d.ts +48 -6
  111. package/dist/types/sdk/index.d.ts +5 -4
  112. package/dist/types/sdk/prepare/PrepareApi.d.ts +15 -3
  113. package/dist/types/sdk/prepare/index.d.ts +4 -3
  114. package/dist/types/sdk/prepare/types.d.ts +176 -49
  115. package/package.json +1 -1
@@ -7,9 +7,11 @@ import { IntentPreviewError } from "../../validation/raise.js";
7
7
  import "../../validation/index.js";
8
8
  import { isPhantomToken } from "./utils/pick-token.js";
9
9
  import { assertMarketOperable } from "./guards.js";
10
+ import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
11
+ import { buildBorrowState } from "./borrow.js";
10
12
  import { calcLeverageBand } from "./leverage-band.js";
13
+ import { maxBorrow } from "./maxBorrow.js";
11
14
  import { maxWithdrawCollateral } from "./maxWithdrawCollateral.js";
12
- import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
13
15
  import { buildOpenStrategyState } from "./open-strategy.js";
14
16
  import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
15
17
  import { accountView } from "./view.js";
@@ -132,6 +134,34 @@ var CreditAccountOperationsService = class extends SDKConstruct {
132
134
  });
133
135
  }
134
136
  /**
137
+ * Largest loan a given collateral supports at `targetHF`, in the payout
138
+ * token's units — the ceiling a borrow form should offer.
139
+ *
140
+ * Reads no account, like {@link leverageBand}: the borrow opens one. The
141
+ * collateral is valued the way the transaction will be judged, at safe
142
+ * prices and under the quota the borrow buys, and the answer is then held to
143
+ * what the market will lend.
144
+ *
145
+ * A ceiling, not a verdict: the facade's `minDebt` is a floor and is not
146
+ * applied here, so collateral too small for this market still answers with
147
+ * what it carries and {@link borrowIntent} is the one that refuses the loan.
148
+ *
149
+ * The default is {@link MIN_HF_LIMITED}, the threshold a form holds an
150
+ * account to.
151
+ *
152
+ * @param props - The manager, the SDK holding its market, the collateral put
153
+ * up, the token to be paid in, and optionally the health factor to land at
154
+ * @returns Amount in the payout token's units; `0n` where no loan of this
155
+ * shape can be funded at any size
156
+ */
157
+ maxBorrow(props) {
158
+ const { targetHF = MIN_HF_LIMITED, ...rest } = props;
159
+ return maxBorrow({
160
+ ...rest,
161
+ targetHF: targetHF + 2n
162
+ });
163
+ }
164
+ /**
135
165
  * Previews the same operation when its source only redeems through its
136
166
  * issuer: a Securitize dsToken, a Mellow share.
137
167
  *
@@ -182,7 +212,10 @@ var CreditAccountOperationsService = class extends SDKConstruct {
182
212
  });
183
213
  return {
184
214
  ...result,
185
- state: tail.state,
215
+ state: {
216
+ ...tail.state,
217
+ executionCost: result.state.executionCost
218
+ },
186
219
  delayed
187
220
  };
188
221
  } catch (e) {
@@ -274,6 +307,26 @@ var CreditAccountOperationsService = class extends SDKConstruct {
274
307
  };
275
308
  }
276
309
  /**
310
+ * Previews opening an account that holds nothing.
311
+ *
312
+ * Nothing is put up, drawn or routed, so there is no state to build and no
313
+ * guard to run beyond the market's own: a paused or expired facade takes no
314
+ * multicall, and an opening is a multicall like any other. Answers the same
315
+ * envelope its two neighbours do so a caller branches on `ok` throughout.
316
+ *
317
+ * @param props - The SDK holding the market, and the manager to open in
318
+ * @returns `{ ok: true }`, or `{ ok: false, error }` when the market takes
319
+ * no transaction right now
320
+ */
321
+ async openEmptyAccountIntent(props) {
322
+ try {
323
+ assertMarketOperable(props.sdk.marketRegister.findCreditManager(props.creditManager));
324
+ return { ok: true };
325
+ } catch (e) {
326
+ return asSDKError(e);
327
+ }
328
+ }
329
+ /**
277
330
  * Previews opening a brand-new leveraged position.
278
331
  *
279
332
  * Sits apart from {@link startIntent} because there is no account yet: nothing
@@ -295,6 +348,37 @@ var CreditAccountOperationsService = class extends SDKConstruct {
295
348
  return asSDKError(e);
296
349
  }
297
350
  }
351
+ /**
352
+ * Previews taking a loan against collateral, on an account this same
353
+ * transaction opens.
354
+ *
355
+ * Sits beside {@link openStrategyIntent} rather than under
356
+ * {@link startIntent} for the same reason: there is no account yet, and the
357
+ * output feeds `sdk.accounts.openCA`. What sets it apart from an opening is
358
+ * where the loan goes — out to the wallet rather than into a position — so
359
+ * the debt is named outright instead of following from a leverage, and the
360
+ * collateral is the only thing the account is left holding.
361
+ *
362
+ * `creditAccount` draws the loan on one the wallet already holds instead of
363
+ * opening another, as an opening takes one.
364
+ *
365
+ * @param props - Credit manager, the collateral the wallet puts up and the
366
+ * payout it asks for
367
+ * @returns Debt, the payout's two branches and the projection the account
368
+ * lands in, or `{ ok: false, error }` when the loan is not viable — a debt
369
+ * outside the facade's limits, collateral that cannot carry it, a payout the
370
+ * router has no path to
371
+ */
372
+ async borrowIntent(props) {
373
+ try {
374
+ return {
375
+ ok: true,
376
+ state: await buildBorrowState(props)
377
+ };
378
+ } catch (e) {
379
+ return asSDKError(e);
380
+ }
381
+ }
298
382
  /** Plan → realise → wrap. Unviable requests become `{ ok: false }`. */
299
383
  async #preview(props, plan) {
300
384
  try {
@@ -1,5 +1,6 @@
1
1
  import { BigIntMath } from "../../utils/bigint-math.js";
2
2
  import { LEVERAGE_DECIMALS } from "../../constants/math.js";
3
+ import { resolveCreditManager } from "./utils/common.js";
3
4
  //#region src/onchain/accounts/intents/leverage-band.ts
4
5
  /**
5
6
  * The leverages this market will actually fund for a position of this size.
@@ -29,7 +30,7 @@ import { LEVERAGE_DECIMALS } from "../../constants/math.js";
29
30
  * ```
30
31
  **/
31
32
  function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
32
- const found = resolve(sdk, creditManager);
33
+ const found = resolveCreditManager(sdk, creditManager);
33
34
  if (!found) return;
34
35
  const { suite, market } = found;
35
36
  const target = suite.strategyTargetCollateral;
@@ -54,16 +55,5 @@ function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
54
55
  max
55
56
  };
56
57
  }
57
- /** The manager's suite and market, or nothing while they cannot be resolved. */
58
- function resolve(sdk, creditManager) {
59
- try {
60
- return {
61
- suite: sdk.marketRegister.findCreditManager(creditManager),
62
- market: sdk.marketRegister.findByCreditManager(creditManager)
63
- };
64
- } catch {
65
- return;
66
- }
67
- }
68
58
  //#endregion
69
59
  export { calcLeverageBand };
@@ -0,0 +1,87 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import "../../constants/math.js";
3
+ import "../../utils/index.js";
4
+ import { eq, resolveCreditManager, toTargetDecimals } from "./utils/common.js";
5
+ import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
6
+ import "./utils/index.js";
7
+ import { borrowCollateralQuota } from "./borrow.js";
8
+ import { collateralValuation } from "./collateral-valuation.js";
9
+ //#region src/onchain/accounts/intents/maxBorrow.ts
10
+ /**
11
+ * Largest loan this collateral supports at `targetHF` — the ceiling a borrow
12
+ * form should offer, in the payout token's units.
13
+ *
14
+ * The inverse of a borrow rather than a search for one: the loan leaves the
15
+ * account entirely, so the collateral is the whole of what backs the debt, and
16
+ * the health factor is one division away from the amount. Solving it the other
17
+ * way round costs a division too, and no iteration.
18
+ *
19
+ * Collateral is valued the way the transaction will be judged — at safe
20
+ * prices, under its liquidation threshold, capped by the quota the borrow
21
+ * buys for it, all of which is {@link collateralValuation}'s business. The ceiling
22
+ * is then held to what the market will actually lend: the pool's free
23
+ * liquidity, the manager's own allowance and the facade's `maxDebt`, whichever
24
+ * binds first.
25
+ *
26
+ * The facade's `minDebt` is deliberately not applied. It is a floor, and a
27
+ * ceiling answered as `0n` because the collateral is too small for this market
28
+ * would tell a form nothing about what it is holding — the number a user needs
29
+ * to see is the one they are short of. Collateral that carries something
30
+ * therefore answers with it, whether or not the market would lend that little;
31
+ * a loan under the floor is refused by `borrow` itself, with `debtOutOfRange`
32
+ * naming both ends.
33
+ *
34
+ * Nothing is fetched or simulated — the account does not exist yet and every
35
+ * input is loaded market state, so a form can call this on each keystroke.
36
+ *
37
+ * @param props - {@link MaxBorrowProps}
38
+ * @returns Amount in the payout token's units; `0n` where no loan of this
39
+ * shape exists at any size — a collateral that backs nothing at safe prices, a
40
+ * market with nothing left to lend, and a manager the SDK does not hold yet
41
+ **/
42
+ function maxBorrow(props) {
43
+ const { sdk, creditManager, collateralAmount, targetHF, quotaReserve } = props;
44
+ const found = resolveCreditManager(sdk, creditManager);
45
+ if (!found) return 0n;
46
+ const { suite, market } = found;
47
+ const { priceOracle } = market;
48
+ const underlying = market.pool.underlying.toLowerCase();
49
+ const collateralToken = props.collateralToken.toLowerCase();
50
+ const borrowToken = props.borrowToken.toLowerCase();
51
+ const rwaAsset = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset?.toLowerCase();
52
+ if (eq(collateralToken, borrowToken)) return 0n;
53
+ if (rwaAsset && eq(borrowToken, underlying)) return 0n;
54
+ if (collateralAmount <= 10n || targetHF <= 0n) return 0n;
55
+ const quotas = borrowCollateralQuota({
56
+ sdk,
57
+ creditManager,
58
+ assets: [{
59
+ token: collateralToken,
60
+ balance: collateralAmount
61
+ }],
62
+ quotaReserve
63
+ });
64
+ const holding = {
65
+ token: collateralToken,
66
+ balance: collateralAmount,
67
+ quota: quotas.find((q) => eq(q.token, collateralToken))?.balance ?? 0n,
68
+ mask: 0n,
69
+ success: true
70
+ };
71
+ const valuation = collateralValuation({
72
+ ...unopenedAccountSlice({
73
+ creditManager,
74
+ creditFacade: suite.creditFacade.address,
75
+ underlying
76
+ }),
77
+ tokens: [holding]
78
+ }, sdk);
79
+ const weighted = valuation.checkedUsd(holding) * valuation.lt(collateralToken);
80
+ const backed = quotas.some((q) => eq(q.token, collateralToken)) ? BigIntMath.min(valuation.quotaValue(holding), weighted) : weighted;
81
+ if (backed <= 0n) return 0n;
82
+ const ceiling = BigIntMath.min(priceOracle.safeConvertFromUSD(underlying, backed / targetHF).value, suite.maxBorrowAmount().amount.value);
83
+ const unwrapsPayout = !!rwaAsset && eq(borrowToken, rwaAsset);
84
+ return eq(borrowToken, underlying) ? ceiling : unwrapsPayout ? toTargetDecimals(ceiling, underlying, borrowToken, sdk) : priceOracle.safeConvert(underlying, borrowToken, ceiling).value;
85
+ }
86
+ //#endregion
87
+ export { maxBorrow };
@@ -2,16 +2,16 @@ import { BigIntMath } from "../../utils/bigint-math.js";
2
2
  import "../../constants/math.js";
3
3
  import "../../utils/index.js";
4
4
  import { eq } from "./utils/common.js";
5
- import { collateralMoney } from "./collateral-money.js";
5
+ import { collateralValuation } from "./collateral-valuation.js";
6
6
  //#region src/onchain/accounts/intents/maxWithdrawCollateral.ts
7
7
  /**
8
8
  * Largest amount of one collateral the account can withdraw while its health
9
9
  * factor stays at or above `targetHF`.
10
10
  *
11
11
  * This is the collateral check solved for one balance, and it counts what that
12
- * check counts — see {@link collateralMoney} for the valuation, safe prices
13
- * included. The debt is valued at the main feed, as the check does. Zero debt
14
- * frees the whole balance.
12
+ * check counts — see {@link collateralValuation} for it, safe prices included.
13
+ * The debt is valued at the main feed, as the check does. Zero debt frees the
14
+ * whole balance.
15
15
  *
16
16
  * Rounding always favours the account, so the answer clears the check rather
17
17
  * than landing a wei short of it.
@@ -25,20 +25,20 @@ function maxWithdrawCollateral(props) {
25
25
  const target = creditAccount.tokens.find((t) => eq(t.token, token));
26
26
  if (!target || target.balance <= 10n) return 0n;
27
27
  if (creditAccount.totalDebt === 0n) return target.balance;
28
- const money = collateralMoney(creditAccount, sdk);
29
- let otherMoney = 0n;
28
+ const valuation = collateralValuation(creditAccount, sdk);
29
+ let otherValue = 0n;
30
30
  for (const t of creditAccount.tokens) {
31
- if (eq(t.token, token) || !money.counts(t)) continue;
32
- otherMoney += money.weigh(t);
31
+ if (eq(t.token, token) || !valuation.counts(t)) continue;
32
+ otherValue += valuation.weigh(t);
33
33
  }
34
- const borrowed = money.mainUsd(money.underlying, creditAccount.totalDebt);
34
+ const borrowed = valuation.mainUsd(valuation.underlying, creditAccount.totalDebt);
35
35
  if (borrowed === void 0 || borrowed <= 0n) return 0n;
36
36
  const required = borrowed * targetHF;
37
- if (required <= otherMoney) return target.balance;
38
- const shortfall = required - otherMoney;
39
- if (target.quota > 0n && money.quotaMoney(target) < shortfall) return 0n;
40
- const targetLt = money.lt(target.token);
41
- const targetUsd = money.checkedUsd(target);
37
+ if (required <= otherValue) return target.balance;
38
+ const shortfall = required - otherValue;
39
+ if (target.quota > 0n && valuation.quotaValue(target) < shortfall) return 0n;
40
+ const targetLt = valuation.lt(target.token);
41
+ const targetUsd = valuation.checkedUsd(target);
42
42
  if (targetLt === 0n || targetUsd === 0n) return 0n;
43
43
  const keptUsd = BigIntMath.ceilDiv(shortfall, targetLt);
44
44
  const kept = BigIntMath.ceilDiv(target.balance * keptUsd, targetUsd);
@@ -3,17 +3,13 @@ import "../../../model/index.js";
3
3
  import { IntentPreviewError } from "../../validation/raise.js";
4
4
  import { assertCanBorrow, assertCollateralised, assertGrowthAllowed, assertMarketOperable, assertQuotaAvailable } from "./guards.js";
5
5
  import { assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage } from "./math.js";
6
+ import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
6
7
  import { collectPriceImpact } from "./utils/price-impact.js";
7
8
  import { getQuotasForUpdate } from "./utils/quotas-for-update.js";
8
9
  import { createRouterPaths } from "./utils/router-path.js";
9
10
  import "./utils/index.js";
10
11
  //#region src/onchain/accounts/intents/open-strategy.ts
11
12
  /**
12
- * Stand-in account address, used when the opening creates its own account:
13
- * nothing exists on chain until the tx lands.
14
- */
15
- const NO_ACCOUNT = "0x0000000000000000000000000000000000000000";
16
- /**
17
13
  * Builds the state opening a leveraged position out of wallet collateral would
18
14
  * reach.
19
15
  *
@@ -26,7 +22,6 @@ const NO_ACCOUNT = "0x0000000000000000000000000000000000000000";
26
22
  * `sdk.accounts.openCA`.
27
23
  */
28
24
  async function buildOpenStrategyState(props) {
29
- if (props.empty) return emptyOpenState(props);
30
25
  const { sdk, creditManager, collateral, targetToken, leverage, slippage = 0, quotaReserve, leftoverBalances = [], creditAccount: existing } = props;
31
26
  assertLeverageAtLeastOne(leverage);
32
27
  const suite = sdk.marketRegister.findCreditManager(creditManager);
@@ -37,16 +32,11 @@ async function buildOpenStrategyState(props) {
37
32
  const margin = collateral.reduce((acc, a) => acc + convert(a.token, underlying, a.balance), 0n);
38
33
  if (margin <= 0n) throw new IntentPreviewError(insufficientBalance(), "openStrategy: collateral is worth nothing in underlying");
39
34
  const debt = debtForLeverage(margin, leverage);
40
- const account = existing ?? {
41
- creditAccount: NO_ACCOUNT,
42
- creditManager: creditManager.toLowerCase(),
43
- creditFacade: suite.creditFacade.address.toLowerCase(),
44
- underlying,
45
- enabledTokensMask: 0n,
46
- totalDebtUSD: 0n,
47
- totalDebt: 0n,
48
- tokens: []
49
- };
35
+ const account = existing ?? unopenedAccountSlice({
36
+ creditManager,
37
+ creditFacade: suite.creditFacade.address,
38
+ underlying
39
+ });
50
40
  assertDebtLimits(sdk, debt, suite.creditFacade, underlying);
51
41
  assertCanBorrow(sdk, suite, debt);
52
42
  const paths = createRouterPaths({
@@ -110,35 +100,6 @@ async function buildOpenStrategyState(props) {
110
100
  creditAccount: existing?.creditAccount
111
101
  };
112
102
  }
113
- /**
114
- * The opening that holds an account and nothing else.
115
- *
116
- * Taken before the walk rather than threaded through it: the router has no
117
- * guard for an empty basket and would still make its `eth_call`, and every
118
- * assertion below reads amounts that are not there.
119
- */
120
- async function emptyOpenState(props) {
121
- const { sdk, creditManager } = props;
122
- assertMarketOperable(sdk.marketRegister.findCreditManager(creditManager));
123
- const snapshot = {
124
- creditManager,
125
- assets: [],
126
- quotas: [],
127
- totalDebt: 0n,
128
- totalValue: 0n
129
- };
130
- const { assets: _assets, quotas: _quotas, ...projection } = sdk.positions.projection(snapshot, { availableLiquidityChange: 0n });
131
- return {
132
- ...projection,
133
- currentPrice: sdk.positions.currentPrice(snapshot),
134
- priceImpact: void 0,
135
- averageAssets: [],
136
- minAssets: [],
137
- averageQuota: [],
138
- minQuota: [],
139
- calls: []
140
- };
141
- }
142
103
  /** Collateral plus the borrowed underlying, folded into one balance per token. */
143
104
  function mergeExpectedBalances(collateral, underlying, debt) {
144
105
  const merged = /* @__PURE__ */ new Map();
@@ -1,3 +1,4 @@
1
+ import { PERCENTAGE_FACTOR_1KK } from "../../constants/math.js";
1
2
  import { insufficientBalance } from "../../../model/errors/operation-errors.js";
2
3
  import { multipleDelayedWithdrawals, noDelayedRoute, withdrawalInProgress } from "../../../model/errors/prepare-errors.js";
3
4
  import "../../../model/index.js";
@@ -72,6 +73,26 @@ async function realize(steps, props) {
72
73
  let raised = 0n;
73
74
  /** The request, before the walk's end state can be attached to it. */
74
75
  let delayed;
76
+ /** Oracle value in the underlying of what routed legs and requests spend and return. */
77
+ const traded = {
78
+ spentUnd: 0n,
79
+ returnedUnd: 0n,
80
+ priced: true
81
+ };
82
+ const trade = (spent, returned) => {
83
+ const underlyingValue = (legs) => {
84
+ let sum = 0n;
85
+ for (const { token, amount } of legs) {
86
+ if (amount === 0n) continue;
87
+ const value = price(token, underlying, amount);
88
+ if (value <= 0n) traded.priced = false;
89
+ sum += value;
90
+ }
91
+ return sum;
92
+ };
93
+ traded.spentUnd += underlyingValue(spent);
94
+ traded.returnedUnd += underlyingValue(returned);
95
+ };
75
96
  /**
76
97
  * Set by a `clearQuotas` step, which settles the quotas mid-walk instead of
77
98
  * at the end — and settles them at none, whatever the balances turn out to be.
@@ -173,6 +194,13 @@ async function realize(steps, props) {
173
194
  ...swap,
174
195
  amountOut: leg.amount
175
196
  });
197
+ trade([{
198
+ token: step.from,
199
+ amount
200
+ }], [{
201
+ token: step.to,
202
+ amount: leg.amount
203
+ }]);
176
204
  raised = leg.minAmount;
177
205
  break;
178
206
  }
@@ -198,6 +226,13 @@ async function realize(steps, props) {
198
226
  })),
199
227
  amountOut: leg.amount
200
228
  });
229
+ trade(balances.map((a) => ({
230
+ token: a.token,
231
+ amount: a.balance
232
+ })), [{
233
+ token: underlying,
234
+ amount: leg.amount
235
+ }]);
201
236
  }
202
237
  }
203
238
  raised = ledger.balanceOf(underlying);
@@ -242,6 +277,13 @@ async function realize(steps, props) {
242
277
  amount: toTargetDecimals(queued.amount, queued.token, asset.underlying, sdk)
243
278
  } : void 0
244
279
  };
280
+ trade([{
281
+ token: preview.token,
282
+ amount: preview.amountIn
283
+ }], [...preview.outputs.filter((o) => !o.isDelayed).map((o) => ({
284
+ token: o.token,
285
+ amount: o.amount
286
+ })), ...delayed.claim ? [delayed.claim] : []]);
245
287
  raised = instantOutput(preview.outputs)?.amount ?? 0n;
246
288
  break;
247
289
  }
@@ -337,9 +379,11 @@ async function realize(steps, props) {
337
379
  netValue: projected.totalValue - debt,
338
380
  toUnderlying: (from, amount) => price(from, underlying, amount)
339
381
  });
382
+ const executionCost = traded.priced && traded.spentUnd > 0n ? PERCENTAGE_FACTOR_1KK * (traded.returnedUnd - traded.spentUnd) / traded.spentUnd : void 0;
340
383
  const state = {
341
384
  ...projection,
342
385
  priceImpact,
386
+ executionCost,
343
387
  currentPrice: sdk.positions.currentPrice(snapshot)
344
388
  };
345
389
  return {
@@ -203,6 +203,7 @@ function buildMockSdk(args) {
203
203
  liquidationThresholds,
204
204
  collateralTokens,
205
205
  feeInterest: args.feeInterest ?? 0,
206
+ maxEnabledTokens: args.maxEnabledTokens ?? 4,
206
207
  maxLeverage: (collateral, targetHF) => calcMaxLeverage(liquidationThresholds.get(collateral) ?? 0, targetHF)
207
208
  },
208
209
  creditFacade: {
@@ -2,6 +2,24 @@ import { AddressMap } from "../../../utils/AddressMap.js";
2
2
  //#region src/onchain/accounts/intents/utils/common.ts
3
3
  /** Case-insensitive address equality. */
4
4
  const eq = (a, b) => a.toLowerCase() === b.toLowerCase();
5
+ /**
6
+ * The suite and market behind a credit manager, or nothing where the register
7
+ * has no entry for it.
8
+ *
9
+ * For the reads a form calls on every keystroke, including before the SDK has
10
+ * finished attaching: a question the register cannot answer yet is not an
11
+ * error. Everything that prepares a transaction wants the throw instead.
12
+ */
13
+ function resolveCreditManager(sdk, creditManager) {
14
+ try {
15
+ return {
16
+ suite: sdk.marketRegister.findCreditManager(creditManager),
17
+ market: sdk.marketRegister.findByCreditManager(creditManager)
18
+ };
19
+ } catch {
20
+ return;
21
+ }
22
+ }
5
23
  function toTargetDecimals(fromAmount, fromToken, toToken, sdk) {
6
24
  const fromDecimals = sdk.tokensMeta.get(fromToken)?.decimals ?? 18;
7
25
  const toDecimals = sdk.tokensMeta.get(toToken)?.decimals ?? 18;
@@ -37,4 +55,4 @@ function toRouterCaSlice(creditAccount, expectedBalances = []) {
37
55
  };
38
56
  }
39
57
  //#endregion
40
- export { eq, toRouterCaSlice, toTargetDecimals };
58
+ export { eq, resolveCreditManager, toRouterCaSlice, toTargetDecimals };
@@ -26,6 +26,26 @@ function toCreditAccountSlice(ca) {
26
26
  };
27
27
  }
28
28
  /**
29
+ * The slice a flow that has no account yet quotes against.
30
+ *
31
+ * Nothing of it exists on chain until the transaction lands, and nothing has
32
+ * to: the pathfinder is asked about the credit manager, and every balance the
33
+ * flow reasons about is one the transaction itself puts there. The zero
34
+ * address stands in for the account so the shape is complete.
35
+ */
36
+ function unopenedAccountSlice(args) {
37
+ return {
38
+ creditAccount: "0x0000000000000000000000000000000000000000",
39
+ creditManager: args.creditManager.toLowerCase(),
40
+ creditFacade: args.creditFacade.toLowerCase(),
41
+ underlying: args.underlying.toLowerCase(),
42
+ enabledTokensMask: 0n,
43
+ totalDebtUSD: 0n,
44
+ totalDebt: 0n,
45
+ tokens: []
46
+ };
47
+ }
48
+ /**
29
49
  * Reads an account by address and narrows it to {@link CreditAccountSlice}.
30
50
  *
31
51
  * The shared read model's `StrategyPosition` carries neither `tokens` nor
@@ -40,4 +60,4 @@ async function fetchCreditAccountSlice(sdk, creditAccount) {
40
60
  return toCreditAccountSlice(data);
41
61
  }
42
62
  //#endregion
43
- export { fetchCreditAccountSlice, toCreditAccountSlice };
63
+ export { fetchCreditAccountSlice, toCreditAccountSlice, unopenedAccountSlice };
@@ -1,11 +1,11 @@
1
- import { eq, toRouterCaSlice, toTargetDecimals } from "./common.js";
1
+ import { eq, resolveCreditManager, toRouterCaSlice, toTargetDecimals } from "./common.js";
2
2
  import { isPhantomToken, isRedemptionPhantomToken, pickFattestNonPhantomToken, rankAccountTokens } from "./pick-token.js";
3
3
  import { adjustStateToSnapshot } from "./adjust-state-to-snapshot.js";
4
4
  import { assembleOperationCalls } from "./assemble-operation-calls.js";
5
5
  import { calcBorrowedAmountPlusInterestAndFees } from "./borrowed-amount-plus-interest-and-fees.js";
6
- import { fetchCreditAccountSlice, toCreditAccountSlice } from "./credit-account-slice.js";
6
+ import { fetchCreditAccountSlice, toCreditAccountSlice, unopenedAccountSlice } from "./credit-account-slice.js";
7
7
  import { OperationLedger } from "./ledger.js";
8
8
  import { collectPriceImpact, lossRate, startProbe } from "./price-impact.js";
9
9
  import { clearedQuotas, getQuotasForUpdate, quotasAfterUpdate } from "./quotas-for-update.js";
10
10
  import { createOraclePaths, createRouterPaths } from "./router-path.js";
11
- export { OperationLedger, adjustStateToSnapshot, assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, clearedQuotas, collectPriceImpact, createOraclePaths, createRouterPaths, eq, fetchCreditAccountSlice, getQuotasForUpdate, isPhantomToken, isRedemptionPhantomToken, lossRate, pickFattestNonPhantomToken, quotasAfterUpdate, rankAccountTokens, startProbe, toCreditAccountSlice, toRouterCaSlice, toTargetDecimals };
11
+ export { OperationLedger, adjustStateToSnapshot, assembleOperationCalls, calcBorrowedAmountPlusInterestAndFees, clearedQuotas, collectPriceImpact, createOraclePaths, createRouterPaths, eq, fetchCreditAccountSlice, getQuotasForUpdate, isPhantomToken, isRedemptionPhantomToken, lossRate, pickFattestNonPhantomToken, quotasAfterUpdate, rankAccountTokens, resolveCreditManager, startProbe, toCreditAccountSlice, toRouterCaSlice, toTargetDecimals, unopenedAccountSlice };
@@ -18,12 +18,12 @@ function probeBasket(balances, oracle) {
18
18
  if (usd > 0n) basketWad += usd * WAD / PRICE_DECIMALS;
19
19
  }
20
20
  if (basketWad <= 0n) return;
21
- const probeWad = PROBE_UNIT_USD_WAD;
22
21
  const scaled = balances.map((asset) => ({
23
22
  token: asset.token,
24
- balance: asset.balance * probeWad / basketWad
23
+ balance: asset.balance * PROBE_UNIT_USD_WAD / basketWad
25
24
  }));
26
- if (!scaled.some((a) => a.balance > 0n)) return;
25
+ const probeWad = scaled.reduce((sum, a) => sum + oracle.safeConvertToUSD(a.token, a.balance).value * WAD / PRICE_DECIMALS, 0n);
26
+ if (probeWad <= 0n) return;
27
27
  return {
28
28
  balances: scaled,
29
29
  basketWad,
@@ -3,8 +3,8 @@ import "../../utils/index.js";
3
3
  import { MIN_HEALTH_FACTOR_FACADE } from "../../validation/helpers/health-factor-limits.js";
4
4
  import "../../validation/index.js";
5
5
  import { eq } from "./utils/common.js";
6
- import { collateralMoney } from "./collateral-money.js";
7
6
  import { maxProportionalWithdrawal } from "./math.js";
7
+ import { collateralValuation } from "./collateral-valuation.js";
8
8
  import { accountView } from "./view.js";
9
9
  //#region src/onchain/accounts/intents/withdraw-limits.ts
10
10
  /**
@@ -38,7 +38,7 @@ function withdrawLimits(props) {
38
38
  * in underlying units.
39
39
  *
40
40
  * A withdrawal hands funds over, so the facade weighs the account it leaves
41
- * behind at safe prices rather than main ones — see {@link collateralMoney}.
41
+ * behind at safe prices rather than main ones — see {@link collateralValuation}.
42
42
  * That is a second limit on top of the facade's `debtLimits`, and the two are
43
43
  * independent: a caller wanting the amount a form may actually offer takes the
44
44
  * lesser of this and `maxProportionalWithdrawal`.
@@ -71,20 +71,20 @@ function maxSafeWithdrawal(props) {
71
71
  const view = accountView(creditAccount, sdk);
72
72
  if (view.collateral <= 0n) return 0n;
73
73
  if (view.debt === 0n) return view.collateral;
74
- const money = collateralMoney(creditAccount, sdk);
74
+ const valuation = collateralValuation(creditAccount, sdk);
75
75
  const source = props.sourceToken ?? view.fattest();
76
76
  const holding = source === void 0 ? void 0 : creditAccount.tokens.find((t) => eq(t.token, source));
77
77
  if (!holding) return view.collateral;
78
78
  let total = 0n;
79
- for (const t of creditAccount.tokens) if (money.counts(t)) total += money.weigh(t);
80
- const debtUsd = money.mainUsd(money.underlying, view.debt);
79
+ for (const t of creditAccount.tokens) if (valuation.counts(t)) total += valuation.weigh(t);
80
+ const debtUsd = valuation.mainUsd(valuation.underlying, view.debt);
81
81
  if (debtUsd === void 0 || debtUsd <= 0n) return view.collateral;
82
82
  const slack = total - debtUsd * targetHF;
83
83
  if (slack < 0n) return 0n;
84
- const sourceMainUsd = money.mainUsd(holding.token, holding.balance);
84
+ const sourceMainUsd = valuation.mainUsd(holding.token, holding.balance);
85
85
  if (sourceMainUsd === void 0 || sourceMainUsd <= 0n) return view.collateral;
86
- const sourceRate = money.lt(holding.token) * money.checkedUsd(holding);
87
- const tvlUsd = money.mainUsd(money.underlying, view.collateral + view.debt);
86
+ const sourceRate = valuation.lt(holding.token) * valuation.checkedUsd(holding);
87
+ const tvlUsd = valuation.mainUsd(valuation.underlying, view.collateral + view.debt);
88
88
  if (tvlUsd === void 0) return view.collateral;
89
89
  const drain = sourceRate * tvlUsd - targetHF * debtUsd * sourceMainUsd;
90
90
  if (drain <= 0n) return view.collateral;
@@ -1,14 +1,11 @@
1
1
  import { iVersionAbi } from "../../abi/iVersion.js";
2
- import { AP_MARKET_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR } from "../constants/address-provider.js";
2
+ import "../constants/address-provider.js";
3
3
  import { isV310 } from "../constants/versions.js";
4
4
  import "../constants/index.js";
5
5
  import { hexEq } from "../utils/hex.js";
6
6
  import { AddressProviderV310Contract } from "./AddressProviderV310Contract.js";
7
7
  //#region src/onchain/core/createAddressProvider.ts
8
- const OVERRIDE_ADDRESSES = { Mainnet: {
9
- [AP_PRICE_FEED_COMPRESSOR]: { 311: "0x1fA2637B9fab0CD14290A7EE908DDc9688a15120" },
10
- [AP_MARKET_COMPRESSOR]: { 311: "0x0C27F242f6e9F2A9AD3261bE6e439De3B948bcA2" }
11
- } };
8
+ const OVERRIDE_ADDRESSES = {};
12
9
  async function createAddressProvider(sdk, address) {
13
10
  let v;
14
11
  if (hexEq(address, "0xF7f0a609BfAb9a0A98786951ef10e5FE26cC1E38")) v = 310n;