@morpho-org/morpho-sdk 10.4.0 → 10.5.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 (193) hide show
  1. package/lib/cjs/actions/blue/common.js +12 -3
  2. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
  3. package/lib/cjs/actions/midnight/takeBorrow.js +14 -8
  4. package/lib/cjs/actions/midnight/takeLend.js +15 -9
  5. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  6. package/lib/cjs/actions/midnight/takeWithdraw.js +14 -8
  7. package/lib/cjs/constants.d.ts +1 -1
  8. package/lib/cjs/constants.js +3 -2
  9. package/lib/cjs/entities/midnight/midnight.d.ts +106 -103
  10. package/lib/cjs/entities/midnight/midnight.js +120 -101
  11. package/lib/cjs/entities/vaultV1/vaultV1.js +0 -1
  12. package/lib/cjs/entities/vaultV2/vaultV2.js +0 -1
  13. package/lib/cjs/helpers/constant.d.ts +7 -0
  14. package/lib/cjs/helpers/constant.js +8 -1
  15. package/lib/cjs/helpers/index.d.ts +1 -1
  16. package/lib/cjs/helpers/index.js +2 -1
  17. package/lib/cjs/helpers/validate.d.ts +25 -1
  18. package/lib/cjs/helpers/validate.js +25 -1
  19. package/lib/cjs/transactionPlan/assemble.d.ts +24 -0
  20. package/lib/cjs/transactionPlan/assemble.js +25 -0
  21. package/lib/cjs/transactionPlan/blue/borrow.js +14 -64
  22. package/lib/cjs/transactionPlan/blue/refinance.js +9 -11
  23. package/lib/cjs/transactionPlan/blue/repay.js +10 -24
  24. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +49 -45
  25. package/lib/cjs/transactionPlan/blue/stored.d.ts +26 -0
  26. package/lib/cjs/transactionPlan/blue/stored.js +87 -0
  27. package/lib/cjs/transactionPlan/blue/supply.js +7 -22
  28. package/lib/cjs/transactionPlan/blue/supplyCollateral.d.ts +1 -1
  29. package/lib/cjs/transactionPlan/blue/supplyCollateral.js +10 -15
  30. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +14 -64
  31. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +2 -3
  32. package/lib/cjs/transactionPlan/blue/withdraw.js +67 -79
  33. package/lib/cjs/transactionPlan/blue/withdrawCollateral.d.ts +2 -3
  34. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +31 -30
  35. package/lib/cjs/transactionPlan/deposit.js +4 -7
  36. package/lib/cjs/transactionPlan/intent.d.ts +1 -1
  37. package/lib/cjs/transactionPlan/midnight/makeBorrow.d.ts +1 -1
  38. package/lib/cjs/transactionPlan/midnight/makeBorrow.js +1 -1
  39. package/lib/cjs/transactionPlan/midnight/makeLend.d.ts +1 -1
  40. package/lib/cjs/transactionPlan/midnight/makeLend.js +1 -1
  41. package/lib/cjs/transactionPlan/midnight/makeRepay.d.ts +1 -1
  42. package/lib/cjs/transactionPlan/midnight/makeRepay.js +1 -1
  43. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.d.ts +1 -1
  44. package/lib/cjs/transactionPlan/midnight/repayWithdrawCollateral.js +1 -1
  45. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.d.ts +1 -1
  46. package/lib/cjs/transactionPlan/midnight/supplyBlueMakeLend.js +1 -1
  47. package/lib/cjs/transactionPlan/midnight/supplyCollateral.d.ts +1 -1
  48. package/lib/cjs/transactionPlan/midnight/supplyCollateral.js +1 -1
  49. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.d.ts +1 -1
  50. package/lib/cjs/transactionPlan/midnight/supplyCollateralBatch.js +1 -1
  51. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +1 -1
  52. package/lib/cjs/transactionPlan/midnight/supplyCollateralMakeBorrow.js +1 -1
  53. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.d.ts +1 -1
  54. package/lib/cjs/transactionPlan/midnight/supplyCollateralWithNative.js +1 -1
  55. package/lib/cjs/transactionPlan/midnight/takeBorrow.d.ts +6 -2
  56. package/lib/cjs/transactionPlan/midnight/takeBorrow.js +10 -4
  57. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  58. package/lib/cjs/transactionPlan/midnight/takeRepayWithdrawCollateral.js +1 -1
  59. package/lib/cjs/transactionPlan/midnight/takeWithdraw.d.ts +1 -1
  60. package/lib/cjs/transactionPlan/midnight/takeWithdraw.js +1 -1
  61. package/lib/cjs/transactionPlan/permit.d.ts +15 -2
  62. package/lib/cjs/transactionPlan/permit.js +26 -68
  63. package/lib/cjs/transactionPlan/plan.d.ts +51 -1
  64. package/lib/cjs/transactionPlan/plan.js +56 -13
  65. package/lib/cjs/transactionPlan/redeem.js +4 -7
  66. package/lib/cjs/transactionPlan/types.d.ts +4 -3
  67. package/lib/cjs/transactionPlan/vaultBinding.d.ts +29 -0
  68. package/lib/cjs/transactionPlan/vaultBinding.js +69 -0
  69. package/lib/cjs/transactionPlan/vaultRequirements.d.ts +20 -0
  70. package/lib/cjs/transactionPlan/vaultRequirements.js +37 -0
  71. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +1 -1
  72. package/lib/cjs/transactionPlan/vaultv1/deposit.js +2 -13
  73. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +2 -2
  74. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +10 -41
  75. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +1 -1
  76. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +6 -18
  77. package/lib/cjs/transactionPlan/vaultv1/redeem.js +1 -12
  78. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +1 -1
  79. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +2 -13
  80. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +1 -1
  81. package/lib/cjs/transactionPlan/vaultv2/deposit.js +2 -13
  82. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +1 -1
  83. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +4 -7
  84. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +2 -2
  85. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +12 -42
  86. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +2 -2
  87. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +10 -41
  88. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +1 -1
  89. package/lib/cjs/transactionPlan/vaultv2/redeem.js +2 -13
  90. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +1 -1
  91. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +2 -13
  92. package/lib/cjs/transactionPlan/withdraw.js +4 -7
  93. package/lib/cjs/types/error.d.ts +27 -1
  94. package/lib/cjs/types/error.js +32 -3
  95. package/lib/cjs/version.d.ts +1 -1
  96. package/lib/cjs/version.js +1 -1
  97. package/lib/esm/actions/blue/common.js +13 -4
  98. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +16 -11
  99. package/lib/esm/actions/midnight/takeBorrow.js +14 -8
  100. package/lib/esm/actions/midnight/takeLend.js +15 -9
  101. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +19 -13
  102. package/lib/esm/actions/midnight/takeWithdraw.js +14 -8
  103. package/lib/esm/constants.d.ts +1 -1
  104. package/lib/esm/constants.js +1 -1
  105. package/lib/esm/entities/midnight/midnight.d.ts +106 -103
  106. package/lib/esm/entities/midnight/midnight.js +120 -101
  107. package/lib/esm/entities/vaultV1/vaultV1.js +0 -1
  108. package/lib/esm/entities/vaultV2/vaultV2.js +0 -1
  109. package/lib/esm/helpers/constant.d.ts +7 -0
  110. package/lib/esm/helpers/constant.js +7 -0
  111. package/lib/esm/helpers/index.d.ts +1 -1
  112. package/lib/esm/helpers/index.js +1 -1
  113. package/lib/esm/helpers/validate.d.ts +25 -1
  114. package/lib/esm/helpers/validate.js +25 -2
  115. package/lib/esm/transactionPlan/assemble.d.ts +24 -0
  116. package/lib/esm/transactionPlan/assemble.js +21 -0
  117. package/lib/esm/transactionPlan/blue/borrow.js +15 -65
  118. package/lib/esm/transactionPlan/blue/refinance.js +10 -12
  119. package/lib/esm/transactionPlan/blue/repay.js +11 -25
  120. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +50 -46
  121. package/lib/esm/transactionPlan/blue/stored.d.ts +26 -0
  122. package/lib/esm/transactionPlan/blue/stored.js +80 -0
  123. package/lib/esm/transactionPlan/blue/supply.js +7 -22
  124. package/lib/esm/transactionPlan/blue/supplyCollateral.d.ts +1 -1
  125. package/lib/esm/transactionPlan/blue/supplyCollateral.js +10 -15
  126. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +15 -65
  127. package/lib/esm/transactionPlan/blue/withdraw.d.ts +2 -3
  128. package/lib/esm/transactionPlan/blue/withdraw.js +70 -82
  129. package/lib/esm/transactionPlan/blue/withdrawCollateral.d.ts +2 -3
  130. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +32 -31
  131. package/lib/esm/transactionPlan/deposit.js +5 -8
  132. package/lib/esm/transactionPlan/intent.d.ts +1 -1
  133. package/lib/esm/transactionPlan/midnight/makeBorrow.d.ts +1 -1
  134. package/lib/esm/transactionPlan/midnight/makeBorrow.js +1 -1
  135. package/lib/esm/transactionPlan/midnight/makeLend.d.ts +1 -1
  136. package/lib/esm/transactionPlan/midnight/makeLend.js +1 -1
  137. package/lib/esm/transactionPlan/midnight/makeRepay.d.ts +1 -1
  138. package/lib/esm/transactionPlan/midnight/makeRepay.js +1 -1
  139. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.d.ts +1 -1
  140. package/lib/esm/transactionPlan/midnight/repayWithdrawCollateral.js +1 -1
  141. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.d.ts +1 -1
  142. package/lib/esm/transactionPlan/midnight/supplyBlueMakeLend.js +1 -1
  143. package/lib/esm/transactionPlan/midnight/supplyCollateral.d.ts +1 -1
  144. package/lib/esm/transactionPlan/midnight/supplyCollateral.js +1 -1
  145. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.d.ts +1 -1
  146. package/lib/esm/transactionPlan/midnight/supplyCollateralBatch.js +1 -1
  147. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.d.ts +1 -1
  148. package/lib/esm/transactionPlan/midnight/supplyCollateralMakeBorrow.js +1 -1
  149. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.d.ts +1 -1
  150. package/lib/esm/transactionPlan/midnight/supplyCollateralWithNative.js +1 -1
  151. package/lib/esm/transactionPlan/midnight/takeBorrow.d.ts +6 -2
  152. package/lib/esm/transactionPlan/midnight/takeBorrow.js +11 -5
  153. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  154. package/lib/esm/transactionPlan/midnight/takeRepayWithdrawCollateral.js +1 -1
  155. package/lib/esm/transactionPlan/midnight/takeWithdraw.d.ts +1 -1
  156. package/lib/esm/transactionPlan/midnight/takeWithdraw.js +1 -1
  157. package/lib/esm/transactionPlan/permit.d.ts +15 -2
  158. package/lib/esm/transactionPlan/permit.js +25 -68
  159. package/lib/esm/transactionPlan/plan.d.ts +51 -1
  160. package/lib/esm/transactionPlan/plan.js +55 -13
  161. package/lib/esm/transactionPlan/redeem.js +5 -8
  162. package/lib/esm/transactionPlan/types.d.ts +4 -3
  163. package/lib/esm/transactionPlan/vaultBinding.d.ts +29 -0
  164. package/lib/esm/transactionPlan/vaultBinding.js +65 -0
  165. package/lib/esm/transactionPlan/vaultRequirements.d.ts +20 -0
  166. package/lib/esm/transactionPlan/vaultRequirements.js +34 -0
  167. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +1 -1
  168. package/lib/esm/transactionPlan/vaultv1/deposit.js +3 -14
  169. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +2 -2
  170. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +12 -43
  171. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +1 -1
  172. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +9 -21
  173. package/lib/esm/transactionPlan/vaultv1/redeem.js +2 -13
  174. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +1 -1
  175. package/lib/esm/transactionPlan/vaultv1/withdraw.js +3 -14
  176. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +1 -1
  177. package/lib/esm/transactionPlan/vaultv2/deposit.js +3 -14
  178. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +1 -1
  179. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +5 -8
  180. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +2 -2
  181. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +15 -45
  182. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +2 -2
  183. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +12 -43
  184. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +1 -1
  185. package/lib/esm/transactionPlan/vaultv2/redeem.js +3 -14
  186. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +1 -1
  187. package/lib/esm/transactionPlan/vaultv2/withdraw.js +3 -14
  188. package/lib/esm/transactionPlan/withdraw.js +5 -8
  189. package/lib/esm/types/error.d.ts +27 -1
  190. package/lib/esm/types/error.js +30 -2
  191. package/lib/esm/version.d.ts +1 -1
  192. package/lib/esm/version.js +1 -1
  193. package/package.json +3 -3
@@ -12,6 +12,7 @@ import { getParsedMidnightAuthorizationRequirement, parseMidnightAuthorizationRe
12
12
  import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
13
13
  import { resolveTransactionMetadata } from "../../helpers/metadata.js";
14
14
  import { parseMidnightNativeCollateralAmount } from "../../helpers/parseMidnight.js";
15
+ import { validateMidnightBorrowMaturity } from "../../helpers/validate.js";
15
16
  import { validateMidnightAddress } from "../../helpers/validateMidnightAccount.js";
16
17
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
17
18
  import { validateMidnightTakeFeasibility } from "../../helpers/validateMidnightTakeFeasibility.js";
@@ -163,22 +164,22 @@ export class MorphoMidnight {
163
164
  * On an assets target, sell offers whose tick is out of range or whose buyer price is zero or
164
165
  * above one are dropped from the transaction because one of them would revert the whole bundle.
165
166
  *
166
- * @param params - Lender, market snapshot, buy target, offers, fee cap, deadline, and optional referral fee.
167
- * @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
168
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
169
- * @param params.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`.
170
- * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
167
+ * @param raw - Lender, market snapshot, buy target, offers, fee cap, deadline, and optional referral fee.
168
+ * @param raw.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
169
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
170
+ * @param raw.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`.
171
+ * @param raw.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
171
172
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
172
173
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
173
174
  * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
174
175
  * required for the full pulled amount.
175
- * @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
176
- * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
176
+ * @param raw.takeableOffers - Borrow-side offers returned by the Midnight API.
177
+ * @param raw.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
177
178
  * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
178
179
  * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
179
- * @param params.deadline - Bundle execution deadline timestamp.
180
- * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
181
- * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
180
+ * @param raw.deadline - Bundle execution deadline timestamp.
181
+ * @param raw.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
182
+ * @param raw.referralFeeRecipient - Referral fee recipient; required with a positive fee.
182
183
  * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
183
184
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
184
185
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
@@ -226,7 +227,7 @@ export class MorphoMidnight {
226
227
  * marketData,
227
228
  * target: { type: "assets", assets: 1_000_000n, minUnits: 900_000n },
228
229
  * takeableOffers: quote.data.takeableOffers,
229
- * maxContinuousFee: maxUint256,
230
+ * maxContinuousFee: BigInt(marketData.continuousFee),
230
231
  * now: (await client.getBlock()).timestamp,
231
232
  * deadline: (await client.getBlock()).timestamp + 600n,
232
233
  * });
@@ -286,26 +287,26 @@ export class MorphoMidnight {
286
287
  * settlement fee until `deadline` (at or below it on an assets target) are dropped from the transaction because one of them would
287
288
  * revert the whole bundle.
288
289
  *
289
- * @param params - Borrower, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
290
- * @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
291
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
292
- * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
290
+ * @param raw - Borrower, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
291
+ * @param raw.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
292
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
293
+ * @param raw.positionData - Owner-bound position snapshot returned by `getPositionData`. The
293
294
  * `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
294
295
  * does not see transactions mined or prices moved since, so two transactions built from one
295
296
  * snapshot can together end inside the buffer. Midnight still rejects any position above
296
297
  * LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
297
- * @param params.collateralPrices - Values from `price()` on each
298
+ * @param raw.collateralPrices - Values from `price()` on each
298
299
  * `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
299
300
  * scaled by `ORACLE_PRICE_SCALE`. A price is required for every held or supplied collateral
300
301
  * index, because debt after a borrow is always positive.
301
- * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
302
- * @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
302
+ * @param raw.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
303
+ * @param raw.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
303
304
  * Midnight protocol and market token contracts are rejected.
304
- * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
305
- * @param params.deadline - Bounded bundle execution deadline timestamp.
306
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
305
+ * @param raw.takeableOffers - Lend-side offers returned by the Midnight API.
306
+ * @param raw.deadline - Bounded bundle execution deadline timestamp.
307
+ * @param raw.referralFeePct - Optional WAD-scaled referral fee taken from the sale
307
308
  * proceeds; on an assets target it is added on top of `target.assets`.
308
- * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
309
+ * @param raw.referralFeeRecipient - Referral fee recipient; required with a positive fee.
309
310
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
310
311
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
311
312
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
@@ -346,6 +347,9 @@ export class MorphoMidnight {
346
347
  * withdrawal.
347
348
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
348
349
  * its bounds cannot hold at any fill.
350
+ * @throws {MidnightBorrowTooCloseToMaturityError} when `now` is not past maturity and `deadline` is less
351
+ * than `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the
352
+ * target; use `takeWithdraw` to sell credit only.
349
353
  * @example
350
354
  * ```ts
351
355
  * import { blueOracleAbi } from "@morpho-org/morpho-sdk/abis";
@@ -398,12 +402,13 @@ export class MorphoMidnight {
398
402
  throw new BorrowExceedsSafeLtvError(requestedUnits, MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
399
403
  }
400
404
  }
405
+ const now = params.now ?? Time.timestamp();
401
406
  const takeableOffers = validateMidnightTakeFeasibility({
402
407
  side: "sell",
403
408
  takeableOffers: parsed.takeableOffers,
404
409
  accountAddress: accountAddress,
405
410
  marketData: params.marketData,
406
- now: params.now ?? Time.timestamp(),
411
+ now,
407
412
  deadline: parsed.deadline,
408
413
  referralFeePct: parsed.referralFeePct,
409
414
  // Credit is withdrawn first, up to the market's withdrawable liquidity.
@@ -412,6 +417,11 @@ export class MorphoMidnight {
412
417
  target: parsed.target,
413
418
  increasesDebt: true,
414
419
  });
420
+ validateMidnightBorrowMaturity({
421
+ marketData: params.marketData,
422
+ now,
423
+ deadline: parsed.deadline,
424
+ });
415
425
  if (takeableOffers !== parsed.takeableOffers) {
416
426
  tx = encodeMidnightTakeBorrow(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
417
427
  }
@@ -431,17 +441,17 @@ export class MorphoMidnight {
431
441
  * settlement fee until `deadline` (at or below it on an assets target) are dropped from the transaction because one of them would
432
442
  * revert the whole bundle.
433
443
  *
434
- * @param params - Lender, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
435
- * @param params.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
436
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
437
- * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
438
- * @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
444
+ * @param raw - Lender, market snapshot, sell target, offers, deadline, receiver, and optional referral fee.
445
+ * @param raw.accountAddress - Lender; must send the transaction, since V2 acts for `msg.sender`.
446
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
447
+ * @param raw.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
448
+ * @param raw.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
439
449
  * Midnight protocol and market token contracts are rejected.
440
- * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
441
- * @param params.deadline - Bundle execution deadline timestamp.
442
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
450
+ * @param raw.takeableOffers - Lend-side offers returned by the Midnight API.
451
+ * @param raw.deadline - Bundle execution deadline timestamp.
452
+ * @param raw.referralFeePct - Optional WAD-scaled referral fee taken from the sale
443
453
  * proceeds; on an assets target it is added on top of `target.assets`.
444
- * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
454
+ * @param raw.referralFeeRecipient - Referral fee recipient; required with a positive fee.
445
455
  * @returns Lazy `MidnightBundlesV2` authorization requirement and a synchronous transaction builder.
446
456
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
447
457
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
@@ -528,32 +538,32 @@ export class MorphoMidnight {
528
538
  * settlement fee until `deadline` (at or below it on an assets target) are dropped from the transaction because one of them would
529
539
  * revert the whole bundle.
530
540
  *
531
- * @param params - Borrower, market snapshot, collateral supplies, sell target, offers, deadline, receiver, and optional referral fee.
532
- * @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
533
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
534
- * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
541
+ * @param raw - Borrower, market snapshot, collateral supplies, sell target, offers, deadline, receiver, and optional referral fee.
542
+ * @param raw.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
543
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
544
+ * @param raw.positionData - Owner-bound position snapshot returned by `getPositionData`. The
535
545
  * `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
536
546
  * does not see transactions mined or prices moved since, so two transactions built from one
537
547
  * snapshot can together end inside the buffer. Midnight still rejects any position above
538
548
  * LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
539
- * @param params.collateralPrices - Values from `price()` on each
549
+ * @param raw.collateralPrices - Values from `price()` on each
540
550
  * `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
541
551
  * scaled by `ORACLE_PRICE_SCALE`. A price is required for every held or supplied collateral
542
552
  * index, because debt after a borrow is always positive.
543
- * @param params.collateralSupplies - Collateral index and assets per supply; must not be empty.
544
- * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
545
- * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
553
+ * @param raw.collateralSupplies - Collateral index and assets per supply; must not be empty.
554
+ * @param raw.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
555
+ * @param raw.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
546
556
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
547
557
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
548
558
  * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
549
559
  * required for the full pulled amount.
550
- * @param params.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
560
+ * @param raw.receiver - Optional loan-asset recipient; defaults to `accountAddress`.
551
561
  * Midnight protocol and market token contracts are rejected.
552
- * @param params.takeableOffers - Lend-side offers returned by the Midnight API.
553
- * @param params.deadline - Bounded bundle execution deadline timestamp.
554
- * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the sale
562
+ * @param raw.takeableOffers - Lend-side offers returned by the Midnight API.
563
+ * @param raw.deadline - Bounded bundle execution deadline timestamp.
564
+ * @param raw.referralFeePct - Optional WAD-scaled referral fee taken from the sale
555
565
  * proceeds; on an assets target it is added on top of `target.assets`.
556
- * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
566
+ * @param raw.referralFeeRecipient - Referral fee recipient; required with a positive fee.
557
567
  * @returns Lazy collateral approvals and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
558
568
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
559
569
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
@@ -600,6 +610,9 @@ export class MorphoMidnight {
600
610
  * withdrawal.
601
611
  * @throws {MidnightTakeTargetUnreachableError} when the live offers cannot hold the target, or
602
612
  * its bounds cannot hold at any fill.
613
+ * @throws {MidnightBorrowTooCloseToMaturityError} when `now` is not past maturity and `deadline` is less
614
+ * than `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` (2 hours) before it, even when credit covers the
615
+ * target; use `takeWithdraw` to sell credit only.
603
616
  * @example
604
617
  * ```ts
605
618
  * const output = midnight.supplyCollateralTakeBorrow({
@@ -648,12 +661,13 @@ export class MorphoMidnight {
648
661
  throw new BorrowExceedsSafeLtvError(requestedUnits, MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
649
662
  }
650
663
  }
664
+ const now = params.now ?? Time.timestamp();
651
665
  const takeableOffers = validateMidnightTakeFeasibility({
652
666
  side: "sell",
653
667
  takeableOffers: parsed.takeableOffers,
654
668
  accountAddress: accountAddress,
655
669
  marketData: params.marketData,
656
- now: params.now ?? Time.timestamp(),
670
+ now,
657
671
  deadline: parsed.deadline,
658
672
  referralFeePct: parsed.referralFeePct,
659
673
  // Credit is withdrawn first, up to the market's withdrawable liquidity.
@@ -662,6 +676,11 @@ export class MorphoMidnight {
662
676
  target: parsed.target,
663
677
  increasesDebt: true,
664
678
  });
679
+ validateMidnightBorrowMaturity({
680
+ marketData: params.marketData,
681
+ now,
682
+ deadline: parsed.deadline,
683
+ });
665
684
  if (takeableOffers !== parsed.takeableOffers) {
666
685
  tx = encodeMidnightSupplyCollateralTakeBorrow(parsed, takeableOffers.map((offer) => parsed.takeableOffers.indexOf(offer)));
667
686
  }
@@ -696,37 +715,37 @@ export class MorphoMidnight {
696
715
  * On an assets target, sell offers whose tick is out of range or whose buyer price is zero or
697
716
  * above one are dropped from the transaction because one of them would revert the whole bundle.
698
717
  *
699
- * @param params - Borrower, market snapshot, buy target, offers, repay fallback, withdrawals, fee cap, deadline and optional referral fee.
700
- * @param params.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
701
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
702
- * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
718
+ * @param raw - Borrower, market snapshot, buy target, offers, repay fallback, withdrawals, fee cap, deadline and optional referral fee.
719
+ * @param raw.accountAddress - Borrower; must send the transaction, since V2 acts for `msg.sender`.
720
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
721
+ * @param raw.positionData - Owner-bound position snapshot returned by `getPositionData`. The
703
722
  * `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
704
723
  * does not see transactions mined or prices moved since, so two transactions built from one
705
724
  * snapshot can together end inside the buffer. Midnight still rejects any position above
706
725
  * LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
707
- * @param params.collateralPrices - Values from `price()` on each
726
+ * @param raw.collateralPrices - Values from `price()` on each
708
727
  * `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
709
728
  * scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
710
729
  * `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a units
711
730
  * `target` covering `positionData.debt`, or an assets target whose `minUnits` covers it.
712
- * @param params.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`; `units: maxUint256` targets the sender's whole debt, capped by `maxBuyerAssets` (must be finite; `units: maxUint256` already selects the whole debt).
713
- * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
731
+ * @param raw.target - `{ type: "assets", assets, minUnits }` or `{ type: "units", units, maxBuyerAssets }`; `units: maxUint256` targets the sender's whole debt, capped by `maxBuyerAssets` (must be finite; `units: maxUint256` already selects the whole debt).
732
+ * @param raw.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
714
733
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
715
734
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
716
735
  * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
717
736
  * required for the full pulled amount.
718
- * @param params.takeableOffers - Borrow-side offers returned by the Midnight API.
719
- * @param params.repayEnabled - Whether the unfilled remainder is repaid directly to Midnight.
720
- * @param params.collateralWithdrawals - Optional collateral withdrawals; `maxUint256` assets withdraws the whole balance.
721
- * @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`,
737
+ * @param raw.takeableOffers - Borrow-side offers returned by the Midnight API.
738
+ * @param raw.repayEnabled - Whether the unfilled remainder is repaid directly to Midnight.
739
+ * @param raw.collateralWithdrawals - Optional collateral withdrawals; `maxUint256` assets withdraws the whole balance.
740
+ * @param raw.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`,
722
741
  * must be non-zero and not a Midnight protocol or market token contract when
723
742
  * `collateralWithdrawals` is non-empty, and is unused otherwise.
724
- * @param params.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
743
+ * @param raw.maxContinuousFee - Largest market continuous fee accepted, in the unit of the market's
725
744
  * onchain `continuousFee` (`Market.continuousFee`): a WAD-scaled per-second rate, so `317097919n`
726
745
  * is about 1% per year. The take reverts if the market fee is higher. Pass `maxUint256` for no cap.
727
- * @param params.deadline - Bundle execution deadline timestamp.
728
- * @param params.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
729
- * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
746
+ * @param raw.deadline - Bundle execution deadline timestamp.
747
+ * @param raw.referralFeePct - Optional WAD-scaled referral fee paid out of the pulled assets.
748
+ * @param raw.referralFeeRecipient - Referral fee recipient; required with a positive fee.
730
749
  * @returns Lazy loan-token approval and `MidnightBundlesV2` authorization requirements, and a synchronous transaction builder.
731
750
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
732
751
  * @throws {ChainIdMismatchError} when client or market data targets another chain, or from
@@ -790,7 +809,7 @@ export class MorphoMidnight {
790
809
  * takeableOffers: quote.data.takeableOffers,
791
810
  * repayEnabled: true,
792
811
  * collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
793
- * maxContinuousFee: maxUint256,
812
+ * maxContinuousFee: BigInt(marketData.continuousFee),
794
813
  * now: (await client.getBlock()).timestamp,
795
814
  * deadline: (await client.getBlock()).timestamp + 600n,
796
815
  * });
@@ -890,18 +909,18 @@ export class MorphoMidnight {
890
909
  * Uses the supplied position snapshot to resolve maxUint256 and check collateral health.
891
910
  * No requirements or RPC reads are needed. The signing account must be accountAddress.
892
911
  *
893
- * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
894
- * @param params.accountAddress - Collateral owner. This account must send the transaction.
895
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
896
- * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
897
- * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
912
+ * @param raw - Market, owner-bound position, collateral prices and withdrawal amount.
913
+ * @param raw.accountAddress - Collateral owner. This account must send the transaction.
914
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
915
+ * @param raw.positionData - Owner-bound position snapshot returned by getPositionData.
916
+ * @param raw.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
898
917
  * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
899
- * @param params.collateralIndex - Optional collateral index; defaults to 0n. Indexes follow the
918
+ * @param raw.collateralIndex - Optional collateral index; defaults to 0n. Indexes follow the
900
919
  * market's collateral parameters, which Midnight sorts by token address, not the order they were
901
920
  * listed in when the market was built; check marketData.getCollateralByIndex(index).token.
902
- * @param params.assets - Collateral assets to withdraw. maxUint256 resolves the whole balance of
921
+ * @param raw.assets - Collateral assets to withdraw. maxUint256 resolves the whole balance of
903
922
  * the selected collateral from positionData before building the transaction.
904
- * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
923
+ * @param raw.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
905
924
  * @returns Lazy handles for a direct Midnight withdrawal.
906
925
  * @throws {ChainIdMismatchError} when the client or market targets another chain.
907
926
  * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
@@ -970,15 +989,15 @@ export class MorphoMidnight {
970
989
  * Duplicates are rejected, unlike bundle flows which sum them.
971
990
  * No requirements or RPC reads are needed. The signing account must be accountAddress.
972
991
  *
973
- * @param params - Market, owner-bound position, collateral prices and withdrawal amount.
974
- * @param params.accountAddress - Collateral owner. This account must send the transaction.
975
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
976
- * @param params.positionData - Owner-bound position snapshot returned by getPositionData.
977
- * @param params.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
992
+ * @param raw - Market, owner-bound position, collateral prices and withdrawal amount.
993
+ * @param raw.accountAddress - Collateral owner. This account must send the transaction.
994
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
995
+ * @param raw.positionData - Owner-bound position snapshot returned by getPositionData.
996
+ * @param raw.collateralPrices - Oracle prices indexed like positionData.collateral and scaled by
978
997
  * ORACLE_PRICE_SCALE; required when the position has debt, otherwise an empty array is safe.
979
- * @param params.collateralWithdrawals - Nonempty ordered withdrawals, one per index.
998
+ * @param raw.collateralWithdrawals - Nonempty ordered withdrawals, one per index.
980
999
  * maxUint256 resolves that index's full snapshot balance.
981
- * @param params.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
1000
+ * @param raw.receiver - Account receiving the withdrawn collateral; defaults to accountAddress.
982
1001
  * @returns Lazy handles for a direct Midnight withdrawal.
983
1002
  * @throws {ChainIdMismatchError} when the client or market targets another chain.
984
1003
  * @throws {MidnightCalldataEncodingError} when accountAddress is malformed or an input cannot be ABI-encoded.
@@ -1048,18 +1067,18 @@ export class MorphoMidnight {
1048
1067
  /**
1049
1068
  * Prepares a direct collateral supply using a caller-provided market snapshot.
1050
1069
  *
1051
- * @param params.accountAddress - Account receiving the supplied collateral position. It must send
1070
+ * @param raw.accountAddress - Account receiving the supplied collateral position. It must send
1052
1071
  * the transaction: Midnight pulls the collateral from `msg.sender` and only lets the position owner
1053
1072
  * or its operators supply for it, and the approval requirements are resolved for this account.
1054
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1055
- * @param params.collateralAssets - Collateral assets supplied in this transaction.
1056
- * @param params.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
1073
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
1074
+ * @param raw.collateralAssets - Collateral assets supplied in this transaction.
1075
+ * @param raw.reservedCollateralAssets - Existing collateral reserved by other open maker groups.
1057
1076
  * Only raises the approval requirement so those groups keep their allowance; the transaction
1058
1077
  * transfers only `collateralAssets`.
1059
- * @param params.collateralIndex - Optional collateral index; defaults to `0n`. Indexes follow the
1078
+ * @param raw.collateralIndex - Optional collateral index; defaults to `0n`. Indexes follow the
1060
1079
  * market's collateral parameters, which Midnight sorts by token address, not the order they were
1061
1080
  * listed in when the market was built; check `marketData.getCollateralByIndex(index).token`.
1062
- * @param params.now - Optional reference timestamp in seconds; used for metadata only when the
1081
+ * @param raw.now - Optional reference timestamp in seconds; used for metadata only when the
1063
1082
  * client sets `metadata.timestamp: true`.
1064
1083
  * @returns Lazy token-approval requirements and a synchronous transaction builder.
1065
1084
  * @throws {NegativeInputError} when the resolved metadata timestamp is negative, or the reserve is negative.
@@ -1257,9 +1276,9 @@ export class MorphoMidnight {
1257
1276
  * Prepares ordered direct collateral supplies in one Midnight multicall.
1258
1277
  * Pass one entry per index: duplicates are rejected, unlike bundle flows which sum them.
1259
1278
  *
1260
- * @param params.accountAddress - Sender and collateral beneficiary.
1261
- * @param params.marketData - Snapshot of the target market.
1262
- * @param params.collateralSupplies - Ordered supplies with optional reserved allowance amounts.
1279
+ * @param raw.accountAddress - Sender and collateral beneficiary.
1280
+ * @param raw.marketData - Snapshot of the target market.
1281
+ * @param raw.collateralSupplies - Ordered supplies with optional reserved allowance amounts.
1263
1282
  * @returns A lazy approval resolver and synchronous stateless transaction builder.
1264
1283
  * @throws {ChainIdMismatchError} when the client or market targets another chain.
1265
1284
  * @throws {MidnightMarketAddressMismatchError} when the deployment differs.
@@ -1908,14 +1927,14 @@ export class MorphoMidnight {
1908
1927
  /**
1909
1928
  * Prepares redemption of accrued Midnight credit from a position snapshot.
1910
1929
  *
1911
- * @param params - Position owner, accrued position, optional unit amount, and receiver.
1912
- * @param params.accountAddress - Position owner whose credit is redeemed. It must send the
1930
+ * @param raw - Position owner, accrued position, optional unit amount, and receiver.
1931
+ * @param raw.accountAddress - Position owner whose credit is redeemed. It must send the
1913
1932
  * transaction (or authorize the sender): Midnight reverts `Unauthorized()` otherwise, which
1914
1933
  * `getRequirements()` cannot detect because it does not know the sender.
1915
- * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`.
1916
- * @param params.receiver - Optional credit receiver; defaults to the position owner.
1934
+ * @param raw.positionData - Owner-bound position snapshot returned by `getPositionData`.
1935
+ * @param raw.receiver - Optional credit receiver; defaults to the position owner.
1917
1936
  * Midnight protocol and market token contracts are rejected.
1918
- * @param params.units - Optional credit units to redeem; defaults to the position face value.
1937
+ * @param raw.units - Optional credit units to redeem; defaults to the position face value.
1919
1938
  * Credit is checked after applying the realized losses and continuous fees that Midnight
1920
1939
  * charges before a withdrawal, accrued up to now. Fees keep accruing until maturity, so `units` close to the accrued
1921
1940
  * credit can still revert when the transaction lands later. The default face value does not
@@ -1964,30 +1983,30 @@ export class MorphoMidnight {
1964
1983
  /**
1965
1984
  * Prepares a direct `MidnightBundlesV2` repayment, collateral withdrawal, or both, for `accountAddress`.
1966
1985
  *
1967
- * @param params - Account, market snapshot, `repay` mode, collateral withdrawals, optional collateral receiver, and deadline.
1968
- * @param params.accountAddress - Position owner and transaction sender.
1969
- * @param params.marketData - Hydrated market snapshot used for validation and transaction construction.
1970
- * @param params.positionData - Owner-bound position snapshot returned by `getPositionData`. The
1986
+ * @param raw - Account, market snapshot, `repay` mode, collateral withdrawals, optional collateral receiver, and deadline.
1987
+ * @param raw.accountAddress - Position owner and transaction sender.
1988
+ * @param raw.marketData - Hydrated market snapshot used for validation and transaction construction.
1989
+ * @param raw.positionData - Owner-bound position snapshot returned by `getPositionData`. The
1971
1990
  * `DEFAULT_LLTV_BUFFER` check is only as current as this snapshot and `collateralPrices`: it
1972
1991
  * does not see transactions mined or prices moved since, so two transactions built from one
1973
1992
  * snapshot can together end inside the buffer. Midnight still rejects any position above
1974
1993
  * LLTV onchain. Midnight debt and collateral do not accrue, so the check needs no accrual.
1975
- * @param params.collateralPrices - Values from `price()` on each
1994
+ * @param raw.collateralPrices - Values from `price()` on each
1976
1995
  * `marketData.params.collateralParams[i].oracle`, indexed like `positionData.collateral` and
1977
1996
  * scaled by `ORACLE_PRICE_SCALE`. An empty array is safe only when
1978
1997
  * `collateralWithdrawals` is empty or the conservative post-operation debt is zero: a `full`
1979
1998
  * repay, or `repay.assets` covering `positionData.debt`.
1980
- * @param params.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`; a loan-token approval to `MidnightBundlesV2` is required when the allowance is below the pulled amount (unlimited: `maxUint256`, capped per token by `MAX_TOKEN_APPROVALS`), and any unused part is refunded.
1981
- * @param params.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1999
+ * @param raw.repay - `{ type: "assets", assets }` (`0n` to only withdraw) or `{ type: "full", maxBuyerAssets }`; a loan-token approval to `MidnightBundlesV2` is required when the allowance is below the pulled amount (unlimited: `maxUint256`, capped per token by `MAX_TOKEN_APPROVALS`), and any unused part is refunded.
2000
+ * @param raw.nativeAmount - Optional native ETH sent as `value`; the bundle wraps it into the
1982
2001
  * chain's wNative and transfers it to `msg.sender` before pulling. It may cover part or all of
1983
2002
  * the maximum wNative amount this call can pull, but not more. Any wrapped native not pulled
1984
2003
  * stays in the sender's wallet as wNative. The wNative approval to `MidnightBundlesV2` is still
1985
2004
  * required for the full pulled amount.
1986
- * @param params.collateralWithdrawals - Optional withdrawals; `assets: maxUint256` withdraws the full balance.
1987
- * @param params.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`,
2005
+ * @param raw.collateralWithdrawals - Optional withdrawals; `assets: maxUint256` withdraws the full balance.
2006
+ * @param raw.collateralReceiver - Optional collateral recipient; defaults to `accountAddress`,
1988
2007
  * must be non-zero and not a Midnight protocol or market token contract when
1989
2008
  * `collateralWithdrawals` is non-empty, and is unused otherwise.
1990
- * @param params.deadline - Bundle execution deadline timestamp. Unlike taker builders,
2009
+ * @param raw.deadline - Bundle execution deadline timestamp. Unlike taker builders,
1991
2010
  * `maxUint256` is accepted because no offers are filled; the pull remains bounded by
1992
2011
  * `repay.assets` or `repay.maxBuyerAssets`.
1993
2012
  * @returns Lazy loan approval/authorization requirements and a synchronous transaction builder.
@@ -195,7 +195,6 @@ export class MorphoVaultV1 {
195
195
  if (amount <= 0n) {
196
196
  throw new NonPositiveInputError("amount", amount);
197
197
  }
198
- // Reject values outside the ABI range before resolving any requirements.
199
198
  const parsedAmount = parseUint256("amount", amount);
200
199
  const createdAt = suppliedNow ?? Time.timestamp();
201
200
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
@@ -196,7 +196,6 @@ export class MorphoVaultV2 {
196
196
  if (amount <= 0n) {
197
197
  throw new NonPositiveInputError("amount", amount);
198
198
  }
199
- // Reject values outside the ABI range before resolving any requirements.
200
199
  const parsedAmount = parseUint256("amount", amount);
201
200
  const createdAt = suppliedNow ?? Time.timestamp();
202
201
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
@@ -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
@@ -5,6 +5,13 @@ import { maxUint96 } from "viem";
5
5
  export const VAULT_DEPOSIT_MAX_DEADLINE_SECONDS = 604800n;
6
6
  /** Maximum time between now and a Midnight taker-flow deadline, in seconds. */
7
7
  export const MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS = 3600n;
8
+ /**
9
+ * Minimum time between a Midnight borrow's deadline and its market maturity, in seconds (2 hours).
10
+ * Debt still open at maturity becomes liquidatable, so entity and TransactionPlan borrows prepared at
11
+ * or before maturity that could execute closer to it are rejected. Credit covering the target at
12
+ * preparation does not exempt a borrow; sell credit only inside the window with `takeWithdraw`.
13
+ */
14
+ export const MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY = Time.s.from.h(2n);
8
15
  /**
9
16
  * Matches MAX_SLIPPAGE_TOLERANCE, the SDK's other ceiling on a WAD share of user funds; higher fees are rejected as likely unit mistakes.
10
17
  * @internal
@@ -1,5 +1,5 @@
1
1
  export { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "./callback.js";
2
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
2
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
3
3
  export { validateBlueMarketDeadShares, validateVaultV1DeadShares, validateVaultV2DeadShares, } from "./deadShares.js";
4
4
  export { addTransactionMetadata } from "./metadata.js";
5
5
  export { type PreviewVaultV2ForceWithdrawParams, previewVaultV2ForceWithdraw, type VaultV2ForceWithdrawPreview, } from "./previewVaultV2ForceWithdraw.js";
@@ -1,5 +1,5 @@
1
1
  export { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "./callback.js";
2
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
2
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY, MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS, MIN_DEAD_SHARES, MIN_VAULT_V2_DEAD_ASSETS, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
3
3
  export { validateBlueMarketDeadShares, validateVaultV1DeadShares, validateVaultV2DeadShares, } from "./deadShares.js";
4
4
  export { addTransactionMetadata } from "./metadata.js";
5
5
  export { previewVaultV2ForceWithdraw, } from "./previewVaultV2ForceWithdraw.js";
@@ -235,6 +235,20 @@ export declare const validateMidnightBorrowHealth: (params: {
235
235
  readonly debt: bigint;
236
236
  readonly borrowUnits: bigint;
237
237
  }) => void;
238
+ /**
239
+ * @internal Rejects a Midnight borrow that could execute less than
240
+ * `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` before the market's maturity, when unpaid debt becomes
241
+ * liquidatable. The sell is not reduce-only, so any units beyond the credit left at execution open
242
+ * debt; credit covering the target when the borrow is prepared does not exempt it. Once `now` is
243
+ * past maturity the protocol rejects new debt, so the check does not apply, matching the
244
+ * post-maturity credit cap in `validateMidnightTakeFeasibility`.
245
+ * Used by the entity and TransactionPlan borrow flows.
246
+ */
247
+ export declare const validateMidnightBorrowMaturity: (params: {
248
+ readonly marketData: MidnightMarket;
249
+ readonly now: bigint;
250
+ readonly deadline: bigint;
251
+ }) => void;
238
252
  /**
239
253
  * @internal Rejects a Midnight collateral withdrawal whose post-operation debt exceeds the remaining
240
254
  * collateral's capacity at LLTV minus `DEFAULT_LLTV_BUFFER`, with the same check and error as the
@@ -497,8 +511,18 @@ export declare const validateRepayShares: (params: {
497
511
  repayShares: bigint;
498
512
  marketId: MarketId;
499
513
  }) => void;
514
+ /** Plain allocation fields shared by reallocation validation and stored withdrawal plans. @internal */
515
+ export type BlueReallocationInput = Omit<VaultV2BlueReallocation, "from"> & {
516
+ readonly from: {
517
+ readonly type: "market";
518
+ readonly adapter: Address;
519
+ readonly marketParams: Readonly<InputMarketParams>;
520
+ } | Extract<VaultV2BlueReallocation["from"], {
521
+ type: "idle";
522
+ }>;
523
+ };
500
524
  /** @internal */
501
- export declare const validateVaultV2BlueReallocations: (reallocations: Iterable<VaultV2BlueReallocation>, { targetMarketId, maxPenalty, }: {
525
+ export declare const validateVaultV2BlueReallocations: (reallocations: Iterable<BlueReallocationInput>, { targetMarketId, maxPenalty, }: {
502
526
  readonly targetMarketId: MarketId;
503
527
  readonly maxPenalty?: bigint;
504
528
  }) => void;
@@ -2,9 +2,9 @@ import { getChainAddresses, MarketUtils, MathLib, ORACLE_PRICE_SCALE, } from "@m
2
2
  import { MarketUtils as MidnightMarketUtils, } from "@morpho-org/midnight-sdk";
3
3
  import { isDefined, isHexEqual } from "@morpho-org/morpho-ts";
4
4
  import { isAddress, isAddressEqual, maxUint128, maxUint256, zeroAddress, } from "viem";
5
- import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, ExcessiveSlippageToleranceError, InconsistentReallocationPenaltyError, InputExceedsMaxError, InvalidBigIntInputError, InvalidMidnightNativeAmountTypeError, InvalidReallocationAddressError, InvalidReallocationSourceTypeError, InvalidVaultV2BlueReallocationShapeError, MarketIdMismatchError, MidnightRepayExceedsDebtError, MidnightTakeTargetUnreachableError, MissingClientPropertyError, MissingMarketPriceError, NativeAmountOnNonWNativeAssetError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, ReallocationWithdrawalOnTargetMarketError, ReferralFeePctExceededError, ReferralFeeRecipientMissingError, RepayExceedsDebtError, RepaySharesExceedDebtError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
5
+ import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, ExcessiveSlippageToleranceError, InconsistentReallocationPenaltyError, InputExceedsMaxError, InvalidBigIntInputError, InvalidMidnightNativeAmountTypeError, InvalidReallocationAddressError, InvalidReallocationSourceTypeError, InvalidVaultV2BlueReallocationShapeError, MarketIdMismatchError, MidnightBorrowTooCloseToMaturityError, MidnightRepayExceedsDebtError, MidnightTakeTargetUnreachableError, MissingClientPropertyError, MissingMarketPriceError, NativeAmountOnNonWNativeAssetError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, ReallocationWithdrawalOnTargetMarketError, ReferralFeePctExceededError, ReferralFeeRecipientMissingError, RepayExceedsDebtError, RepaySharesExceedDebtError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
6
6
  import { computeMidnightPostWithdrawalCollateral } from "./computeMidnightPostWithdrawalCollateral.js";
7
- import { DEFAULT_LLTV_BUFFER, MAX_SLIPPAGE_TOLERANCE, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
7
+ import { DEFAULT_LLTV_BUFFER, MAX_SLIPPAGE_TOLERANCE, MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY, VAULT_DEPOSIT_MAX_DEADLINE_SECONDS, } from "./constant.js";
8
8
  import { resolveMaxPenalty } from "./reallocationPenalty.js";
9
9
  import { validateMidnightAddress } from "./validateMidnightAccount.js";
10
10
  import { validateMidnightReferralFeeCap } from "./validateMidnightBounds.js";
@@ -323,6 +323,29 @@ export const validateMidnightBorrowHealth = (params) => {
323
323
  throw new BorrowExceedsSafeLtvError(params.borrowUnits, MathLib.zeroFloorSub(maxSafeDebt, params.debt));
324
324
  }
325
325
  };
326
+ /**
327
+ * @internal Rejects a Midnight borrow that could execute less than
328
+ * `MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY` before the market's maturity, when unpaid debt becomes
329
+ * liquidatable. The sell is not reduce-only, so any units beyond the credit left at execution open
330
+ * debt; credit covering the target when the borrow is prepared does not exempt it. Once `now` is
331
+ * past maturity the protocol rejects new debt, so the check does not apply, matching the
332
+ * post-maturity credit cap in `validateMidnightTakeFeasibility`.
333
+ * Used by the entity and TransactionPlan borrow flows.
334
+ */
335
+ export const validateMidnightBorrowMaturity = (params) => {
336
+ const { maturity } = params.marketData.params;
337
+ if (params.now > maturity) {
338
+ return;
339
+ }
340
+ const latestDeadline = maturity - MIDNIGHT_MIN_BORROW_TIME_TO_MATURITY;
341
+ if (params.deadline > latestDeadline) {
342
+ throw new MidnightBorrowTooCloseToMaturityError({
343
+ deadline: params.deadline,
344
+ maturity,
345
+ latestDeadline,
346
+ });
347
+ }
348
+ };
326
349
  /**
327
350
  * @internal Rejects a Midnight collateral withdrawal whose post-operation debt exceeds the remaining
328
351
  * collateral's capacity at LLTV minus `DEFAULT_LLTV_BUFFER`, with the same check and error as the