@morpho-org/morpho-sdk 9.8.0 → 10.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/MIGRATION-v9-to-v10.md +114 -0
  2. package/README.md +5 -1
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +5 -1
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -1
  7. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -1
  8. package/lib/cjs/actions/midnight/cancelAndMake.js +2 -1
  9. package/lib/cjs/actions/midnight/cancelOffers.d.ts +54 -0
  10. package/lib/cjs/actions/midnight/cancelOffers.js +107 -0
  11. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  12. package/lib/cjs/actions/midnight/index.js +1 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  14. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +1 -1
  15. package/lib/cjs/actions/midnight/takeBorrow.d.ts +1 -1
  16. package/lib/cjs/actions/midnight/takeBorrow.js +1 -1
  17. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -1
  18. package/lib/cjs/actions/midnight/takeLend.js +1 -1
  19. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  20. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -1
  21. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +1 -1
  22. package/lib/cjs/actions/midnight/takeWithdraw.js +1 -1
  23. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  25. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  26. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +3 -3
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +3 -2
  31. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  32. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  33. package/lib/cjs/blue/abis.d.ts +1 -1
  34. package/lib/cjs/blue/abis.js +5 -1
  35. package/lib/cjs/blue/entities.d.ts +4 -4
  36. package/lib/cjs/blue/entities.js +3 -1
  37. package/lib/cjs/blue/errors.d.ts +2 -2
  38. package/lib/cjs/blue/errors.js +5 -1
  39. package/lib/cjs/blue/fetch.d.ts +2 -2
  40. package/lib/cjs/blue/fetch.js +3 -1
  41. package/lib/cjs/blue/utils.d.ts +1 -1
  42. package/lib/cjs/blue/utils.js +2 -1
  43. package/lib/cjs/entities/blue/blue.d.ts +34 -28
  44. package/lib/cjs/entities/blue/blue.js +99 -73
  45. package/lib/cjs/entities/index.d.ts +4 -4
  46. package/lib/cjs/entities/index.js +3 -1
  47. package/lib/cjs/entities/midnight/deadline.d.ts +2 -2
  48. package/lib/cjs/entities/midnight/deadline.js +2 -2
  49. package/lib/cjs/entities/midnight/midnight.d.ts +49 -51
  50. package/lib/cjs/entities/midnight/midnight.js +144 -131
  51. package/lib/cjs/entities/midnight/publication.d.ts +2 -0
  52. package/lib/cjs/entities/midnight/publication.js +126 -100
  53. package/lib/cjs/entities/midnight/types.d.ts +4 -4
  54. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  55. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +17 -17
  56. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +3 -4
  57. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +1 -1
  58. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +12 -12
  59. package/lib/cjs/entities/vaultV1/vaultV1.js +83 -57
  60. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +50 -24
  61. package/lib/cjs/entities/vaultV2/vaultV2.js +166 -90
  62. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +17 -2
  63. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1410 -806
  64. package/lib/cjs/errors.d.ts +4 -4
  65. package/lib/cjs/errors.js +7 -5
  66. package/lib/cjs/fetch.d.ts +2 -2
  67. package/lib/cjs/fetch.js +3 -1
  68. package/lib/cjs/helpers/deadShares.js +55 -34
  69. package/lib/cjs/helpers/metadata.d.ts +14 -2
  70. package/lib/cjs/helpers/metadata.js +39 -4
  71. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +34 -22
  72. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +7 -1
  73. package/lib/cjs/helpers/validate.js +76 -61
  74. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +154 -103
  75. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +31 -20
  76. package/lib/cjs/midnight/errors.d.ts +2 -1
  77. package/lib/cjs/midnight/errors.js +5 -4
  78. package/lib/cjs/transactionPlan/plan.js +6 -3
  79. package/lib/cjs/transactionPlan/serde.js +7 -7
  80. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +6 -4
  81. package/lib/cjs/transactionPlan/vaultv2/deposit.js +5 -3
  82. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  83. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +5 -3
  84. package/lib/cjs/types/action.d.ts +26 -2
  85. package/lib/cjs/types/action.js +1 -1
  86. package/lib/cjs/types/error.js +11 -5
  87. package/lib/cjs/types/metadata.d.ts +12 -2
  88. package/lib/cjs/utils.d.ts +2 -2
  89. package/lib/cjs/utils.js +4 -2
  90. package/lib/cjs/version.d.ts +1 -1
  91. package/lib/cjs/version.js +1 -1
  92. package/lib/esm/abis.d.ts +1 -1
  93. package/lib/esm/abis.js +1 -1
  94. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  95. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +1 -1
  96. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -1
  97. package/lib/esm/actions/midnight/cancelAndMake.js +2 -1
  98. package/lib/esm/actions/midnight/cancelOffers.d.ts +54 -0
  99. package/lib/esm/actions/midnight/cancelOffers.js +103 -0
  100. package/lib/esm/actions/midnight/index.d.ts +1 -0
  101. package/lib/esm/actions/midnight/index.js +1 -0
  102. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  103. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +1 -1
  104. package/lib/esm/actions/midnight/takeBorrow.d.ts +1 -1
  105. package/lib/esm/actions/midnight/takeBorrow.js +1 -1
  106. package/lib/esm/actions/midnight/takeLend.d.ts +1 -1
  107. package/lib/esm/actions/midnight/takeLend.js +1 -1
  108. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  109. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -1
  110. package/lib/esm/actions/midnight/takeWithdraw.d.ts +1 -1
  111. package/lib/esm/actions/midnight/takeWithdraw.js +1 -1
  112. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  113. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  114. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  115. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  116. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  117. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +3 -3
  118. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  119. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +3 -2
  120. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  121. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  122. package/lib/esm/blue/abis.d.ts +1 -1
  123. package/lib/esm/blue/abis.js +1 -1
  124. package/lib/esm/blue/entities.d.ts +4 -4
  125. package/lib/esm/blue/entities.js +2 -2
  126. package/lib/esm/blue/errors.d.ts +2 -2
  127. package/lib/esm/blue/errors.js +2 -2
  128. package/lib/esm/blue/fetch.d.ts +2 -2
  129. package/lib/esm/blue/fetch.js +2 -2
  130. package/lib/esm/blue/utils.d.ts +1 -1
  131. package/lib/esm/blue/utils.js +1 -1
  132. package/lib/esm/entities/blue/blue.d.ts +34 -28
  133. package/lib/esm/entities/blue/blue.js +99 -73
  134. package/lib/esm/entities/index.d.ts +4 -4
  135. package/lib/esm/entities/index.js +2 -2
  136. package/lib/esm/entities/midnight/deadline.d.ts +2 -2
  137. package/lib/esm/entities/midnight/deadline.js +2 -2
  138. package/lib/esm/entities/midnight/midnight.d.ts +49 -51
  139. package/lib/esm/entities/midnight/midnight.js +145 -132
  140. package/lib/esm/entities/midnight/publication.d.ts +2 -0
  141. package/lib/esm/entities/midnight/publication.js +126 -100
  142. package/lib/esm/entities/midnight/types.d.ts +4 -4
  143. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  144. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +17 -17
  145. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +3 -4
  146. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +1 -1
  147. package/lib/esm/entities/vaultV1/vaultV1.d.ts +12 -12
  148. package/lib/esm/entities/vaultV1/vaultV1.js +83 -57
  149. package/lib/esm/entities/vaultV2/vaultV2.d.ts +50 -24
  150. package/lib/esm/entities/vaultV2/vaultV2.js +166 -90
  151. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +17 -2
  152. package/lib/esm/entities/vaultV2BlueReallocationData.js +1410 -806
  153. package/lib/esm/errors.d.ts +4 -4
  154. package/lib/esm/errors.js +4 -4
  155. package/lib/esm/fetch.d.ts +2 -2
  156. package/lib/esm/fetch.js +2 -2
  157. package/lib/esm/helpers/deadShares.js +56 -35
  158. package/lib/esm/helpers/metadata.d.ts +14 -2
  159. package/lib/esm/helpers/metadata.js +38 -4
  160. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +34 -22
  161. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +7 -1
  162. package/lib/esm/helpers/validate.js +76 -61
  163. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +153 -102
  164. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +31 -20
  165. package/lib/esm/midnight/errors.d.ts +2 -1
  166. package/lib/esm/midnight/errors.js +2 -1
  167. package/lib/esm/transactionPlan/plan.js +6 -3
  168. package/lib/esm/transactionPlan/serde.js +7 -7
  169. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +6 -4
  170. package/lib/esm/transactionPlan/vaultv2/deposit.js +5 -3
  171. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  172. package/lib/esm/transactionPlan/vaultv2/withdraw.js +5 -3
  173. package/lib/esm/types/action.d.ts +26 -2
  174. package/lib/esm/types/action.js +1 -1
  175. package/lib/esm/types/error.js +11 -5
  176. package/lib/esm/types/metadata.d.ts +12 -2
  177. package/lib/esm/utils.d.ts +2 -2
  178. package/lib/esm/utils.js +2 -2
  179. package/lib/esm/version.d.ts +1 -1
  180. package/lib/esm/version.js +1 -1
  181. package/package.json +8 -7
@@ -7,11 +7,58 @@ import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundl
7
7
  import { encodeErc20Approval, encodeVaultSharesPermit, vaultV1Deposit, vaultV1InKindRedeem, vaultV1MigrateToV2, vaultV1Redeem, vaultV1Withdraw, } from "../../actions/index.js";
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
10
+ import { resolveTransactionMetadata } from "../../helpers/metadata.js";
10
11
  import { validateDeadline, validateNativeVaultAsset, validateUint256Field, } from "../../helpers/validate.js";
11
12
  import { AmountAndSharesExclusiveError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, SameVaultMigrationError, VaultAddressMismatchError, VaultAssetMismatchError, VaultIsBlueFeeRecipientError, VaultMorphoMismatchError, } from "../../types/index.js";
12
13
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
13
14
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
14
15
  import { getBundlesTokenRequirements } from "../requirements/index.js";
16
+ function validateInKindCoverage({ amount, marketParamsListSnapshot, vaultData, now, }) {
17
+ let covered = 0n;
18
+ const assignedByMarket = new Map();
19
+ for (const marketParams of marketParamsListSnapshot) {
20
+ if (covered === amount)
21
+ break;
22
+ const marketId = MarketUtils.getMarketId(marketParams);
23
+ const allocation = vaultData.allocations.get(marketId);
24
+ if (allocation?.config.enabled !== true)
25
+ continue;
26
+ if (allocation.position.supplyShares === 0n)
27
+ continue;
28
+ const market = allocation.position.market.accrueInterest(now);
29
+ const available = market.toSupplyAssets(allocation.position.supplyShares);
30
+ const assigned = assignedByMarket.get(marketId) ?? 0n;
31
+ const chunk = MathLib.min(available, amount - covered);
32
+ if (assigned + chunk > available) {
33
+ throw new InKindRedeemCoverageError({
34
+ required: amount,
35
+ covered,
36
+ maxExitAssets: covered,
37
+ });
38
+ }
39
+ assignedByMarket.set(marketId, assigned + chunk);
40
+ covered += chunk;
41
+ }
42
+ if (covered < amount) {
43
+ throw new InKindRedeemCoverageError({
44
+ required: amount,
45
+ covered,
46
+ maxExitAssets: covered,
47
+ });
48
+ }
49
+ }
50
+ function getMigrationAmounts(params) {
51
+ const assets = "assets" in params ? params.assets : undefined;
52
+ const shares = "shares" in params ? params.shares : undefined;
53
+ if ((assets == null) === (shares == null)) {
54
+ throw new AmountAndSharesExclusiveError();
55
+ }
56
+ const selectedAmount = assets ?? shares ?? 0n;
57
+ if (selectedAmount <= 0n) {
58
+ throw new NonPositiveInputError(assets != null ? "assets" : "shares", selectedAmount);
59
+ }
60
+ return { assets, shares };
61
+ }
15
62
  /** Binds a viem client to a Vault V1 (MetaMorpho) vault's action builders. */
16
63
  export class MorphoVaultV1 {
17
64
  client;
@@ -48,13 +95,15 @@ export class MorphoVaultV1 {
48
95
  }
49
96
  /** {@inheritDoc VaultV1Actions.deposit} */
50
97
  deposit(params) {
98
+ const suppliedNow = params.now;
99
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
51
100
  const { userAddress, vaultData } = params;
52
101
  const { asset: vaultAsset } = vaultData;
53
102
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
54
103
  if (!isAddressEqual(vaultData.address, this.vault)) {
55
104
  throw new VaultAddressMismatchError(this.vault, vaultData.address);
56
105
  }
57
- const createdAt = Time.timestamp();
106
+ const createdAt = suppliedNow ?? Time.timestamp();
58
107
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
59
108
  if (deadline <= createdAt)
60
109
  throw new ExpiredDeadlineError(deadline, createdAt);
@@ -81,7 +130,7 @@ export class MorphoVaultV1 {
81
130
  let pendingRequirements;
82
131
  return Object.freeze({
83
132
  getRequirements: async (requirementOptions) => {
84
- const now = Time.timestamp();
133
+ const now = suppliedNow ?? Time.timestamp();
85
134
  if (deadline <= now)
86
135
  throw new ExpiredDeadlineError(deadline, now);
87
136
  if (pendingRequirements != null)
@@ -135,12 +184,14 @@ export class MorphoVaultV1 {
135
184
  referralFeeRecipient: common.referralFeeRecipient,
136
185
  deadline,
137
186
  },
138
- metadata: this.client.options.metadata,
187
+ metadata,
139
188
  });
140
189
  },
141
190
  });
142
191
  }
143
192
  withdraw(params) {
193
+ const suppliedNow = params.now;
194
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
144
195
  const { amount, userAddress, vaultData } = params;
145
196
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
146
197
  if (!isAddressEqual(vaultData.address, this.vault)) {
@@ -150,7 +201,7 @@ export class MorphoVaultV1 {
150
201
  throw new NonPositiveInputError("amount", amount);
151
202
  // Reject values outside the ABI range before resolving any requirements.
152
203
  validateUint256Field("amount", amount);
153
- const createdAt = Time.timestamp();
204
+ const createdAt = suppliedNow ?? Time.timestamp();
154
205
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
155
206
  if (deadline <= createdAt)
156
207
  throw new ExpiredDeadlineError(deadline, createdAt);
@@ -171,7 +222,7 @@ export class MorphoVaultV1 {
171
222
  });
172
223
  return Object.freeze({
173
224
  getRequirements: async () => {
174
- const now = Time.timestamp();
225
+ const now = suppliedNow ?? Time.timestamp();
175
226
  if (deadline <= now)
176
227
  throw new ExpiredDeadlineError(deadline, now);
177
228
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
@@ -203,18 +254,20 @@ export class MorphoVaultV1 {
203
254
  referralFeeRecipient: common.referralFeeRecipient,
204
255
  deadline,
205
256
  },
206
- metadata: this.client.options.metadata,
257
+ metadata,
207
258
  });
208
259
  },
209
260
  });
210
261
  }
211
262
  /** {@inheritDoc VaultV1Actions.redeem} */
212
263
  redeem(params) {
264
+ const suppliedNow = params.now;
265
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
213
266
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
214
267
  const { shares, userAddress } = params;
215
268
  if (shares <= 0n)
216
269
  throw new NonPositiveInputError("shares", shares);
217
- const createdAt = Time.timestamp();
270
+ const createdAt = suppliedNow ?? Time.timestamp();
218
271
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
219
272
  if (deadline <= createdAt)
220
273
  throw new ExpiredDeadlineError(deadline, createdAt);
@@ -226,7 +279,7 @@ export class MorphoVaultV1 {
226
279
  const spender = getChainAddress(this.chainId, "bundles.vaultBundlesV1");
227
280
  return Object.freeze({
228
281
  getRequirements: async () => {
229
- const now = Time.timestamp();
282
+ const now = suppliedNow ?? Time.timestamp();
230
283
  if (deadline <= now)
231
284
  throw new ExpiredDeadlineError(deadline, now);
232
285
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
@@ -257,13 +310,16 @@ export class MorphoVaultV1 {
257
310
  referralFeeRecipient: common.referralFeeRecipient,
258
311
  deadline,
259
312
  },
260
- metadata: this.client.options.metadata,
313
+ metadata,
261
314
  });
262
315
  },
263
316
  });
264
317
  }
265
318
  /** {@inheritDoc VaultV1Actions.inKindRedeem} */
266
- inKindRedeem({ amount, marketParamsList, vaultData, userAddress, deadline: deadlineOverride, }) {
319
+ inKindRedeem(params) {
320
+ const suppliedNow = params.now;
321
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
322
+ const { amount, marketParamsList, vaultData, userAddress, deadline: deadlineOverride, } = params;
267
323
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
268
324
  if (!isAddressEqual(vaultData.address, this.vault)) {
269
325
  throw new VaultAddressMismatchError(this.vault, vaultData.address);
@@ -279,7 +335,7 @@ export class MorphoVaultV1 {
279
335
  irm,
280
336
  lltv,
281
337
  }));
282
- const now = Time.timestamp();
338
+ const now = suppliedNow ?? Time.timestamp();
283
339
  const deadline = deadlineOverride ?? now + Time.s.from.h(2n);
284
340
  // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
285
341
  // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
@@ -288,38 +344,13 @@ export class MorphoVaultV1 {
288
344
  throw new ExpiredDeadlineError(deadline, now);
289
345
  const vaultExitBundlesV1 = getChainAddress(this.chainId, "bundles.vaultExitBundlesV1");
290
346
  const blue = getChainAddress(this.chainId, "blue");
291
- let covered = 0n;
292
- const assignedByMarket = new Map();
293
- for (const marketParams of marketParamsListSnapshot) {
294
- if (covered === amount)
295
- break;
296
- const marketId = MarketUtils.getMarketId(marketParams);
297
- const allocation = vaultData.allocations.get(marketId);
298
- if (allocation?.config.enabled !== true)
299
- continue;
300
- if (allocation.position.supplyShares === 0n)
301
- continue;
302
- const market = allocation.position.market.accrueInterest(now);
303
- const available = market.toSupplyAssets(allocation.position.supplyShares);
304
- const assigned = assignedByMarket.get(marketId) ?? 0n;
305
- const chunk = MathLib.min(available, amount - covered);
306
- if (assigned + chunk > available) {
307
- throw new InKindRedeemCoverageError({
308
- required: amount,
309
- covered,
310
- maxExitAssets: covered,
311
- });
312
- }
313
- assignedByMarket.set(marketId, assigned + chunk);
314
- covered += chunk;
315
- }
316
- if (covered < amount) {
317
- throw new InKindRedeemCoverageError({
318
- required: amount,
319
- covered,
320
- maxExitAssets: covered,
321
- });
322
- }
347
+ // Reject insufficient ordered market coverage before preparing share requirements.
348
+ validateInKindCoverage({
349
+ amount,
350
+ marketParamsListSnapshot,
351
+ vaultData,
352
+ now,
353
+ });
323
354
  const requiredShareAllowance = computeVaultMaxShareAllowance({
324
355
  vaultData,
325
356
  deadline: now,
@@ -328,7 +359,7 @@ export class MorphoVaultV1 {
328
359
  });
329
360
  return {
330
361
  getRequirements: async () => {
331
- const requirementsTimestamp = Time.timestamp();
362
+ const requirementsTimestamp = suppliedNow ?? Time.timestamp();
332
363
  if (deadline <= requirementsTimestamp) {
333
364
  throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
334
365
  }
@@ -390,6 +421,7 @@ export class MorphoVaultV1 {
390
421
  if (this.client.options.supportSignature) {
391
422
  return [
392
423
  encodeVaultSharesPermit({
424
+ now: suppliedNow == null ? undefined : now,
393
425
  vault: vaultData,
394
426
  version: "vaultV1",
395
427
  spender: vaultExitBundlesV1,
@@ -424,13 +456,15 @@ export class MorphoVaultV1 {
424
456
  deadline,
425
457
  requirementSignature: permit,
426
458
  },
427
- metadata: this.client.options.metadata,
459
+ metadata,
428
460
  });
429
461
  },
430
462
  };
431
463
  }
432
464
  /** {@inheritDoc VaultV1Actions.migrateToV2} */
433
465
  migrateToV2(params) {
466
+ const suppliedNow = params.now;
467
+ const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
434
468
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
435
469
  if (!isAddressEqual(params.sourceVault.address, this.vault)) {
436
470
  throw new VaultAddressMismatchError(this.vault, params.sourceVault.address);
@@ -441,18 +475,10 @@ export class MorphoVaultV1 {
441
475
  if (isAddressEqual(this.vault, params.targetVault.address)) {
442
476
  throw new SameVaultMigrationError(this.vault);
443
477
  }
444
- const assets = "assets" in params ? params.assets : undefined;
445
- const shares = "shares" in params ? params.shares : undefined;
446
- if ((assets == null) === (shares == null)) {
447
- throw new AmountAndSharesExclusiveError();
448
- }
449
- const selectedAmount = assets ?? shares ?? 0n;
450
- if (selectedAmount <= 0n) {
451
- throw new NonPositiveInputError(assets != null ? "assets" : "shares", selectedAmount);
452
- }
478
+ const { assets, shares } = getMigrationAmounts(params);
453
479
  const slippageTolerance = params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE;
454
480
  validateSlippageTolerance(slippageTolerance);
455
- const createdAt = Time.timestamp();
481
+ const createdAt = suppliedNow ?? Time.timestamp();
456
482
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
457
483
  if (deadline <= createdAt)
458
484
  throw new ExpiredDeadlineError(deadline, createdAt);
@@ -501,7 +527,7 @@ export class MorphoVaultV1 {
501
527
  });
502
528
  return Object.freeze({
503
529
  getRequirements: async () => {
504
- const now = Time.timestamp();
530
+ const now = suppliedNow ?? Time.timestamp();
505
531
  if (deadline <= now)
506
532
  throw new ExpiredDeadlineError(deadline, now);
507
533
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
@@ -540,7 +566,7 @@ export class MorphoVaultV1 {
540
566
  referralFeeRecipient: common.referralFeeRecipient,
541
567
  deadline,
542
568
  },
543
- metadata: this.client.options.metadata,
569
+ metadata,
544
570
  });
545
571
  },
546
572
  });
@@ -2,7 +2,7 @@ import { type AccrualVaultV2, MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
3
  import { type Address } from "viem";
4
4
  import type { FetchParameters } from "../../types/data.js";
5
- import { type ActionOutput, type ActionRequirement, type BundlesFundingArgs, type BundlesTokenRequirementsOptions, type Deallocation, type MorphoClientType, type RequirementSignature, type Transaction, type VaultV2DepositAction, type VaultV2ForceRedeemAction, type VaultV2ForceWithdrawAction, type VaultV2InKindRedeemAction, type VaultV2RedeemAction, type VaultV2WithdrawAction } from "../../types/index.js";
5
+ import { type ActionOutput, type ActionRequirement, type BundlesFundingArgs, type BundlesTokenRequirementsOptions, type Deallocation, type MorphoClientType, type ReferenceTimestampParams, type RequirementSignature, type Transaction, type VaultV2DepositAction, type VaultV2ForceRedeemAction, type VaultV2ForceWithdrawAction, type VaultV2InKindRedeemAction, type VaultV2RedeemAction, type VaultV2WithdrawAction } from "../../types/index.js";
6
6
  /**
7
7
  * Action surface for Vault V2 reads and writes; writes route through VaultBundlesV1 and
8
8
  * VaultExitBundlesV1, except `forceRedeem`, which uses the vault's native multicall.
@@ -65,7 +65,9 @@ export interface VaultV2Actions {
65
65
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
66
66
  * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
67
67
  * @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a non-wNative vault.
68
- * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256.
68
+ * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or when the vault's
69
+ * liquidity adapter is a Midnight adapter (it cannot receive vault allocations, so no deposit
70
+ * fits and `max` is `0n`).
69
71
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
70
72
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
71
73
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -113,7 +115,7 @@ export interface VaultV2Actions {
113
115
  readonly referralFeePct?: bigint;
114
116
  readonly referralFeeRecipient?: Address;
115
117
  readonly deadline?: bigint;
116
- } & BundlesFundingArgs) => ActionOutput<VaultV2DepositAction, readonly RequirementSignature[], BundlesTokenRequirementsOptions>;
118
+ } & ReferenceTimestampParams & BundlesFundingArgs) => ActionOutput<VaultV2DepositAction, readonly RequirementSignature[], BundlesTokenRequirementsOptions>;
117
119
  /**
118
120
  * Prepares an exact-assets Vault V2 withdrawal through VaultBundlesV1.
119
121
  *
@@ -147,7 +149,9 @@ export interface VaultV2Actions {
147
149
  * @throws {NonPositiveInputError} when `amount` or the computed required share amount is not positive.
148
150
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
149
151
  * at any `getRequirements()` call.
150
- * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
152
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation,
153
+ * or when the vault's liquidity adapter is a Midnight adapter and `amount` exceeds the vault's
154
+ * idle assets plus what the adapter can withdraw from the liquidity market.
151
155
  * @throws {NegativeInputError} when `referralFeePct` or `slippageTolerance` is negative.
152
156
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
153
157
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
@@ -192,7 +196,7 @@ export interface VaultV2Actions {
192
196
  readonly referralFeePct?: bigint;
193
197
  readonly referralFeeRecipient?: Address;
194
198
  readonly deadline?: bigint;
195
- }) => ActionOutput<VaultV2WithdrawAction, readonly RequirementSignature[], undefined>;
199
+ } & ReferenceTimestampParams) => ActionOutput<VaultV2WithdrawAction, readonly RequirementSignature[], undefined>;
196
200
  /**
197
201
  * Prepares an exact-shares Vault V2 redemption through VaultBundlesV1.
198
202
  *
@@ -213,7 +217,25 @@ export interface VaultV2Actions {
213
217
  * @throws {NonPositiveInputError} when `shares` is not positive.
214
218
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
215
219
  * requirement resolution.
216
- * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
220
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256, or from
221
+ * `getRequirements()` when the vault's liquidity adapter is a Midnight adapter and `shares`
222
+ * are worth more than the vault's idle assets plus what the adapter can withdraw from the
223
+ * liquidity market.
224
+ * @throws {UnknownBlueFactory} from `getRequirements()` when the configured chain has no VaultV2 factory.
225
+ * @throws {UnknownBlueOfFactory} from `getRequirements()` when the vault is not a VaultV2 from the
226
+ * configured factory.
227
+ * @throws {UnsupportedBlueVaultV2AdapterError} from `getRequirements()` when the vault or one of its
228
+ * adapters uses an unsupported adapter class.
229
+ * @throws {UnsupportedBlueMarketIrmError} from `getRequirements()` when the vault's liquidity adapter
230
+ * is a Midnight adapter and accrual projects an underlying market with positive debt that uses an
231
+ * unsupported IRM.
232
+ * @throws {UnknownBlueMarketAllocationError} from `getRequirements()` when the vault's liquidity
233
+ * adapter is a Midnight adapter and accrual meets a nested Vault V1 withdraw queue market without
234
+ * allocation data.
235
+ * @throws {InvalidMidnightPositionLossFactorError} from `getRequirements()` when the vault's liquidity
236
+ * adapter is a Midnight adapter and accrual meets a market loss factor below a position's.
237
+ * @throws {InvalidMidnightPositionAccrualStateError} from `getRequirements()` when the vault's
238
+ * liquidity adapter is a Midnight adapter and accrual meets invalid Midnight position inputs.
217
239
  * @throws {NegativeInputError} when `referralFeePct` is negative.
218
240
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
219
241
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -221,7 +243,7 @@ export interface VaultV2Actions {
221
243
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
222
244
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
223
245
  * contract has no code at its registered address.
224
- * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, `eth_chainId`, or
246
+ * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance, nonce, `eth_chainId`, or
225
247
  * `eth_getCode` read fails.
226
248
  * @throws {UnknownTokenError} from `getRequirements()` when the share token fetched by
227
249
  * `getData()` has unusable decimals.
@@ -257,7 +279,7 @@ export interface VaultV2Actions {
257
279
  readonly referralFeePct?: bigint;
258
280
  readonly referralFeeRecipient?: Address;
259
281
  readonly deadline?: bigint;
260
- }) => ActionOutput<VaultV2RedeemAction, readonly RequirementSignature[], undefined>;
282
+ } & ReferenceTimestampParams) => ActionOutput<VaultV2RedeemAction, readonly RequirementSignature[], undefined>;
261
283
  /**
262
284
  * Prepares an illiquid Vault V2 exit into idle assets and Morpho Blue supply positions.
263
285
  *
@@ -299,9 +321,11 @@ export interface VaultV2Actions {
299
321
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
300
322
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
301
323
  * requirement resolution.
302
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter.
324
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter, including
325
+ * a vault that mixes Blue and Midnight adapters.
303
326
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
304
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
327
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
328
+ * including a Midnight adapter.
305
329
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
306
330
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
307
331
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
@@ -346,7 +370,7 @@ export interface VaultV2Actions {
346
370
  readonly userAddress: Address;
347
371
  readonly adapter?: Address;
348
372
  readonly deadline?: bigint;
349
- }) => ActionOutput<VaultV2InKindRedeemAction, readonly RequirementSignature[], undefined>;
373
+ } & ReferenceTimestampParams) => ActionOutput<VaultV2InKindRedeemAction, readonly RequirementSignature[], undefined>;
350
374
  /**
351
375
  * Prepares a Vault V2 force withdrawal through VaultExitBundlesV1.
352
376
  *
@@ -426,9 +450,11 @@ export interface VaultV2Actions {
426
450
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
427
451
  * requirement resolution.
428
452
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
429
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter.
453
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter,
454
+ * including a vault that mixes Blue and Midnight adapters.
430
455
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
431
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
456
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
457
+ * including a Midnight adapter.
432
458
  * @throws {VaultV2UnsupportedLiquidityAdapterError} when the vault routes liquidity through
433
459
  * another adapter.
434
460
  * @throws {VaultV2UndecodableLiquidityDataError} when the vault's `liquidityData` does not decode
@@ -488,7 +514,7 @@ export interface VaultV2Actions {
488
514
  readonly minSharePriceE27?: bigint;
489
515
  readonly referralFeePct?: bigint;
490
516
  readonly referralFeeRecipient?: Address;
491
- }) => ActionOutput<VaultV2ForceWithdrawAction, readonly RequirementSignature[], undefined>;
517
+ } & ReferenceTimestampParams) => ActionOutput<VaultV2ForceWithdrawAction, readonly RequirementSignature[], undefined>;
492
518
  /**
493
519
  * Prepares a force redeem transaction for the VaultV2 contract using the vault's native multicall.
494
520
  *
@@ -533,7 +559,7 @@ export interface VaultV2Actions {
533
559
  shares: bigint;
534
560
  };
535
561
  userAddress: Address;
536
- }) => {
562
+ } & ReferenceTimestampParams) => {
537
563
  buildTx: () => Readonly<Transaction<VaultV2ForceRedeemAction>>;
538
564
  };
539
565
  }
@@ -561,7 +587,7 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
561
587
  readonly referralFeePct?: bigint;
562
588
  readonly referralFeeRecipient?: Address;
563
589
  readonly deadline?: bigint;
564
- } & BundlesFundingArgs): Readonly<{
590
+ } & ReferenceTimestampParams & BundlesFundingArgs): Readonly<{
565
591
  getRequirements: (requirementOptions?: BundlesTokenRequirementsOptions) => Promise<readonly ActionRequirement[]>;
566
592
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<VaultV2DepositAction>>;
567
593
  }>;
@@ -573,7 +599,7 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
573
599
  readonly referralFeePct?: bigint;
574
600
  readonly referralFeeRecipient?: Address;
575
601
  readonly deadline?: bigint;
576
- }): Readonly<{
602
+ } & ReferenceTimestampParams): Readonly<{
577
603
  getRequirements: () => Promise<readonly (Readonly<Transaction<import("../../types/action.js").ERC20ApprovalAction>> | import("../../types/action.js").Requirement<import("../../types/action.js").Erc2612RequirementSignature, undefined>)[]>;
578
604
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<VaultV2WithdrawAction>>;
579
605
  }>;
@@ -584,21 +610,21 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
584
610
  readonly referralFeePct?: bigint;
585
611
  readonly referralFeeRecipient?: Address;
586
612
  readonly deadline?: bigint;
587
- }): Readonly<{
613
+ } & ReferenceTimestampParams): Readonly<{
588
614
  getRequirements: () => Promise<readonly (Readonly<Transaction<import("../../types/action.js").ERC20ApprovalAction>> | import("../../types/action.js").Requirement<import("../../types/action.js").Erc2612RequirementSignature, undefined>)[]>;
589
615
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<VaultV2RedeemAction>>;
590
616
  }>;
591
617
  /** {@inheritDoc VaultV2Actions.inKindRedeem} */
592
- inKindRedeem({ amount, marketParamsList, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, }: {
618
+ inKindRedeem(params: {
593
619
  readonly amount: bigint;
594
620
  readonly marketParamsList: readonly MarketParams[];
595
621
  readonly vaultData: AccrualVaultV2;
596
622
  readonly userAddress: Address;
597
623
  readonly adapter?: Address;
598
624
  readonly deadline?: bigint;
599
- }): ActionOutput<VaultV2InKindRedeemAction, readonly RequirementSignature[], undefined>;
625
+ } & ReferenceTimestampParams): ActionOutput<VaultV2InKindRedeemAction, readonly RequirementSignature[], undefined>;
600
626
  /** {@inheritDoc VaultV2Actions.forceWithdraw} */
601
- forceWithdraw({ exitAssets, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, slippageTolerance, minSharePriceE27: minSharePriceE27Override, referralFeePct, referralFeeRecipient, }: {
627
+ forceWithdraw(params: {
602
628
  readonly exitAssets: bigint;
603
629
  readonly vaultData: AccrualVaultV2;
604
630
  readonly userAddress: Address;
@@ -608,14 +634,14 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
608
634
  readonly minSharePriceE27?: bigint;
609
635
  readonly referralFeePct?: bigint;
610
636
  readonly referralFeeRecipient?: Address;
611
- }): ActionOutput<VaultV2ForceWithdrawAction, readonly RequirementSignature[], undefined>;
612
- forceRedeem({ deallocations, redeem, userAddress, }: {
637
+ } & ReferenceTimestampParams): ActionOutput<VaultV2ForceWithdrawAction, readonly RequirementSignature[], undefined>;
638
+ forceRedeem(params: {
613
639
  deallocations: readonly Deallocation[];
614
640
  redeem: {
615
641
  shares: bigint;
616
642
  };
617
643
  userAddress: Address;
618
- }): {
644
+ } & ReferenceTimestampParams): {
619
645
  buildTx: () => Readonly<Transaction<VaultV2ForceRedeemAction>>;
620
646
  };
621
647
  }