@morpho-org/morpho-sdk 9.7.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 (185) 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/index.d.ts +1 -0
  77. package/lib/cjs/index.js +3 -1
  78. package/lib/cjs/midnight/errors.d.ts +2 -1
  79. package/lib/cjs/midnight/errors.js +5 -4
  80. package/lib/cjs/transactionPlan/plan.js +6 -3
  81. package/lib/cjs/transactionPlan/serde.js +7 -7
  82. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +6 -4
  83. package/lib/cjs/transactionPlan/vaultv2/deposit.js +5 -3
  84. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  85. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +5 -3
  86. package/lib/cjs/types/action.d.ts +26 -2
  87. package/lib/cjs/types/action.js +1 -1
  88. package/lib/cjs/types/error.js +11 -5
  89. package/lib/cjs/types/metadata.d.ts +12 -2
  90. package/lib/cjs/utils.d.ts +2 -2
  91. package/lib/cjs/utils.js +4 -2
  92. package/lib/cjs/version.d.ts +2 -0
  93. package/lib/cjs/version.js +6 -0
  94. package/lib/esm/abis.d.ts +1 -1
  95. package/lib/esm/abis.js +1 -1
  96. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  97. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +1 -1
  98. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -1
  99. package/lib/esm/actions/midnight/cancelAndMake.js +2 -1
  100. package/lib/esm/actions/midnight/cancelOffers.d.ts +54 -0
  101. package/lib/esm/actions/midnight/cancelOffers.js +103 -0
  102. package/lib/esm/actions/midnight/index.d.ts +1 -0
  103. package/lib/esm/actions/midnight/index.js +1 -0
  104. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  105. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +1 -1
  106. package/lib/esm/actions/midnight/takeBorrow.d.ts +1 -1
  107. package/lib/esm/actions/midnight/takeBorrow.js +1 -1
  108. package/lib/esm/actions/midnight/takeLend.d.ts +1 -1
  109. package/lib/esm/actions/midnight/takeLend.js +1 -1
  110. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  111. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -1
  112. package/lib/esm/actions/midnight/takeWithdraw.d.ts +1 -1
  113. package/lib/esm/actions/midnight/takeWithdraw.js +1 -1
  114. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  115. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  116. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  117. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  118. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  119. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +3 -3
  120. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  121. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +3 -2
  122. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  123. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  124. package/lib/esm/blue/abis.d.ts +1 -1
  125. package/lib/esm/blue/abis.js +1 -1
  126. package/lib/esm/blue/entities.d.ts +4 -4
  127. package/lib/esm/blue/entities.js +2 -2
  128. package/lib/esm/blue/errors.d.ts +2 -2
  129. package/lib/esm/blue/errors.js +2 -2
  130. package/lib/esm/blue/fetch.d.ts +2 -2
  131. package/lib/esm/blue/fetch.js +2 -2
  132. package/lib/esm/blue/utils.d.ts +1 -1
  133. package/lib/esm/blue/utils.js +1 -1
  134. package/lib/esm/entities/blue/blue.d.ts +34 -28
  135. package/lib/esm/entities/blue/blue.js +99 -73
  136. package/lib/esm/entities/index.d.ts +4 -4
  137. package/lib/esm/entities/index.js +2 -2
  138. package/lib/esm/entities/midnight/deadline.d.ts +2 -2
  139. package/lib/esm/entities/midnight/deadline.js +2 -2
  140. package/lib/esm/entities/midnight/midnight.d.ts +49 -51
  141. package/lib/esm/entities/midnight/midnight.js +145 -132
  142. package/lib/esm/entities/midnight/publication.d.ts +2 -0
  143. package/lib/esm/entities/midnight/publication.js +126 -100
  144. package/lib/esm/entities/midnight/types.d.ts +4 -4
  145. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  146. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +17 -17
  147. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +3 -4
  148. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +1 -1
  149. package/lib/esm/entities/vaultV1/vaultV1.d.ts +12 -12
  150. package/lib/esm/entities/vaultV1/vaultV1.js +83 -57
  151. package/lib/esm/entities/vaultV2/vaultV2.d.ts +50 -24
  152. package/lib/esm/entities/vaultV2/vaultV2.js +166 -90
  153. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +17 -2
  154. package/lib/esm/entities/vaultV2BlueReallocationData.js +1410 -806
  155. package/lib/esm/errors.d.ts +4 -4
  156. package/lib/esm/errors.js +4 -4
  157. package/lib/esm/fetch.d.ts +2 -2
  158. package/lib/esm/fetch.js +2 -2
  159. package/lib/esm/helpers/deadShares.js +56 -35
  160. package/lib/esm/helpers/metadata.d.ts +14 -2
  161. package/lib/esm/helpers/metadata.js +38 -4
  162. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +34 -22
  163. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +7 -1
  164. package/lib/esm/helpers/validate.js +76 -61
  165. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +153 -102
  166. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +31 -20
  167. package/lib/esm/index.d.ts +1 -0
  168. package/lib/esm/index.js +1 -0
  169. package/lib/esm/midnight/errors.d.ts +2 -1
  170. package/lib/esm/midnight/errors.js +2 -1
  171. package/lib/esm/transactionPlan/plan.js +6 -3
  172. package/lib/esm/transactionPlan/serde.js +7 -7
  173. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +6 -4
  174. package/lib/esm/transactionPlan/vaultv2/deposit.js +5 -3
  175. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  176. package/lib/esm/transactionPlan/vaultv2/withdraw.js +5 -3
  177. package/lib/esm/types/action.d.ts +26 -2
  178. package/lib/esm/types/action.js +1 -1
  179. package/lib/esm/types/error.js +11 -5
  180. package/lib/esm/types/metadata.d.ts +12 -2
  181. package/lib/esm/utils.d.ts +2 -2
  182. package/lib/esm/utils.js +2 -2
  183. package/lib/esm/version.d.ts +2 -0
  184. package/lib/esm/version.js +3 -0
  185. package/package.json +8 -7
@@ -80,40 +80,14 @@ const validateMidnightTakeFeasibility = (params) => {
80
80
  // The raw builder rejects an empty list with `EmptyMidnightTakeableOffersError`.
81
81
  if (params.takeableOffers.length === 0)
82
82
  return params.takeableOffers;
83
- const { marketData, now, deadline, referralFeePct, target } = params;
83
+ const { marketData, now, deadline } = params;
84
84
  // The entity checked the deadline on an earlier clock read; recheck so the fee window is never empty.
85
85
  if (deadline <= now)
86
86
  throw new index_js_1.ExpiredDeadlineError(deadline, now);
87
87
  const maturity = marketData.params.maturity;
88
88
  const marketFee = BigInt(marketData.continuousFee);
89
- if (params.side === "buy") {
90
- if (params.maxContinuousFee < marketFee) {
91
- throw new index_js_1.MidnightContinuousFeeAboveMaxError({
92
- maxContinuousFee: params.maxContinuousFee,
93
- continuousFee: marketFee,
94
- });
95
- }
96
- const { debt, target: buyTarget } = params;
97
- if (debt !== undefined) {
98
- // Reduce-only buys fill at most the debt, and an assets target pays at most one asset per unit.
99
- const repay = buyTarget.type === "units"
100
- ? buyTarget.units === viem_1.maxUint256
101
- ? undefined
102
- : { field: "target.units", value: buyTarget.units }
103
- : buyTarget.minUnits > debt
104
- ? {
105
- field: "target.minUnits",
106
- value: buyTarget.minUnits,
107
- }
108
- : {
109
- field: "target.assets",
110
- value: netOfReferralFee(buyTarget.assets, referralFeePct),
111
- };
112
- if (repay && repay.value > debt) {
113
- throw new index_js_1.MidnightRepayExceedsDebtError({ ...repay, debt });
114
- }
115
- }
116
- }
89
+ // Reject buy fee and debt violations before evaluating settlement fees or offers.
90
+ assertMidnightBuyBounds(params, marketFee);
117
91
  const fees = [
118
92
  maturity - deadline,
119
93
  maturity - now,
@@ -126,82 +100,21 @@ const validateMidnightTakeFeasibility = (params) => {
126
100
  }));
127
101
  const minFee = blue_sdk_1.MathLib.min(...fees);
128
102
  const maxFee = blue_sdk_1.MathLib.max(...fees);
129
- const dead = [];
130
- const removed = new Set();
131
103
  // Post-maturity sells cannot open debt, so offers only take the credit left after the withdrawal.
132
104
  const sellableCredit = params.side === "sell" && params.increasesDebt && now > maturity
133
105
  ? blue_sdk_1.MathLib.zeroFloorSub(params.credit ?? 0n, params.fallbackUnits)
134
106
  : undefined;
135
- let liveUnits = 0n;
136
- let minBuyerPrice = params.fallbackUnits > 0n ? blue_sdk_1.MathLib.WAD : viem_1.maxUint256;
137
- for (const [index, { units, offer }] of params.takeableOffers.entries()) {
138
- const tickInRange = offer.tick >= 0n && offer.tick <= midnight_sdk_1.MAX_TICK;
139
- const offerPrice = tickInRange ? midnight_sdk_1.TickLib.tickToPrice(offer.tick) : 0n;
140
- let reason;
141
- // The bundle converts every buy assets target price outside its per-offer catch,
142
- // so a degenerate price aborts the bundle even when the offer is otherwise dead.
143
- if (params.side === "buy" && target.type === "assets") {
144
- if (!tickInRange)
145
- reason = "tickOutOfRange";
146
- else if (offerPrice + maxFee === 0n)
147
- reason = "zeroBuyerPrice";
148
- else if (offerPrice + minFee > blue_sdk_1.MathLib.WAD)
149
- reason = "buyerPriceAboveOne";
150
- if (reason)
151
- removed.add(index);
152
- }
153
- // Every sell converts a buy offer's price outside the catch too, which underflows below the fee.
154
- if (params.side === "sell") {
155
- if (!tickInRange)
156
- reason = "tickOutOfRange";
157
- else if (offerPrice === 0n)
158
- reason = "zeroBuyerPrice";
159
- // An assets target also divides by the seller price, which is zero at the fee.
160
- else if (offerPrice < minFee ||
161
- (target.type === "assets" && offerPrice === minFee))
162
- reason = "priceBelowSettlementFee";
163
- if (reason)
164
- removed.add(index);
165
- }
166
- if (!reason) {
167
- if (units === 0n)
168
- reason = "zeroUnits";
169
- else if (!tickInRange)
170
- reason = "tickOutOfRange";
171
- else if (offer.expiry < now)
172
- reason = "expired";
173
- else if (offer.start > deadline)
174
- reason = "notStarted";
175
- else if ((0, viem_1.isAddressEqual)(offer.maker, params.accountAddress))
176
- reason = "selfTake";
177
- else if (offer.continuousFeeCap < marketFee)
178
- reason = "continuousFeeCapBelowMarketFee";
179
- else if (params.side === "sell" &&
180
- !(0, viem_1.isAddressEqual)(offer.receiverIfMakerIsSeller, viem_1.zeroAddress))
181
- reason = "receiverIfMakerIsSellerNotZero";
182
- else if (sellableCredit === 0n)
183
- reason = "marketMatured";
184
- }
185
- if (reason) {
186
- dead.push({ index, reason });
187
- continue;
188
- }
189
- liveUnits += units;
190
- minBuyerPrice = blue_sdk_1.MathLib.min(minBuyerPrice, offerPrice + minFee);
191
- }
107
+ const { dead, removed, liveUnits, minBuyerPrice } = collectOfferCapacity(params, {
108
+ minFee,
109
+ maxFee,
110
+ marketFee,
111
+ sellableCredit,
112
+ });
192
113
  if (dead.length === params.takeableOffers.length &&
193
114
  (params.fallbackUnits === 0n || removed.size === dead.length)) {
194
115
  throw new index_js_1.MidnightTakeableOffersNotFillableError(dead);
195
116
  }
196
- const requiredUnits = params.side === "sell"
197
- ? target.type === "units"
198
- ? target.units
199
- : (0, referralFee_js_1.grossFromNetAssets)({ netAssets: target.assets, referralFeePct })
200
- : params.target.type === "units"
201
- ? params.target.units === viem_1.maxUint256
202
- ? (params.debt ?? 0n)
203
- : params.target.units
204
- : blue_sdk_1.MathLib.max(netOfReferralFee(params.target.assets, referralFeePct), params.target.minUnits);
117
+ const requiredUnits = resolveRequiredUnits(params);
205
118
  const fillableUnits = (sellableCredit === undefined
206
119
  ? liveUnits
207
120
  : blue_sdk_1.MathLib.min(liveUnits, sellableCredit)) + params.fallbackUnits;
@@ -212,10 +125,152 @@ const validateMidnightTakeFeasibility = (params) => {
212
125
  limit: requiredUnits,
213
126
  });
214
127
  }
128
+ // Capacity errors precede the buyer's maximum-pull bound.
129
+ assertBuyerAssetCapacity(params, { requiredUnits, minBuyerPrice });
130
+ return removed.size === 0
131
+ ? params.takeableOffers
132
+ : params.takeableOffers.filter((_, index) => !removed.has(index));
133
+ };
134
+ exports.validateMidnightTakeFeasibility = validateMidnightTakeFeasibility;
135
+ /** Resolves a reduce-only buy's repay bound without changing target precedence. @internal */
136
+ function resolveRepayTarget(target, { debt, referralFeePct, }) {
137
+ if (target.type === "units") {
138
+ if (target.units === viem_1.maxUint256)
139
+ return undefined;
140
+ return { field: "target.units", value: target.units };
141
+ }
142
+ if (target.minUnits > debt)
143
+ return { field: "target.minUnits", value: target.minUnits };
144
+ return {
145
+ field: "target.assets",
146
+ value: netOfReferralFee(target.assets, referralFeePct),
147
+ };
148
+ }
149
+ /** Rejects excessive continuous fees and reduce-only buys exceeding debt. @internal */
150
+ function assertMidnightBuyBounds(params, marketFee) {
151
+ if (params.side !== "buy")
152
+ return;
153
+ if (params.maxContinuousFee < marketFee) {
154
+ throw new index_js_1.MidnightContinuousFeeAboveMaxError({
155
+ maxContinuousFee: params.maxContinuousFee,
156
+ continuousFee: marketFee,
157
+ });
158
+ }
159
+ const { debt, target: buyTarget } = params;
160
+ if (debt !== undefined) {
161
+ // Reduce-only buys fill at most the debt, and an assets target pays at most one asset per unit.
162
+ const repay = resolveRepayTarget(buyTarget, {
163
+ debt,
164
+ referralFeePct: params.referralFeePct,
165
+ });
166
+ if (repay && repay.value > debt) {
167
+ throw new index_js_1.MidnightRepayExceedsDebtError({ ...repay, debt });
168
+ }
169
+ }
170
+ }
171
+ /** Resolves price failures that abort bundle conversion outside the offer catch. @internal */
172
+ function getOfferPriceReason(params, { tickInRange, offerPrice, minFee, maxFee, }) {
173
+ // The bundle converts every buy assets target price outside its per-offer catch.
174
+ if (params.side === "buy" && params.target.type === "assets") {
175
+ if (!tickInRange)
176
+ return "tickOutOfRange";
177
+ if (offerPrice + maxFee === 0n)
178
+ return "zeroBuyerPrice";
179
+ if (offerPrice + minFee > blue_sdk_1.MathLib.WAD)
180
+ return "buyerPriceAboveOne";
181
+ return undefined;
182
+ }
183
+ // Every sell converts a buy offer's price outside the catch too.
184
+ if (params.side !== "sell")
185
+ return undefined;
186
+ if (!tickInRange)
187
+ return "tickOutOfRange";
188
+ if (offerPrice === 0n)
189
+ return "zeroBuyerPrice";
190
+ // An assets target also divides by the seller price, which is zero at the fee.
191
+ if (offerPrice < minFee ||
192
+ (params.target.type === "assets" && offerPrice === minFee))
193
+ return "priceBelowSettlementFee";
194
+ return undefined;
195
+ }
196
+ /** Finds the first non-price condition preventing an offer from filling. @internal */
197
+ function getOfferDeadReason({ units, offer }, { params, tickInRange, marketFee, sellableCredit, }) {
198
+ if (units === 0n)
199
+ return "zeroUnits";
200
+ if (!tickInRange)
201
+ return "tickOutOfRange";
202
+ if (offer.expiry < params.now)
203
+ return "expired";
204
+ if (offer.start > params.deadline)
205
+ return "notStarted";
206
+ if ((0, viem_1.isAddressEqual)(offer.maker, params.accountAddress))
207
+ return "selfTake";
208
+ if (offer.continuousFeeCap < marketFee)
209
+ return "continuousFeeCapBelowMarketFee";
210
+ if (params.side === "sell" &&
211
+ !(0, viem_1.isAddressEqual)(offer.receiverIfMakerIsSeller, viem_1.zeroAddress))
212
+ return "receiverIfMakerIsSellerNotZero";
213
+ if (sellableCredit === 0n)
214
+ return "marketMatured";
215
+ return undefined;
216
+ }
217
+ /** Accumulates live offer capacity and preserves removal and error order. @internal */
218
+ function collectOfferCapacity(params, { minFee, maxFee, marketFee, sellableCredit, }) {
219
+ const dead = [];
220
+ const removed = new Set();
221
+ let liveUnits = 0n;
222
+ let minBuyerPrice = params.fallbackUnits > 0n ? blue_sdk_1.MathLib.WAD : viem_1.maxUint256;
223
+ for (const [index, { units, offer }] of params.takeableOffers.entries()) {
224
+ const tickInRange = offer.tick >= 0n && offer.tick <= midnight_sdk_1.MAX_TICK;
225
+ const offerPrice = tickInRange ? midnight_sdk_1.TickLib.tickToPrice(offer.tick) : 0n;
226
+ const priceReason = getOfferPriceReason(params, {
227
+ tickInRange,
228
+ offerPrice,
229
+ minFee,
230
+ maxFee,
231
+ });
232
+ if (priceReason)
233
+ removed.add(index);
234
+ const reason = priceReason ??
235
+ getOfferDeadReason({ units, offer }, {
236
+ params,
237
+ tickInRange,
238
+ marketFee,
239
+ sellableCredit,
240
+ });
241
+ if (reason) {
242
+ dead.push({ index, reason });
243
+ continue;
244
+ }
245
+ liveUnits += units;
246
+ minBuyerPrice = blue_sdk_1.MathLib.min(minBuyerPrice, offerPrice + minFee);
247
+ }
248
+ return { dead, removed, liveUnits, minBuyerPrice };
249
+ }
250
+ /** Converts the taker's target into its required gross unit capacity. @internal */
251
+ function resolveRequiredUnits(params) {
252
+ const { target, referralFeePct } = params;
253
+ if (params.side === "sell") {
254
+ if (target.type === "units")
255
+ return target.units;
256
+ return (0, referralFee_js_1.grossFromNetAssets)({ netAssets: target.assets, referralFeePct });
257
+ }
258
+ if (params.target.type === "units") {
259
+ return params.target.units === viem_1.maxUint256
260
+ ? (params.debt ?? 0n)
261
+ : params.target.units;
262
+ }
263
+ return blue_sdk_1.MathLib.max(netOfReferralFee(params.target.assets, referralFeePct), params.target.minUnits);
264
+ }
265
+ /** Rejects a units buy whose cheapest possible asset pull exceeds its cap. @internal */
266
+ function assertBuyerAssetCapacity(params, { requiredUnits, minBuyerPrice, }) {
215
267
  if (params.side === "buy" && params.target.type === "units") {
216
268
  // Every unit costs at least the cheapest live price, and the fee is grossed up on top.
217
269
  const minCost = blue_sdk_1.MathLib.mulDivDown(requiredUnits, minBuyerPrice, blue_sdk_1.MathLib.WAD);
218
- const minPull = (0, referralFee_js_1.grossFromNetAssets)({ netAssets: minCost, referralFeePct });
270
+ const minPull = (0, referralFee_js_1.grossFromNetAssets)({
271
+ netAssets: minCost,
272
+ referralFeePct: params.referralFeePct,
273
+ });
219
274
  if (params.target.maxBuyerAssets < minPull) {
220
275
  throw new index_js_1.MidnightTakeTargetUnreachableError({
221
276
  field: "target.maxBuyerAssets",
@@ -224,8 +279,4 @@ const validateMidnightTakeFeasibility = (params) => {
224
279
  });
225
280
  }
226
281
  }
227
- return removed.size === 0
228
- ? params.takeableOffers
229
- : params.takeableOffers.filter((_, index) => !removed.has(index));
230
- };
231
- exports.validateMidnightTakeFeasibility = validateMidnightTakeFeasibility;
282
+ }
@@ -208,25 +208,7 @@ function computeVaultV2ForceWithdrawPlan(params) {
208
208
  if (liquidityMarketId != null && drainedFromLiquidityMarket > 0n) {
209
209
  availableByMarket.set(liquidityMarketId, blue_sdk_1.MathLib.zeroFloorSub(liquidityCapacity, drainedFromLiquidityMarket));
210
210
  }
211
- let coveredAssets = 0n;
212
- const nonEmpty = [];
213
- for (const available of availableByMarket.values()) {
214
- if (available <= 0n)
215
- continue;
216
- coveredAssets += available;
217
- nonEmpty.push(available);
218
- }
219
- // `maxExitAssets` must not depend on the requested amount. At the ceiling the penalty-free leg
220
- // always drains the liquidity market completely, so that market contributes nothing to the
221
- // force-deallocation loop — whereas a small request leaves part of it, which would overstate the
222
- // ceiling for callers using it to cap an input.
223
- let saturatedCoveredAssets = 0n;
224
- for (const [marketId, available] of availableByMarket) {
225
- if (marketId === liquidityMarketId)
226
- continue;
227
- if (available > 0n)
228
- saturatedCoveredAssets += available;
229
- }
211
+ const { coveredAssets, nonEmpty, saturatedCoveredAssets } = summarizeMarketCoverage(availableByMarket, liquidityMarketId);
230
212
  // Worst-case leg count is the ascending walk: the most markets the loop can touch is the number
231
213
  // of smallest positions that together reach `assetsToDeallocate`. Deliberately an upper bound, not
232
214
  // a replay of the contract's prefetched `marketIds` order (where an earlier market may cover the
@@ -239,7 +221,13 @@ function computeVaultV2ForceWithdrawPlan(params) {
239
221
  // coverage of the snapshot-vs-execution divergence.
240
222
  let penaltyLegs = 0;
241
223
  let remaining = assetsToDeallocate;
242
- for (const available of nonEmpty.toSorted((a, b) => a === b ? 0 : a > b ? 1 : -1)) {
224
+ for (const available of nonEmpty.toSorted((a, b) => {
225
+ if (a === b)
226
+ return 0;
227
+ if (a > b)
228
+ return 1;
229
+ return -1;
230
+ })) {
243
231
  if (remaining <= 0n)
244
232
  break;
245
233
  penaltyLegs += 1;
@@ -435,3 +423,26 @@ function computeVaultV2ForceWithdrawMinSharesBurnt(params) {
435
423
  return vaultData.toShares(blue_sdk_1.MathLib.min(plan.withdrawnAssets +
436
424
  blue_sdk_1.MathLib.wMulUp(plan.assetsToDeallocate, plan.penalty), blue_sdk_1.MathLib.zeroFloorSub(plan.exitAssets, 1n)), "Down");
437
425
  }
426
+ /** Sums usable market liquidity and the ceiling's non-liquidity-market coverage. @internal */
427
+ function summarizeMarketCoverage(availableByMarket, liquidityMarketId) {
428
+ let coveredAssets = 0n;
429
+ const nonEmpty = [];
430
+ for (const available of availableByMarket.values()) {
431
+ if (available <= 0n)
432
+ continue;
433
+ coveredAssets += available;
434
+ nonEmpty.push(available);
435
+ }
436
+ // `maxExitAssets` must not depend on the requested amount. At the ceiling the penalty-free leg
437
+ // always drains the liquidity market completely, so that market contributes nothing to the
438
+ // force-deallocation loop — whereas a small request leaves part of it, which would overstate the
439
+ // ceiling for callers using it to cap an input.
440
+ let saturatedCoveredAssets = 0n;
441
+ for (const [marketId, available] of availableByMarket) {
442
+ if (marketId === liquidityMarketId)
443
+ continue;
444
+ if (available > 0n)
445
+ saturatedCoveredAssets += available;
446
+ }
447
+ return { coveredAssets, nonEmpty, saturatedCoveredAssets };
448
+ }
@@ -6,3 +6,4 @@ export * from "./helpers/index.js";
6
6
  export type { Action, Funding, IntentParams, ReferralFee, SignatureRequest, Step, TransactionPlan, VaultV2DepositPlanParams, VaultV2WithdrawPlanParams, } from "./transactionPlan/index.js";
7
7
  export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, parseTransactionPlan, prepareVaultV2Deposit, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./transactionPlan/index.js";
8
8
  export * from "./types/index.js";
9
+ export { version } from "./version.js";
package/lib/cjs/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.ZeroAccountError = exports.UnsupportedTransactionPlanVersionError = exports.UnsupportedTransactionPlanActionError = exports.TransactionPlanSignatureMismatchError = exports.serializeTransactionPlan = exports.prepareVaultV2Withdraw = exports.prepareVaultV2Deposit = exports.parseTransactionPlan = exports.NonIntegerInputError = exports.InvalidTransactionPlanError = exports.InvalidCalldataOriginError = exports.IncompleteTransactionPlanError = exports.getPendingSignatureRequests = exports.buildTransactions = exports.buildTransaction = exports.applySignatures = exports.validateClientChainId = void 0;
17
+ exports.version = exports.ZeroAccountError = exports.UnsupportedTransactionPlanVersionError = exports.UnsupportedTransactionPlanActionError = exports.TransactionPlanSignatureMismatchError = exports.serializeTransactionPlan = exports.prepareVaultV2Withdraw = exports.prepareVaultV2Deposit = exports.parseTransactionPlan = exports.NonIntegerInputError = exports.InvalidTransactionPlanError = exports.InvalidCalldataOriginError = exports.IncompleteTransactionPlanError = exports.getPendingSignatureRequests = exports.buildTransactions = exports.buildTransaction = exports.applySignatures = exports.validateClientChainId = void 0;
18
18
  __exportStar(require("./actions/index.js"), exports);
19
19
  var validateClientChainId_js_1 = require("./actions/requirements/validateClientChainId.js");
20
20
  Object.defineProperty(exports, "validateClientChainId", { enumerable: true, get: function () { return validateClientChainId_js_1.validateClientChainId; } });
@@ -39,3 +39,5 @@ Object.defineProperty(exports, "UnsupportedTransactionPlanActionError", { enumer
39
39
  Object.defineProperty(exports, "UnsupportedTransactionPlanVersionError", { enumerable: true, get: function () { return index_js_1.UnsupportedTransactionPlanVersionError; } });
40
40
  Object.defineProperty(exports, "ZeroAccountError", { enumerable: true, get: function () { return index_js_1.ZeroAccountError; } });
41
41
  __exportStar(require("./types/index.js"), exports);
42
+ var version_js_1 = require("./version.js");
43
+ Object.defineProperty(exports, "version", { enumerable: true, get: function () { return version_js_1.version; } });
@@ -1 +1,2 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
2
+ export { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UnknownCollateralIndexError = exports.TickOutOfRangeError = exports.SettlementFeeExceedsPriceError = exports.RatifierV1TakerNotAllowedError = exports.RateRatifierV1BoundOverflowError = exports.PriceGreaterThanOneError = exports.PayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidTypedDataSignatureError = exports.InvalidTreeHeightError = exports.InvalidTreeError = exports.InvalidTickSpacingError = exports.InvalidRatifierV1AddressError = exports.InvalidRateRatifierV1TimeError = exports.InvalidRateRatifierV1TickError = exports.InvalidRateRatifierV1RateError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualTimestampError = exports.InvalidPositionAccrualStateError = exports.InvalidOfferParameterError = exports.InvalidOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMarketParameterError = exports.InvalidEcrecoverSignatureVError = exports.InvalidEcrecoverSignatureError = exports.ChainIdMismatchError = void 0;
3
+ exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualTimestampError = exports.InvalidPositionAccrualStateError = exports.UnknownCollateralIndexError = exports.TickOutOfRangeError = exports.SettlementFeeExceedsPriceError = exports.RatifierV1TakerNotAllowedError = exports.RateRatifierV1BoundOverflowError = exports.PriceGreaterThanOneError = exports.PayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidTypedDataSignatureError = exports.InvalidTreeHeightError = exports.InvalidTreeError = exports.InvalidTickSpacingError = exports.InvalidRatifierV1AddressError = exports.InvalidRateRatifierV1TimeError = exports.InvalidRateRatifierV1TickError = exports.InvalidRateRatifierV1RateError = exports.InvalidOfferParameterError = exports.InvalidOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMarketParameterError = exports.InvalidEcrecoverSignatureVError = exports.InvalidEcrecoverSignatureError = exports.ChainIdMismatchError = void 0;
4
4
  var midnight_sdk_1 = require("@morpho-org/midnight-sdk");
5
5
  Object.defineProperty(exports, "ChainIdMismatchError", { enumerable: true, get: function () { return midnight_sdk_1.ChainIdMismatchError; } });
6
6
  Object.defineProperty(exports, "InvalidEcrecoverSignatureError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidEcrecoverSignatureError; } });
@@ -10,9 +10,6 @@ Object.defineProperty(exports, "InvalidMidnightApiQuoteTargetError", { enumerabl
10
10
  Object.defineProperty(exports, "InvalidMidnightApiResponseError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidMidnightApiResponseError; } });
11
11
  Object.defineProperty(exports, "InvalidOfferGroupError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidOfferGroupError; } });
12
12
  Object.defineProperty(exports, "InvalidOfferParameterError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidOfferParameterError; } });
13
- Object.defineProperty(exports, "InvalidPositionAccrualStateError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidPositionAccrualStateError; } });
14
- Object.defineProperty(exports, "InvalidPositionAccrualTimestampError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidPositionAccrualTimestampError; } });
15
- Object.defineProperty(exports, "InvalidPositionLossFactorError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidPositionLossFactorError; } });
16
13
  Object.defineProperty(exports, "InvalidRateRatifierV1RateError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidRateRatifierV1RateError; } });
17
14
  Object.defineProperty(exports, "InvalidRateRatifierV1TickError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidRateRatifierV1TickError; } });
18
15
  Object.defineProperty(exports, "InvalidRateRatifierV1TimeError", { enumerable: true, get: function () { return midnight_sdk_1.InvalidRateRatifierV1TimeError; } });
@@ -30,3 +27,7 @@ Object.defineProperty(exports, "RatifierV1TakerNotAllowedError", { enumerable: t
30
27
  Object.defineProperty(exports, "SettlementFeeExceedsPriceError", { enumerable: true, get: function () { return midnight_sdk_1.SettlementFeeExceedsPriceError; } });
31
28
  Object.defineProperty(exports, "TickOutOfRangeError", { enumerable: true, get: function () { return midnight_sdk_1.TickOutOfRangeError; } });
32
29
  Object.defineProperty(exports, "UnknownCollateralIndexError", { enumerable: true, get: function () { return midnight_sdk_1.UnknownCollateralIndexError; } });
30
+ var morpho_ts_1 = require("@morpho-org/morpho-ts");
31
+ Object.defineProperty(exports, "InvalidPositionAccrualStateError", { enumerable: true, get: function () { return morpho_ts_1.InvalidPositionAccrualStateError; } });
32
+ Object.defineProperty(exports, "InvalidPositionAccrualTimestampError", { enumerable: true, get: function () { return morpho_ts_1.InvalidPositionAccrualTimestampError; } });
33
+ Object.defineProperty(exports, "InvalidPositionLossFactorError", { enumerable: true, get: function () { return morpho_ts_1.InvalidPositionLossFactorError; } });
@@ -66,6 +66,8 @@ function applySignatures(plan, signatures) {
66
66
  return plan;
67
67
  for (const [id, signature] of updates) {
68
68
  const request = requests.find((candidate) => candidate.id === id);
69
+ if (request === undefined)
70
+ throw new error_js_2.TransactionPlanSignatureMismatchError(id, "reference");
69
71
  const normalized = (0, common_js_1.normalizeBundlesSignature)(signature);
70
72
  let recovered;
71
73
  try {
@@ -86,9 +88,10 @@ function applySignatures(plan, signatures) {
86
88
  }
87
89
  return {
88
90
  ...plan,
89
- signatureRequests: plan.signatureRequests.map((request) => updates.has(request.id)
90
- ? { ...request, signature: updates.get(request.id) }
91
- : request),
91
+ signatureRequests: plan.signatureRequests.map((request) => {
92
+ const signature = updates.get(request.id);
93
+ return signature === undefined ? request : { ...request, signature };
94
+ }),
92
95
  };
93
96
  }
94
97
  /** @internal Lists the signature request IDs a step's action names, in role order. */
@@ -182,13 +182,13 @@ function parseTransactionPlan(json) {
182
182
  catch (cause) {
183
183
  if (cause instanceof error_js_1.TransactionPlanSignatureMismatchError) {
184
184
  const index = result.signatureRequests.findIndex((request) => request.id === cause.id);
185
- const field = cause.field === "reference"
186
- ? "id"
187
- : cause.field === "value"
188
- ? "args.amount"
189
- : cause.field.startsWith("args.")
190
- ? cause.field
191
- : `typedData.${cause.field}`;
185
+ let field = `typedData.${cause.field}`;
186
+ if (cause.field === "reference")
187
+ field = "id";
188
+ else if (cause.field === "value")
189
+ field = "args.amount";
190
+ else if (cause.field.startsWith("args."))
191
+ field = cause.field;
192
192
  throw new error_js_1.InvalidTransactionPlanError({
193
193
  path: `$.signatureRequests[${index}].${field}`,
194
194
  reason: "expected agreement with every referencing action",
@@ -1,6 +1,6 @@
1
1
  import { type AccrualVaultV2 } from "@morpho-org/blue-sdk";
2
2
  import { type Address, type Client } from "viem";
3
- import { type Transaction, type VaultV2DepositAction } from "../../types/index.js";
3
+ import { type ReferenceTimestampParams, type Transaction, type VaultV2DepositAction } from "../../types/index.js";
4
4
  import { type Funding, type IntentParams } from "../intent.js";
5
5
  import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
6
6
  /** @internal Validates the stored Vault V2 deposit action's input shape. */
@@ -9,7 +9,7 @@ export declare function validateDepositPlanAction(action: Record<string, unknown
9
9
  * Caller intent for a Vault V2 deposit, mirroring the Actions API deposit inputs, plus the snapshot.
10
10
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
11
11
  */
12
- export interface VaultV2DepositPlanParams extends IntentParams {
12
+ export interface VaultV2DepositPlanParams extends IntentParams, ReferenceTimestampParams {
13
13
  /** WAD-scaled tolerance for the share-price bound; defaults to `DEFAULT_SLIPPAGE_TOLERANCE`. */
14
14
  readonly slippageTolerance?: bigint;
15
15
  readonly vault: Address;
@@ -39,14 +39,15 @@ export interface VaultV2DepositPlanParams extends IntentParams {
39
39
  * @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
40
40
  * @param params.slippageTolerance - Optional WAD-scaled tolerance for the share-price bound; defaults to `DEFAULT_SLIPPAGE_TOLERANCE` and must not exceed `MAX_SLIPPAGE_TOLERANCE`.
41
41
  * @param params.supportSignature - Optional ERC-2612 preference, defaulting to `false`; when enabled, falls back to direct approval if no permit is available.
42
- * @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
42
+ * @param params.now - Reference timestamp in seconds, normally the latest block's `timestamp`; uses the device clock when omitted.
43
+ * @param params.expiresAt - Optional Unix timestamp in seconds as a safe integer, later than `now`; defaults to `now + 2h` (device clock when `now` is omitted).
43
44
  * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
44
45
  * @param params.deployless - Optional permission to use deployless aggregation for token permit metadata reads.
45
46
  * @returns A plan with approvals, concrete signature requests and the deposit step.
46
47
  * @throws {ZeroAccountError} when `account` is the zero address.
47
48
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
48
49
  * @throws {NonPositiveInputError} when `expiresAt`, `amount`, net assets or previewed shares are not positive.
49
- * @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
50
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now` (device clock when `now` is omitted).
50
51
  * @throws {NegativeInputError} when `referralFee.bps` or `slippageTolerance` is negative.
51
52
  * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
52
53
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds `MAX_SLIPPAGE_TOLERANCE`.
@@ -69,6 +70,7 @@ export interface VaultV2DepositPlanParams extends IntentParams {
69
70
  * const plan = await prepareVaultV2Deposit(client, {
70
71
  * vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
71
72
  * vaultData: await fetchAccrualVaultV2(vault, client),
73
+ * now: (await client.getBlock()).timestamp,
72
74
  * });
73
75
  * // Sign the pending requests, verify and attach with applySignatures, then build.
74
76
  * ```
@@ -81,14 +81,15 @@ function resolveDepositInputs(params, now) {
81
81
  * @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
82
82
  * @param params.slippageTolerance - Optional WAD-scaled tolerance for the share-price bound; defaults to `DEFAULT_SLIPPAGE_TOLERANCE` and must not exceed `MAX_SLIPPAGE_TOLERANCE`.
83
83
  * @param params.supportSignature - Optional ERC-2612 preference, defaulting to `false`; when enabled, falls back to direct approval if no permit is available.
84
- * @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
84
+ * @param params.now - Reference timestamp in seconds, normally the latest block's `timestamp`; uses the device clock when omitted.
85
+ * @param params.expiresAt - Optional Unix timestamp in seconds as a safe integer, later than `now`; defaults to `now + 2h` (device clock when `now` is omitted).
85
86
  * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
86
87
  * @param params.deployless - Optional permission to use deployless aggregation for token permit metadata reads.
87
88
  * @returns A plan with approvals, concrete signature requests and the deposit step.
88
89
  * @throws {ZeroAccountError} when `account` is the zero address.
89
90
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
90
91
  * @throws {NonPositiveInputError} when `expiresAt`, `amount`, net assets or previewed shares are not positive.
91
- * @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
92
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now` (device clock when `now` is omitted).
92
93
  * @throws {NegativeInputError} when `referralFee.bps` or `slippageTolerance` is negative.
93
94
  * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
94
95
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds `MAX_SLIPPAGE_TOLERANCE`.
@@ -111,6 +112,7 @@ function resolveDepositInputs(params, now) {
111
112
  * const plan = await prepareVaultV2Deposit(client, {
112
113
  * vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
113
114
  * vaultData: await fetchAccrualVaultV2(vault, client),
115
+ * now: (await client.getBlock()).timestamp,
114
116
  * });
115
117
  * // Sign the pending requests, verify and attach with applySignatures, then build.
116
118
  * ```
@@ -118,7 +120,7 @@ function resolveDepositInputs(params, now) {
118
120
  */
119
121
  async function prepareVaultV2Deposit(client, params) {
120
122
  const { vault, chainId, account, amount } = params;
121
- const now = morpho_ts_1.Time.timestamp();
123
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
122
124
  const { intent, native, common, asset, maxSharePrice } = resolveDepositInputs(params, now);
123
125
  const spender = (0, morpho_ts_1.getChainAddress)(chainId, "bundles.vaultBundlesV1");
124
126
  const [requirements] = await Promise.all([
@@ -1,6 +1,6 @@
1
1
  import { type AccrualVaultV2 } from "@morpho-org/blue-sdk";
2
2
  import { type Address, type Client } from "viem";
3
- import { type Transaction, type VaultV2WithdrawAction } from "../../types/index.js";
3
+ import { type ReferenceTimestampParams, type Transaction, type VaultV2WithdrawAction } from "../../types/index.js";
4
4
  import { type IntentParams } from "../intent.js";
5
5
  import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
6
6
  /** @internal Validates the stored Vault V2 withdrawal action's input shape. */
@@ -9,7 +9,7 @@ export declare function validateWithdrawPlanAction(action: Record<string, unknow
9
9
  * Caller intent for a Vault V2 asset withdrawal, mirroring the Actions API withdraw inputs, plus the snapshot.
10
10
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
11
11
  */
12
- export interface VaultV2WithdrawPlanParams extends IntentParams {
12
+ export interface VaultV2WithdrawPlanParams extends IntentParams, ReferenceTimestampParams {
13
13
  readonly vault: Address;
14
14
  /** Gross assets withdrawn, before the referral fee. */
15
15
  readonly amount: bigint;
@@ -36,14 +36,15 @@ export interface VaultV2WithdrawPlanParams extends IntentParams {
36
36
  * @param params.referralFee.bps - Optional integer fee in basis points of the gross amount; defaults to zero and must be below 10,000.
37
37
  * @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
38
38
  * @param params.supportSignature - Optional unlimited share-permit preference, defaulting to `false`; otherwise uses unlimited direct share approval when allowance is insufficient.
39
- * @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
39
+ * @param params.now - Reference timestamp in seconds, normally the latest block's `timestamp`; uses the device clock when omitted.
40
+ * @param params.expiresAt - Optional Unix timestamp in seconds as a safe integer, later than `now`; defaults to `now + 2h` (device clock when `now` is omitted).
40
41
  * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
41
42
  * @param params.deployless - Optional shared intent field; unused by withdrawal share-permit reads.
42
43
  * @returns A plan with the withdrawal step and any required share approval or signature request.
43
44
  * @throws {ZeroAccountError} when `account` is the zero address.
44
45
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
45
46
  * @throws {NonPositiveInputError} when `expiresAt`, `amount` or the computed required shares are not positive.
46
- * @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
47
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now` (device clock when `now` is omitted).
47
48
  * @throws {NegativeInputError} when `referralFee.bps` is negative.
48
49
  * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
49
50
  * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
@@ -65,6 +66,7 @@ export interface VaultV2WithdrawPlanParams extends IntentParams {
65
66
  * const plan = await prepareVaultV2Withdraw(client, {
66
67
  * vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
67
68
  * vaultData: await fetchAccrualVaultV2(vault, client),
69
+ * now: (await client.getBlock()).timestamp,
68
70
  * });
69
71
  * // Sign the pending requests, verify and attach with applySignatures, then build.
70
72
  * ```
@@ -69,14 +69,15 @@ function resolveWithdrawInputs(params, now) {
69
69
  * @param params.referralFee.bps - Optional integer fee in basis points of the gross amount; defaults to zero and must be below 10,000.
70
70
  * @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
71
71
  * @param params.supportSignature - Optional unlimited share-permit preference, defaulting to `false`; otherwise uses unlimited direct share approval when allowance is insufficient.
72
- * @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
72
+ * @param params.now - Reference timestamp in seconds, normally the latest block's `timestamp`; uses the device clock when omitted.
73
+ * @param params.expiresAt - Optional Unix timestamp in seconds as a safe integer, later than `now`; defaults to `now + 2h` (device clock when `now` is omitted).
73
74
  * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
74
75
  * @param params.deployless - Optional shared intent field; unused by withdrawal share-permit reads.
75
76
  * @returns A plan with the withdrawal step and any required share approval or signature request.
76
77
  * @throws {ZeroAccountError} when `account` is the zero address.
77
78
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
78
79
  * @throws {NonPositiveInputError} when `expiresAt`, `amount` or the computed required shares are not positive.
79
- * @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
80
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now` (device clock when `now` is omitted).
80
81
  * @throws {NegativeInputError} when `referralFee.bps` is negative.
81
82
  * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
82
83
  * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
@@ -98,6 +99,7 @@ function resolveWithdrawInputs(params, now) {
98
99
  * const plan = await prepareVaultV2Withdraw(client, {
99
100
  * vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
100
101
  * vaultData: await fetchAccrualVaultV2(vault, client),
102
+ * now: (await client.getBlock()).timestamp,
101
103
  * });
102
104
  * // Sign the pending requests, verify and attach with applySignatures, then build.
103
105
  * ```
@@ -105,7 +107,7 @@ function resolveWithdrawInputs(params, now) {
105
107
  */
106
108
  async function prepareVaultV2Withdraw(client, params) {
107
109
  const { vault, chainId, account, amount } = params;
108
- const now = morpho_ts_1.Time.timestamp();
110
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
109
111
  const { intent, common, requiredShareAllowance } = resolveWithdrawInputs(params, now);
110
112
  const spender = (0, morpho_ts_1.getChainAddress)(chainId, "bundles.vaultBundlesV1");
111
113
  const [, , requirements] = await Promise.all([