@morpho-org/morpho-sdk 10.5.0-next.0 → 10.6.0-next.0

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 (170) hide show
  1. package/README.md +44 -1
  2. package/lib/cjs/abis.d.ts +793 -0
  3. package/lib/cjs/abis.js +811 -1
  4. package/lib/cjs/actions/blue/close.d.ts +169 -0
  5. package/lib/cjs/actions/blue/close.js +270 -0
  6. package/lib/cjs/actions/blue/common.js +2 -2
  7. package/lib/cjs/actions/blue/delever.d.ts +156 -0
  8. package/lib/cjs/actions/blue/delever.js +223 -0
  9. package/lib/cjs/actions/blue/index.d.ts +3 -0
  10. package/lib/cjs/actions/blue/index.js +3 -0
  11. package/lib/cjs/actions/blue/lever.d.ts +184 -0
  12. package/lib/cjs/actions/blue/lever.js +272 -0
  13. package/lib/cjs/actions/blue/leverageIntent.d.ts +65 -0
  14. package/lib/cjs/actions/blue/leverageIntent.js +103 -0
  15. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
  16. package/lib/cjs/actions/midnight/takeBorrow.js +14 -8
  17. package/lib/cjs/actions/midnight/takeLend.js +15 -9
  18. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  19. package/lib/cjs/actions/midnight/takeWithdraw.js +14 -8
  20. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  21. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.js +59 -0
  22. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  23. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.js +193 -0
  24. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  25. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.js +66 -0
  26. package/lib/cjs/actions/requirements/blue/index.d.ts +3 -0
  27. package/lib/cjs/actions/requirements/blue/index.js +17 -0
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
  30. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +11 -6
  31. package/lib/cjs/actions/requirements/getRequirementsApproval.js +29 -5
  32. package/lib/cjs/addresses.d.ts +1 -1
  33. package/lib/cjs/addresses.js +6 -1
  34. package/lib/cjs/blue/addresses.d.ts +1 -1
  35. package/lib/cjs/blue/addresses.js +6 -1
  36. package/lib/cjs/constants.d.ts +1 -1
  37. package/lib/cjs/constants.js +7 -2
  38. package/lib/cjs/entities/blue/blue.d.ts +486 -2
  39. package/lib/cjs/entities/blue/blue.js +529 -34
  40. package/lib/cjs/entities/index.d.ts +1 -1
  41. package/lib/cjs/entities/midnight/midnight.d.ts +6 -0
  42. package/lib/cjs/entities/midnight/midnight.js +21 -2
  43. package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
  44. package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
  45. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +117 -0
  46. package/lib/cjs/entities/vaultV2BlueReallocationData.js +226 -2
  47. package/lib/cjs/helpers/constant.d.ts +41 -0
  48. package/lib/cjs/helpers/constant.js +42 -1
  49. package/lib/cjs/helpers/getZeroExLeverageBundle.d.ts +13 -0
  50. package/lib/cjs/helpers/getZeroExLeverageBundle.js +27 -0
  51. package/lib/cjs/helpers/index.d.ts +4 -1
  52. package/lib/cjs/helpers/index.js +29 -1
  53. package/lib/cjs/helpers/leverage/index.d.ts +1 -0
  54. package/lib/cjs/helpers/leverage/index.js +11 -0
  55. package/lib/cjs/helpers/leverage/limits.d.ts +472 -0
  56. package/lib/cjs/helpers/leverage/limits.js +715 -0
  57. package/lib/cjs/helpers/leverage/positionMarket.d.ts +17 -0
  58. package/lib/cjs/helpers/leverage/positionMarket.js +28 -0
  59. package/lib/cjs/helpers/leverage/reallocations.d.ts +159 -0
  60. package/lib/cjs/helpers/leverage/reallocations.js +276 -0
  61. package/lib/cjs/helpers/validate.d.ts +14 -0
  62. package/lib/cjs/helpers/validate.js +25 -1
  63. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  64. package/lib/cjs/helpers/validateRequirementSpender.js +4 -0
  65. package/lib/cjs/helpers/zeroExQuote.d.ts +250 -0
  66. package/lib/cjs/helpers/zeroExQuote.js +763 -0
  67. package/lib/cjs/index.d.ts +1 -0
  68. package/lib/cjs/index.js +5 -2
  69. package/lib/cjs/reads/assertContractCode.d.ts +25 -0
  70. package/lib/cjs/reads/assertContractCode.js +30 -0
  71. package/lib/cjs/reads/fetchZeroExQuote.d.ts +123 -0
  72. package/lib/cjs/reads/fetchZeroExQuote.js +330 -0
  73. package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +4 -0
  74. package/lib/cjs/transactionPlan/midnight/takeBorrow.js +8 -2
  75. package/lib/cjs/types/action.d.ts +130 -1
  76. package/lib/cjs/types/error.d.ts +84 -0
  77. package/lib/cjs/types/error.js +110 -3
  78. package/lib/cjs/types/index.d.ts +2 -0
  79. package/lib/cjs/types/index.js +2 -0
  80. package/lib/cjs/types/leverageError.d.ts +1552 -0
  81. package/lib/cjs/types/leverageError.js +1711 -0
  82. package/lib/cjs/types/zeroEx.d.ts +171 -0
  83. package/lib/cjs/types/zeroEx.js +2 -0
  84. package/lib/cjs/version.d.ts +1 -1
  85. package/lib/cjs/version.js +1 -1
  86. package/lib/esm/abis.d.ts +793 -0
  87. package/lib/esm/abis.js +809 -0
  88. package/lib/esm/actions/blue/close.d.ts +169 -0
  89. package/lib/esm/actions/blue/close.js +266 -0
  90. package/lib/esm/actions/blue/common.js +3 -3
  91. package/lib/esm/actions/blue/delever.d.ts +156 -0
  92. package/lib/esm/actions/blue/delever.js +219 -0
  93. package/lib/esm/actions/blue/index.d.ts +3 -0
  94. package/lib/esm/actions/blue/index.js +3 -0
  95. package/lib/esm/actions/blue/lever.d.ts +184 -0
  96. package/lib/esm/actions/blue/lever.js +268 -0
  97. package/lib/esm/actions/blue/leverageIntent.d.ts +65 -0
  98. package/lib/esm/actions/blue/leverageIntent.js +96 -0
  99. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
  100. package/lib/esm/actions/midnight/takeBorrow.js +14 -8
  101. package/lib/esm/actions/midnight/takeLend.js +15 -9
  102. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  103. package/lib/esm/actions/midnight/takeWithdraw.js +14 -8
  104. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  105. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.js +55 -0
  106. package/lib/esm/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  107. package/lib/esm/actions/requirements/blue/getLeverageRequirements.js +189 -0
  108. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  109. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.js +62 -0
  110. package/lib/esm/actions/requirements/blue/index.d.ts +3 -0
  111. package/lib/esm/actions/requirements/blue/index.js +3 -0
  112. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  113. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  114. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +11 -6
  115. package/lib/esm/actions/requirements/getRequirementsApproval.js +29 -5
  116. package/lib/esm/addresses.d.ts +1 -1
  117. package/lib/esm/addresses.js +1 -1
  118. package/lib/esm/blue/addresses.d.ts +1 -1
  119. package/lib/esm/blue/addresses.js +1 -1
  120. package/lib/esm/constants.d.ts +1 -1
  121. package/lib/esm/constants.js +1 -1
  122. package/lib/esm/entities/blue/blue.d.ts +486 -2
  123. package/lib/esm/entities/blue/blue.js +501 -6
  124. package/lib/esm/entities/index.d.ts +1 -1
  125. package/lib/esm/entities/midnight/midnight.d.ts +6 -0
  126. package/lib/esm/entities/midnight/midnight.js +21 -2
  127. package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
  128. package/lib/esm/entities/requirements/assertContractCode.js +1 -25
  129. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +117 -0
  130. package/lib/esm/entities/vaultV2BlueReallocationData.js +227 -3
  131. package/lib/esm/helpers/constant.d.ts +41 -0
  132. package/lib/esm/helpers/constant.js +41 -0
  133. package/lib/esm/helpers/getZeroExLeverageBundle.d.ts +13 -0
  134. package/lib/esm/helpers/getZeroExLeverageBundle.js +23 -0
  135. package/lib/esm/helpers/index.d.ts +4 -1
  136. package/lib/esm/helpers/index.js +4 -1
  137. package/lib/esm/helpers/leverage/index.d.ts +1 -0
  138. package/lib/esm/helpers/leverage/index.js +1 -0
  139. package/lib/esm/helpers/leverage/limits.d.ts +472 -0
  140. package/lib/esm/helpers/leverage/limits.js +705 -0
  141. package/lib/esm/helpers/leverage/positionMarket.d.ts +17 -0
  142. package/lib/esm/helpers/leverage/positionMarket.js +24 -0
  143. package/lib/esm/helpers/leverage/reallocations.d.ts +159 -0
  144. package/lib/esm/helpers/leverage/reallocations.js +271 -0
  145. package/lib/esm/helpers/validate.d.ts +14 -0
  146. package/lib/esm/helpers/validate.js +25 -2
  147. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  148. package/lib/esm/helpers/validateRequirementSpender.js +5 -1
  149. package/lib/esm/helpers/zeroExQuote.d.ts +250 -0
  150. package/lib/esm/helpers/zeroExQuote.js +754 -0
  151. package/lib/esm/index.d.ts +1 -0
  152. package/lib/esm/index.js +1 -0
  153. package/lib/esm/reads/assertContractCode.d.ts +25 -0
  154. package/lib/esm/reads/assertContractCode.js +26 -0
  155. package/lib/esm/reads/fetchZeroExQuote.d.ts +123 -0
  156. package/lib/esm/reads/fetchZeroExQuote.js +326 -0
  157. package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +4 -0
  158. package/lib/esm/transactionPlan/midnight/takeBorrow.js +9 -3
  159. package/lib/esm/types/action.d.ts +130 -1
  160. package/lib/esm/types/error.d.ts +84 -0
  161. package/lib/esm/types/error.js +103 -0
  162. package/lib/esm/types/index.d.ts +2 -0
  163. package/lib/esm/types/index.js +2 -0
  164. package/lib/esm/types/leverageError.d.ts +1552 -0
  165. package/lib/esm/types/leverageError.js +1660 -0
  166. package/lib/esm/types/zeroEx.d.ts +171 -0
  167. package/lib/esm/types/zeroEx.js +1 -0
  168. package/lib/esm/version.d.ts +1 -1
  169. package/lib/esm/version.js +1 -1
  170. package/package.json +7 -7
@@ -10,7 +10,7 @@ PreLiquidationParams as BluePreLiquidationParams,
10
10
  PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MidnightAdapter, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
11
11
  export type { AnyTree as MidnightAnyTree, AnyTreeSnapshot as MidnightAnyTreeSnapshot, BuildOfferParams as MidnightBuildOfferParams, CollateralParams as MidnightCollateralParams, EcrecoverTreeCreateRequest as MidnightEcrecoverTreeCreateRequest, GroupInput as MidnightGroupInput, IAccrualPosition as IMidnightAccrualPosition, ICollateralParams as IMidnightCollateralParams, IGroup as IMidnightGroup, IMarket as IMidnightMarket, IMarketParams as IMidnightMarketParams, IOffer as IMidnightOffer, IPosition as IMidnightPosition, MarketInput as MidnightMarketInput, OfferStruct as MidnightOfferStruct, PriceRatifierV1TreeCreateRequest as MidnightPriceRatifierV1TreeCreateRequest, RateRatifierV1TreeCreateRequest as MidnightRateRatifierV1TreeCreateRequest, RatifierKind as MidnightRatifierKind, RatifierTreeInput as MidnightRatifierTreeInput, RatifierTypes as MidnightRatifierTypes, SetterTreeCreateRequest as MidnightSetterTreeCreateRequest, SettlementFeeCbps as MidnightSettlementFeeCbps, TreeCreateParams as MidnightTreeCreateParams, TreeCreateRequest as MidnightTreeCreateRequest, TreeData as MidnightTreeData, TreeDescriptor as MidnightTreeDescriptor, TreeEntry as MidnightTreeEntry, TreeInput as MidnightTreeInput, TreeLike as MidnightTreeLike, TreeMempoolValidateParams as MidnightTreeMempoolValidateParams, TreeMempoolValidateRatification as MidnightTreeMempoolValidateRatification, TreeProof as MidnightTreeProof, TreeSnapshot as MidnightTreeSnapshot, TypedRatifierTreeInput as MidnightTypedRatifierTreeInput, TypedTreeMempoolValidateParams as MidnightTypedTreeMempoolValidateParams, } from "@morpho-org/midnight-sdk";
12
12
  export { AccrualPosition as MidnightAccrualPosition, Group as MidnightGroup, Market as MidnightMarket, MarketParams as MidnightMarketParams, Offer as MidnightOffer, Position as MidnightPosition, Tree as MidnightTree, } from "@morpho-org/midnight-sdk";
13
- export type { BlueActions, BlueTokenRequirementsParams, } from "./blue/index.js";
13
+ export type { BlueActions, BlueLeverageData, BlueTokenRequirementsParams, } from "./blue/index.js";
14
14
  export { MorphoBlue } from "./blue/index.js";
15
15
  export type { GetOffersDataParams as MidnightGetOffersDataParams, GetPositionDataParams as MidnightGetPositionDataParams, MakeLendParams as MidnightMakeLendParams, MakeOffersOutput as MidnightMakeOffersOutput, MakeOffersParams as MidnightMakeOffersParams, MarketActionParams as MidnightMarketActionParams, MidnightMakerTreeInput, MidnightPositionHealthParams, OffersData as MidnightOffersData, OfferValidationParams as MidnightOfferValidationParams, RedeemParams as MidnightRedeemParams, RepayWithdrawCollateralParams as MidnightRepayWithdrawCollateralParams, SupplyBlueMakeLendParams as MidnightSupplyBlueMakeLendParams, SupplyCollateralBatchParams as MidnightSupplyCollateralBatchParams, SupplyCollateralMakeBorrowParams as MidnightSupplyCollateralMakeBorrowParams, SupplyCollateralParams as MidnightSupplyCollateralParams, SupplyCollateralTakeBorrowParams as MidnightSupplyCollateralTakeBorrowParams, TakeBorrowParams as MidnightTakeBorrowParams, TakeLendParams as MidnightTakeLendParams, TakeRepayWithdrawCollateralParams as MidnightTakeRepayWithdrawCollateralParams, TakeWithdrawParams as MidnightTakeWithdrawParams, WithdrawCollateralBatchParams as MidnightWithdrawCollateralBatchParams, WithdrawCollateralParams as MidnightWithdrawCollateralParams, } from "./midnight/index.js";
16
16
  export { type MidnightActionOutput, type MidnightActions, type MidnightRequirementsParams, MorphoMidnight, } from "./midnight/index.js";
@@ -293,6 +293,9 @@ export declare class MorphoMidnight {
293
293
  * withdrawal.
294
294
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
295
295
  * its bounds cannot hold at any fill.
296
+ * @throws {MidnightBorrowTooCloseToMaturityError} when `now` is not past maturity and `deadline` is less
297
+ * than `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the
298
+ * target; use `takeWithdraw` to sell credit only.
296
299
  * @example
297
300
  * ```ts
298
301
  * import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";
@@ -471,6 +474,9 @@ export declare class MorphoMidnight {
471
474
  * withdrawal.
472
475
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
473
476
  * its bounds cannot hold at any fill.
477
+ * @throws {MidnightBorrowTooCloseToMaturityError} when `now` is not past maturity and `deadline` is less
478
+ * than `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the
479
+ * target; use `takeWithdraw` to sell credit only.
474
480
  * @example
475
481
  * ```ts
476
482
  * const output = midnight.supplyCollateralTakeBorrow({
@@ -15,6 +15,7 @@ const getMidnightAuthorizationRequirement_js_1 = require("../../actions/requirem
15
15
  const index_js_1 = require("../../helpers/index.js");
16
16
  const metadata_js_1 = require("../../helpers/metadata.js");
17
17
  const parseMidnight_js_1 = require("../../helpers/parseMidnight.js");
18
+ const validate_js_1 = require("../../helpers/validate.js");
18
19
  const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
19
20
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
20
21
  const validateMidnightTakeFeasibility_js_1 = require("../../helpers/validateMidnightTakeFeasibility.js");
@@ -349,6 +350,9 @@ class MorphoMidnight {
349
350
  * withdrawal.
350
351
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
351
352
  * its bounds cannot hold at any fill.
353
+ * @throws {MidnightBorrowTooCloseToMaturityError} when `now` is not past maturity and `deadline` is less
354
+ * than `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the
355
+ * target; use `takeWithdraw` to sell credit only.
352
356
  * @example
353
357
  * ```ts
354
358
  * import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";
@@ -401,12 +405,13 @@ class MorphoMidnight {
401
405
  throw new index_js_2.BorrowExceedsSafeLtvError(requestedUnits, blue_sdk_1.MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
402
406
  }
403
407
  }
408
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
404
409
  const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)({
405
410
  side: "sell",
406
411
  takeableOffers: parsed.takeableOffers,
407
412
  accountAddress: accountAddress,
408
413
  marketData: params.marketData,
409
- now: params.now ?? morpho_ts_1.Time.timestamp(),
414
+ now,
410
415
  deadline: parsed.deadline,
411
416
  referralFeePct: parsed.referralFeePct,
412
417
  // Credit is withdrawn first, up to the market's withdrawable liquidity.
@@ -415,6 +420,11 @@ class MorphoMidnight {
415
420
  target: parsed.target,
416
421
  increasesDebt: true,
417
422
  });
423
+ (0, validate_js_1.validateMidnightBorrowMaturity)({
424
+ marketData: params.marketData,
425
+ now,
426
+ deadline: parsed.deadline,
427
+ });
418
428
  if (takeableOffers !== parsed.takeableOffers) {
419
429
  tx = (0, encode_js_1.encodeMidnightTakeBorrow)(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
420
430
  }
@@ -603,6 +613,9 @@ class MorphoMidnight {
603
613
  * withdrawal.
604
614
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
605
615
  * its bounds cannot hold at any fill.
616
+ * @throws {MidnightBorrowTooCloseToMaturityError} when `now` is not past maturity and `deadline` is less
617
+ * than `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the
618
+ * target; use `takeWithdraw` to sell credit only.
606
619
  * @example
607
620
  * ```ts
608
621
  * const output = midnight.supplyCollateralTakeBorrow({
@@ -651,12 +664,13 @@ class MorphoMidnight {
651
664
  throw new index_js_2.BorrowExceedsSafeLtvError(requestedUnits, blue_sdk_1.MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
652
665
  }
653
666
  }
667
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
654
668
  const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)({
655
669
  side: "sell",
656
670
  takeableOffers: parsed.takeableOffers,
657
671
  accountAddress: accountAddress,
658
672
  marketData: params.marketData,
659
- now: params.now ?? morpho_ts_1.Time.timestamp(),
673
+ now,
660
674
  deadline: parsed.deadline,
661
675
  referralFeePct: parsed.referralFeePct,
662
676
  // Credit is withdrawn first, up to the market's withdrawable liquidity.
@@ -665,6 +679,11 @@ class MorphoMidnight {
665
679
  target: parsed.target,
666
680
  increasesDebt: true,
667
681
  });
682
+ (0, validate_js_1.validateMidnightBorrowMaturity)({
683
+ marketData: params.marketData,
684
+ now,
685
+ deadline: parsed.deadline,
686
+ });
668
687
  if (takeableOffers !== parsed.takeableOffers) {
669
688
  tx = (0, encode_js_1.encodeMidnightSupplyCollateralTakeBorrow)(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
670
689
  }
@@ -1,29 +1,6 @@
1
1
  import type { AddressLabel } from "@morpho-org/morpho-ts";
2
2
  import type { Address, Client } from "viem";
3
3
  import { type ChainCheck } from "../../actions/requirements/chainCheck.js";
4
- /**
5
- * Asserts that a configured contract address holds deployed code on the client's chain.
6
- *
7
- * A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
8
- * registered target before returning requirements. The `eth_getCode` read runs at the
9
- * client's default block; transport failures propagate unwrapped because they are
10
- * infrastructure failures, not configuration failures.
11
- *
12
- * @param client - Connected viem client used for the `eth_getCode` read.
13
- * @param params - Assertion parameters.
14
- * @param params.address - Contract address expected to hold code.
15
- * @param params.chainId - Chain id the flow targets, reported on the error.
16
- * @param params.role - Registry label naming the address's role in the flow.
17
- * @returns Nothing when the address holds code.
18
- * @throws {MissingContractCodeError} when the address has no deployed bytecode.
19
- * @throws {viem.BaseError} when the `eth_getCode` read itself fails.
20
- * @internal
21
- */
22
- export declare const assertContractCode: (client: Client, params: {
23
- readonly address: Address;
24
- readonly chainId: number;
25
- readonly role: AddressLabel;
26
- }) => Promise<void>;
27
4
  /**
28
5
  * Asserts that each distinct target in a flow's write-surface list holds code.
29
6
  *
@@ -1,34 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assertRegistryTargetsHaveCode = exports.assertContractCode = void 0;
4
- const actions_1 = require("viem/actions");
3
+ exports.assertRegistryTargetsHaveCode = void 0;
5
4
  const chainCheck_js_1 = require("../../actions/requirements/chainCheck.js");
5
+ const assertContractCode_js_1 = require("../../reads/assertContractCode.js");
6
6
  const index_js_1 = require("../../types/index.js");
7
- /**
8
- * Asserts that a configured contract address holds deployed code on the client's chain.
9
- *
10
- * A call to a code-less address succeeds on-chain as a no-op, so entity flows check each
11
- * registered target before returning requirements. The `eth_getCode` read runs at the
12
- * client's default block; transport failures propagate unwrapped because they are
13
- * infrastructure failures, not configuration failures.
14
- *
15
- * @param client - Connected viem client used for the `eth_getCode` read.
16
- * @param params - Assertion parameters.
17
- * @param params.address - Contract address expected to hold code.
18
- * @param params.chainId - Chain id the flow targets, reported on the error.
19
- * @param params.role - Registry label naming the address's role in the flow.
20
- * @returns Nothing when the address holds code.
21
- * @throws {MissingContractCodeError} when the address has no deployed bytecode.
22
- * @throws {viem.BaseError} when the `eth_getCode` read itself fails.
23
- * @internal
24
- */
25
- const assertContractCode = async (client, params) => {
26
- const bytecode = await (0, actions_1.getBytecode)(client, { address: params.address });
27
- if (bytecode === undefined || bytecode === "0x") {
28
- throw new index_js_1.MissingContractCodeError(params.address, params.chainId, params.role);
29
- }
30
- };
31
- exports.assertContractCode = assertContractCode;
32
7
  /**
33
8
  * Asserts that each distinct target in a flow's write-surface list holds code.
34
9
  *
@@ -62,7 +37,7 @@ const assertRegistryTargetsHaveCode = async (client, chainId, targets, chainChec
62
37
  continue;
63
38
  }
64
39
  seen.add(target.address);
65
- checks.push((0, exports.assertContractCode)(client, {
40
+ checks.push((0, assertContractCode_js_1.assertContractCode)(client, {
66
41
  address: target.address,
67
42
  chainId,
68
43
  role: target.role,
@@ -578,6 +578,123 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
578
578
  * ```
579
579
  */
580
580
  getPublicReallocationLiquidity(marketId: MarketId, options?: VaultV2BluePublicAllocatorOptions): bigint;
581
+ /**
582
+ * Replays `reallocations` toward `marketId` in order, as one transaction at `timestamp`, and
583
+ * returns the first leg that leaves a target cap id over its cap, with the interest reserve the
584
+ * planner keeps through `timestamp + capAccrualBuffer`, or a market-sourced leg whose source market's
585
+ * liquidity or source adapter's supply no longer covers its amount (for example, replayed against a newer snapshot). Idle legs are checked against
586
+ * the caps only. A plan from
587
+ * `computeVaultV2BlueReallocations` fits; a leg cut below the amount the planner chose may not,
588
+ * because a shared relative cap can require a larger move whose penalty donation lifts the cap.
589
+ *
590
+ * @param params - Replay inputs.
591
+ * @param params.marketId - Target Blue market id.
592
+ * @param params.reallocations - Legs to replay, in execution order.
593
+ * @param params.timestamp - Optional timestamp, as given to the planner.
594
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
595
+ * @returns The first leg outside its caps or not funded by its source market, or `undefined` when every
596
+ * leg fits.
597
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
598
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
599
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
600
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
601
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
602
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
603
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
604
+ * @example
605
+ * ```ts
606
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
607
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
608
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
609
+ * const block = await client.getBlock();
610
+ * const data = await market.getVaultV2BlueReallocationData({
611
+ * vaultAddresses: [keyrockUsdcVaultV2],
612
+ * block: { number: block.number, timestamp: block.timestamp },
613
+ * });
614
+ * const { reallocations } = data.computeVaultV2BlueReallocations(
615
+ * marketParams.id,
616
+ * { timestamp: block.timestamp, operation: { type: "borrow", amount: 1_000_000n } },
617
+ * );
618
+ * const outside = data.findVaultV2BlueReallocationOutsideCaps({
619
+ * marketId: marketParams.id,
620
+ * reallocations,
621
+ * timestamp: block.timestamp,
622
+ * });
623
+ * // outside === undefined: the planner's own plan fits every cap.
624
+ * ```
625
+ */
626
+ findVaultV2BlueReallocationOutsideCaps({ marketId, reallocations, timestamp, capAccrualBuffer, }: Pick<VaultV2BluePublicAllocatorOptions, "timestamp" | "capAccrualBuffer"> & {
627
+ readonly marketId: MarketId;
628
+ readonly reallocations: readonly VaultV2BlueReallocation[];
629
+ }): VaultV2BlueReallocation | undefined;
630
+ /**
631
+ * Replays `reallocations` toward `marketId` once, as in
632
+ * `findVaultV2BlueReallocationOutsideCaps`, then returns the first of `amounts` at which
633
+ * `reallocation`, executed next, stays within its target vault's caps. It checks the vault caps and the interest
634
+ * reserve only, not the allocator's own max-in, which the planner applies when it sizes a leg, so only try amounts at
635
+ * or below a planned leg's `assets`. Amounts outside the positive `uint128`
636
+ * range are skipped, since no reallocation can move them, and so are amounts the leg's source cannot
637
+ * fund: above the source market's liquidity or the source adapter's supply in it, or, from idle, above the vault's idle balance left by
638
+ * the earlier legs, not counting their penalty donations, as the planner counts it. Only `reallocation` is probed at
639
+ * each amount, so a search over many amounts costs one replay of the earlier legs.
640
+ *
641
+ * @param params - Search inputs.
642
+ * @param params.marketId - Target Blue market id.
643
+ * @param params.reallocations - Earlier legs, in execution order.
644
+ * @param params.reallocation - Leg to size; its `assets` is ignored.
645
+ * @param params.amounts - Candidate amounts, tried in order; non-positive or above-`uint128` ones are skipped.
646
+ * @param params.timestamp - Optional timestamp, as given to the planner.
647
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
648
+ * @returns The first amount that fits, or `undefined` when none does or an earlier leg is outside its
649
+ * caps, outside the positive `uint128` range, or above what its source can fund.
650
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
651
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
652
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
653
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
654
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
655
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
656
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
657
+ * @example
658
+ * ```ts
659
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
660
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
661
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
662
+ * const block = await client.getBlock();
663
+ * const data = await market.getVaultV2BlueReallocationData({
664
+ * vaultAddresses: [keyrockUsdcVaultV2],
665
+ * block: { number: block.number, timestamp: block.timestamp },
666
+ * });
667
+ * const {
668
+ * reallocations: [leg],
669
+ * } = data.computeVaultV2BlueReallocations(marketParams.id, {
670
+ * timestamp: block.timestamp,
671
+ * operation: { type: "borrow", amount: 1_000_000n },
672
+ * });
673
+ * // No leg: the market funds the borrow without a reallocation, so there is nothing to resize.
674
+ * if (leg == null) return;
675
+ * const assets = data.findVaultV2BlueReallocationFittingAssets({
676
+ * marketId: marketParams.id,
677
+ * reallocations: [],
678
+ * reallocation: leg,
679
+ * amounts: [leg.assets / 2n, leg.assets],
680
+ * timestamp: block.timestamp,
681
+ * });
682
+ * // assets === leg.assets / 2n when that smaller move fits the vault caps, else leg.assets.
683
+ * ```
684
+ */
685
+ findVaultV2BlueReallocationFittingAssets({ marketId, reallocations, reallocation, amounts, timestamp, capAccrualBuffer, }: Pick<VaultV2BluePublicAllocatorOptions, "timestamp" | "capAccrualBuffer"> & {
686
+ readonly marketId: MarketId;
687
+ readonly reallocations: readonly VaultV2BlueReallocation[];
688
+ readonly reallocation: VaultV2BlueReallocation;
689
+ readonly amounts: Iterable<bigint>;
690
+ }): bigint | undefined;
691
+ /**
692
+ * Starts a cap replay toward `marketId` at `timestamp`. Each call of the returned function prepares
693
+ * the next leg: `funds(assets)` checks that `assets` is a positive `uint128` its source holds
694
+ * (market liquidity capped at the source adapter's supply, or idle without penalty donations), `fits(assets)` probes the leg at a positive `assets`, at the replay timestamp, against its target caps and
695
+ * the planner's interest reserve, and `apply()` executes it at its own amount so later legs see it.
696
+ */
697
+ private createCapReplay;
581
698
  /**
582
699
  * Computes borrow liquidity to a target utilization, including friendly
583
700
  * Vault V2 public reallocations. Market/vault state and returned post-state
@@ -990,6 +990,230 @@ class VaultV2BlueReallocationData {
990
990
  })
991
991
  .reallocations.reduce((total, { assets }) => total + assets, 0n);
992
992
  }
993
+ /**
994
+ * Replays `reallocations` toward `marketId` in order, as one transaction at `timestamp`, and
995
+ * returns the first leg that leaves a target cap id over its cap, with the interest reserve the
996
+ * planner keeps through `timestamp + capAccrualBuffer`, or a market-sourced leg whose source market's
997
+ * liquidity or source adapter's supply no longer covers its amount (for example, replayed against a newer snapshot). Idle legs are checked against
998
+ * the caps only. A plan from
999
+ * `computeVaultV2BlueReallocations` fits; a leg cut below the amount the planner chose may not,
1000
+ * because a shared relative cap can require a larger move whose penalty donation lifts the cap.
1001
+ *
1002
+ * @param params - Replay inputs.
1003
+ * @param params.marketId - Target Blue market id.
1004
+ * @param params.reallocations - Legs to replay, in execution order.
1005
+ * @param params.timestamp - Optional timestamp, as given to the planner.
1006
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
1007
+ * @returns The first leg outside its caps or not funded by its source market, or `undefined` when every
1008
+ * leg fits.
1009
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
1010
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
1011
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
1012
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
1013
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
1014
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
1015
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
1016
+ * @example
1017
+ * ```ts
1018
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
1019
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
1020
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
1021
+ * const block = await client.getBlock();
1022
+ * const data = await market.getVaultV2BlueReallocationData({
1023
+ * vaultAddresses: [keyrockUsdcVaultV2],
1024
+ * block: { number: block.number, timestamp: block.timestamp },
1025
+ * });
1026
+ * const { reallocations } = data.computeVaultV2BlueReallocations(
1027
+ * marketParams.id,
1028
+ * { timestamp: block.timestamp, operation: { type: "borrow", amount: 1_000_000n } },
1029
+ * );
1030
+ * const outside = data.findVaultV2BlueReallocationOutsideCaps({
1031
+ * marketId: marketParams.id,
1032
+ * reallocations,
1033
+ * timestamp: block.timestamp,
1034
+ * });
1035
+ * // outside === undefined: the planner's own plan fits every cap.
1036
+ * ```
1037
+ */
1038
+ findVaultV2BlueReallocationOutsideCaps({ marketId, reallocations, timestamp, capAccrualBuffer, }) {
1039
+ const prepareLeg = this.createCapReplay({
1040
+ marketId,
1041
+ timestamp,
1042
+ capAccrualBuffer,
1043
+ });
1044
+ for (const reallocation of reallocations) {
1045
+ const leg = prepareLeg(reallocation);
1046
+ if ((reallocation.from.type === "market" &&
1047
+ !leg.funds(reallocation.assets)) ||
1048
+ !leg.fits(reallocation.assets)) {
1049
+ return reallocation;
1050
+ }
1051
+ leg.apply();
1052
+ }
1053
+ }
1054
+ /**
1055
+ * Replays `reallocations` toward `marketId` once, as in
1056
+ * `findVaultV2BlueReallocationOutsideCaps`, then returns the first of `amounts` at which
1057
+ * `reallocation`, executed next, stays within its target vault's caps. It checks the vault caps and the interest
1058
+ * reserve only, not the allocator's own max-in, which the planner applies when it sizes a leg, so only try amounts at
1059
+ * or below a planned leg's `assets`. Amounts outside the positive `uint128`
1060
+ * range are skipped, since no reallocation can move them, and so are amounts the leg's source cannot
1061
+ * fund: above the source market's liquidity or the source adapter's supply in it, or, from idle, above the vault's idle balance left by
1062
+ * the earlier legs, not counting their penalty donations, as the planner counts it. Only `reallocation` is probed at
1063
+ * each amount, so a search over many amounts costs one replay of the earlier legs.
1064
+ *
1065
+ * @param params - Search inputs.
1066
+ * @param params.marketId - Target Blue market id.
1067
+ * @param params.reallocations - Earlier legs, in execution order.
1068
+ * @param params.reallocation - Leg to size; its `assets` is ignored.
1069
+ * @param params.amounts - Candidate amounts, tried in order; non-positive or above-`uint128` ones are skipped.
1070
+ * @param params.timestamp - Optional timestamp, as given to the planner.
1071
+ * @param params.capAccrualBuffer - Optional cap-accrual buffer, as given to the planner.
1072
+ * @returns The first amount that fits, or `undefined` when none does or an earlier leg is outside its
1073
+ * caps, outside the positive `uint128` range, or above what its source can fund.
1074
+ * @throws {UnsupportedBlueMarketIrmError} when a Blue market the replay accrues has positive debt and an unsupported
1075
+ * IRM: the target, a source, or, on a vault's first allocation, any other market the vault holds.
1076
+ * @throws {NegativeInputError} when `capAccrualBuffer` is negative.
1077
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
1078
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
1079
+ * @throws {UnknownReallocationAdapterError} when a leg's adapter is absent.
1080
+ * @throws {UnknownReallocationAllocationError} when a leg's cap or allocation state is absent.
1081
+ * @example
1082
+ * ```ts
1083
+ * // `client` is a mainnet viem client extended with `morphoViemExtension()`, and
1084
+ * // `market = client.morpho.blue(marketParams, mainnet.id)` for a USDC market Keyrock's vault supplies.
1085
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
1086
+ * const block = await client.getBlock();
1087
+ * const data = await market.getVaultV2BlueReallocationData({
1088
+ * vaultAddresses: [keyrockUsdcVaultV2],
1089
+ * block: { number: block.number, timestamp: block.timestamp },
1090
+ * });
1091
+ * const {
1092
+ * reallocations: [leg],
1093
+ * } = data.computeVaultV2BlueReallocations(marketParams.id, {
1094
+ * timestamp: block.timestamp,
1095
+ * operation: { type: "borrow", amount: 1_000_000n },
1096
+ * });
1097
+ * // No leg: the market funds the borrow without a reallocation, so there is nothing to resize.
1098
+ * if (leg == null) return;
1099
+ * const assets = data.findVaultV2BlueReallocationFittingAssets({
1100
+ * marketId: marketParams.id,
1101
+ * reallocations: [],
1102
+ * reallocation: leg,
1103
+ * amounts: [leg.assets / 2n, leg.assets],
1104
+ * timestamp: block.timestamp,
1105
+ * });
1106
+ * // assets === leg.assets / 2n when that smaller move fits the vault caps, else leg.assets.
1107
+ * ```
1108
+ */
1109
+ findVaultV2BlueReallocationFittingAssets({ marketId, reallocations, reallocation, amounts, timestamp, capAccrualBuffer, }) {
1110
+ const prepareLeg = this.createCapReplay({
1111
+ marketId,
1112
+ timestamp,
1113
+ capAccrualBuffer,
1114
+ });
1115
+ for (const earlier of reallocations) {
1116
+ const leg = prepareLeg(earlier);
1117
+ if (!(leg.funds(earlier.assets) && leg.fits(earlier.assets))) {
1118
+ return undefined;
1119
+ }
1120
+ leg.apply();
1121
+ }
1122
+ const leg = prepareLeg(reallocation);
1123
+ for (const assets of amounts) {
1124
+ if (!leg.funds(assets)) {
1125
+ continue;
1126
+ }
1127
+ if (leg.fits(assets)) {
1128
+ return assets;
1129
+ }
1130
+ }
1131
+ }
1132
+ /**
1133
+ * Starts a cap replay toward `marketId` at `timestamp`. Each call of the returned function prepares
1134
+ * the next leg: `funds(assets)` checks that `assets` is a positive `uint128` its source holds
1135
+ * (market liquidity capped at the source adapter's supply, or idle without penalty donations), `fits(assets)` probes the leg at a positive `assets`, at the replay timestamp, against its target caps and
1136
+ * the planner's interest reserve, and `apply()` executes it at its own amount so later legs see it.
1137
+ */
1138
+ createCapReplay({ marketId, timestamp: inputTimestamp, capAccrualBuffer, }) {
1139
+ const timestamp = inputTimestamp == null
1140
+ ? this.getLatestSnapshotTimestamp()
1141
+ : BigInt(inputTimestamp);
1142
+ const reserves = createCapReserveState(this.mutableMarkets);
1143
+ const adapterIdsCache = new Map();
1144
+ const { getPair, capReserve } = createCapReserveResolvers({
1145
+ reserves,
1146
+ adapterIdsCache,
1147
+ timestamp,
1148
+ capAccrualBuffer: (0, utilization_js_1.resolveCapAccrualBuffer)(capAccrualBuffer),
1149
+ });
1150
+ let data = this.clone();
1151
+ data.setMarkets([data.getMarket(marketId).accrueInterest(timestamp)]);
1152
+ let context = createSimulationContext();
1153
+ return (reallocation) => {
1154
+ const { vault, from } = reallocation;
1155
+ const targetMarket = data.getMarket(marketId);
1156
+ const targetPair = getPair(vault, data.getAdapter(vault, reallocation.to.adapter), targetMarket);
1157
+ let sourcePair;
1158
+ let fundable;
1159
+ if (from.type === "market") {
1160
+ const sourceMarket = data
1161
+ .getMarket(from.marketParams.id)
1162
+ .accrueInterest(timestamp);
1163
+ data.setMarkets([sourceMarket]);
1164
+ const sourceAdapter = data.getAdapter(vault, from.adapter);
1165
+ fundable = blue_sdk_1.MathLib.min(sourceMarket.liquidity, sourceMarket.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n));
1166
+ sourcePair = getPair(vault, sourceAdapter, sourceMarket);
1167
+ }
1168
+ else {
1169
+ const donatedKey = findAddressKey(context.donatedPenaltyAssets, vault);
1170
+ fundable = blue_sdk_1.MathLib.zeroFloorSub(data.getVault(vault).assetBalance, donatedKey == null
1171
+ ? 0n
1172
+ : /* v8 ignore start: findAddressKey returns a key the record holds. */
1173
+ (context.donatedPenaltyAssets[donatedKey] ?? 0n));
1174
+ }
1175
+ const pairs = sourcePair == null ? [targetPair] : [targetPair, sourcePair];
1176
+ const sourceIds = new Set(sourcePair?.ids ?? []);
1177
+ const reserveById = new Map(targetPair.ids.map((id) => [id, capReserve(vault, id, pairs)]));
1178
+ const applyPublicReallocation = data.applyPublicReallocation.bind(data);
1179
+ const simulationContext = context;
1180
+ const targetSupplyHeadroom = blue_sdk_1.MathLib.zeroFloorSub(blue_sdk_1.MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
1181
+ return {
1182
+ funds: (assets) => assets > 0n && assets <= viem_1.maxUint128 && assets <= fundable,
1183
+ fits: (assets) => assets > 0n &&
1184
+ assets <= targetSupplyHeadroom &&
1185
+ probeCandidateReallocation({
1186
+ assets,
1187
+ timestamp,
1188
+ targetMarket,
1189
+ applyPublicReallocation,
1190
+ simulationContext,
1191
+ reallocation,
1192
+ marketId,
1193
+ adapterIdsCache,
1194
+ targetIds: targetPair.ids,
1195
+ sourceIds,
1196
+ reserveById,
1197
+ })?.withinAllCaps === true,
1198
+ apply: () => {
1199
+ const vaultKey = vault.toLowerCase();
1200
+ const touched = reserves.touchedPairs.get(vaultKey) ??
1201
+ new Map();
1202
+ for (const pair of pairs) {
1203
+ touched.set(pair.key, pair);
1204
+ }
1205
+ reserves.touchedPairs.set(vaultKey, touched);
1206
+ ({ data, context } = data.applyPublicReallocation({
1207
+ context,
1208
+ reallocation,
1209
+ targetMarketId: marketId,
1210
+ timestamp,
1211
+ adapterIdsCache,
1212
+ }));
1213
+ },
1214
+ };
1215
+ };
1216
+ }
993
1217
  /**
994
1218
  * Computes borrow liquidity to a target utilization, including friendly
995
1219
  * Vault V2 public reallocations. Market/vault state and returned post-state
@@ -1892,7 +2116,7 @@ function fitCandidateCaps(params) {
1892
2116
  }
1893
2117
  /** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
1894
2118
  function probeCandidateReallocation(params) {
1895
- const { assets, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
2119
+ const { assets, timestamp = params.targetMarket.lastUpdate, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
1896
2120
  if (targetMarket.totalSupplyShares +
1897
2121
  targetMarket.toSupplyShares(assets, "Down") >
1898
2122
  blue_sdk_1.MathLib.MAX_UINT_128) {
@@ -1902,7 +2126,7 @@ function probeCandidateReallocation(params) {
1902
2126
  context: simulationContext,
1903
2127
  reallocation: { ...reallocation, assets },
1904
2128
  targetMarketId: marketId,
1905
- timestamp: targetMarket.lastUpdate,
2129
+ timestamp,
1906
2130
  adapterIdsCache,
1907
2131
  probe: true,
1908
2132
  }), index_js_1.ReallocationAllocationUnderflowError, index_js_1.ReallocationAdapterSupplySharesUnderflowError);
@@ -3,6 +3,13 @@ import { type Address } from "viem";
3
3
  export declare const VAULT_DEPOSIT_MAX_DEADLINE_SECONDS = 604800n;
4
4
  /** Maximum time between now and a Midnight taker-flow deadline, in seconds. */
5
5
  export declare const MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS = 3600n;
6
+ /**
7
+ * Minimum time between a Midnight borrow's deadline and its market maturity, in seconds (2 hours).
8
+ * Debt still open at maturity becomes liquidatable, so entity and TransactionPlan borrows prepared at
9
+ * or before maturity that could execute closer to it are rejected. Credit covering the target at
10
+ * preparation does not exempt a borrow; sell credit only inside the window with `takeWithdraw`.
11
+ */
12
+ export declare const MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY: bigint;
6
13
  /**
7
14
  * Matches MAX_SLIPPAGE_TOLERANCE, the SDK's other ceiling on a WAD share of user funds; higher fees are rejected as likely unit mistakes.
8
15
  * @internal
@@ -14,8 +21,42 @@ export declare const MAX_SLIPPAGE_TOLERANCE: bigint;
14
21
  export declare const DEFAULT_MAX_REALLOCATION_PENALTY = 0n;
15
22
  /** Maximum Vault V2 reallocation penalty: 100%. */
16
23
  export declare const MAX_REALLOCATION_PENALTY = 1000000000000000000n;
24
+ /**
25
+ * Maximum penalty rate a ZeroExLeverageBundlesV1 Lever accepts per public-allocator reallocation:
26
+ * 1%, WAD-scaled. Fixed; no caller option.
27
+ */
28
+ export declare const LEVERAGE_MAX_REALLOCATION_PENALTY: bigint;
17
29
  /** Default LLTV buffer: 0.5% below LLTV. Prevents instant liquidation on new positions. */
18
30
  export declare const DEFAULT_LLTV_BUFFER: bigint;
31
+ /**
32
+ * SDK slippage ceiling per leverage action, WAD-scaled: `MAX_SLIPPAGE_TOLERANCE` (10%) for every action, the
33
+ * ceiling `fetchZeroExQuote` enforces, so the fetch and the builders cannot drift apart. Not configurable.
34
+ */
35
+ export declare const LEVERAGE_MAX_EXECUTION_LOSS: Readonly<{
36
+ readonly lever: bigint;
37
+ readonly delever: bigint;
38
+ readonly close: bigint;
39
+ }>;
40
+ /**
41
+ * Largest amount a Lever's worst swap price (`maxSwapIn` per `minCollateralToBuy`) may be above the market's oracle
42
+ * price, WAD-scaled: 15%. Exactly 15% is accepted, and a price below the oracle, which favours the user, is never
43
+ * refused. Delever and Close are not checked. The worst price uses `maxSwapIn`, which already includes the caller's
44
+ * slippage, so the room left for a gap between 0x's price and the oracle is about 15% minus that slippage (5% at the
45
+ * 10% ceiling).
46
+ * Not configurable.
47
+ */
48
+ export declare const LEVERAGE_MAX_ORACLE_DEVIATION: bigint;
49
+ /** Leverage deadline window after the data block, in seconds (1 hour). */
50
+ export declare const LEVERAGE_DEADLINE_WINDOW = 3600n;
51
+ /**
52
+ * Margin applied to the interest a Close's debt may accrue before its deadline: the buffer is the debt accrued for
53
+ * the one-hour deadline window at 4× the data block's borrow rate. The factor matches the AdaptiveCurveIrm curve
54
+ * steepness (`AdaptiveCurveIrmLib.CURVE_STEEPNESS` in blue-sdk), the most utilization can raise the rate over its
55
+ * rate at target, while that rate at target itself drifts by well under 1% in an hour (`ADJUSTMENT_SPEED` is 50 per
56
+ * year). It does not cover a rate that rises more than 4×, such as one quoted below target that jumps to full
57
+ * utilization; the Close then reverts instead of overpaying. Fixed; no caller option.
58
+ */
59
+ export declare const LEVERAGE_CLOSE_INTEREST_BUFFER_FACTOR = 4n;
19
60
  /**
20
61
  * Forward interest-accrual window, in seconds (2 hours), reserved in target-market
21
62
  * cap checks (BluePublicAllocator max-in, Vault V2 absolute and relative caps) when