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