@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
@@ -10,6 +10,7 @@ const common_js_1 = require("../../actions/bundles/common.js");
10
10
  const index_js_1 = require("../../actions/index.js");
11
11
  const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
12
12
  const index_js_2 = require("../../helpers/index.js");
13
+ const metadata_js_1 = require("../../helpers/metadata.js");
13
14
  const validate_js_1 = require("../../helpers/validate.js");
14
15
  const index_js_3 = require("../../types/index.js");
15
16
  const assertContractCode_js_1 = require("../requirements/assertContractCode.js");
@@ -18,6 +19,90 @@ const index_js_4 = require("../requirements/index.js");
18
19
  // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
19
20
  // accrual model stays well-defined inside it.
20
21
  const VAULT_V2_FEE_PROJECTION_HORIZON = morpho_ts_1.Time.s.from.y(1n);
22
+ function getInKindShareAllowance({ soleAdapter, marketParamsListSnapshot, marketIdListSnapshot, vaultData, now, deadline, idleAssets, assetsToDeallocate, penalty, }) {
23
+ const assetsByMarket = new Map(soleAdapter.markets
24
+ .filter((market) => (soleAdapter.supplyShares[market.id] ?? 0n) !== 0n)
25
+ .map((market) => [
26
+ market.id,
27
+ market
28
+ .accrueInterest(now)
29
+ .toSupplyAssets(soleAdapter.supplyShares[market.id] ?? 0n),
30
+ ]));
31
+ const uniqueMarketIds = new Set(marketIdListSnapshot);
32
+ let covered = 0n;
33
+ for (const id of uniqueMarketIds)
34
+ covered += assetsByMarket.get(id) ?? 0n;
35
+ if (covered < assetsToDeallocate) {
36
+ const maxExitAssets = covered === 0n
37
+ ? idleAssets
38
+ : idleAssets + blue_sdk_1.MathLib.wMulUp(covered + 1n, blue_sdk_1.MathLib.WAD + penalty) - 1n;
39
+ throw new index_js_3.InKindRedeemCoverageError({
40
+ required: assetsToDeallocate,
41
+ covered,
42
+ maxExitAssets,
43
+ });
44
+ }
45
+ let remaining = assetsToDeallocate;
46
+ let peak = 0n;
47
+ const consumedMarketIds = new Set();
48
+ const { vault: allowanceVault } = vaultData.accrueInterest(deadline);
49
+ // Interest can lower the burn, while management fees can raise it; bound both endpoints.
50
+ const previewAllowance = (assets) => blue_sdk_1.MathLib.max(vaultData.toShares(assets, "Up"), allowanceVault.toShares(assets, "Up"));
51
+ let requiredShareAllowance = previewAllowance(BigInt(marketParamsListSnapshot.length));
52
+ // Pre-burn previews upper-bound each separately rounded idle, penalty, and main burn.
53
+ requiredShareAllowance += previewAllowance(idleAssets);
54
+ for (const id of marketIdListSnapshot) {
55
+ const available = consumedMarketIds.has(id)
56
+ ? 0n
57
+ : (assetsByMarket.get(id) ?? 0n);
58
+ consumedMarketIds.add(id);
59
+ const chunk = blue_sdk_1.MathLib.min(available, remaining);
60
+ peak = blue_sdk_1.MathLib.max(peak, chunk);
61
+ requiredShareAllowance += previewAllowance(blue_sdk_1.MathLib.wMulUp(chunk, penalty));
62
+ requiredShareAllowance += previewAllowance(chunk);
63
+ remaining -= chunk;
64
+ }
65
+ return { peak, requiredShareAllowance };
66
+ }
67
+ function getForceWithdrawSharePrice({ minSharePriceE27Override, withdrawnAssets, sharesBurntForFloor, slippageTolerance, }) {
68
+ if (minSharePriceE27Override != null) {
69
+ // The maximum-slippage threshold only bounds the override; unlike the transaction floor it
70
+ // may round to zero, in which case every positive override is acceptable.
71
+ const minAllowedSharePriceE27 = (0, morpho_ts_1._try)(() => (0, index_js_2.computeMinForceWithdrawSharePrice)({
72
+ withdrawnAssets: withdrawnAssets,
73
+ sharesBurnt: sharesBurntForFloor,
74
+ slippageTolerance: index_js_2.MAX_SLIPPAGE_TOLERANCE,
75
+ }), index_js_3.VaultV2ForceWithdrawZeroSharePriceError) ?? 1n;
76
+ if (minSharePriceE27Override < minAllowedSharePriceE27) {
77
+ throw new index_js_3.VaultV2ForceWithdrawSharePriceBelowFloorError({
78
+ minSharePriceE27: minSharePriceE27Override,
79
+ floorE27: minAllowedSharePriceE27,
80
+ });
81
+ }
82
+ }
83
+ const minSharePriceE27 = minSharePriceE27Override ??
84
+ (0, index_js_2.computeMinForceWithdrawSharePrice)({
85
+ withdrawnAssets: withdrawnAssets,
86
+ sharesBurnt: sharesBurntForFloor,
87
+ slippageTolerance,
88
+ });
89
+ // The floor is deliberately *not* capped at `MAX_ABSOLUTE_SHARE_PRICE` (100 assets/share):
90
+ // lowering a lower bound weakens it, so any vault whose share price grew past that would be left
91
+ // with no real protection. Its two sibling `computeMin*SharePrice` helpers cap nothing either —
92
+ // only the `computeMax*` ones do, where capping relaxes an upper bound and is safe.
93
+ (0, validate_js_1.validateUint256Field)("minSharePriceE27", minSharePriceE27);
94
+ return minSharePriceE27;
95
+ }
96
+ /**
97
+ * Midnight adapters revert vault-initiated `allocate` (`SelfAllocationOnly`), so a vault routing
98
+ * liquidity through one accepts no deposit. Exits are served from idle assets plus what the adapter's
99
+ * `withdrawToVault` path can withdraw from the liquidity market.
100
+ */
101
+ const isMidnightLiquidityAdapter = (vaultData) => vaultData.accrualLiquidityAdapter?.type === "VaultV2MidnightAdapter";
102
+ /** Idle assets plus what the Midnight liquidity adapter can withdraw to the vault onchain. */
103
+ const midnightWithdrawLiquidity = (vaultData) => vaultData.assetBalance +
104
+ (vaultData.accrualLiquidityAdapter?.maxWithdraw(vaultData.liquidityData)
105
+ .value ?? 0n);
21
106
  /** Binds a viem client to a Vault V2 vault's action builders. */
22
107
  class MorphoVaultV2 {
23
108
  client;
@@ -54,13 +139,15 @@ class MorphoVaultV2 {
54
139
  }
55
140
  /** {@inheritDoc VaultV2Actions.deposit} */
56
141
  deposit(params) {
142
+ const suppliedNow = params.now;
143
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, suppliedNow);
57
144
  const { userAddress, vaultData } = params;
58
145
  const { asset: vaultAsset } = vaultData;
59
146
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
60
147
  if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
61
148
  throw new index_js_3.VaultAddressMismatchError(this.vault, vaultData.address);
62
149
  }
63
- const createdAt = morpho_ts_1.Time.timestamp();
150
+ const createdAt = suppliedNow ?? morpho_ts_1.Time.timestamp();
64
151
  const deadline = params.deadline ?? createdAt + morpho_ts_1.Time.s.from.h(2n);
65
152
  if (deadline <= createdAt)
66
153
  throw new index_js_3.ExpiredDeadlineError(deadline, createdAt);
@@ -76,6 +163,13 @@ class MorphoVaultV2 {
76
163
  // The native path must target the chain's registered wrapped-native asset.
77
164
  (0, validate_js_1.validateNativeVaultAsset)(this.chainId, vaultAsset);
78
165
  }
166
+ if (isMidnightLiquidityAdapter(vaultData)) {
167
+ throw new index_js_3.InputExceedsMaxError({
168
+ field: funding.value > 0n ? "nativeAmount" : "amount",
169
+ value: funding.assets,
170
+ max: 0n,
171
+ });
172
+ }
79
173
  const referralFeeAssets = (0, common_js_1.getBundlesReferralFeeAssets)(funding.assets, common.referralFeePct);
80
174
  const maxSharePrice = (0, index_js_2.computeVaultMaxSharePrice)({
81
175
  vaultData,
@@ -87,7 +181,7 @@ class MorphoVaultV2 {
87
181
  let pendingRequirements;
88
182
  return Object.freeze({
89
183
  getRequirements: async (requirementOptions) => {
90
- const now = morpho_ts_1.Time.timestamp();
184
+ const now = suppliedNow ?? morpho_ts_1.Time.timestamp();
91
185
  if (deadline <= now)
92
186
  throw new index_js_3.ExpiredDeadlineError(deadline, now);
93
187
  if (pendingRequirements != null)
@@ -141,12 +235,14 @@ class MorphoVaultV2 {
141
235
  referralFeeRecipient: common.referralFeeRecipient,
142
236
  deadline,
143
237
  },
144
- metadata: this.client.options.metadata,
238
+ metadata,
145
239
  });
146
240
  },
147
241
  });
148
242
  }
149
243
  withdraw(params) {
244
+ const suppliedNow = params.now;
245
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, suppliedNow);
150
246
  const { amount, userAddress, vaultData } = params;
151
247
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
152
248
  if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
@@ -156,7 +252,15 @@ class MorphoVaultV2 {
156
252
  throw new index_js_3.NonPositiveInputError("amount", amount);
157
253
  // Reject values outside the ABI range before resolving any requirements.
158
254
  (0, validate_js_1.validateUint256Field)("amount", amount);
159
- const createdAt = morpho_ts_1.Time.timestamp();
255
+ if (isMidnightLiquidityAdapter(vaultData) &&
256
+ amount > midnightWithdrawLiquidity(vaultData)) {
257
+ throw new index_js_3.InputExceedsMaxError({
258
+ field: "amount",
259
+ value: amount,
260
+ max: midnightWithdrawLiquidity(vaultData),
261
+ });
262
+ }
263
+ const createdAt = suppliedNow ?? morpho_ts_1.Time.timestamp();
160
264
  const deadline = params.deadline ?? createdAt + morpho_ts_1.Time.s.from.h(2n);
161
265
  if (deadline <= createdAt)
162
266
  throw new index_js_3.ExpiredDeadlineError(deadline, createdAt);
@@ -177,7 +281,7 @@ class MorphoVaultV2 {
177
281
  });
178
282
  return Object.freeze({
179
283
  getRequirements: async () => {
180
- const now = morpho_ts_1.Time.timestamp();
284
+ const now = suppliedNow ?? morpho_ts_1.Time.timestamp();
181
285
  if (deadline <= now)
182
286
  throw new index_js_3.ExpiredDeadlineError(deadline, now);
183
287
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
@@ -209,18 +313,20 @@ class MorphoVaultV2 {
209
313
  referralFeeRecipient: common.referralFeeRecipient,
210
314
  deadline,
211
315
  },
212
- metadata: this.client.options.metadata,
316
+ metadata,
213
317
  });
214
318
  },
215
319
  });
216
320
  }
217
321
  /** {@inheritDoc VaultV2Actions.redeem} */
218
322
  redeem(params) {
323
+ const suppliedNow = params.now;
324
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, suppliedNow);
219
325
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
220
326
  const { shares, userAddress } = params;
221
327
  if (shares <= 0n)
222
328
  throw new index_js_3.NonPositiveInputError("shares", shares);
223
- const createdAt = morpho_ts_1.Time.timestamp();
329
+ const createdAt = suppliedNow ?? morpho_ts_1.Time.timestamp();
224
330
  const deadline = params.deadline ?? createdAt + morpho_ts_1.Time.s.from.h(2n);
225
331
  if (deadline <= createdAt)
226
332
  throw new index_js_3.ExpiredDeadlineError(deadline, createdAt);
@@ -232,12 +338,25 @@ class MorphoVaultV2 {
232
338
  const spender = (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.vaultBundlesV1");
233
339
  return Object.freeze({
234
340
  getRequirements: async () => {
235
- const now = morpho_ts_1.Time.timestamp();
341
+ const now = suppliedNow ?? morpho_ts_1.Time.timestamp();
236
342
  if (deadline <= now)
237
343
  throw new index_js_3.ExpiredDeadlineError(deadline, now);
238
344
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
345
+ const vaultData = await this.getData();
346
+ if (isMidnightLiquidityAdapter(vaultData)) {
347
+ // Onchain redeem accrues interest before converting shares to assets.
348
+ const { vault: accrued } = vaultData.accrueInterest(now);
349
+ const liquidity = midnightWithdrawLiquidity(accrued);
350
+ if (accrued.toAssets(shares) > liquidity) {
351
+ throw new index_js_3.InputExceedsMaxError({
352
+ field: "shares",
353
+ value: shares,
354
+ max: accrued.toShares(liquidity),
355
+ });
356
+ }
357
+ }
239
358
  return (0, getVaultBundlesSharesRequirements_js_1.getVaultBundlesSharesRequirements)(this.client.viemClient, {
240
- vaultData: await this.getData(),
359
+ vaultData,
241
360
  version: "vaultV2",
242
361
  owner: userAddress,
243
362
  chainId: this.chainId,
@@ -263,13 +382,16 @@ class MorphoVaultV2 {
263
382
  referralFeeRecipient: common.referralFeeRecipient,
264
383
  deadline,
265
384
  },
266
- metadata: this.client.options.metadata,
385
+ metadata,
267
386
  });
268
387
  },
269
388
  });
270
389
  }
271
390
  /** {@inheritDoc VaultV2Actions.inKindRedeem} */
272
- inKindRedeem({ amount, marketParamsList, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, }) {
391
+ inKindRedeem(params) {
392
+ const suppliedNow = params.now;
393
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, suppliedNow);
394
+ const { amount, marketParamsList, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, } = params;
273
395
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
274
396
  if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
275
397
  throw new index_js_3.VaultAddressMismatchError(this.vault, vaultData.address);
@@ -284,7 +406,7 @@ class MorphoVaultV2 {
284
406
  lltv,
285
407
  }));
286
408
  const marketIdListSnapshot = marketParamsListSnapshot.map((marketParams) => blue_sdk_1.MarketUtils.getMarketId(marketParams));
287
- const now = morpho_ts_1.Time.timestamp();
409
+ const now = suppliedNow ?? morpho_ts_1.Time.timestamp();
288
410
  const deadline = deadlineOverride ?? now + morpho_ts_1.Time.s.from.h(2n);
289
411
  // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
290
412
  // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
@@ -318,55 +440,22 @@ class MorphoVaultV2 {
318
440
  if (assetsToDeallocate > 0n && marketParamsListSnapshot.length === 0) {
319
441
  throw new index_js_3.EmptyMarketParamsListError();
320
442
  }
321
- const assetsByMarket = new Map(soleAdapter.markets
322
- .filter((market) => (soleAdapter.supplyShares[market.id] ?? 0n) !== 0n)
323
- .map((market) => [
324
- market.id,
325
- market
326
- .accrueInterest(now)
327
- .toSupplyAssets(soleAdapter.supplyShares[market.id] ?? 0n),
328
- ]));
329
- const uniqueMarketIds = new Set(marketIdListSnapshot);
330
- let covered = 0n;
331
- for (const id of uniqueMarketIds)
332
- covered += assetsByMarket.get(id) ?? 0n;
333
- if (covered < assetsToDeallocate) {
334
- const maxExitAssets = covered === 0n
335
- ? idleAssets
336
- : idleAssets +
337
- blue_sdk_1.MathLib.wMulUp(covered + 1n, blue_sdk_1.MathLib.WAD + penalty) -
338
- 1n;
339
- throw new index_js_3.InKindRedeemCoverageError({
340
- required: assetsToDeallocate,
341
- covered,
342
- maxExitAssets,
343
- });
344
- }
345
- let remaining = assetsToDeallocate;
346
- let peak = 0n;
347
- const consumedMarketIds = new Set();
348
- const { vault: allowanceVault } = vaultData.accrueInterest(deadline);
349
- // Interest can lower the burn, while management fees can raise it; bound both endpoints.
350
- const previewAllowance = (assets) => blue_sdk_1.MathLib.max(vaultData.toShares(assets, "Up"), allowanceVault.toShares(assets, "Up"));
351
- let requiredShareAllowance = previewAllowance(BigInt(marketParamsListSnapshot.length));
352
- // Pre-burn previews upper-bound each separately rounded idle, penalty, and main burn.
353
- requiredShareAllowance += previewAllowance(idleAssets);
354
- for (const id of marketIdListSnapshot) {
355
- const available = consumedMarketIds.has(id)
356
- ? 0n
357
- : (assetsByMarket.get(id) ?? 0n);
358
- consumedMarketIds.add(id);
359
- const chunk = blue_sdk_1.MathLib.min(available, remaining);
360
- peak = blue_sdk_1.MathLib.max(peak, chunk);
361
- requiredShareAllowance += previewAllowance(blue_sdk_1.MathLib.wMulUp(chunk, penalty));
362
- requiredShareAllowance += previewAllowance(chunk);
363
- remaining -= chunk;
364
- }
443
+ const { peak, requiredShareAllowance } = getInKindShareAllowance({
444
+ soleAdapter,
445
+ marketParamsListSnapshot,
446
+ marketIdListSnapshot,
447
+ vaultData,
448
+ now,
449
+ deadline,
450
+ idleAssets,
451
+ assetsToDeallocate,
452
+ penalty,
453
+ });
365
454
  const vaultExitBundlesV1 = (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.vaultExitBundlesV1");
366
455
  const blue = (0, morpho_ts_1.getChainAddress)(this.chainId, "blue");
367
456
  return {
368
457
  getRequirements: async () => {
369
- const requirementsTimestamp = morpho_ts_1.Time.timestamp();
458
+ const requirementsTimestamp = suppliedNow ?? morpho_ts_1.Time.timestamp();
370
459
  if (deadline <= requirementsTimestamp) {
371
460
  throw new index_js_3.ExpiredDeadlineError(deadline, requirementsTimestamp);
372
461
  }
@@ -410,6 +499,7 @@ class MorphoVaultV2 {
410
499
  if (this.client.options.supportSignature) {
411
500
  return [
412
501
  (0, index_js_1.encodeVaultSharesPermit)({
502
+ now: suppliedNow == null ? undefined : now,
413
503
  vault: vaultData,
414
504
  version: "vaultV2",
415
505
  spender: vaultExitBundlesV1,
@@ -445,13 +535,16 @@ class MorphoVaultV2 {
445
535
  deadline,
446
536
  requirementSignature: permit,
447
537
  },
448
- metadata: this.client.options.metadata,
538
+ metadata,
449
539
  });
450
540
  },
451
541
  };
452
542
  }
453
543
  /** {@inheritDoc VaultV2Actions.forceWithdraw} */
454
- forceWithdraw({ exitAssets, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, minSharePriceE27: minSharePriceE27Override, referralFeePct = 0n, referralFeeRecipient, }) {
544
+ forceWithdraw(params) {
545
+ const suppliedNow = params.now;
546
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, suppliedNow);
547
+ const { exitAssets, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, minSharePriceE27: minSharePriceE27Override, referralFeePct = 0n, referralFeeRecipient, } = params;
455
548
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
456
549
  if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
457
550
  throw new index_js_3.VaultAddressMismatchError(this.vault, vaultData.address);
@@ -473,7 +566,7 @@ class MorphoVaultV2 {
473
566
  // `getRequirements()` has already asked for an approval or a permit signature.
474
567
  (0, validate_js_1.validateUint256Field)("minSharePriceE27", minSharePriceE27Override);
475
568
  }
476
- const now = morpho_ts_1.Time.timestamp();
569
+ const now = suppliedNow ?? morpho_ts_1.Time.timestamp();
477
570
  const deadline = deadlineOverride ?? now + morpho_ts_1.Time.s.from.h(2n);
478
571
  // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
479
572
  // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
@@ -582,32 +675,12 @@ class MorphoVaultV2 {
582
675
  }
583
676
  // sharesBurntNow ≥ minSharesBurntNow ≥ minSharesBurntProjected > feeSharesProjected ≥ feeSharesNow
584
677
  const sharesBurntForFloor = blue_sdk_1.MathLib.max(sharesBurntRaw, sharesBurntNow - feeSharesNow);
585
- if (minSharePriceE27Override != null) {
586
- // The maximum-slippage threshold only bounds the override; unlike the transaction floor it
587
- // may round to zero, in which case every positive override is acceptable.
588
- const minAllowedSharePriceE27 = (0, morpho_ts_1._try)(() => (0, index_js_2.computeMinForceWithdrawSharePrice)({
589
- withdrawnAssets: plan.withdrawnAssets,
590
- sharesBurnt: sharesBurntForFloor,
591
- slippageTolerance: index_js_2.MAX_SLIPPAGE_TOLERANCE,
592
- }), index_js_3.VaultV2ForceWithdrawZeroSharePriceError) ?? 1n;
593
- if (minSharePriceE27Override < minAllowedSharePriceE27) {
594
- throw new index_js_3.VaultV2ForceWithdrawSharePriceBelowFloorError({
595
- minSharePriceE27: minSharePriceE27Override,
596
- floorE27: minAllowedSharePriceE27,
597
- });
598
- }
599
- }
600
- const minSharePriceE27 = minSharePriceE27Override ??
601
- (0, index_js_2.computeMinForceWithdrawSharePrice)({
602
- withdrawnAssets: plan.withdrawnAssets,
603
- sharesBurnt: sharesBurntForFloor,
604
- slippageTolerance,
605
- });
606
- // The floor is deliberately *not* capped at `MAX_ABSOLUTE_SHARE_PRICE` (100 assets/share):
607
- // lowering a lower bound weakens it, so any vault whose share price grew past that would be left
608
- // with no real protection. Its two sibling `computeMin*SharePrice` helpers cap nothing either —
609
- // only the `computeMax*` ones do, where capping relaxes an upper bound and is safe.
610
- (0, validate_js_1.validateUint256Field)("minSharePriceE27", minSharePriceE27);
678
+ const minSharePriceE27 = getForceWithdrawSharePrice({
679
+ minSharePriceE27Override,
680
+ withdrawnAssets: plan.withdrawnAssets,
681
+ sharesBurntForFloor,
682
+ slippageTolerance,
683
+ });
611
684
  // This is the minimum allowance needed for successful execution, not an exit cap: the bundle
612
685
  // independently rejects a realized share price below `minSharePriceE27`. Include the fee
613
686
  // shares minted by the first withdrawal and enough headroom for the configured tolerance.
@@ -616,7 +689,7 @@ class MorphoVaultV2 {
616
689
  const vaultExitBundlesV1 = (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.vaultExitBundlesV1");
617
690
  return {
618
691
  getRequirements: async () => {
619
- const requirementsTimestamp = morpho_ts_1.Time.timestamp();
692
+ const requirementsTimestamp = suppliedNow ?? morpho_ts_1.Time.timestamp();
620
693
  if (deadline <= requirementsTimestamp) {
621
694
  throw new index_js_3.ExpiredDeadlineError(deadline, requirementsTimestamp);
622
695
  }
@@ -645,6 +718,7 @@ class MorphoVaultV2 {
645
718
  return [];
646
719
  if (this.client.options.supportSignature) {
647
720
  const requirement = (0, index_js_1.encodeVaultSharesPermit)({
721
+ now: suppliedNow == null ? undefined : now,
648
722
  vault: vaultData,
649
723
  version: "vaultV2",
650
724
  spender: vaultExitBundlesV1,
@@ -682,12 +756,14 @@ class MorphoVaultV2 {
682
756
  referralFeeRecipient,
683
757
  requirementSignature: permit,
684
758
  },
685
- metadata: this.client.options.metadata,
759
+ metadata,
686
760
  });
687
761
  },
688
762
  };
689
763
  }
690
- forceRedeem({ deallocations, redeem, userAddress, }) {
764
+ forceRedeem(params) {
765
+ const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
766
+ const { deallocations, redeem, userAddress } = params;
691
767
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
692
768
  const shares = redeem.shares;
693
769
  const deallocationsSnapshot = deallocations.map(({ adapter, marketParams, amount }) => ({
@@ -703,7 +779,7 @@ class MorphoVaultV2 {
703
779
  redeem: { shares, recipient: userAddress },
704
780
  onBehalf: userAddress,
705
781
  },
706
- metadata: this.client.options.metadata,
782
+ metadata,
707
783
  }),
708
784
  };
709
785
  }
@@ -56,7 +56,8 @@ export interface InputVaultV2BlueReallocationData {
56
56
  /**
57
57
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
58
58
  *
59
- * Constructor inputs are cloned. Every simulated reallocation returns a new
59
+ * Constructor inputs are cloned, except read-only Midnight adapter snapshots, which are
60
+ * shared by reference. Every simulated reallocation returns a new
60
61
  * instance. Planning keeps the transaction-scoped `firstTotalAssets`
61
62
  * denominator outside the durable snapshot while applying reallocations in
62
63
  * contract order. Penalty donations update simulated vault accounting but are
@@ -128,10 +129,12 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
128
129
  * @throws {UnsupportedBlueVaultV2AdapterError} when a vault contains an unsupported adapter type.
129
130
  */
130
131
  constructor(input: InputVaultV2BlueReallocationData);
132
+ /** Copies allocation entries, retaining the clone path's shallow-copy semantics. @internal */
133
+ private copyAllocationSnapshots;
131
134
  /**
132
135
  * Clones the complete simulation snapshot.
133
136
  *
134
- * @returns A deep clone of this simulation state.
137
+ * @returns A deep clone of this simulation state; read-only Midnight adapter snapshots are shared by reference.
135
138
  * @example
136
139
  * ```ts
137
140
  * import { markets } from "@morpho-org/morpho-test";
@@ -518,6 +521,8 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
518
521
  readonly reallocations: readonly VaultV2BlueReallocation[];
519
522
  readonly data: VaultV2BlueReallocationData;
520
523
  };
524
+ /** Resolves the operation's accrued market and shared-Blue liquidity snapshot. @internal */
525
+ private resolveOperationSnapshot;
521
526
  private computeVaultV2BlueReallocationsAtUtilizationInPlace;
522
527
  /**
523
528
  * Sums friendly Vault V2 shared liquidity available to a target market.
@@ -615,6 +620,16 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
615
620
  getAvailableLiquidityToUtilization(marketId: MarketId, utilization?: bigint, options?: VaultV2BluePublicAllocatorOptions): bigint;
616
621
  private getLatestSnapshotTimestamp;
617
622
  private applyPublicReallocation;
623
+ /** Supplies the target position and books its rounded allocation changes. @internal */
624
+ private supplyReallocationTarget;
625
+ /** Credits shared Blue liquidity when an idle allocation enters the target market. @internal */
626
+ private creditIdleReallocationBalance;
627
+ /** Builds the isolated markets, adapter views and caps used by a transition probe. @internal */
628
+ private cloneReallocationProbe;
629
+ /** Withdraws the source market position and books its cap changes before target supply. @internal */
630
+ private withdrawReallocationSource;
631
+ /** Books the vault's first-allocation denominator once per simulated transaction. @internal */
632
+ private accrueReallocationFirstAllocation;
618
633
  /** Updates canonical markets in bulk and refreshes only dependent adapter views. */
619
634
  private setMarkets;
620
635
  }