@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
@@ -13,6 +13,7 @@ const callback_js_1 = require("../../helpers/callback.js");
13
13
  const constant_js_1 = require("../../helpers/constant.js");
14
14
  const encodeMidnightCalldata_js_1 = require("../../helpers/encodeMidnightCalldata.js");
15
15
  const index_js_3 = require("../../helpers/index.js");
16
+ const metadata_js_1 = require("../../helpers/metadata.js");
16
17
  const validateMidnightAccount_js_1 = require("../../helpers/validateMidnightAccount.js");
17
18
  const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
18
19
  const validateMidnightCollateralBatch_js_1 = require("../../helpers/validateMidnightCollateralBatch.js");
@@ -33,8 +34,7 @@ const validatePositionBinding = (params) => {
33
34
  throw new index_js_4.AccrualPositionUserMismatchError(params.positionData.user, params.accountAddress);
34
35
  }
35
36
  };
36
- const validateTakeDeadlineWindow = (deadline) => {
37
- const now = morpho_ts_1.Time.timestamp();
37
+ const validateTakeDeadlineWindow = (deadline, now = morpho_ts_1.Time.timestamp()) => {
38
38
  // Throws when the deadline is at or before now.
39
39
  (0, deadline_js_1.validateMidnightDeadline)(deadline, now);
40
40
  const maxDeadline = now + constant_js_1.MIDNIGHT_TAKE_MAX_DEADLINE_SECONDS;
@@ -150,6 +150,29 @@ const getOffersDataInternal = async ({ client, chainId, params, marketCreationTi
150
150
  payload: await midnight_sdk_1.Payload.encode(items),
151
151
  };
152
152
  };
153
+ const getPostWithdrawalCollateral = (params) => {
154
+ const market = params.marketData.params;
155
+ const collateralWithdrawals = params.collateralWithdrawals ?? [];
156
+ const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
157
+ let withdrawAmount = 0n;
158
+ for (const withdrawal of collateralWithdrawals) {
159
+ // Reject unconfigured collateral indexes before updating postCollateral.
160
+ midnight_sdk_1.MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
161
+ const index = Number(withdrawal.collateralIndex);
162
+ const available = postCollateral[index] ?? 0n;
163
+ const amount = withdrawal.assets === viem_1.maxUint256 ? available : withdrawal.assets;
164
+ if (amount > available) {
165
+ throw new index_js_4.WithdrawExceedsCollateralError({
166
+ withdrawAmount: amount,
167
+ available,
168
+ market: params.marketData.id,
169
+ });
170
+ }
171
+ postCollateral[index] = available - amount;
172
+ withdrawAmount += amount;
173
+ }
174
+ return { postCollateral, withdrawAmount };
175
+ };
153
176
  const validateMarketData = (market, chainId) => {
154
177
  // Reject snapshots from another chain deployment before exposing requirements.
155
178
  (0, validateMidnightMarket_js_1.validateMidnightMarket)({ market, chainId });
@@ -364,15 +387,18 @@ class MorphoMidnight {
364
387
  * target: { type: "assets", assets: 1_000_000n, minUnits: 900_000n },
365
388
  * takeableOffers: quote.data.takeableOffers,
366
389
  * maxContinuousFee: maxUint256,
367
- * deadline: Time.timestamp() + 600n,
390
+ * now: (await client.getBlock()).timestamp,
391
+ * deadline: (await client.getBlock()).timestamp + 600n,
368
392
  * });
369
393
  * ```
370
394
  */
371
395
  takeLend(params) {
396
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
372
397
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
373
398
  // Reject the zero account before preparing anything for it.
374
399
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
375
- validateTakeDeadlineWindow(params.deadline);
400
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
401
+ validateTakeDeadlineWindow(params.deadline, now);
376
402
  const market = params.marketData.params;
377
403
  const rawParams = {
378
404
  chainId: this.chainId,
@@ -384,7 +410,7 @@ class MorphoMidnight {
384
410
  deadline: params.deadline,
385
411
  referralFeePct: params.referralFeePct,
386
412
  referralFeeRecipient: params.referralFeeRecipient,
387
- metadata: this.client.options.metadata,
413
+ metadata,
388
414
  };
389
415
  let tx = (0, index_js_1.midnightTakeLend)(rawParams);
390
416
  const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)({
@@ -392,7 +418,7 @@ class MorphoMidnight {
392
418
  takeableOffers: params.takeableOffers,
393
419
  accountAddress: params.accountAddress,
394
420
  marketData: params.marketData,
395
- now: morpho_ts_1.Time.timestamp(),
421
+ now: params.now ?? morpho_ts_1.Time.timestamp(),
396
422
  deadline: params.deadline,
397
423
  referralFeePct: tx.action.args.referralFeePct,
398
424
  fallbackUnits: 0n,
@@ -511,15 +537,18 @@ class MorphoMidnight {
511
537
  * collateralPrices,
512
538
  * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
513
539
  * takeableOffers: quote.data.takeableOffers,
514
- * deadline: Time.timestamp() + 600n,
540
+ * now: (await client.getBlock()).timestamp,
541
+ * deadline: (await client.getBlock()).timestamp + 600n,
515
542
  * });
516
543
  * ```
517
544
  */
518
545
  takeBorrow(params) {
546
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
519
547
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
520
548
  // Reject the zero account before preparing anything for it.
521
549
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
522
- validateTakeDeadlineWindow(params.deadline);
550
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
551
+ validateTakeDeadlineWindow(params.deadline, now);
523
552
  const rawParams = {
524
553
  chainId: this.chainId,
525
554
  market: params.marketData.params,
@@ -529,7 +558,7 @@ class MorphoMidnight {
529
558
  deadline: params.deadline,
530
559
  referralFeePct: params.referralFeePct,
531
560
  referralFeeRecipient: params.referralFeeRecipient,
532
- metadata: this.client.options.metadata,
561
+ metadata,
533
562
  };
534
563
  let tx = (0, index_js_1.midnightTakeBorrow)(rawParams);
535
564
  validatePositionBinding({
@@ -551,7 +580,6 @@ class MorphoMidnight {
551
580
  throw new index_js_4.BorrowExceedsSafeLtvError(requestedUnits, blue_sdk_1.MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
552
581
  }
553
582
  }
554
- const now = morpho_ts_1.Time.timestamp();
555
583
  const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)({
556
584
  side: "sell",
557
585
  takeableOffers: params.takeableOffers,
@@ -638,15 +666,18 @@ class MorphoMidnight {
638
666
  * marketData,
639
667
  * target: { type: "units", units: credit, minSellerAssets: 990_000n },
640
668
  * takeableOffers: quote.data.takeableOffers,
641
- * deadline: Time.timestamp() + 600n,
669
+ * now: (await client.getBlock()).timestamp,
670
+ * deadline: (await client.getBlock()).timestamp + 600n,
642
671
  * });
643
672
  * ```
644
673
  */
645
674
  takeWithdraw(params) {
675
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
646
676
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
647
677
  // Reject the zero account before preparing anything for it.
648
678
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
649
- validateTakeDeadlineWindow(params.deadline);
679
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
680
+ validateTakeDeadlineWindow(params.deadline, now);
650
681
  const rawParams = {
651
682
  chainId: this.chainId,
652
683
  market: params.marketData.params,
@@ -656,7 +687,7 @@ class MorphoMidnight {
656
687
  deadline: params.deadline,
657
688
  referralFeePct: params.referralFeePct,
658
689
  referralFeeRecipient: params.referralFeeRecipient,
659
- metadata: this.client.options.metadata,
690
+ metadata,
660
691
  };
661
692
  let tx = (0, index_js_1.midnightTakeWithdraw)(rawParams);
662
693
  const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)({
@@ -664,7 +695,7 @@ class MorphoMidnight {
664
695
  takeableOffers: params.takeableOffers,
665
696
  accountAddress: params.accountAddress,
666
697
  marketData: params.marketData,
667
- now: morpho_ts_1.Time.timestamp(),
698
+ now: params.now ?? morpho_ts_1.Time.timestamp(),
668
699
  deadline: params.deadline,
669
700
  referralFeePct: tx.action.args.referralFeePct,
670
701
  // The bundle redeems credit first, up to the market's withdrawable liquidity.
@@ -771,15 +802,18 @@ class MorphoMidnight {
771
802
  * collateralSupplies: [{ collateralIndex: 0n, assets: 2_000_000n }],
772
803
  * target: { type: "assets", assets: 1_000_000n, maxUnits: 1_100_000n },
773
804
  * takeableOffers: quote.data.takeableOffers,
774
- * deadline: Time.timestamp() + 600n,
805
+ * now: (await client.getBlock()).timestamp,
806
+ * deadline: (await client.getBlock()).timestamp + 600n,
775
807
  * });
776
808
  * ```
777
809
  */
778
810
  supplyCollateralTakeBorrow(params) {
811
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
779
812
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
780
813
  // Reject the zero account before preparing anything for it.
781
814
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
782
- validateTakeDeadlineWindow(params.deadline);
815
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
816
+ validateTakeDeadlineWindow(params.deadline, now);
783
817
  const market = params.marketData.params;
784
818
  const rawParams = {
785
819
  chainId: this.chainId,
@@ -792,7 +826,7 @@ class MorphoMidnight {
792
826
  deadline: params.deadline,
793
827
  referralFeePct: params.referralFeePct,
794
828
  referralFeeRecipient: params.referralFeeRecipient,
795
- metadata: this.client.options.metadata,
829
+ metadata,
796
830
  };
797
831
  let tx = (0, index_js_1.midnightSupplyCollateralTakeBorrow)(rawParams);
798
832
  validatePositionBinding({
@@ -821,7 +855,6 @@ class MorphoMidnight {
821
855
  throw new index_js_4.BorrowExceedsSafeLtvError(requestedUnits, blue_sdk_1.MathLib.zeroFloorSub(maxSafeDebt, params.positionData.debt));
822
856
  }
823
857
  }
824
- const now = morpho_ts_1.Time.timestamp();
825
858
  const takeableOffers = (0, validateMidnightTakeFeasibility_js_1.validateMidnightTakeFeasibility)({
826
859
  side: "sell",
827
860
  takeableOffers: params.takeableOffers,
@@ -965,15 +998,18 @@ class MorphoMidnight {
965
998
  * repayEnabled: true,
966
999
  * collateralWithdrawals: [{ collateralIndex: 0n, assets: maxUint256 }],
967
1000
  * maxContinuousFee: maxUint256,
968
- * deadline: Time.timestamp() + 600n,
1001
+ * now: (await client.getBlock()).timestamp,
1002
+ * deadline: (await client.getBlock()).timestamp + 600n,
969
1003
  * });
970
1004
  * ```
971
1005
  */
972
1006
  takeRepayWithdrawCollateral(params) {
1007
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
973
1008
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
974
1009
  // Reject the zero account before preparing anything for it.
975
1010
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
976
- validateTakeDeadlineWindow(params.deadline);
1011
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
1012
+ validateTakeDeadlineWindow(params.deadline, now);
977
1013
  const market = params.marketData.params;
978
1014
  const rawParams = {
979
1015
  chainId: this.chainId,
@@ -988,7 +1024,7 @@ class MorphoMidnight {
988
1024
  deadline: params.deadline,
989
1025
  referralFeePct: params.referralFeePct,
990
1026
  referralFeeRecipient: params.referralFeeRecipient,
991
- metadata: this.client.options.metadata,
1027
+ metadata,
992
1028
  };
993
1029
  let tx = (0, index_js_1.midnightTakeRepayWithdrawCollateral)(rawParams);
994
1030
  validatePositionBinding({
@@ -997,24 +1033,7 @@ class MorphoMidnight {
997
1033
  marketData: params.marketData,
998
1034
  });
999
1035
  const collateralWithdrawals = params.collateralWithdrawals ?? [];
1000
- const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
1001
- let withdrawAmount = 0n;
1002
- for (const withdrawal of collateralWithdrawals) {
1003
- // Reject unconfigured collateral indexes before updating postCollateral.
1004
- midnight_sdk_1.MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
1005
- const index = Number(withdrawal.collateralIndex);
1006
- const available = postCollateral[index] ?? 0n;
1007
- const amount = withdrawal.assets === viem_1.maxUint256 ? available : withdrawal.assets;
1008
- if (amount > available) {
1009
- throw new index_js_4.WithdrawExceedsCollateralError({
1010
- withdrawAmount: amount,
1011
- available,
1012
- market: params.marketData.id,
1013
- });
1014
- }
1015
- postCollateral[index] = available - amount;
1016
- withdrawAmount += amount;
1017
- }
1036
+ const { postCollateral, withdrawAmount } = getPostWithdrawalCollateral(params);
1018
1037
  const debtReduction = params.target.type === "units"
1019
1038
  ? params.target.units
1020
1039
  : params.target.minUnits;
@@ -1040,7 +1059,7 @@ class MorphoMidnight {
1040
1059
  takeableOffers: params.takeableOffers,
1041
1060
  accountAddress: params.accountAddress,
1042
1061
  marketData: params.marketData,
1043
- now: morpho_ts_1.Time.timestamp(),
1062
+ now: params.now ?? morpho_ts_1.Time.timestamp(),
1044
1063
  deadline: params.deadline,
1045
1064
  referralFeePct: tx.action.args.referralFeePct,
1046
1065
  // With repayEnabled the bundle repays the unfilled debt directly, at par.
@@ -1120,6 +1139,7 @@ class MorphoMidnight {
1120
1139
  * ```
1121
1140
  */
1122
1141
  withdrawCollateral(params) {
1142
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
1123
1143
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1124
1144
  // Reject invalid owners before preparing the direct call.
1125
1145
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
@@ -1138,7 +1158,7 @@ class MorphoMidnight {
1138
1158
  assets,
1139
1159
  onBehalf: params.accountAddress,
1140
1160
  receiver: params.receiver ?? params.accountAddress,
1141
- metadata: this.client.options.metadata,
1161
+ metadata,
1142
1162
  });
1143
1163
  if (assets > available) {
1144
1164
  throw new index_js_4.WithdrawExceedsCollateralError({
@@ -1211,6 +1231,7 @@ class MorphoMidnight {
1211
1231
  * ```
1212
1232
  */
1213
1233
  withdrawCollateralBatch(params) {
1234
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
1214
1235
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1215
1236
  // Reject invalid owners before preparing the direct call.
1216
1237
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
@@ -1234,12 +1255,12 @@ class MorphoMidnight {
1234
1255
  collateralWithdrawals,
1235
1256
  onBehalf: params.accountAddress,
1236
1257
  receiver: params.receiver ?? params.accountAddress,
1237
- metadata: this.client.options.metadata,
1258
+ metadata,
1238
1259
  });
1239
1260
  const collateral = Array.from({ length: params.marketData.params.collateralParams.length }, (_, i) => params.positionData.collateral[i] ?? 0n);
1240
1261
  for (const { collateralIndex, assets } of collateralWithdrawals) {
1241
1262
  const index = Number(collateralIndex);
1242
- const available = collateral[index];
1263
+ const available = collateral[index] ?? 0n;
1243
1264
  if (assets > available) {
1244
1265
  throw new index_js_4.WithdrawExceedsCollateralError({
1245
1266
  withdrawAmount: assets,
@@ -1303,6 +1324,7 @@ class MorphoMidnight {
1303
1324
  * ```
1304
1325
  */
1305
1326
  supplyCollateral(params) {
1327
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
1306
1328
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1307
1329
  // Reject a malformed account here; the builder rejects the zero account.
1308
1330
  (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
@@ -1335,7 +1357,7 @@ class MorphoMidnight {
1335
1357
  collateralIndex,
1336
1358
  assets: params.collateralAssets,
1337
1359
  onBehalf: params.accountAddress,
1338
- metadata: this.client.options.metadata,
1360
+ metadata,
1339
1361
  }),
1340
1362
  };
1341
1363
  }
@@ -1367,6 +1389,7 @@ class MorphoMidnight {
1367
1389
  * ```
1368
1390
  */
1369
1391
  supplyCollateralBatch(params) {
1392
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
1370
1393
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
1371
1394
  // Reject malformed accounts before resolving token requirements.
1372
1395
  (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
@@ -1408,7 +1431,7 @@ class MorphoMidnight {
1408
1431
  market: params.marketData.params,
1409
1432
  collateralSupplies: params.collateralSupplies.map(({ collateralIndex, assets }) => ({ collateralIndex, assets })),
1410
1433
  onBehalf: params.accountAddress,
1411
- metadata: this.client.options.metadata,
1434
+ metadata,
1412
1435
  }),
1413
1436
  };
1414
1437
  }
@@ -1468,7 +1491,7 @@ class MorphoMidnight {
1468
1491
  * @throws {MidnightMarketLiquidationCursorNotEnabledError} when an uncreated market uses a disabled liquidation cursor.
1469
1492
  * @throws {MidnightMarketOracleWithoutCodeError} when an uncreated market's oracle has no code.
1470
1493
  * @throws {viem.BaseError} when a pinned block, contract, or oracle-code read fails.
1471
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1494
+ * @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.
1472
1495
  * @example
1473
1496
  * ```ts
1474
1497
  * const output = await midnight.makeLend({
@@ -1486,7 +1509,8 @@ class MorphoMidnight {
1486
1509
  // Reject the zero account before preparing anything for it.
1487
1510
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1488
1511
  // Fails before any API read or build when the deadline has already passed.
1489
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1512
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
1513
+ (0, deadline_js_1.validateMidnightDeadline)(params.deadline, now);
1490
1514
  const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1491
1515
  rejectReduceOnlyOffers(tree.offers);
1492
1516
  return this.prepareLendOffers({ ...params, offers: tree });
@@ -1542,7 +1566,7 @@ class MorphoMidnight {
1542
1566
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1543
1567
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1544
1568
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1545
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1569
+ * @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.
1546
1570
  * @example
1547
1571
  * ```ts
1548
1572
  * const output = await midnight.makeBorrow({
@@ -1557,7 +1581,8 @@ class MorphoMidnight {
1557
1581
  // Reject the zero account before preparing anything for it.
1558
1582
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1559
1583
  // Fails before any API read or build when the deadline has already passed.
1560
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1584
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
1585
+ (0, deadline_js_1.validateMidnightDeadline)(params.deadline, now);
1561
1586
  const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1562
1587
  rejectReduceOnlyOffers(tree.offers);
1563
1588
  return this.prepareBorrowOffers({ ...params, offers: tree });
@@ -1566,6 +1591,7 @@ class MorphoMidnight {
1566
1591
  * Prepares lend-side offers for publication.
1567
1592
  */
1568
1593
  async prepareLendOffers(params) {
1594
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
1569
1595
  // Reject a malformed address before viem compares offer markets with it.
1570
1596
  (0, validateMidnightAccount_js_1.validateMidnightAddress)("loanToken", params.loanToken);
1571
1597
  assertPositiveAmount("loanAssets", params.loanAssets);
@@ -1592,7 +1618,7 @@ class MorphoMidnight {
1592
1618
  chainId: this.chainId,
1593
1619
  cancellations: params.cancellations ?? [],
1594
1620
  deadline: params.deadline,
1595
- metadata: this.client.options.metadata,
1621
+ metadata,
1596
1622
  publication: {
1597
1623
  ratifier: data.ratifier,
1598
1624
  root: data.tree.root,
@@ -1708,7 +1734,7 @@ class MorphoMidnight {
1708
1734
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1709
1735
  * @throws {InvalidMidnightHexInputError} when a cancellation group or `callbackSalt` is not 32-byte hex.
1710
1736
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1711
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1737
+ * @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.
1712
1738
  * @example
1713
1739
  * ```ts
1714
1740
  * const callback = getMidnightBlueBuyCallbackAddress({ chainId, owner: maker, salt: callbackSalt });
@@ -1727,6 +1753,8 @@ class MorphoMidnight {
1727
1753
  * ```
1728
1754
  */
1729
1755
  async supplyBlueMakeLend(params) {
1756
+ const suppliedNow = params.now;
1757
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, suppliedNow);
1730
1758
  // Reject the zero account before preparing anything for it.
1731
1759
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1732
1760
  // Reject wrong-sized salts before callback derivation pads them or any read occurs.
@@ -1738,7 +1766,8 @@ class MorphoMidnight {
1738
1766
  rejectReduceOnlyOffers(tree.offers);
1739
1767
  await (0, validateClientChainId_js_1.validateClientChainId)(this.client.viemClient, this.chainId);
1740
1768
  // Fails before any API read or build when the deadline has already passed.
1741
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1769
+ const now = suppliedNow ?? morpho_ts_1.Time.timestamp();
1770
+ (0, deadline_js_1.validateMidnightDeadline)(params.deadline, now);
1742
1771
  const { callbackSalt } = params;
1743
1772
  // Encode the whole Blue market first so a malformed field fails typed, before the RPC read.
1744
1773
  const callbackData = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("blueMarket", () => (0, callback_js_1.getMidnightBlueBuyCallbackData)(params.blueMarket));
@@ -1758,7 +1787,7 @@ class MorphoMidnight {
1758
1787
  deployless: this.client.options.supportDeployless,
1759
1788
  }),
1760
1789
  ]);
1761
- const market = (0, morpho_ts_1._try)(() => fetched.accrueInterest(blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), fetched.lastUpdate)), blue_sdk_1.UnsupportedMarketIrmError) ?? fetched;
1790
+ const market = (0, morpho_ts_1._try)(() => fetched.accrueInterest(blue_sdk_1.MathLib.max(suppliedNow ?? morpho_ts_1.Time.timestamp(), fetched.lastUpdate)), blue_sdk_1.UnsupportedMarketIrmError) ?? fetched;
1762
1791
  if (market.totalSupplyShares === 0n) {
1763
1792
  throw new index_js_4.EmptyBlueParkingMarketError({ marketId: blueMarketId });
1764
1793
  }
@@ -1808,7 +1837,7 @@ class MorphoMidnight {
1808
1837
  nativeAmount: params.nativeAmount,
1809
1838
  cancellations: params.cancellations ?? [],
1810
1839
  deadline: params.deadline,
1811
- metadata: this.client.options.metadata,
1840
+ metadata,
1812
1841
  });
1813
1842
  return {
1814
1843
  groups: data.groups,
@@ -1833,6 +1862,7 @@ class MorphoMidnight {
1833
1862
  * Prepares borrow-side offers for publication.
1834
1863
  */
1835
1864
  async prepareBorrowOffers(params) {
1865
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
1836
1866
  const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1837
1867
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
1838
1868
  (0, publication_js_1.validateMidnightMakerOfferCallbacks)(tree.offers);
@@ -1845,7 +1875,7 @@ class MorphoMidnight {
1845
1875
  chainId: this.chainId,
1846
1876
  cancellations: params.cancellations ?? [],
1847
1877
  deadline: params.deadline,
1848
- metadata: this.client.options.metadata,
1878
+ metadata,
1849
1879
  publication: {
1850
1880
  ratifier: data.ratifier,
1851
1881
  root: data.tree.root,
@@ -1915,7 +1945,7 @@ class MorphoMidnight {
1915
1945
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
1916
1946
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
1917
1947
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
1918
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
1948
+ * @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.
1919
1949
  * @example
1920
1950
  * ```ts
1921
1951
  * const output = await midnight.makeWithdraw({
@@ -1932,7 +1962,8 @@ class MorphoMidnight {
1932
1962
  // Reject the zero account before preparing anything for it.
1933
1963
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
1934
1964
  // Fails before any API read or build when the deadline has already passed.
1935
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
1965
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
1966
+ (0, deadline_js_1.validateMidnightDeadline)(params.deadline, now);
1936
1967
  const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
1937
1968
  // Reject the wrong exit intent before calling the mempool validation API.
1938
1969
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, false);
@@ -2003,7 +2034,7 @@ class MorphoMidnight {
2003
2034
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
2004
2035
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
2005
2036
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
2006
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2037
+ * @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.
2007
2038
  * @example
2008
2039
  * ```ts
2009
2040
  * const output = await midnight.makeRepay({
@@ -2022,7 +2053,8 @@ class MorphoMidnight {
2022
2053
  // Reject the zero account before preparing anything for it.
2023
2054
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
2024
2055
  // Fails before any API read or build when the deadline has already passed.
2025
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
2056
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
2057
+ (0, deadline_js_1.validateMidnightDeadline)(params.deadline, now);
2026
2058
  const tree = (0, encodeMidnightCalldata_js_1.wrapMidnightEncoding)("offers", () => midnight_sdk_1.Tree.from(params.offers));
2027
2059
  // Reject the wrong exit intent before calling the mempool validation API.
2028
2060
  (0, validateOfferSides_js_1.validateOfferSides)(tree.offers, true);
@@ -2100,7 +2132,7 @@ class MorphoMidnight {
2100
2132
  * @throws {MidnightReplacementGroupCancelledError} when a published group is also cancelled.
2101
2133
  * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
2102
2134
  * @throws {DuplicateMidnightGroupCancellationError} when a cancelled group appears more than once.
2103
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2135
+ * @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.
2104
2136
  * @example
2105
2137
  * ```ts
2106
2138
  * const output = await midnight.supplyCollateralMakeBorrow({
@@ -2115,11 +2147,13 @@ class MorphoMidnight {
2115
2147
  * ```
2116
2148
  */
2117
2149
  async supplyCollateralMakeBorrow(params) {
2150
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
2118
2151
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
2119
2152
  // Reject the zero account before preparing anything for it.
2120
2153
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
2121
2154
  // Fails before any API read or build when the deadline has already passed.
2122
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
2155
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
2156
+ (0, deadline_js_1.validateMidnightDeadline)(params.deadline, now);
2123
2157
  const market = params.collateral.market instanceof midnight_sdk_1.MarketParams
2124
2158
  ? params.collateral.market
2125
2159
  : midnight_sdk_1.MarketParams.from(params.collateral.market);
@@ -2145,7 +2179,7 @@ class MorphoMidnight {
2145
2179
  nativeAmount: params.nativeAmount,
2146
2180
  cancellations: params.cancellations ?? [],
2147
2181
  deadline: params.deadline,
2148
- metadata: this.client.options.metadata,
2182
+ metadata,
2149
2183
  publication: {
2150
2184
  ratifier: data.ratifier,
2151
2185
  root: data.tree.root,
@@ -2231,6 +2265,7 @@ class MorphoMidnight {
2231
2265
  * ```
2232
2266
  */
2233
2267
  redeem(params) {
2268
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
2234
2269
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
2235
2270
  // Reject a malformed account here; the builder rejects the zero account.
2236
2271
  (0, validateMidnightAccount_js_1.validateMidnightAddress)("accountAddress", params.accountAddress);
@@ -2247,7 +2282,8 @@ class MorphoMidnight {
2247
2282
  validateMarketData(market, this.chainId);
2248
2283
  // Apply realized losses and continuous fees the way `Midnight._updatePosition` does before a
2249
2284
  // withdrawal; never accrue to before the snapshot's `lastAccrual`.
2250
- const accrued = params.positionData.accrueInterest(blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), params.positionData.lastAccrual));
2285
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
2286
+ const accrued = params.positionData.accrueInterest(blue_sdk_1.MathLib.max(now, params.positionData.lastAccrual));
2251
2287
  const units = params.units ?? accrued.faceValue;
2252
2288
  if (params.units !== undefined && units <= 0n) {
2253
2289
  throw new index_js_4.NonPositiveInputError("units", units);
@@ -2276,7 +2312,7 @@ class MorphoMidnight {
2276
2312
  units,
2277
2313
  onBehalf: params.accountAddress,
2278
2314
  receiver: params.receiver,
2279
- metadata: this.client.options.metadata,
2315
+ metadata,
2280
2316
  });
2281
2317
  return {
2282
2318
  getRequirements: async () => [],
@@ -2341,7 +2377,7 @@ class MorphoMidnight {
2341
2377
  * during this method call, before the lazy output is returned.
2342
2378
  * @throws {MidnightContractReceiverError} when `collateralReceiver` is a Midnight protocol
2343
2379
  * contract or a market token contract.
2344
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2380
+ * @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.
2345
2381
  * @example
2346
2382
  * ```ts
2347
2383
  * // Close the position: repay all debt, withdraw all collateral.
@@ -2357,11 +2393,13 @@ class MorphoMidnight {
2357
2393
  * ```
2358
2394
  */
2359
2395
  repayWithdrawCollateral(params) {
2396
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
2360
2397
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
2361
2398
  // Reject the zero account before preparing anything for it.
2362
2399
  (0, validateMidnightAccount_js_1.validateMidnightAccount)("accountAddress", params.accountAddress);
2363
2400
  // Fails before any API read or build when the deadline has already passed.
2364
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
2401
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
2402
+ (0, deadline_js_1.validateMidnightDeadline)(params.deadline, now);
2365
2403
  const market = params.marketData.params;
2366
2404
  const tx = (0, index_js_1.midnightRepayWithdrawCollateral)({
2367
2405
  chainId: this.chainId,
@@ -2371,7 +2409,7 @@ class MorphoMidnight {
2371
2409
  collateralWithdrawals: params.collateralWithdrawals ?? [],
2372
2410
  collateralReceiver: params.collateralReceiver ?? params.accountAddress,
2373
2411
  deadline: params.deadline,
2374
- metadata: this.client.options.metadata,
2412
+ metadata,
2375
2413
  });
2376
2414
  validatePositionBinding({
2377
2415
  positionData: params.positionData,
@@ -2379,24 +2417,7 @@ class MorphoMidnight {
2379
2417
  marketData: params.marketData,
2380
2418
  });
2381
2419
  const collateralWithdrawals = params.collateralWithdrawals ?? [];
2382
- const postCollateral = Array.from({ length: market.collateralParams.length }, (_, index) => params.positionData.collateral[index] ?? 0n);
2383
- let withdrawAmount = 0n;
2384
- for (const withdrawal of collateralWithdrawals) {
2385
- // Reject unconfigured collateral indexes before updating postCollateral.
2386
- midnight_sdk_1.MarketUtils.getCollateralByIndex(market, withdrawal.collateralIndex);
2387
- const index = Number(withdrawal.collateralIndex);
2388
- const available = postCollateral[index] ?? 0n;
2389
- const amount = withdrawal.assets === viem_1.maxUint256 ? available : withdrawal.assets;
2390
- if (amount > available) {
2391
- throw new index_js_4.WithdrawExceedsCollateralError({
2392
- withdrawAmount: amount,
2393
- available,
2394
- market: params.marketData.id,
2395
- });
2396
- }
2397
- postCollateral[index] = available - amount;
2398
- withdrawAmount += amount;
2399
- }
2420
+ const { postCollateral, withdrawAmount } = getPostWithdrawalCollateral(params);
2400
2421
  // The bundle must fill the whole assets target and the direct repay is capped at the debt, so a repay above it reverts `OutOfOffers()`.
2401
2422
  if (params.repay.type === "assets" &&
2402
2423
  params.repay.assets > params.positionData.debt) {
@@ -2414,11 +2435,11 @@ class MorphoMidnight {
2414
2435
  limit: params.positionData.debt,
2415
2436
  });
2416
2437
  }
2417
- const postDebt = params.repay.type === "full"
2418
- ? 0n
2419
- : params.positionData.debt > params.repay.assets
2420
- ? params.positionData.debt - params.repay.assets
2421
- : 0n;
2438
+ let postDebt = 0n;
2439
+ if (params.repay.type !== "full" &&
2440
+ params.positionData.debt > params.repay.assets) {
2441
+ postDebt = params.positionData.debt - params.repay.assets;
2442
+ }
2422
2443
  if (collateralWithdrawals.length > 0 && postDebt > 0n) {
2423
2444
  const maxSafeDebt = (0, index_js_3.getMidnightMaxSafeDebt)({
2424
2445
  market: params.marketData,
@@ -2455,42 +2476,37 @@ class MorphoMidnight {
2455
2476
  };
2456
2477
  }
2457
2478
  /**
2458
- * Prepares guarded cancellation of several maker offer groups through `MidnightBundlesV2`.
2479
+ * Prepares a full cancellation of one or more maker offer groups as a direct call to Midnight.
2459
2480
  *
2460
- * The transaction reverts as a whole when any group's consumption exceeds its
2461
- * `maxConsumed` ceiling, so fills landing before execution never leave a partial cancel.
2481
+ * One group builds a bare `setConsumed(group, maxUint128, accountAddress)`. Two or more groups
2482
+ * build one Midnight `multicall` of such calls, in list order, which cancels every group or
2483
+ * none. Only the single-group transaction is matchable by a wallet policy that allows
2484
+ * `setConsumed` by method name; cancel one group per transaction when the signer's policy names
2485
+ * `setConsumed`.
2462
2486
  *
2463
- * @param params - Maker account, groups with consumption ceilings, and deadline.
2464
- * @param params.accountAddress - Maker that must send the transaction. It is used only to check
2465
- * the maker's Midnight authorization of `MidnightBundlesV2`; the bundle cancels the groups of
2466
- * `msg.sender`. A transaction sent from another account that has also authorized
2467
- * `MidnightBundlesV2` does not revert: it cancels that account's groups and leaves the maker's
2468
- * offers fillable.
2469
- * @param params.cancellations - Offer groups and the largest consumption accepted for each.
2470
- * To cancel unconditionally, set `maxConsumed` to `maxUint128`; the contract treats
2471
- * `type(uint128).max` as no limit.
2472
- * Cancellation is per group: it does not unratify roots or revoke
2473
- * `MidnightBundlesV2` or ratifier authorization.
2474
- * @param params.deadline - Bundle execution deadline timestamp.
2475
- * @returns Lazy Midnight authorization requirement for `MidnightBundlesV2` and a synchronous transaction builder.
2476
- * @throws {ChainIdMismatchError} when the client targets another chain, or from
2477
- * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
2478
- * @throws {MidnightCalldataEncodingError} when an input cannot be ABI-encoded, such as an out-of-range integer.
2479
- * @throws {viem.BaseError} from `getRequirements()` when an `eth_chainId` request or requirement
2480
- * RPC read fails.
2481
- * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
2482
- * @throws {UnknownAddressError} when the chain has no `midnightBundlesV2` deployment.
2483
- * @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
2487
+ * Nothing is required before sending: no Midnight authorization, approval, signature or
2488
+ * deadline. Cancellation is per group and always full; it does not unratify roots or revoke
2489
+ * authorizations, and cancelling a group again succeeds.
2490
+ *
2491
+ * @param params - Maker account and the offer groups to cancel.
2492
+ * @param params.accountAddress - Maker whose groups are cancelled. The maker, or an operator it
2493
+ * authorized on Midnight, must send the transaction; a transaction from any other account
2494
+ * reverts `Unauthorized()` and changes no group.
2495
+ * @param params.groups - Nonempty list of distinct 32-byte offer groups to cancel.
2496
+ * @param params.now - Optional reference timestamp used to resolve `metadata.timestamp: true`.
2497
+ * @returns A handle whose `getRequirements()` resolves to an empty list without reading the
2498
+ * chain, and whose synchronous `buildTx()` returns the transaction targeting `Midnight`.
2499
+ * @throws {ChainIdMismatchError} when the client targets another chain.
2484
2500
  * @throws {MidnightInvalidAccountAddressError} when `accountAddress` is malformed or zero.
2485
- * @throws {InvalidMidnightHexInputError} when a cancellation group is not 32-byte hex.
2501
+ * @throws {EmptyMidnightGroupCancellationsError} when no groups are provided.
2502
+ * @throws {InvalidMidnightHexInputError} when a group is not 32-byte hex.
2486
2503
  * @throws {DuplicateMidnightGroupCancellationError} when a group appears more than once.
2487
- * @throws {NegativeInputError} when a `maxConsumed` ceiling is negative.
2488
- * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256` or a `maxConsumed` ceiling exceeds `uint128`.
2489
- * @throws {ExpiredDeadlineError} when `params.deadline` is at or before the local clock (`Time.timestamp()`), including zero or negative values.
2504
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
2505
+ * @throws {UnknownAddressError} when the chain has no `midnight` deployment.
2490
2506
  * @example
2491
2507
  * ```ts
2492
2508
  * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
2493
- * import { createPublicClient, http, maxUint256, type Address, type Hex } from "viem";
2509
+ * import { createPublicClient, http, type Address, type Hex } from "viem";
2494
2510
  * import { base } from "viem/chains";
2495
2511
  *
2496
2512
  * declare const maker: Address;
@@ -2499,30 +2515,27 @@ class MorphoMidnight {
2499
2515
  * morphoViemExtension(),
2500
2516
  * );
2501
2517
  * const midnight = client.morpho.midnight(base.id);
2502
- * const output = midnight.cancelOffers({
2503
- * accountAddress: maker,
2504
- * cancellations: [{ group, maxConsumed: 0n }],
2505
- * deadline: maxUint256,
2506
- * });
2518
+ * const output = midnight.cancelOffers({ accountAddress: maker, groups: [group] });
2519
+ * await output.getRequirements(); // => []
2520
+ * const tx = output.buildTx(); // calldata: setConsumed(group, maxUint128, maker)
2507
2521
  * ```
2508
2522
  */
2509
2523
  cancelOffers(params) {
2524
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
2510
2525
  (0, index_js_3.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
2511
2526
  const { accountAddress } = params;
2512
2527
  if (!(0, viem_1.isAddress)(accountAddress) ||
2513
2528
  (0, viem_1.isAddressEqual)(accountAddress, viem_1.zeroAddress)) {
2514
2529
  throw new index_js_4.MidnightInvalidAccountAddressError(accountAddress);
2515
2530
  }
2516
- // Fails before any API read or build when the deadline has already passed.
2517
- (0, deadline_js_1.validateMidnightDeadline)(params.deadline);
2518
- const tx = (0, index_js_1.midnightCancelAndMake)({
2531
+ const tx = (0, index_js_1.midnightCancelOffers)({
2519
2532
  chainId: this.chainId,
2520
- cancellations: params.cancellations,
2521
- deadline: params.deadline,
2522
- metadata: this.client.options.metadata,
2533
+ groups: params.groups,
2534
+ onBehalf: accountAddress,
2535
+ metadata,
2523
2536
  });
2524
2537
  return {
2525
- getRequirements: () => this.getBundlesV2AuthorizationRequirements(accountAddress),
2538
+ getRequirements: async () => [],
2526
2539
  buildTx: () => tx,
2527
2540
  };
2528
2541
  }