@morpho-org/morpho-sdk 9.8.0 → 10.0.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 (181) hide show
  1. package/MIGRATION-v9-to-v10.md +114 -0
  2. package/README.md +5 -1
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +5 -1
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -1
  7. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -1
  8. package/lib/cjs/actions/midnight/cancelAndMake.js +2 -1
  9. package/lib/cjs/actions/midnight/cancelOffers.d.ts +54 -0
  10. package/lib/cjs/actions/midnight/cancelOffers.js +107 -0
  11. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  12. package/lib/cjs/actions/midnight/index.js +1 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  14. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +1 -1
  15. package/lib/cjs/actions/midnight/takeBorrow.d.ts +1 -1
  16. package/lib/cjs/actions/midnight/takeBorrow.js +1 -1
  17. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -1
  18. package/lib/cjs/actions/midnight/takeLend.js +1 -1
  19. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  20. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -1
  21. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +1 -1
  22. package/lib/cjs/actions/midnight/takeWithdraw.js +1 -1
  23. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  25. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  26. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +3 -3
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +3 -2
  31. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  32. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  33. package/lib/cjs/blue/abis.d.ts +1 -1
  34. package/lib/cjs/blue/abis.js +5 -1
  35. package/lib/cjs/blue/entities.d.ts +4 -4
  36. package/lib/cjs/blue/entities.js +3 -1
  37. package/lib/cjs/blue/errors.d.ts +2 -2
  38. package/lib/cjs/blue/errors.js +5 -1
  39. package/lib/cjs/blue/fetch.d.ts +2 -2
  40. package/lib/cjs/blue/fetch.js +3 -1
  41. package/lib/cjs/blue/utils.d.ts +1 -1
  42. package/lib/cjs/blue/utils.js +2 -1
  43. package/lib/cjs/entities/blue/blue.d.ts +34 -28
  44. package/lib/cjs/entities/blue/blue.js +99 -73
  45. package/lib/cjs/entities/index.d.ts +4 -4
  46. package/lib/cjs/entities/index.js +3 -1
  47. package/lib/cjs/entities/midnight/deadline.d.ts +2 -2
  48. package/lib/cjs/entities/midnight/deadline.js +2 -2
  49. package/lib/cjs/entities/midnight/midnight.d.ts +49 -51
  50. package/lib/cjs/entities/midnight/midnight.js +144 -131
  51. package/lib/cjs/entities/midnight/publication.d.ts +2 -0
  52. package/lib/cjs/entities/midnight/publication.js +126 -100
  53. package/lib/cjs/entities/midnight/types.d.ts +4 -4
  54. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  55. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +17 -17
  56. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +3 -4
  57. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +1 -1
  58. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +12 -12
  59. package/lib/cjs/entities/vaultV1/vaultV1.js +83 -57
  60. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +50 -24
  61. package/lib/cjs/entities/vaultV2/vaultV2.js +166 -90
  62. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +17 -2
  63. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1410 -806
  64. package/lib/cjs/errors.d.ts +4 -4
  65. package/lib/cjs/errors.js +7 -5
  66. package/lib/cjs/fetch.d.ts +2 -2
  67. package/lib/cjs/fetch.js +3 -1
  68. package/lib/cjs/helpers/deadShares.js +55 -34
  69. package/lib/cjs/helpers/metadata.d.ts +14 -2
  70. package/lib/cjs/helpers/metadata.js +39 -4
  71. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +34 -22
  72. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +7 -1
  73. package/lib/cjs/helpers/validate.js +76 -61
  74. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +154 -103
  75. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +31 -20
  76. package/lib/cjs/midnight/errors.d.ts +2 -1
  77. package/lib/cjs/midnight/errors.js +5 -4
  78. package/lib/cjs/transactionPlan/plan.js +6 -3
  79. package/lib/cjs/transactionPlan/serde.js +7 -7
  80. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +6 -4
  81. package/lib/cjs/transactionPlan/vaultv2/deposit.js +5 -3
  82. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  83. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +5 -3
  84. package/lib/cjs/types/action.d.ts +26 -2
  85. package/lib/cjs/types/action.js +1 -1
  86. package/lib/cjs/types/error.js +11 -5
  87. package/lib/cjs/types/metadata.d.ts +12 -2
  88. package/lib/cjs/utils.d.ts +2 -2
  89. package/lib/cjs/utils.js +4 -2
  90. package/lib/cjs/version.d.ts +1 -1
  91. package/lib/cjs/version.js +1 -1
  92. package/lib/esm/abis.d.ts +1 -1
  93. package/lib/esm/abis.js +1 -1
  94. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  95. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +1 -1
  96. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -1
  97. package/lib/esm/actions/midnight/cancelAndMake.js +2 -1
  98. package/lib/esm/actions/midnight/cancelOffers.d.ts +54 -0
  99. package/lib/esm/actions/midnight/cancelOffers.js +103 -0
  100. package/lib/esm/actions/midnight/index.d.ts +1 -0
  101. package/lib/esm/actions/midnight/index.js +1 -0
  102. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  103. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +1 -1
  104. package/lib/esm/actions/midnight/takeBorrow.d.ts +1 -1
  105. package/lib/esm/actions/midnight/takeBorrow.js +1 -1
  106. package/lib/esm/actions/midnight/takeLend.d.ts +1 -1
  107. package/lib/esm/actions/midnight/takeLend.js +1 -1
  108. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  109. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -1
  110. package/lib/esm/actions/midnight/takeWithdraw.d.ts +1 -1
  111. package/lib/esm/actions/midnight/takeWithdraw.js +1 -1
  112. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  113. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  114. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  115. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  116. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  117. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +3 -3
  118. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  119. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +3 -2
  120. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  121. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  122. package/lib/esm/blue/abis.d.ts +1 -1
  123. package/lib/esm/blue/abis.js +1 -1
  124. package/lib/esm/blue/entities.d.ts +4 -4
  125. package/lib/esm/blue/entities.js +2 -2
  126. package/lib/esm/blue/errors.d.ts +2 -2
  127. package/lib/esm/blue/errors.js +2 -2
  128. package/lib/esm/blue/fetch.d.ts +2 -2
  129. package/lib/esm/blue/fetch.js +2 -2
  130. package/lib/esm/blue/utils.d.ts +1 -1
  131. package/lib/esm/blue/utils.js +1 -1
  132. package/lib/esm/entities/blue/blue.d.ts +34 -28
  133. package/lib/esm/entities/blue/blue.js +99 -73
  134. package/lib/esm/entities/index.d.ts +4 -4
  135. package/lib/esm/entities/index.js +2 -2
  136. package/lib/esm/entities/midnight/deadline.d.ts +2 -2
  137. package/lib/esm/entities/midnight/deadline.js +2 -2
  138. package/lib/esm/entities/midnight/midnight.d.ts +49 -51
  139. package/lib/esm/entities/midnight/midnight.js +145 -132
  140. package/lib/esm/entities/midnight/publication.d.ts +2 -0
  141. package/lib/esm/entities/midnight/publication.js +126 -100
  142. package/lib/esm/entities/midnight/types.d.ts +4 -4
  143. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  144. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +17 -17
  145. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +3 -4
  146. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +1 -1
  147. package/lib/esm/entities/vaultV1/vaultV1.d.ts +12 -12
  148. package/lib/esm/entities/vaultV1/vaultV1.js +83 -57
  149. package/lib/esm/entities/vaultV2/vaultV2.d.ts +50 -24
  150. package/lib/esm/entities/vaultV2/vaultV2.js +166 -90
  151. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +17 -2
  152. package/lib/esm/entities/vaultV2BlueReallocationData.js +1410 -806
  153. package/lib/esm/errors.d.ts +4 -4
  154. package/lib/esm/errors.js +4 -4
  155. package/lib/esm/fetch.d.ts +2 -2
  156. package/lib/esm/fetch.js +2 -2
  157. package/lib/esm/helpers/deadShares.js +56 -35
  158. package/lib/esm/helpers/metadata.d.ts +14 -2
  159. package/lib/esm/helpers/metadata.js +38 -4
  160. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +34 -22
  161. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +7 -1
  162. package/lib/esm/helpers/validate.js +76 -61
  163. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +153 -102
  164. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +31 -20
  165. package/lib/esm/midnight/errors.d.ts +2 -1
  166. package/lib/esm/midnight/errors.js +2 -1
  167. package/lib/esm/transactionPlan/plan.js +6 -3
  168. package/lib/esm/transactionPlan/serde.js +7 -7
  169. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +6 -4
  170. package/lib/esm/transactionPlan/vaultv2/deposit.js +5 -3
  171. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  172. package/lib/esm/transactionPlan/vaultv2/withdraw.js +5 -3
  173. package/lib/esm/types/action.d.ts +26 -2
  174. package/lib/esm/types/action.js +1 -1
  175. package/lib/esm/types/error.js +11 -5
  176. package/lib/esm/types/metadata.d.ts +12 -2
  177. package/lib/esm/utils.d.ts +2 -2
  178. package/lib/esm/utils.js +2 -2
  179. package/lib/esm/version.d.ts +1 -1
  180. package/lib/esm/version.js +1 -1
  181. package/package.json +8 -7
@@ -3,13 +3,14 @@ import { fetchMarket as fetchBlueMarket } from "@morpho-org/blue-sdk-viem";
3
3
  import { fetchAccrualPosition, fetchMarket, MarketParams, MarketUtils, Payload, PriceRatifierV1, RateRatifierV1, Tree, } from "@morpho-org/midnight-sdk";
4
4
  import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
5
5
  import { isAddress, isAddressEqual, maxUint256, zeroAddress, } from "viem";
6
- import { midnightCancelAndMake, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralBatch, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, midnightWithdrawCollateral, midnightWithdrawCollateralBatch, } from "../../actions/midnight/index.js";
6
+ import { midnightCancelAndMake, midnightCancelOffers, midnightRedeem, midnightRepayWithdrawCollateral, midnightSupplyCollateral, midnightSupplyCollateralBatch, midnightSupplyCollateralTakeBorrow, midnightTakeBorrow, midnightTakeLend, midnightTakeRepayWithdrawCollateral, midnightTakeWithdraw, midnightWithdrawCollateral, midnightWithdrawCollateralBatch, } from "../../actions/midnight/index.js";
7
7
  import { getMidnightApprovalRequirements, getMidnightAuthorizationRequirement, } from "../../actions/requirements/index.js";
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { getMidnightBlueBuyCallbackAddress, getMidnightBlueBuyCallbackData, } from "../../helpers/callback.js";
10
10
  import { MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS } from "../../helpers/constant.js";
11
11
  import { encodeMidnightMarketId, wrapMidnightEncoding, } from "../../helpers/encodeMidnightCalldata.js";
12
12
  import { getMidnightMaxSafeDebt, validateChainId, } from "../../helpers/index.js";
13
+ import { resolveTransactionMetadata } from "../../helpers/metadata.js";
13
14
  import { validateMidnightAccount, validateMidnightAddress, } from "../../helpers/validateMidnightAccount.js";
14
15
  import { validateMidnightUint128Field } from "../../helpers/validateMidnightBounds.js";
15
16
  import { validateMidnightCollateralBatch } from "../../helpers/validateMidnightCollateralBatch.js";
@@ -30,8 +31,7 @@ const validatePositionBinding = (params) => {
30
31
  throw new AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
31
32
  }
32
33
  };
33
- const validateTakeDeadlineWindow = (deadline) => {
34
- const now = Time.timestamp();
34
+ const validateTakeDeadlineWindow = (deadline, now = Time.timestamp()) => {
35
35
  // Throws when the deadline is at or before now.
36
36
  validateMidnightDeadline(deadline, now);
37
37
  const maxDeadline = now + MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
@@ -147,6 +147,29 @@ const getOffersDataInternal = async ({ client, chainId, params, marketCreationTi
147
147
  payload: await Payload.encode(items),
148
148
  };
149
149
  };
150
+ const getPostWithdrawalCollateral = (params) => {
151
+ const market = params.marketData.params;
152
+ const collateralWithdrawals = params.collateralWithdrawals ?? [];
153
+ const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
154
+ let withdrawAmount = 0n;
155
+ for (const withdrawal of collateralWithdrawals) {
156
+ // Reject unconfigured collateral indexes before updating postCollateral.
157
+ MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
158
+ const index = Number(withdrawal.collateralIndex);
159
+ const available = postCollateral[index] ?? 0n;
160
+ const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
161
+ if (amount > available) {
162
+ throw new WithdrawExceedsCollateralError({
163
+ withdrawAmount: amount,
164
+ available,
165
+ market: params.marketData.id,
166
+ });
167
+ }
168
+ postCollateral[index] = available - amount;
169
+ withdrawAmount += amount;
170
+ }
171
+ return { postCollateral, withdrawAmount };
172
+ };
150
173
  const validateMarketData = (market, chainId) => {
151
174
  // Reject snapshots from another chain deployment before exposing requirements.
152
175
  validateMidnightMarket({ market, chainId });
@@ -361,15 +384,18 @@ export class MorphoMidnight {
361
384
  * target: { type: "assets", assets: 1_000_000n, minUnits: 900_000n },
362
385
  * takeableOffers: quote.data.takeableOffers,
363
386
  * maxContinuousFee: maxUint256,
364
- * deadline: Time.timestamp() + 600n,
387
+ * now: (await client.getBlock()).timestamp,
388
+ * deadline: (await client.getBlock()).timestamp + 600n,
365
389
  * });
366
390
  * ```
367
391
  */
368
392
  takeLend(params) {
393
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
369
394
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
370
395
  // Reject the zero account before preparing anything for it.
371
396
  validateMidnightAccount("accountAddress", params.accountAddress);
372
- validateTakeDeadlineWindow(params.deadline);
397
+ const now = params.now ?? Time.timestamp();
398
+ validateTakeDeadlineWindow(params.deadline, now);
373
399
  const market = params.marketData.params;
374
400
  const rawParams = {
375
401
  chainId: this.chainId,
@@ -381,7 +407,7 @@ export class MorphoMidnight {
381
407
  deadline: params.deadline,
382
408
  referralFeePct: params.referralFeePct,
383
409
  referralFeeRecipient: params.referralFeeRecipient,
384
- metadata: this.client.options.metadata,
410
+ metadata,
385
411
  };
386
412
  let tx = midnightTakeLend(rawParams);
387
413
  const takeableOffers = validateMidnightTakeFeasibility({
@@ -389,7 +415,7 @@ export class MorphoMidnight {
389
415
  takeableOffers: params.takeableOffers,
390
416
  accountAddress: params.accountAddress,
391
417
  marketData: params.marketData,
392
- now: Time.timestamp(),
418
+ now: params.now ?? Time.timestamp(),
393
419
  deadline: params.deadline,
394
420
  referralFeePct: tx.action.args.referralFeePct,
395
421
  fallbackUnits: 0n,
@@ -508,15 +534,18 @@ export class MorphoMidnight {
508
534
  * collateralPrices,
509
535
  * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
510
536
  * takeableOffers: quote.data.takeableOffers,
511
- * deadline: Time.timestamp() + 600n,
537
+ * now: (await client.getBlock()).timestamp,
538
+ * deadline: (await client.getBlock()).timestamp + 600n,
512
539
  * });
513
540
  * ```
514
541
  */
515
542
  takeBorrow(params) {
543
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
516
544
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
517
545
  // Reject the zero account before preparing anything for it.
518
546
  validateMidnightAccount("accountAddress", params.accountAddress);
519
- validateTakeDeadlineWindow(params.deadline);
547
+ const now = params.now ?? Time.timestamp();
548
+ validateTakeDeadlineWindow(params.deadline, now);
520
549
  const rawParams = {
521
550
  chainId: this.chainId,
522
551
  market: params.marketData.params,
@@ -526,7 +555,7 @@ export class MorphoMidnight {
526
555
  deadline: params.deadline,
527
556
  referralFeePct: params.referralFeePct,
528
557
  referralFeeRecipient: params.referralFeeRecipient,
529
- metadata: this.client.options.metadata,
558
+ metadata,
530
559
  };
531
560
  let tx = midnightTakeBorrow(rawParams);
532
561
  validatePositionBinding({
@@ -548,7 +577,6 @@ export class MorphoMidnight {
548
577
  throw new BorrowExceedsSafeLtvError(requestedUnits, MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
549
578
  }
550
579
  }
551
- const now = Time.timestamp();
552
580
  const takeableOffers = validateMidnightTakeFeasibility({
553
581
  side: "sell",
554
582
  takeableOffers: params.takeableOffers,
@@ -635,15 +663,18 @@ export class MorphoMidnight {
635
663
  * marketData,
636
664
  * target: { type: "units", units: credit, minSellerAssets: 990_000n },
637
665
  * takeableOffers: quote.data.takeableOffers,
638
- * deadline: Time.timestamp() + 600n,
666
+ * now: (await client.getBlock()).timestamp,
667
+ * deadline: (await client.getBlock()).timestamp + 600n,
639
668
  * });
640
669
  * ```
641
670
  */
642
671
  takeWithdraw(params) {
672
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
643
673
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
644
674
  // Reject the zero account before preparing anything for it.
645
675
  validateMidnightAccount("accountAddress", params.accountAddress);
646
- validateTakeDeadlineWindow(params.deadline);
676
+ const now = params.now ?? Time.timestamp();
677
+ validateTakeDeadlineWindow(params.deadline, now);
647
678
  const rawParams = {
648
679
  chainId: this.chainId,
649
680
  market: params.marketData.params,
@@ -653,7 +684,7 @@ export class MorphoMidnight {
653
684
  deadline: params.deadline,
654
685
  referralFeePct: params.referralFeePct,
655
686
  referralFeeRecipient: params.referralFeeRecipient,
656
- metadata: this.client.options.metadata,
687
+ metadata,
657
688
  };
658
689
  let tx = midnightTakeWithdraw(rawParams);
659
690
  const takeableOffers = validateMidnightTakeFeasibility({
@@ -661,7 +692,7 @@ export class MorphoMidnight {
661
692
  takeableOffers: params.takeableOffers,
662
693
  accountAddress: params.accountAddress,
663
694
  marketData: params.marketData,
664
- now: Time.timestamp(),
695
+ now: params.now ?? Time.timestamp(),
665
696
  deadline: params.deadline,
666
697
  referralFeePct: tx.action.args.referralFeePct,
667
698
  // The bundle redeems credit first, up to the market's withdrawable liquidity.
@@ -768,15 +799,18 @@ export class MorphoMidnight {
768
799
  * collateralSupplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
769
800
  * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
770
801
  * takeableOffers: quote.data.takeableOffers,
771
- * deadline: Time.timestamp() + 600n,
802
+ * now: (await client.getBlock()).timestamp,
803
+ * deadline: (await client.getBlock()).timestamp + 600n,
772
804
  * });
773
805
  * ```
774
806
  */
775
807
  supplyCollateralTakeBorrow(params) {
808
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
776
809
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
777
810
  // Reject the zero account before preparing anything for it.
778
811
  validateMidnightAccount("accountAddress", params.accountAddress);
779
- validateTakeDeadlineWindow(params.deadline);
812
+ const now = params.now ?? Time.timestamp();
813
+ validateTakeDeadlineWindow(params.deadline, now);
780
814
  const market = params.marketData.params;
781
815
  const rawParams = {
782
816
  chainId: this.chainId,
@@ -789,7 +823,7 @@ export class MorphoMidnight {
789
823
  deadline: params.deadline,
790
824
  referralFeePct: params.referralFeePct,
791
825
  referralFeeRecipient: params.referralFeeRecipient,
792
- metadata: this.client.options.metadata,
826
+ metadata,
793
827
  };
794
828
  let tx = midnightSupplyCollateralTakeBorrow(rawParams);
795
829
  validatePositionBinding({
@@ -818,7 +852,6 @@ export class MorphoMidnight {
818
852
  throw new BorrowExceedsSafeLtvError(requestedUnits, MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
819
853
  }
820
854
  }
821
- const now = Time.timestamp();
822
855
  const takeableOffers = validateMidnightTakeFeasibility({
823
856
  side: "sell",
824
857
  takeableOffers: params.takeableOffers,
@@ -962,15 +995,18 @@ export class MorphoMidnight {
962
995
  * repayEnabled: true,
963
996
  * collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
964
997
  * maxContinuousFee: maxUint256,
965
- * deadline: Time.timestamp() + 600n,
998
+ * now: (await client.getBlock()).timestamp,
999
+ * deadline: (await client.getBlock()).timestamp + 600n,
966
1000
  * });
967
1001
  * ```
968
1002
  */
969
1003
  takeRepayWithdrawCollateral(params) {
1004
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
970
1005
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
971
1006
  // Reject the zero account before preparing anything for it.
972
1007
  validateMidnightAccount("accountAddress", params.accountAddress);
973
- validateTakeDeadlineWindow(params.deadline);
1008
+ const now = params.now ?? Time.timestamp();
1009
+ validateTakeDeadlineWindow(params.deadline, now);
974
1010
  const market = params.marketData.params;
975
1011
  const rawParams = {
976
1012
  chainId: this.chainId,
@@ -985,7 +1021,7 @@ export class MorphoMidnight {
985
1021
  deadline: params.deadline,
986
1022
  referralFeePct: params.referralFeePct,
987
1023
  referralFeeRecipient: params.referralFeeRecipient,
988
- metadata: this.client.options.metadata,
1024
+ metadata,
989
1025
  };
990
1026
  let tx = midnightTakeRepayWithdrawCollateral(rawParams);
991
1027
  validatePositionBinding({
@@ -994,24 +1030,7 @@ export class MorphoMidnight {
994
1030
  marketData: params.marketData,
995
1031
  });
996
1032
  const collateralWithdrawals = params.collateralWithdrawals ?? [];
997
- const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
998
- let withdrawAmount = 0n;
999
- for (const withdrawal of collateralWithdrawals) {
1000
- // Reject unconfigured collateral indexes before updating postCollateral.
1001
- MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
1002
- const index = Number(withdrawal.collateralIndex);
1003
- const available = postCollateral[index] ?? 0n;
1004
- const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
1005
- if (amount > available) {
1006
- throw new WithdrawExceedsCollateralError({
1007
- withdrawAmount: amount,
1008
- available,
1009
- market: params.marketData.id,
1010
- });
1011
- }
1012
- postCollateral[index] = available - amount;
1013
- withdrawAmount += amount;
1014
- }
1033
+ const { postCollateral, withdrawAmount } = getPostWithdrawalCollateral(params);
1015
1034
  const debtReduction = params.target.type === "units"
1016
1035
  ? params.target.units
1017
1036
  : params.target.minUnits;
@@ -1037,7 +1056,7 @@ export class MorphoMidnight {
1037
1056
  takeableOffers: params.takeableOffers,
1038
1057
  accountAddress: params.accountAddress,
1039
1058
  marketData: params.marketData,
1040
- now: Time.timestamp(),
1059
+ now: params.now ?? Time.timestamp(),
1041
1060
  deadline: params.deadline,
1042
1061
  referralFeePct: tx.action.args.referralFeePct,
1043
1062
  // With repayEnabled the bundle repays the unfilled debt directly, at par.
@@ -1117,6 +1136,7 @@ export class MorphoMidnight {
1117
1136
  * ```
1118
1137
  */
1119
1138
  withdrawCollateral(params) {
1139
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1120
1140
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1121
1141
  // Reject invalid owners before preparing the direct call.
1122
1142
  validateMidnightAccount("accountAddress", params.accountAddress);
@@ -1135,7 +1155,7 @@ export class MorphoMidnight {
1135
1155
  assets,
1136
1156
  onBehalf: params.accountAddress,
1137
1157
  receiver: params.receiver ?? params.accountAddress,
1138
- metadata: this.client.options.metadata,
1158
+ metadata,
1139
1159
  });
1140
1160
  if (assets > available) {
1141
1161
  throw new WithdrawExceedsCollateralError({
@@ -1208,6 +1228,7 @@ export class MorphoMidnight {
1208
1228
  * ```
1209
1229
  */
1210
1230
  withdrawCollateralBatch(params) {
1231
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1211
1232
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1212
1233
  // Reject invalid owners before preparing the direct call.
1213
1234
  validateMidnightAccount("accountAddress", params.accountAddress);
@@ -1231,12 +1252,12 @@ export class MorphoMidnight {
1231
1252
  collateralWithdrawals,
1232
1253
  onBehalf: params.accountAddress,
1233
1254
  receiver: params.receiver ?? params.accountAddress,
1234
- metadata: this.client.options.metadata,
1255
+ metadata,
1235
1256
  });
1236
1257
  const collateral = Array.from({ length: params.marketData.params.collateralParams.length }, (_, i) => params.positionData.collateral[i] ?? 0n);
1237
1258
  for (const { collateralIndex, assets } of collateralWithdrawals) {
1238
1259
  const index = Number(collateralIndex);
1239
- const available = collateral[index];
1260
+ const available = collateral[index] ?? 0n;
1240
1261
  if (assets > available) {
1241
1262
  throw new WithdrawExceedsCollateralError({
1242
1263
  withdrawAmount: assets,
@@ -1300,6 +1321,7 @@ export class MorphoMidnight {
1300
1321
  * ```
1301
1322
  */
1302
1323
  supplyCollateral(params) {
1324
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1303
1325
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1304
1326
  // Reject a malformed account here; the builder rejects the zero account.
1305
1327
  validateMidnightAddress("accountAddress", params.accountAddress);
@@ -1332,7 +1354,7 @@ export class MorphoMidnight {
1332
1354
  collateralIndex,
1333
1355
  assets: params.collateralAssets,
1334
1356
  onBehalf: params.accountAddress,
1335
- metadata: this.client.options.metadata,
1357
+ metadata,
1336
1358
  }),
1337
1359
  };
1338
1360
  }
@@ -1364,6 +1386,7 @@ export class MorphoMidnight {
1364
1386
  * ```
1365
1387
  */
1366
1388
  supplyCollateralBatch(params) {
1389
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1367
1390
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
1368
1391
  // Reject malformed accounts before resolving token requirements.
1369
1392
  validateMidnightAddress("accountAddress", params.accountAddress);
@@ -1405,7 +1428,7 @@ export class MorphoMidnight {
1405
1428
  market: params.marketData.params,
1406
1429
  collateralSupplies: params.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
1407
1430
  onBehalf: params.accountAddress,
1408
- metadata: this.client.options.metadata,
1431
+ metadata,
1409
1432
  }),
1410
1433
  };
1411
1434
  }
@@ -1465,7 +1488,7 @@ export class MorphoMidnight {
1465
1488
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1466
1489
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1467
1490
  * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1468
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1491
+ * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the reference timestamp (`params.now`, or the deprecated device-clock fallback), including zero or negative values.
1469
1492
  * @example
1470
1493
  * ```ts
1471
1494
  * const output = await midnight.makeLend({
@@ -1483,7 +1506,8 @@ export class MorphoMidnight {
1483
1506
  // Reject the zero account before preparing anything for it.
1484
1507
  validateMidnightAccount("accountAddress", params.accountAddress);
1485
1508
  // Fails before any API read or build when the deadline has already passed.
1486
- validateMidnightDeadline(params.deadline);
1509
+ const now = params.now ?? Time.timestamp();
1510
+ validateMidnightDeadline(params.deadline, now);
1487
1511
  const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1488
1512
  rejectReduceOnlyOffers(tree.offers);
1489
1513
  return this.prepareLendOffers({ ...params, offers: tree });
@@ -1539,7 +1563,7 @@ export class MorphoMidnight {
1539
1563
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1540
1564
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1541
1565
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1542
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1566
+ * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the reference timestamp (`params.now`, or the deprecated device-clock fallback), including zero or negative values.
1543
1567
  * @example
1544
1568
  * ```ts
1545
1569
  * const output = await midnight.makeBorrow({
@@ -1554,7 +1578,8 @@ export class MorphoMidnight {
1554
1578
  // Reject the zero account before preparing anything for it.
1555
1579
  validateMidnightAccount("accountAddress", params.accountAddress);
1556
1580
  // Fails before any API read or build when the deadline has already passed.
1557
- validateMidnightDeadline(params.deadline);
1581
+ const now = params.now ?? Time.timestamp();
1582
+ validateMidnightDeadline(params.deadline, now);
1558
1583
  const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1559
1584
  rejectReduceOnlyOffers(tree.offers);
1560
1585
  return this.prepareBorrowOffers({ ...params, offers: tree });
@@ -1563,6 +1588,7 @@ export class MorphoMidnight {
1563
1588
  * Prepares lend-side offers for publication.
1564
1589
  */
1565
1590
  async prepareLendOffers(params) {
1591
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1566
1592
  // Reject a malformed address before viem compares offer markets with it.
1567
1593
  validateMidnightAddress("loanToken", params.loanToken);
1568
1594
  assertPositiveAmount("loanAssets", params.loanAssets);
@@ -1589,7 +1615,7 @@ export class MorphoMidnight {
1589
1615
  chainId: this.chainId,
1590
1616
  cancellations: params.cancellations ?? [],
1591
1617
  deadline: params.deadline,
1592
- metadata: this.client.options.metadata,
1618
+ metadata,
1593
1619
  publication: {
1594
1620
  ratifier: data.ratifier,
1595
1621
  root: data.tree.root,
@@ -1705,7 +1731,7 @@ export class MorphoMidnight {
1705
1731
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1706
1732
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1707
1733
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1708
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1734
+ * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the reference timestamp (`params.now`, or the deprecated device-clock fallback), including zero or negative values.
1709
1735
  * @example
1710
1736
  * ```ts
1711
1737
  * const callback = getMidnightBlueBuyCallbackAddress({ chainId, owner: maker, salt: callbackSalt });
@@ -1724,6 +1750,8 @@ export class MorphoMidnight {
1724
1750
  * ```
1725
1751
  */
1726
1752
  async supplyBlueMakeLend(params) {
1753
+ const suppliedNow = params.now;
1754
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
1727
1755
  // Reject the zero account before preparing anything for it.
1728
1756
  validateMidnightAccount("accountAddress", params.accountAddress);
1729
1757
  // Reject wrong-sized salts before callback derivation pads them or any read occurs.
@@ -1735,7 +1763,8 @@ export class MorphoMidnight {
1735
1763
  rejectReduceOnlyOffers(tree.offers);
1736
1764
  await validateClientChainId(this.client.viemClient, this.chainId);
1737
1765
  // Fails before any API read or build when the deadline has already passed.
1738
- validateMidnightDeadline(params.deadline);
1766
+ const now = suppliedNow ?? Time.timestamp();
1767
+ validateMidnightDeadline(params.deadline, now);
1739
1768
  const { callbackSalt } = params;
1740
1769
  // Encode the whole Blue market first so a malformed field fails typed, before the RPC read.
1741
1770
  const callbackData = wrapMidnightEncoding("blueMarket", () => getMidnightBlueBuyCallbackData(params.blueMarket));
@@ -1755,7 +1784,7 @@ export class MorphoMidnight {
1755
1784
  deployless: this.client.options.supportDeployless,
1756
1785
  }),
1757
1786
  ]);
1758
- const market = _try(() => fetched.accrueInterest(MathLib.max(Time.timestamp(), fetched.lastUpdate)), UnsupportedMarketIrmError) ?? fetched;
1787
+ const market = _try(() => fetched.accrueInterest(MathLib.max(suppliedNow ?? Time.timestamp(), fetched.lastUpdate)), UnsupportedMarketIrmError) ?? fetched;
1759
1788
  if (market.totalSupplyShares === 0n) {
1760
1789
  throw new EmptyBlueParkingMarketError({ marketId: blueMarketId });
1761
1790
  }
@@ -1805,7 +1834,7 @@ export class MorphoMidnight {
1805
1834
  nativeAmount: params.nativeAmount,
1806
1835
  cancellations: params.cancellations ?? [],
1807
1836
  deadline: params.deadline,
1808
- metadata: this.client.options.metadata,
1837
+ metadata,
1809
1838
  });
1810
1839
  return {
1811
1840
  groups: data.groups,
@@ -1830,6 +1859,7 @@ export class MorphoMidnight {
1830
1859
  * Prepares borrow-side offers for publication.
1831
1860
  */
1832
1861
  async prepareBorrowOffers(params) {
1862
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
1833
1863
  const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1834
1864
  validateOfferSides(tree.offers, false);
1835
1865
  validateMidnightMakerOfferCallbacks(tree.offers);
@@ -1842,7 +1872,7 @@ export class MorphoMidnight {
1842
1872
  chainId: this.chainId,
1843
1873
  cancellations: params.cancellations ?? [],
1844
1874
  deadline: params.deadline,
1845
- metadata: this.client.options.metadata,
1875
+ metadata,
1846
1876
  publication: {
1847
1877
  ratifier: data.ratifier,
1848
1878
  root: data.tree.root,
@@ -1912,7 +1942,7 @@ export class MorphoMidnight {
1912
1942
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1913
1943
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1914
1944
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1915
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1945
+ * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the reference timestamp (`params.now`, or the deprecated device-clock fallback), including zero or negative values.
1916
1946
  * @example
1917
1947
  * ```ts
1918
1948
  * const output = await midnight.makeWithdraw({
@@ -1929,7 +1959,8 @@ export class MorphoMidnight {
1929
1959
  // Reject the zero account before preparing anything for it.
1930
1960
  validateMidnightAccount("accountAddress", params.accountAddress);
1931
1961
  // Fails before any API read or build when the deadline has already passed.
1932
- validateMidnightDeadline(params.deadline);
1962
+ const now = params.now ?? Time.timestamp();
1963
+ validateMidnightDeadline(params.deadline, now);
1933
1964
  const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
1934
1965
  // Reject the wrong exit intent before calling the mempool validation API.
1935
1966
  validateOfferSides(tree.offers, false);
@@ -2000,7 +2031,7 @@ export class MorphoMidnight {
2000
2031
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
2001
2032
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
2002
2033
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
2003
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2034
+ * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the reference timestamp (`params.now`, or the deprecated device-clock fallback), including zero or negative values.
2004
2035
  * @example
2005
2036
  * ```ts
2006
2037
  * const output = await midnight.makeRepay({
@@ -2019,7 +2050,8 @@ export class MorphoMidnight {
2019
2050
  // Reject the zero account before preparing anything for it.
2020
2051
  validateMidnightAccount("accountAddress", params.accountAddress);
2021
2052
  // Fails before any API read or build when the deadline has already passed.
2022
- validateMidnightDeadline(params.deadline);
2053
+ const now = params.now ?? Time.timestamp();
2054
+ validateMidnightDeadline(params.deadline, now);
2023
2055
  const tree = wrapMidnightEncoding("offers", () => Tree.from(params.offers));
2024
2056
  // Reject the wrong exit intent before calling the mempool validation API.
2025
2057
  validateOfferSides(tree.offers, true);
@@ -2097,7 +2129,7 @@ export class MorphoMidnight {
2097
2129
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
2098
2130
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
2099
2131
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
2100
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2132
+ * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the reference timestamp (`params.now`, or the deprecated device-clock fallback), including zero or negative values.
2101
2133
  * @example
2102
2134
  * ```ts
2103
2135
  * const output = await midnight.supplyCollateralMakeBorrow({
@@ -2112,11 +2144,13 @@ export class MorphoMidnight {
2112
2144
  * ```
2113
2145
  */
2114
2146
  async supplyCollateralMakeBorrow(params) {
2147
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2115
2148
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
2116
2149
  // Reject the zero account before preparing anything for it.
2117
2150
  validateMidnightAccount("accountAddress", params.accountAddress);
2118
2151
  // Fails before any API read or build when the deadline has already passed.
2119
- validateMidnightDeadline(params.deadline);
2152
+ const now = params.now ?? Time.timestamp();
2153
+ validateMidnightDeadline(params.deadline, now);
2120
2154
  const market = params.collateral.market instanceof MarketParams
2121
2155
  ? params.collateral.market
2122
2156
  : MarketParams.from(params.collateral.market);
@@ -2142,7 +2176,7 @@ export class MorphoMidnight {
2142
2176
  nativeAmount: params.nativeAmount,
2143
2177
  cancellations: params.cancellations ?? [],
2144
2178
  deadline: params.deadline,
2145
- metadata: this.client.options.metadata,
2179
+ metadata,
2146
2180
  publication: {
2147
2181
  ratifier: data.ratifier,
2148
2182
  root: data.tree.root,
@@ -2228,6 +2262,7 @@ export class MorphoMidnight {
2228
2262
  * ```
2229
2263
  */
2230
2264
  redeem(params) {
2265
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2231
2266
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
2232
2267
  // Reject a malformed account here; the builder rejects the zero account.
2233
2268
  validateMidnightAddress("accountAddress", params.accountAddress);
@@ -2244,7 +2279,8 @@ export class MorphoMidnight {
2244
2279
  validateMarketData(market, this.chainId);
2245
2280
  // Apply realized losses and continuous fees the way `Midnight._updatePosition` does before a
2246
2281
  // withdrawal; never accrue to before the snapshot's `lastAccrual`.
2247
- const accrued = params.positionData.accrueInterest(MathLib.max(Time.timestamp(), params.positionData.lastAccrual));
2282
+ const now = params.now ?? Time.timestamp();
2283
+ const accrued = params.positionData.accrueInterest(MathLib.max(now, params.positionData.lastAccrual));
2248
2284
  const units = params.units ?? accrued.faceValue;
2249
2285
  if (params.units !== undefined && units <= 0n) {
2250
2286
  throw new NonPositiveInputError("units", units);
@@ -2273,7 +2309,7 @@ export class MorphoMidnight {
2273
2309
  units,
2274
2310
  onBehalf: params.accountAddress,
2275
2311
  receiver: params.receiver,
2276
- metadata: this.client.options.metadata,
2312
+ metadata,
2277
2313
  });
2278
2314
  return {
2279
2315
  getRequirements: async () => [],
@@ -2338,7 +2374,7 @@ export class MorphoMidnight {
2338
2374
  * during this method call, before the lazy output is returned.
2339
2375
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
2340
2376
  * contract or a market token contract.
2341
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2377
+ * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the reference timestamp (`params.now`, or the deprecated device-clock fallback), including zero or negative values.
2342
2378
  * @example
2343
2379
  * ```ts
2344
2380
  * // Close the position: repay all debt, withdraw all collateral.
@@ -2354,11 +2390,13 @@ export class MorphoMidnight {
2354
2390
  * ```
2355
2391
  */
2356
2392
  repayWithdrawCollateral(params) {
2393
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2357
2394
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
2358
2395
  // Reject the zero account before preparing anything for it.
2359
2396
  validateMidnightAccount("accountAddress", params.accountAddress);
2360
2397
  // Fails before any API read or build when the deadline has already passed.
2361
- validateMidnightDeadline(params.deadline);
2398
+ const now = params.now ?? Time.timestamp();
2399
+ validateMidnightDeadline(params.deadline, now);
2362
2400
  const market = params.marketData.params;
2363
2401
  const tx = midnightRepayWithdrawCollateral({
2364
2402
  chainId: this.chainId,
@@ -2368,7 +2406,7 @@ export class MorphoMidnight {
2368
2406
  collateralWithdrawals: params.collateralWithdrawals ?? [],
2369
2407
  collateralReceiver: params.collateralReceiver ?? params.accountAddress,
2370
2408
  deadline: params.deadline,
2371
- metadata: this.client.options.metadata,
2409
+ metadata,
2372
2410
  });
2373
2411
  validatePositionBinding({
2374
2412
  positionData: params.positionData,
@@ -2376,24 +2414,7 @@ export class MorphoMidnight {
2376
2414
  marketData: params.marketData,
2377
2415
  });
2378
2416
  const collateralWithdrawals = params.collateralWithdrawals ?? [];
2379
- const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
2380
- let withdrawAmount = 0n;
2381
- for (const withdrawal of collateralWithdrawals) {
2382
- // Reject unconfigured collateral indexes before updating postCollateral.
2383
- MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
2384
- const index = Number(withdrawal.collateralIndex);
2385
- const available = postCollateral[index] ?? 0n;
2386
- const amount = withdrawal.assets === maxUint256 ? available : withdrawal.assets;
2387
- if (amount > available) {
2388
- throw new WithdrawExceedsCollateralError({
2389
- withdrawAmount: amount,
2390
- available,
2391
- market: params.marketData.id,
2392
- });
2393
- }
2394
- postCollateral[index] = available - amount;
2395
- withdrawAmount += amount;
2396
- }
2417
+ const { postCollateral, withdrawAmount } = getPostWithdrawalCollateral(params);
2397
2418
  // The bundle must fill the whole assets target and the direct repay is capped at the debt, so a repay above it reverts `OutOfOffers()`.
2398
2419
  if (params.repay.type === "assets" &&
2399
2420
  params.repay.assets > params.positionData.debt) {
@@ -2411,11 +2432,11 @@ export class MorphoMidnight {
2411
2432
  limit: params.positionData.debt,
2412
2433
  });
2413
2434
  }
2414
- const postDebt = params.repay.type === "full"
2415
- ? 0n
2416
- : params.positionData.debt > params.repay.assets
2417
- ? params.positionData.debt - params.repay.assets
2418
- : 0n;
2435
+ let postDebt = 0n;
2436
+ if (params.repay.type !== "full" &&
2437
+ params.positionData.debt > params.repay.assets) {
2438
+ postDebt = params.positionData.debt - params.repay.assets;
2439
+ }
2419
2440
  if (collateralWithdrawals.length > 0 && postDebt > 0n) {
2420
2441
  const maxSafeDebt = getMidnightMaxSafeDebt({
2421
2442
  market: params.marketData,
@@ -2452,42 +2473,37 @@ export class MorphoMidnight {
2452
2473
  };
2453
2474
  }
2454
2475
  /**
2455
- * Prepares guarded cancellation of several maker offer groups through `MidnightBundlesV2`.
2476
+ * Prepares a full cancellation of one or more maker offer groups as a direct call to Midnight.
2456
2477
  *
2457
- * The transaction reverts as a whole when any group's consumption exceeds its
2458
- * `maxConsumed` ceiling, so fills landing before execution never leave a partial cancel.
2478
+ * One group builds a bare `setConsumed(group, maxUint128, accountAddress)`. Two or more groups
2479
+ * build one Midnight `multicall` of such calls, in list order, which cancels every group or
2480
+ * none. Only the single-group transaction is matchable by a wallet policy that allows
2481
+ * `setConsumed` by method name; cancel one group per transaction when the signer's policy names
2482
+ * `setConsumed`.
2459
2483
  *
2460
- * @param params - Maker account, groups with consumption ceilings, and deadline.
2461
- * @param params.accountAddress - Maker that must send the transaction. It is used only to check
2462
- * the maker's Midnight authorization of `MidnightBundlesV2`; the bundle cancels the groups of
2463
- * `msg.sender`. A transaction sent from another account that has also authorized
2464
- * `MidnightBundlesV2` does not revert: it cancels that account's groups and leaves the maker's
2465
- * offers fillable.
2466
- * @param params.cancellations - Offer groups and the largest consumption accepted for each.
2467
- * To cancel unconditionally, set `maxConsumed` to `maxUint128`; the contract treats
2468
- * `type(uint128).max` as no limit.
2469
- * Cancellation is per group: it does not unratify roots or revoke
2470
- * `MidnightBundlesV2` or ratifier authorization.
2471
- * @param params.deadline - Bundle execution deadline timestamp.
2472
- * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
2473
- * @throws {ChainIdMismatchError} when the client targets another chain, or from
2474
- * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2475
- * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as an out-of-range integer.
2476
- * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
2477
- * RPC read fails.
2478
- * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
2479
- * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
2480
- * @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
2484
+ * Nothing is required before sending: no Midnight authorization, approval, signature or
2485
+ * deadline. Cancellation is per group and always full; it does not unratify roots or revoke
2486
+ * authorizations, and cancelling a group again succeeds.
2487
+ *
2488
+ * @param params - Maker account and the offer groups to cancel.
2489
+ * @param params.accountAddress - Maker whose groups are cancelled. The maker, or an operator it
2490
+ * authorized on Midnight, must send the transaction; a transaction from any other account
2491
+ * reverts `Unauthorized()` and changes no group.
2492
+ * @param params.groups - Nonempty list of distinct 32-byte offer groups to cancel.
2493
+ * @param params.now - Optional reference timestamp used to resolve `metadata.timestamp: true`.
2494
+ * @returns A handle whose `getRequirements()` resolves to an empty list without reading the
2495
+ * chain, and whose synchronous `buildTx()` returns the transaction targeting `Midnight`.
2496
+ * @throws {ChainIdMismatchError} when the client targets another chain.
2481
2497
  * @throws {MidnightInvalidAccountAddressError} when `accountAddress` is malformed or zero.
2482
- * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
2498
+ * @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
2499
+ * @throws {InvalidMidnightHexInputError} when a group is not 32-byte hex.
2483
2500
  * @throws {DuplicateMidnightGroupCancellationError} when a group appears more than once.
2484
- * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
2485
- * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
2486
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2501
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
2502
+ * @throws {UnknownAddressError} when the chain has no `midnight` deployment.
2487
2503
  * @example
2488
2504
  * ```ts
2489
2505
  * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
2490
- * import { createPublicClient, http, maxUint256, type Address, type Hex } from "viem";
2506
+ * import { createPublicClient, http, type Address, type Hex } from "viem";
2491
2507
  * import { base } from "viem/chains";
2492
2508
  *
2493
2509
  * declare const maker: Address;
@@ -2496,30 +2512,27 @@ export class MorphoMidnight {
2496
2512
  * morphoViemExtension(),
2497
2513
  * );
2498
2514
  * const midnight = client.morpho.midnight(base.id);
2499
- * const output = midnight.cancelOffers({
2500
- * accountAddress: maker,
2501
- * cancellations: [{ group, maxConsumed: 0n }],
2502
- * deadline: maxUint256,
2503
- * });
2515
+ * const output = midnight.cancelOffers({ accountAddress: maker, groups: [group] });
2516
+ * await output.getRequirements(); // => []
2517
+ * const tx = output.buildTx(); // calldata: setConsumed(group, maxUint128, maker)
2504
2518
  * ```
2505
2519
  */
2506
2520
  cancelOffers(params) {
2521
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, params.now);
2507
2522
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
2508
2523
  const { accountAddress } = params;
2509
2524
  if (!isAddress(accountAddress) ||
2510
2525
  isAddressEqual(accountAddress, zeroAddress)) {
2511
2526
  throw new MidnightInvalidAccountAddressError(accountAddress);
2512
2527
  }
2513
- // Fails before any API read or build when the deadline has already passed.
2514
- validateMidnightDeadline(params.deadline);
2515
- const tx = midnightCancelAndMake({
2528
+ const tx = midnightCancelOffers({
2516
2529
  chainId: this.chainId,
2517
- cancellations: params.cancellations,
2518
- deadline: params.deadline,
2519
- metadata: this.client.options.metadata,
2530
+ groups: params.groups,
2531
+ onBehalf: accountAddress,
2532
+ metadata,
2520
2533
  });
2521
2534
  return {
2522
- getRequirements: () => this.getBundlesV2AuthorizationRequirements(accountAddress),
2535
+ getRequirements: async () => [],
2523
2536
  buildTx: () => tx,
2524
2537
  };
2525
2538
  }