@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
@@ -76,40 +76,14 @@ export const validateMidnightTakeFeasibility = (params) => {
76
76
  // The raw builder rejects an empty list with `EmptyMidnightTakeableOffersError`.
77
77
  if (params.takeableOffers.length === 0)
78
78
  return params.takeableOffers;
79
- const { marketData, now, deadline, referralFeePct, target } = params;
79
+ const { marketData, now, deadline } = params;
80
80
  // The entity checked the deadline on an earlier clock read; recheck so the fee window is never empty.
81
81
  if (deadline <= now)
82
82
  throw new ExpiredDeadlineError(deadline, now);
83
83
  const maturity = marketData.params.maturity;
84
84
  const marketFee = BigInt(marketData.continuousFee);
85
- if (params.side === "buy") {
86
- if (params.maxContinuousFee < marketFee) {
87
- throw new MidnightContinuousFeeAboveMaxError({
88
- maxContinuousFee: params.maxContinuousFee,
89
- continuousFee: marketFee,
90
- });
91
- }
92
- const { debt, target: buyTarget } = params;
93
- if (debt !== undefined) {
94
- // Reduce-only buys fill at most the debt, and an assets target pays at most one asset per unit.
95
- const repay = buyTarget.type === "units"
96
- ? buyTarget.units === maxUint256
97
- ? undefined
98
- : { field: "target.units", value: buyTarget.units }
99
- : buyTarget.minUnits > debt
100
- ? {
101
- field: "target.minUnits",
102
- value: buyTarget.minUnits,
103
- }
104
- : {
105
- field: "target.assets",
106
- value: netOfReferralFee(buyTarget.assets, referralFeePct),
107
- };
108
- if (repay && repay.value > debt) {
109
- throw new MidnightRepayExceedsDebtError({ ...repay, debt });
110
- }
111
- }
112
- }
85
+ // Reject buy fee and debt violations before evaluating settlement fees or offers.
86
+ assertMidnightBuyBounds(params, marketFee);
113
87
  const fees = [
114
88
  maturity - deadline,
115
89
  maturity - now,
@@ -122,82 +96,21 @@ export const validateMidnightTakeFeasibility = (params) => {
122
96
  }));
123
97
  const minFee = MathLib.min(...fees);
124
98
  const maxFee = MathLib.max(...fees);
125
- const dead = [];
126
- const removed = new Set();
127
99
  // Post-maturity sells cannot open debt, so offers only take the credit left after the withdrawal.
128
100
  const sellableCredit = params.side === "sell" && params.increasesDebt && now > maturity
129
101
  ? MathLib.zeroFloorSub(params.credit ?? 0n, params.fallbackUnits)
130
102
  : undefined;
131
- let liveUnits = 0n;
132
- let minBuyerPrice = params.fallbackUnits > 0n ? MathLib.WAD : maxUint256;
133
- for (const [index, { units, offer }] of params.takeableOffers.entries()) {
134
- const tickInRange = offer.tick >= 0n && offer.tick <= MAX_TICK;
135
- const offerPrice = tickInRange ? TickLib.tickToPrice(offer.tick) : 0n;
136
- let reason;
137
- // The bundle converts every buy assets target price outside its per-offer catch,
138
- // so a degenerate price aborts the bundle even when the offer is otherwise dead.
139
- if (params.side === "buy" && target.type === "assets") {
140
- if (!tickInRange)
141
- reason = "tickOutOfRange";
142
- else if (offerPrice + maxFee === 0n)
143
- reason = "zeroBuyerPrice";
144
- else if (offerPrice + minFee > MathLib.WAD)
145
- reason = "buyerPriceAboveOne";
146
- if (reason)
147
- removed.add(index);
148
- }
149
- // Every sell converts a buy offer's price outside the catch too, which underflows below the fee.
150
- if (params.side === "sell") {
151
- if (!tickInRange)
152
- reason = "tickOutOfRange";
153
- else if (offerPrice === 0n)
154
- reason = "zeroBuyerPrice";
155
- // An assets target also divides by the seller price, which is zero at the fee.
156
- else if (offerPrice < minFee ||
157
- (target.type === "assets" && offerPrice === minFee))
158
- reason = "priceBelowSettlementFee";
159
- if (reason)
160
- removed.add(index);
161
- }
162
- if (!reason) {
163
- if (units === 0n)
164
- reason = "zeroUnits";
165
- else if (!tickInRange)
166
- reason = "tickOutOfRange";
167
- else if (offer.expiry < now)
168
- reason = "expired";
169
- else if (offer.start > deadline)
170
- reason = "notStarted";
171
- else if (isAddressEqual(offer.maker, params.accountAddress))
172
- reason = "selfTake";
173
- else if (offer.continuousFeeCap < marketFee)
174
- reason = "continuousFeeCapBelowMarketFee";
175
- else if (params.side === "sell" &&
176
- !isAddressEqual(offer.receiverIfMakerIsSeller, zeroAddress))
177
- reason = "receiverIfMakerIsSellerNotZero";
178
- else if (sellableCredit === 0n)
179
- reason = "marketMatured";
180
- }
181
- if (reason) {
182
- dead.push({ index, reason });
183
- continue;
184
- }
185
- liveUnits += units;
186
- minBuyerPrice = MathLib.min(minBuyerPrice, offerPrice + minFee);
187
- }
103
+ const { dead, removed, liveUnits, minBuyerPrice } = collectOfferCapacity(params, {
104
+ minFee,
105
+ maxFee,
106
+ marketFee,
107
+ sellableCredit,
108
+ });
188
109
  if (dead.length === params.takeableOffers.length &&
189
110
  (params.fallbackUnits === 0n || removed.size === dead.length)) {
190
111
  throw new MidnightTakeableOffersNotFillableError(dead);
191
112
  }
192
- const requiredUnits = params.side === "sell"
193
- ? target.type === "units"
194
- ? target.units
195
- : grossFromNetAssets({ netAssets: target.assets, referralFeePct })
196
- : params.target.type === "units"
197
- ? params.target.units === maxUint256
198
- ? (params.debt ?? 0n)
199
- : params.target.units
200
- : MathLib.max(netOfReferralFee(params.target.assets, referralFeePct), params.target.minUnits);
113
+ const requiredUnits = resolveRequiredUnits(params);
201
114
  const fillableUnits = (sellableCredit === undefined
202
115
  ? liveUnits
203
116
  : MathLib.min(liveUnits, sellableCredit)) + params.fallbackUnits;
@@ -208,10 +121,151 @@ export const validateMidnightTakeFeasibility = (params) => {
208
121
  limit: requiredUnits,
209
122
  });
210
123
  }
124
+ // Capacity errors precede the buyer's maximum-pull bound.
125
+ assertBuyerAssetCapacity(params, { requiredUnits, minBuyerPrice });
126
+ return removed.size === 0
127
+ ? params.takeableOffers
128
+ : params.takeableOffers.filter((_, index) => !removed.has(index));
129
+ };
130
+ /** Resolves a reduce-only buy's repay bound without changing target precedence. @internal */
131
+ function resolveRepayTarget(target, { debt, referralFeePct, }) {
132
+ if (target.type === "units") {
133
+ if (target.units === maxUint256)
134
+ return undefined;
135
+ return { field: "target.units", value: target.units };
136
+ }
137
+ if (target.minUnits > debt)
138
+ return { field: "target.minUnits", value: target.minUnits };
139
+ return {
140
+ field: "target.assets",
141
+ value: netOfReferralFee(target.assets, referralFeePct),
142
+ };
143
+ }
144
+ /** Rejects excessive continuous fees and reduce-only buys exceeding debt. @internal */
145
+ function assertMidnightBuyBounds(params, marketFee) {
146
+ if (params.side !== "buy")
147
+ return;
148
+ if (params.maxContinuousFee < marketFee) {
149
+ throw new MidnightContinuousFeeAboveMaxError({
150
+ maxContinuousFee: params.maxContinuousFee,
151
+ continuousFee: marketFee,
152
+ });
153
+ }
154
+ const { debt, target: buyTarget } = params;
155
+ if (debt !== undefined) {
156
+ // Reduce-only buys fill at most the debt, and an assets target pays at most one asset per unit.
157
+ const repay = resolveRepayTarget(buyTarget, {
158
+ debt,
159
+ referralFeePct: params.referralFeePct,
160
+ });
161
+ if (repay && repay.value > debt) {
162
+ throw new MidnightRepayExceedsDebtError({ ...repay, debt });
163
+ }
164
+ }
165
+ }
166
+ /** Resolves price failures that abort bundle conversion outside the offer catch. @internal */
167
+ function getOfferPriceReason(params, { tickInRange, offerPrice, minFee, maxFee, }) {
168
+ // The bundle converts every buy assets target price outside its per-offer catch.
169
+ if (params.side === "buy" && params.target.type === "assets") {
170
+ if (!tickInRange)
171
+ return "tickOutOfRange";
172
+ if (offerPrice + maxFee === 0n)
173
+ return "zeroBuyerPrice";
174
+ if (offerPrice + minFee > MathLib.WAD)
175
+ return "buyerPriceAboveOne";
176
+ return undefined;
177
+ }
178
+ // Every sell converts a buy offer's price outside the catch too.
179
+ if (params.side !== "sell")
180
+ return undefined;
181
+ if (!tickInRange)
182
+ return "tickOutOfRange";
183
+ if (offerPrice === 0n)
184
+ return "zeroBuyerPrice";
185
+ // An assets target also divides by the seller price, which is zero at the fee.
186
+ if (offerPrice < minFee ||
187
+ (params.target.type === "assets" && offerPrice === minFee))
188
+ return "priceBelowSettlementFee";
189
+ return undefined;
190
+ }
191
+ /** Finds the first non-price condition preventing an offer from filling. @internal */
192
+ function getOfferDeadReason({ units, offer }, { params, tickInRange, marketFee, sellableCredit, }) {
193
+ if (units === 0n)
194
+ return "zeroUnits";
195
+ if (!tickInRange)
196
+ return "tickOutOfRange";
197
+ if (offer.expiry < params.now)
198
+ return "expired";
199
+ if (offer.start > params.deadline)
200
+ return "notStarted";
201
+ if (isAddressEqual(offer.maker, params.accountAddress))
202
+ return "selfTake";
203
+ if (offer.continuousFeeCap < marketFee)
204
+ return "continuousFeeCapBelowMarketFee";
205
+ if (params.side === "sell" &&
206
+ !isAddressEqual(offer.receiverIfMakerIsSeller, zeroAddress))
207
+ return "receiverIfMakerIsSellerNotZero";
208
+ if (sellableCredit === 0n)
209
+ return "marketMatured";
210
+ return undefined;
211
+ }
212
+ /** Accumulates live offer capacity and preserves removal and error order. @internal */
213
+ function collectOfferCapacity(params, { minFee, maxFee, marketFee, sellableCredit, }) {
214
+ const dead = [];
215
+ const removed = new Set();
216
+ let liveUnits = 0n;
217
+ let minBuyerPrice = params.fallbackUnits > 0n ? MathLib.WAD : maxUint256;
218
+ for (const [index, { units, offer }] of params.takeableOffers.entries()) {
219
+ const tickInRange = offer.tick >= 0n && offer.tick <= MAX_TICK;
220
+ const offerPrice = tickInRange ? TickLib.tickToPrice(offer.tick) : 0n;
221
+ const priceReason = getOfferPriceReason(params, {
222
+ tickInRange,
223
+ offerPrice,
224
+ minFee,
225
+ maxFee,
226
+ });
227
+ if (priceReason)
228
+ removed.add(index);
229
+ const reason = priceReason ??
230
+ getOfferDeadReason({ units, offer }, {
231
+ params,
232
+ tickInRange,
233
+ marketFee,
234
+ sellableCredit,
235
+ });
236
+ if (reason) {
237
+ dead.push({ index, reason });
238
+ continue;
239
+ }
240
+ liveUnits += units;
241
+ minBuyerPrice = MathLib.min(minBuyerPrice, offerPrice + minFee);
242
+ }
243
+ return { dead, removed, liveUnits, minBuyerPrice };
244
+ }
245
+ /** Converts the taker's target into its required gross unit capacity. @internal */
246
+ function resolveRequiredUnits(params) {
247
+ const { target, referralFeePct } = params;
248
+ if (params.side === "sell") {
249
+ if (target.type === "units")
250
+ return target.units;
251
+ return grossFromNetAssets({ netAssets: target.assets, referralFeePct });
252
+ }
253
+ if (params.target.type === "units") {
254
+ return params.target.units === maxUint256
255
+ ? (params.debt ?? 0n)
256
+ : params.target.units;
257
+ }
258
+ return MathLib.max(netOfReferralFee(params.target.assets, referralFeePct), params.target.minUnits);
259
+ }
260
+ /** Rejects a units buy whose cheapest possible asset pull exceeds its cap. @internal */
261
+ function assertBuyerAssetCapacity(params, { requiredUnits, minBuyerPrice, }) {
211
262
  if (params.side === "buy" && params.target.type === "units") {
212
263
  // Every unit costs at least the cheapest live price, and the fee is grossed up on top.
213
264
  const minCost = MathLib.mulDivDown(requiredUnits, minBuyerPrice, MathLib.WAD);
214
- const minPull = grossFromNetAssets({ netAssets: minCost, referralFeePct });
265
+ const minPull = grossFromNetAssets({
266
+ netAssets: minCost,
267
+ referralFeePct: params.referralFeePct,
268
+ });
215
269
  if (params.target.maxBuyerAssets < minPull) {
216
270
  throw new MidnightTakeTargetUnreachableError({
217
271
  field: "target.maxBuyerAssets",
@@ -220,7 +274,4 @@ export const validateMidnightTakeFeasibility = (params) => {
220
274
  });
221
275
  }
222
276
  }
223
- return removed.size === 0
224
- ? params.takeableOffers
225
- : params.takeableOffers.filter((_, index) => !removed.has(index));
226
- };
277
+ }
@@ -201,25 +201,7 @@ export function computeVaultV2ForceWithdrawPlan(params) {
201
201
  if (liquidityMarketId != null && drainedFromLiquidityMarket > 0n) {
202
202
  availableByMarket.set(liquidityMarketId, MathLib.zeroFloorSub(liquidityCapacity, drainedFromLiquidityMarket));
203
203
  }
204
- let coveredAssets = 0n;
205
- const nonEmpty = [];
206
- for (const available of availableByMarket.values()) {
207
- if (available <= 0n)
208
- continue;
209
- coveredAssets += available;
210
- nonEmpty.push(available);
211
- }
212
- // `maxExitAssets` must not depend on the requested amount. At the ceiling the penalty-free leg
213
- // always drains the liquidity market completely, so that market contributes nothing to the
214
- // force-deallocation loop — whereas a small request leaves part of it, which would overstate the
215
- // ceiling for callers using it to cap an input.
216
- let saturatedCoveredAssets = 0n;
217
- for (const [marketId, available] of availableByMarket) {
218
- if (marketId === liquidityMarketId)
219
- continue;
220
- if (available > 0n)
221
- saturatedCoveredAssets += available;
222
- }
204
+ const { coveredAssets, nonEmpty, saturatedCoveredAssets } = summarizeMarketCoverage(availableByMarket, liquidityMarketId);
223
205
  // Worst-case leg count is the ascending walk: the most markets the loop can touch is the number
224
206
  // of smallest positions that together reach `assetsToDeallocate`. Deliberately an upper bound, not
225
207
  // a replay of the contract's prefetched `marketIds` order (where an earlier market may cover the
@@ -232,7 +214,13 @@ export function computeVaultV2ForceWithdrawPlan(params) {
232
214
  // coverage of the snapshot-vs-execution divergence.
233
215
  let penaltyLegs = 0;
234
216
  let remaining = assetsToDeallocate;
235
- for (const available of nonEmpty.toSorted((a, b) => a === b ? 0 : a > b ? 1 : -1)) {
217
+ for (const available of nonEmpty.toSorted((a, b) => {
218
+ if (a === b)
219
+ return 0;
220
+ if (a > b)
221
+ return 1;
222
+ return -1;
223
+ })) {
236
224
  if (remaining <= 0n)
237
225
  break;
238
226
  penaltyLegs += 1;
@@ -428,3 +416,26 @@ export function computeVaultV2ForceWithdrawMinSharesBurnt(params) {
428
416
  return vaultData.toShares(MathLib.min(plan.withdrawnAssets +
429
417
  MathLib.wMulUp(plan.assetsToDeallocate, plan.penalty), MathLib.zeroFloorSub(plan.exitAssets, 1n)), "Down");
430
418
  }
419
+ /** Sums usable market liquidity and the ceiling's non-liquidity-market coverage. @internal */
420
+ function summarizeMarketCoverage(availableByMarket, liquidityMarketId) {
421
+ let coveredAssets = 0n;
422
+ const nonEmpty = [];
423
+ for (const available of availableByMarket.values()) {
424
+ if (available <= 0n)
425
+ continue;
426
+ coveredAssets += available;
427
+ nonEmpty.push(available);
428
+ }
429
+ // `maxExitAssets` must not depend on the requested amount. At the ceiling the penalty-free leg
430
+ // always drains the liquidity market completely, so that market contributes nothing to the
431
+ // force-deallocation loop — whereas a small request leaves part of it, which would overstate the
432
+ // ceiling for callers using it to cap an input.
433
+ let saturatedCoveredAssets = 0n;
434
+ for (const [marketId, available] of availableByMarket) {
435
+ if (marketId === liquidityMarketId)
436
+ continue;
437
+ if (available > 0n)
438
+ saturatedCoveredAssets += available;
439
+ }
440
+ return { coveredAssets, nonEmpty, saturatedCoveredAssets };
441
+ }
@@ -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/esm/index.js CHANGED
@@ -5,3 +5,4 @@ export * from "./entities/requirements/index.js";
5
5
  export * from "./helpers/index.js";
6
6
  export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, parseTransactionPlan, prepareVaultV2Deposit, prepareVaultV2Withdraw, serializeTransactionPlan, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./transactionPlan/index.js";
7
7
  export * from "./types/index.js";
8
+ export { version } from "./version.js";
@@ -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 +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";
@@ -60,6 +60,8 @@ export function applySignatures(plan, signatures) {
60
60
  return plan;
61
61
  for (const [id, signature] of updates) {
62
62
  const request = requests.find((candidate) => candidate.id === id);
63
+ if (request === undefined)
64
+ throw new TransactionPlanSignatureMismatchError(id, "reference");
63
65
  const normalized = normalizeBundlesSignature(signature);
64
66
  let recovered;
65
67
  try {
@@ -80,9 +82,10 @@ export function applySignatures(plan, signatures) {
80
82
  }
81
83
  return {
82
84
  ...plan,
83
- signatureRequests: plan.signatureRequests.map((request) => updates.has(request.id)
84
- ? { ...request, signature: updates.get(request.id) }
85
- : request),
85
+ signatureRequests: plan.signatureRequests.map((request) => {
86
+ const signature = updates.get(request.id);
87
+ return signature === undefined ? request : { ...request, signature };
88
+ }),
86
89
  };
87
90
  }
88
91
  /** @internal Lists the signature request IDs a step's action names, in role order. */
@@ -178,13 +178,13 @@ export function parseTransactionPlan(json) {
178
178
  catch (cause) {
179
179
  if (cause instanceof TransactionPlanSignatureMismatchError) {
180
180
  const index = result.signatureRequests.findIndex((request) => request.id === cause.id);
181
- const field = cause.field === "reference"
182
- ? "id"
183
- : cause.field === "value"
184
- ? "args.amount"
185
- : cause.field.startsWith("args.")
186
- ? cause.field
187
- : `typedData.${cause.field}`;
181
+ let field = `typedData.${cause.field}`;
182
+ if (cause.field === "reference")
183
+ field = "id";
184
+ else if (cause.field === "value")
185
+ field = "args.amount";
186
+ else if (cause.field.startsWith("args."))
187
+ field = cause.field;
188
188
  throw new InvalidTransactionPlanError({
189
189
  path: `$.signatureRequests[${index}].${field}`,
190
190
  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
  * ```
@@ -76,14 +76,15 @@ function resolveDepositInputs(params, now) {
76
76
  * @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
77
77
  * @param params.slippageTolerance - Optional WAD-scaled tolerance for the share-price bound; defaults to `DEFAULT_SLIPPAGE_TOLERANCE` and must not exceed `MAX_SLIPPAGE_TOLERANCE`.
78
78
  * @param params.supportSignature - Optional ERC-2612 preference, defaulting to `false`; when enabled, falls back to direct approval if no permit is available.
79
- * @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
79
+ * @param params.now - Reference timestamp in seconds, normally the latest block's `timestamp`; uses the device clock when omitted.
80
+ * @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).
80
81
  * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
81
82
  * @param params.deployless - Optional permission to use deployless aggregation for token permit metadata reads.
82
83
  * @returns A plan with approvals, concrete signature requests and the deposit step.
83
84
  * @throws {ZeroAccountError} when `account` is the zero address.
84
85
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
85
86
  * @throws {NonPositiveInputError} when `expiresAt`, `amount`, net assets or previewed shares are not positive.
86
- * @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
87
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now` (device clock when `now` is omitted).
87
88
  * @throws {NegativeInputError} when `referralFee.bps` or `slippageTolerance` is negative.
88
89
  * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
89
90
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds `MAX_SLIPPAGE_TOLERANCE`.
@@ -106,6 +107,7 @@ function resolveDepositInputs(params, now) {
106
107
  * const plan = await prepareVaultV2Deposit(client, {
107
108
  * vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
108
109
  * vaultData: await fetchAccrualVaultV2(vault, client),
110
+ * now: (await client.getBlock()).timestamp,
109
111
  * });
110
112
  * // Sign the pending requests, verify and attach with applySignatures, then build.
111
113
  * ```
@@ -113,7 +115,7 @@ function resolveDepositInputs(params, now) {
113
115
  */
114
116
  export async function prepareVaultV2Deposit(client, params) {
115
117
  const { vault, chainId, account, amount } = params;
116
- const now = Time.timestamp();
118
+ const now = params.now ?? Time.timestamp();
117
119
  const { intent, native, common, asset, maxSharePrice } = resolveDepositInputs(params, now);
118
120
  const spender = getChainAddress(chainId, "bundles.vaultBundlesV1");
119
121
  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
  * ```
@@ -64,14 +64,15 @@ function resolveWithdrawInputs(params, now) {
64
64
  * @param params.referralFee.bps - Optional integer fee in basis points of the gross amount; defaults to zero and must be below 10,000.
65
65
  * @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
66
66
  * @param params.supportSignature - Optional unlimited share-permit preference, defaulting to `false`; otherwise uses unlimited direct share approval when allowance is insufficient.
67
- * @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
67
+ * @param params.now - Reference timestamp in seconds, normally the latest block's `timestamp`; uses the device clock when omitted.
68
+ * @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).
68
69
  * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
69
70
  * @param params.deployless - Optional shared intent field; unused by withdrawal share-permit reads.
70
71
  * @returns A plan with the withdrawal step and any required share approval or signature request.
71
72
  * @throws {ZeroAccountError} when `account` is the zero address.
72
73
  * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
73
74
  * @throws {NonPositiveInputError} when `expiresAt`, `amount` or the computed required shares are not positive.
74
- * @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
75
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now` (device clock when `now` is omitted).
75
76
  * @throws {NegativeInputError} when `referralFee.bps` is negative.
76
77
  * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
77
78
  * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
@@ -93,6 +94,7 @@ function resolveWithdrawInputs(params, now) {
93
94
  * const plan = await prepareVaultV2Withdraw(client, {
94
95
  * vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
95
96
  * vaultData: await fetchAccrualVaultV2(vault, client),
97
+ * now: (await client.getBlock()).timestamp,
96
98
  * });
97
99
  * // Sign the pending requests, verify and attach with applySignatures, then build.
98
100
  * ```
@@ -100,7 +102,7 @@ function resolveWithdrawInputs(params, now) {
100
102
  */
101
103
  export async function prepareVaultV2Withdraw(client, params) {
102
104
  const { vault, chainId, account, amount } = params;
103
- const now = Time.timestamp();
105
+ const now = params.now ?? Time.timestamp();
104
106
  const { intent, common, requiredShareAllowance } = resolveWithdrawInputs(params, now);
105
107
  const spender = getChainAddress(chainId, "bundles.vaultBundlesV1");
106
108
  const [, , requirements] = await Promise.all([