@morpho-org/morpho-sdk 10.0.0-next.0 → 10.0.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 (282) hide show
  1. package/README.md +104 -12
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +1 -5
  4. package/lib/cjs/actions/blue/common.js +4 -2
  5. package/lib/cjs/actions/blue/withdrawBuyCallback.js +2 -1
  6. package/lib/cjs/actions/bundles/common.js +20 -14
  7. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -1
  8. package/lib/cjs/actions/midnight/cancelOffers.js +2 -1
  9. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +4 -2
  10. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +2 -1
  11. package/lib/cjs/actions/midnight/takeBorrow.js +2 -1
  12. package/lib/cjs/actions/midnight/takeLend.js +2 -1
  13. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +2 -1
  14. package/lib/cjs/actions/midnight/takeWithdraw.js +2 -1
  15. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +4 -2
  16. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -11
  17. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
  18. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
  19. package/lib/cjs/actions/vaultV1/inKindRedeem.js +6 -3
  20. package/lib/cjs/actions/vaultV1/migrateToV2.js +1 -1
  21. package/lib/cjs/actions/vaultV2/forceWithdraw.js +4 -2
  22. package/lib/cjs/actions/vaultV2/inKindRedeem.js +4 -2
  23. package/lib/cjs/blue/abis.d.ts +1 -1
  24. package/lib/cjs/blue/abis.js +1 -5
  25. package/lib/cjs/blue/entities.d.ts +4 -4
  26. package/lib/cjs/blue/entities.js +1 -3
  27. package/lib/cjs/blue/errors.d.ts +2 -2
  28. package/lib/cjs/blue/errors.js +1 -5
  29. package/lib/cjs/blue/fetch.d.ts +2 -2
  30. package/lib/cjs/blue/fetch.js +1 -3
  31. package/lib/cjs/blue/utils.d.ts +1 -1
  32. package/lib/cjs/blue/utils.js +1 -2
  33. package/lib/cjs/entities/blue/blue.js +8 -4
  34. package/lib/cjs/entities/index.d.ts +4 -4
  35. package/lib/cjs/entities/index.js +1 -3
  36. package/lib/cjs/entities/midnight/deadline.js +2 -1
  37. package/lib/cjs/entities/midnight/midnight.js +14 -7
  38. package/lib/cjs/entities/midnight/publication.js +73 -44
  39. package/lib/cjs/entities/requirements/assertContractCode.js +4 -2
  40. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +9 -13
  41. package/lib/cjs/entities/requirements/getErc2612Permit.js +10 -5
  42. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -0
  43. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +7 -1
  44. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
  45. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.js +111 -0
  46. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
  47. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.js +76 -0
  48. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
  49. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.js +93 -0
  50. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
  51. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.js +85 -0
  52. package/lib/cjs/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
  53. package/lib/cjs/entities/vaultV1/migrateToV2Quote.js +37 -0
  54. package/lib/cjs/entities/vaultV1/vaultV1.js +51 -181
  55. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
  56. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.js +189 -0
  57. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
  58. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.js +110 -0
  59. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +8 -34
  60. package/lib/cjs/entities/vaultV2/vaultV2.js +62 -429
  61. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +2 -3
  62. package/lib/cjs/entities/vaultV2BlueReallocationData.js +346 -234
  63. package/lib/cjs/errors.d.ts +4 -4
  64. package/lib/cjs/errors.js +6 -7
  65. package/lib/cjs/fetch.d.ts +2 -2
  66. package/lib/cjs/fetch.js +1 -3
  67. package/lib/cjs/helpers/deadShares.js +34 -19
  68. package/lib/cjs/helpers/encodeMidnightCalldata.js +4 -2
  69. package/lib/cjs/helpers/metadata.js +12 -6
  70. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +10 -5
  71. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +6 -3
  72. package/lib/cjs/helpers/utilization.js +10 -5
  73. package/lib/cjs/helpers/validate.js +12 -6
  74. package/lib/cjs/helpers/validateMidnightBounds.js +2 -1
  75. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +2 -1
  76. package/lib/cjs/helpers/validateMidnightPublication.js +4 -2
  77. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +44 -22
  78. package/lib/cjs/helpers/validatePositiveInput.js +2 -1
  79. package/lib/cjs/helpers/validateTakeableOffers.js +2 -1
  80. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +14 -7
  81. package/lib/cjs/index.d.ts +2 -2
  82. package/lib/cjs/index.js +10 -1
  83. package/lib/cjs/midnight/errors.d.ts +1 -2
  84. package/lib/cjs/midnight/errors.js +4 -5
  85. package/lib/cjs/transactionPlan/approval.js +12 -1
  86. package/lib/cjs/transactionPlan/deposit.d.ts +22 -0
  87. package/lib/cjs/transactionPlan/deposit.js +139 -0
  88. package/lib/cjs/transactionPlan/error.d.ts +10 -8
  89. package/lib/cjs/transactionPlan/error.js +10 -8
  90. package/lib/cjs/transactionPlan/getTokenPermit.js +2 -1
  91. package/lib/cjs/transactionPlan/index.d.ts +18 -0
  92. package/lib/cjs/transactionPlan/index.js +23 -5
  93. package/lib/cjs/transactionPlan/intent.d.ts +3 -3
  94. package/lib/cjs/transactionPlan/intent.js +14 -7
  95. package/lib/cjs/transactionPlan/permit.d.ts +1 -1
  96. package/lib/cjs/transactionPlan/permit.js +86 -20
  97. package/lib/cjs/transactionPlan/plan.d.ts +16 -6
  98. package/lib/cjs/transactionPlan/plan.js +72 -22
  99. package/lib/cjs/transactionPlan/redeem.d.ts +18 -0
  100. package/lib/cjs/transactionPlan/redeem.js +63 -0
  101. package/lib/cjs/transactionPlan/requirements.d.ts +4 -3
  102. package/lib/cjs/transactionPlan/requirements.js +12 -6
  103. package/lib/cjs/transactionPlan/serde.d.ts +2 -2
  104. package/lib/cjs/transactionPlan/serde.js +41 -15
  105. package/lib/cjs/transactionPlan/shareSpending.d.ts +18 -0
  106. package/lib/cjs/transactionPlan/shareSpending.js +50 -0
  107. package/lib/cjs/transactionPlan/types.d.ts +117 -11
  108. package/lib/cjs/transactionPlan/validateActions.js +11 -1
  109. package/lib/cjs/transactionPlan/validation.js +6 -3
  110. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +93 -0
  111. package/lib/cjs/transactionPlan/vaultv1/deposit.js +94 -0
  112. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
  113. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +203 -0
  114. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
  115. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +217 -0
  116. package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +69 -0
  117. package/lib/cjs/transactionPlan/vaultv1/redeem.js +78 -0
  118. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +77 -0
  119. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +88 -0
  120. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +14 -31
  121. package/lib/cjs/transactionPlan/vaultv2/deposit.js +15 -141
  122. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
  123. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +155 -0
  124. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
  125. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +206 -0
  126. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
  127. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +206 -0
  128. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +84 -0
  129. package/lib/cjs/transactionPlan/vaultv2/redeem.js +86 -0
  130. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +14 -27
  131. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +17 -124
  132. package/lib/cjs/transactionPlan/version.js +2 -1
  133. package/lib/cjs/transactionPlan/withdraw.d.ts +18 -0
  134. package/lib/cjs/transactionPlan/withdraw.js +94 -0
  135. package/lib/cjs/types/action.js +16 -8
  136. package/lib/cjs/types/error.d.ts +8 -1
  137. package/lib/cjs/types/error.js +10 -1
  138. package/lib/cjs/utils.d.ts +2 -2
  139. package/lib/cjs/utils.js +2 -4
  140. package/lib/cjs/version.d.ts +1 -1
  141. package/lib/cjs/version.js +1 -1
  142. package/lib/esm/abis.d.ts +1 -1
  143. package/lib/esm/abis.js +1 -1
  144. package/lib/esm/actions/blue/common.js +4 -2
  145. package/lib/esm/actions/blue/withdrawBuyCallback.js +2 -1
  146. package/lib/esm/actions/bundles/common.js +20 -14
  147. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -1
  148. package/lib/esm/actions/midnight/cancelOffers.js +2 -1
  149. package/lib/esm/actions/midnight/supplyCollateralBatch.js +4 -2
  150. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +2 -1
  151. package/lib/esm/actions/midnight/takeBorrow.js +2 -1
  152. package/lib/esm/actions/midnight/takeLend.js +2 -1
  153. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +2 -1
  154. package/lib/esm/actions/midnight/takeWithdraw.js +2 -1
  155. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +4 -2
  156. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +4 -13
  157. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
  158. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
  159. package/lib/esm/actions/vaultV1/inKindRedeem.js +6 -3
  160. package/lib/esm/actions/vaultV1/migrateToV2.js +1 -1
  161. package/lib/esm/actions/vaultV2/forceWithdraw.js +4 -2
  162. package/lib/esm/actions/vaultV2/inKindRedeem.js +4 -2
  163. package/lib/esm/blue/abis.d.ts +1 -1
  164. package/lib/esm/blue/abis.js +1 -1
  165. package/lib/esm/blue/entities.d.ts +4 -4
  166. package/lib/esm/blue/entities.js +2 -2
  167. package/lib/esm/blue/errors.d.ts +2 -2
  168. package/lib/esm/blue/errors.js +2 -2
  169. package/lib/esm/blue/fetch.d.ts +2 -2
  170. package/lib/esm/blue/fetch.js +2 -2
  171. package/lib/esm/blue/utils.d.ts +1 -1
  172. package/lib/esm/blue/utils.js +1 -1
  173. package/lib/esm/entities/blue/blue.js +8 -4
  174. package/lib/esm/entities/index.d.ts +4 -4
  175. package/lib/esm/entities/index.js +2 -2
  176. package/lib/esm/entities/midnight/deadline.js +2 -1
  177. package/lib/esm/entities/midnight/midnight.js +14 -7
  178. package/lib/esm/entities/midnight/publication.js +73 -44
  179. package/lib/esm/entities/requirements/assertContractCode.js +4 -2
  180. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +10 -14
  181. package/lib/esm/entities/requirements/getErc2612Permit.js +10 -5
  182. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -0
  183. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +7 -1
  184. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
  185. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.js +108 -0
  186. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
  187. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.js +73 -0
  188. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
  189. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.js +90 -0
  190. package/lib/esm/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
  191. package/lib/esm/entities/vaultV1/inKindRedeemQuote.js +82 -0
  192. package/lib/esm/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
  193. package/lib/esm/entities/vaultV1/migrateToV2Quote.js +34 -0
  194. package/lib/esm/entities/vaultV1/vaultV1.js +57 -187
  195. package/lib/esm/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
  196. package/lib/esm/entities/vaultV2/forceWithdrawQuote.js +186 -0
  197. package/lib/esm/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
  198. package/lib/esm/entities/vaultV2/inKindRedeemQuote.js +107 -0
  199. package/lib/esm/entities/vaultV2/vaultV2.d.ts +8 -34
  200. package/lib/esm/entities/vaultV2/vaultV2.js +70 -437
  201. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +2 -3
  202. package/lib/esm/entities/vaultV2BlueReallocationData.js +346 -234
  203. package/lib/esm/errors.d.ts +4 -4
  204. package/lib/esm/errors.js +4 -4
  205. package/lib/esm/fetch.d.ts +2 -2
  206. package/lib/esm/fetch.js +2 -2
  207. package/lib/esm/helpers/deadShares.js +35 -20
  208. package/lib/esm/helpers/encodeMidnightCalldata.js +4 -2
  209. package/lib/esm/helpers/metadata.js +12 -6
  210. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +10 -5
  211. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +6 -3
  212. package/lib/esm/helpers/utilization.js +10 -5
  213. package/lib/esm/helpers/validate.js +12 -6
  214. package/lib/esm/helpers/validateMidnightBounds.js +2 -1
  215. package/lib/esm/helpers/validateMidnightCollateralBatch.js +2 -1
  216. package/lib/esm/helpers/validateMidnightPublication.js +4 -2
  217. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +44 -22
  218. package/lib/esm/helpers/validatePositiveInput.js +2 -1
  219. package/lib/esm/helpers/validateTakeableOffers.js +2 -1
  220. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +14 -7
  221. package/lib/esm/index.d.ts +2 -2
  222. package/lib/esm/index.js +1 -1
  223. package/lib/esm/midnight/errors.d.ts +1 -2
  224. package/lib/esm/midnight/errors.js +1 -2
  225. package/lib/esm/transactionPlan/approval.js +13 -2
  226. package/lib/esm/transactionPlan/deposit.d.ts +22 -0
  227. package/lib/esm/transactionPlan/deposit.js +135 -0
  228. package/lib/esm/transactionPlan/error.d.ts +10 -8
  229. package/lib/esm/transactionPlan/error.js +10 -8
  230. package/lib/esm/transactionPlan/getTokenPermit.js +2 -1
  231. package/lib/esm/transactionPlan/index.d.ts +18 -0
  232. package/lib/esm/transactionPlan/index.js +9 -0
  233. package/lib/esm/transactionPlan/intent.d.ts +3 -3
  234. package/lib/esm/transactionPlan/intent.js +14 -7
  235. package/lib/esm/transactionPlan/permit.d.ts +1 -1
  236. package/lib/esm/transactionPlan/permit.js +86 -20
  237. package/lib/esm/transactionPlan/plan.d.ts +16 -6
  238. package/lib/esm/transactionPlan/plan.js +68 -18
  239. package/lib/esm/transactionPlan/redeem.d.ts +18 -0
  240. package/lib/esm/transactionPlan/redeem.js +59 -0
  241. package/lib/esm/transactionPlan/requirements.d.ts +4 -3
  242. package/lib/esm/transactionPlan/requirements.js +12 -6
  243. package/lib/esm/transactionPlan/serde.d.ts +2 -2
  244. package/lib/esm/transactionPlan/serde.js +41 -15
  245. package/lib/esm/transactionPlan/shareSpending.d.ts +18 -0
  246. package/lib/esm/transactionPlan/shareSpending.js +47 -0
  247. package/lib/esm/transactionPlan/types.d.ts +117 -11
  248. package/lib/esm/transactionPlan/validateActions.js +11 -1
  249. package/lib/esm/transactionPlan/validation.js +6 -3
  250. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +93 -0
  251. package/lib/esm/transactionPlan/vaultv1/deposit.js +90 -0
  252. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
  253. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +198 -0
  254. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
  255. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +212 -0
  256. package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +69 -0
  257. package/lib/esm/transactionPlan/vaultv1/redeem.js +74 -0
  258. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +77 -0
  259. package/lib/esm/transactionPlan/vaultv1/withdraw.js +84 -0
  260. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +14 -31
  261. package/lib/esm/transactionPlan/vaultv2/deposit.js +17 -142
  262. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
  263. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +150 -0
  264. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
  265. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +201 -0
  266. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
  267. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +201 -0
  268. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +84 -0
  269. package/lib/esm/transactionPlan/vaultv2/redeem.js +82 -0
  270. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +14 -27
  271. package/lib/esm/transactionPlan/vaultv2/withdraw.js +19 -125
  272. package/lib/esm/transactionPlan/version.js +2 -1
  273. package/lib/esm/transactionPlan/withdraw.d.ts +18 -0
  274. package/lib/esm/transactionPlan/withdraw.js +90 -0
  275. package/lib/esm/types/action.js +16 -8
  276. package/lib/esm/types/error.d.ts +8 -1
  277. package/lib/esm/types/error.js +10 -1
  278. package/lib/esm/utils.d.ts +2 -2
  279. package/lib/esm/utils.js +2 -2
  280. package/lib/esm/version.d.ts +1 -1
  281. package/lib/esm/version.js +1 -1
  282. package/package.json +15 -15
@@ -1,105 +1,21 @@
1
- import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, MarketParams, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
2
- import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
- import { _try, getChainAddress, Time, } from "@morpho-org/morpho-ts";
4
- import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
- import { readContract } from "viem/actions";
1
+ import { DEFAULT_SLIPPAGE_TOLERANCE, MarketParams, } from "@morpho-org/blue-sdk";
2
+ import { fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
+ import { getChainAddress, Time, } from "@morpho-org/morpho-ts";
4
+ import { isAddressEqual } from "viem";
6
5
  import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesPermitSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
7
- import { encodeErc20Approval, encodeVaultSharesPermit, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
6
+ import { vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
8
7
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
- import { computeMinForceWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, MAX_SLIPPAGE_TOLERANCE, resolveVaultV2ForceWithdrawEligibility, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
8
+ import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
10
9
  import { resolveTransactionMetadata } from "../../helpers/metadata.js";
11
- import { validateDeadline, validateNativeVaultAsset, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
12
- import { AdapterNotPartOfVaultError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemZeroDeallocationError, InputExceedsMaxError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, VaultAddressMismatchError, VaultV2ForceWithdrawCoverageError, VaultV2ForceWithdrawFeeSharesExceedBurnError, VaultV2ForceWithdrawSharePriceBelowFloorError, VaultV2ForceWithdrawZeroSharePriceError, VaultV2ForceWithdrawZeroWithdrawalError, VaultV2SingleAdapterRequiredError, VaultV2UndecodableLiquidityDataError, VaultV2UnsupportedExitAdapterError, VaultV2UnsupportedLiquidityAdapterError, } from "../../types/index.js";
10
+ import { validateNativeVaultAsset, validateUint256Field, } from "../../helpers/validate.js";
11
+ import { ExpiredDeadlineError, NonPositiveInputError, VaultAddressMismatchError, } from "../../types/index.js";
13
12
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
14
13
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
14
+ import { getVaultV2ForceWithdrawRequirements } from "../requirements/getVaultV2ForceWithdrawRequirements.js";
15
+ import { getVaultV2InKindRedeemRequirements } from "../requirements/getVaultV2InKindRedeemRequirements.js";
15
16
  import { getBundlesTokenRequirements } from "../requirements/index.js";
16
- // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
17
- // accrual model stays well-defined inside it.
18
- const VAULT_V2_FEE_PROJECTION_HORIZON = Time.s.from.y(1n);
19
- function getInKindShareAllowance({ soleAdapter, marketParamsListSnapshot, marketIdListSnapshot, vaultData, now, deadline, idleAssets, assetsToDeallocate, penalty, }) {
20
- const assetsByMarket = new Map(soleAdapter.markets
21
- .filter((market) => (soleAdapter.supplyShares[market.id] ?? 0n) !== 0n)
22
- .map((market) => [
23
- market.id,
24
- market
25
- .accrueInterest(now)
26
- .toSupplyAssets(soleAdapter.supplyShares[market.id] ?? 0n),
27
- ]));
28
- const uniqueMarketIds = new Set(marketIdListSnapshot);
29
- let covered = 0n;
30
- for (const id of uniqueMarketIds)
31
- covered += assetsByMarket.get(id) ?? 0n;
32
- if (covered < assetsToDeallocate) {
33
- const maxExitAssets = covered === 0n
34
- ? idleAssets
35
- : idleAssets + MathLib.wMulUp(covered + 1n, MathLib.WAD + penalty) - 1n;
36
- throw new InKindRedeemCoverageError({
37
- required: assetsToDeallocate,
38
- covered,
39
- maxExitAssets,
40
- });
41
- }
42
- let remaining = assetsToDeallocate;
43
- let peak = 0n;
44
- const consumedMarketIds = new Set();
45
- const { vault: allowanceVault } = vaultData.accrueInterest(deadline);
46
- // Interest can lower the burn, while management fees can raise it; bound both endpoints.
47
- const previewAllowance = (assets) => MathLib.max(vaultData.toShares(assets, "Up"), allowanceVault.toShares(assets, "Up"));
48
- let requiredShareAllowance = previewAllowance(BigInt(marketParamsListSnapshot.length));
49
- // Pre-burn previews upper-bound each separately rounded idle, penalty, and main burn.
50
- requiredShareAllowance += previewAllowance(idleAssets);
51
- for (const id of marketIdListSnapshot) {
52
- const available = consumedMarketIds.has(id)
53
- ? 0n
54
- : (assetsByMarket.get(id) ?? 0n);
55
- consumedMarketIds.add(id);
56
- const chunk = MathLib.min(available, remaining);
57
- peak = MathLib.max(peak, chunk);
58
- requiredShareAllowance += previewAllowance(MathLib.wMulUp(chunk, penalty));
59
- requiredShareAllowance += previewAllowance(chunk);
60
- remaining -= chunk;
61
- }
62
- return { peak, requiredShareAllowance };
63
- }
64
- function getForceWithdrawSharePrice({ minSharePriceE27Override, withdrawnAssets, sharesBurntForFloor, slippageTolerance, }) {
65
- if (minSharePriceE27Override != null) {
66
- // The maximum-slippage threshold only bounds the override; unlike the transaction floor it
67
- // may round to zero, in which case every positive override is acceptable.
68
- const minAllowedSharePriceE27 = _try(() => computeMinForceWithdrawSharePrice({
69
- withdrawnAssets: withdrawnAssets,
70
- sharesBurnt: sharesBurntForFloor,
71
- slippageTolerance: MAX_SLIPPAGE_TOLERANCE,
72
- }), VaultV2ForceWithdrawZeroSharePriceError) ?? 1n;
73
- if (minSharePriceE27Override < minAllowedSharePriceE27) {
74
- throw new VaultV2ForceWithdrawSharePriceBelowFloorError({
75
- minSharePriceE27: minSharePriceE27Override,
76
- floorE27: minAllowedSharePriceE27,
77
- });
78
- }
79
- }
80
- const minSharePriceE27 = minSharePriceE27Override ??
81
- computeMinForceWithdrawSharePrice({
82
- withdrawnAssets: withdrawnAssets,
83
- sharesBurnt: sharesBurntForFloor,
84
- slippageTolerance,
85
- });
86
- // The floor is deliberately *not* capped at `MAX_ABSOLUTE_SHARE_PRICE` (100 assets/share):
87
- // lowering a lower bound weakens it, so any vault whose share price grew past that would be left
88
- // with no real protection. Its two sibling `computeMin*SharePrice` helpers cap nothing either —
89
- // only the `computeMax*` ones do, where capping relaxes an upper bound and is safe.
90
- validateUint256Field("minSharePriceE27", minSharePriceE27);
91
- return minSharePriceE27;
92
- }
93
- /**
94
- * Midnight adapters revert vault-initiated `allocate` (`SelfAllocationOnly`), so a vault routing
95
- * liquidity through one accepts no deposit. Exits are served from idle assets plus what the adapter's
96
- * `withdrawToVault` path can withdraw from the liquidity market.
97
- */
98
- const isMidnightLiquidityAdapter = (vaultData) => vaultData.accrualLiquidityAdapter?.type === "VaultV2MidnightAdapter";
99
- /** Idle assets plus what the Midnight liquidity adapter can withdraw to the vault onchain. */
100
- const midnightWithdrawLiquidity = (vaultData) => vaultData.assetBalance +
101
- (vaultData.accrualLiquidityAdapter?.maxWithdraw(vaultData.liquidityData)
102
- .value ?? 0n);
17
+ import { computeVaultV2ForceWithdrawQuote } from "./forceWithdrawQuote.js";
18
+ import { computeVaultV2InKindRedeemQuote } from "./inKindRedeemQuote.js";
103
19
  /** Binds a viem client to a Vault V2 vault's action builders. */
104
20
  export class MorphoVaultV2 {
105
21
  client;
@@ -146,8 +62,9 @@ export class MorphoVaultV2 {
146
62
  }
147
63
  const createdAt = suppliedNow ?? Time.timestamp();
148
64
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
149
- if (deadline <= createdAt)
65
+ if (deadline <= createdAt) {
150
66
  throw new ExpiredDeadlineError(deadline, createdAt);
67
+ }
151
68
  const common = normalizeBundlesCommonParams({
152
69
  deadline,
153
70
  referralFeePct: params.referralFeePct,
@@ -160,13 +77,6 @@ export class MorphoVaultV2 {
160
77
  // The native path must target the chain's registered wrapped-native asset.
161
78
  validateNativeVaultAsset(this.chainId, vaultAsset);
162
79
  }
163
- if (isMidnightLiquidityAdapter(vaultData)) {
164
- throw new InputExceedsMaxError({
165
- field: funding.value > 0n ? "nativeAmount" : "amount",
166
- value: funding.assets,
167
- max: 0n,
168
- });
169
- }
170
80
  const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
171
81
  const maxSharePrice = computeVaultMaxSharePrice({
172
82
  vaultData,
@@ -179,10 +89,12 @@ export class MorphoVaultV2 {
179
89
  return Object.freeze({
180
90
  getRequirements: async (requirementOptions) => {
181
91
  const now = suppliedNow ?? Time.timestamp();
182
- if (deadline <= now)
92
+ if (deadline <= now) {
183
93
  throw new ExpiredDeadlineError(deadline, now);
184
- if (pendingRequirements != null)
94
+ }
95
+ if (pendingRequirements != null) {
185
96
  return await pendingRequirements;
97
+ }
186
98
  // Memoize the in-flight promise so concurrent callers share one round of
187
99
  // allowance/nonce reads.
188
100
  const pending = (async () => {
@@ -208,8 +120,9 @@ export class MorphoVaultV2 {
208
120
  }
209
121
  finally {
210
122
  // Later calls must re-read live allowances/nonces and honor their own options.
211
- if (pendingRequirements === pending)
123
+ if (pendingRequirements === pending) {
212
124
  pendingRequirements = undefined;
125
+ }
213
126
  }
214
127
  },
215
128
  buildTx: (signatures) => {
@@ -245,22 +158,16 @@ export class MorphoVaultV2 {
245
158
  if (!isAddressEqual(vaultData.address, this.vault)) {
246
159
  throw new VaultAddressMismatchError(this.vault, vaultData.address);
247
160
  }
248
- if (amount <= 0n)
161
+ if (amount <= 0n) {
249
162
  throw new NonPositiveInputError("amount", amount);
163
+ }
250
164
  // Reject values outside the ABI range before resolving any requirements.
251
165
  validateUint256Field("amount", amount);
252
- if (isMidnightLiquidityAdapter(vaultData) &&
253
- amount > midnightWithdrawLiquidity(vaultData)) {
254
- throw new InputExceedsMaxError({
255
- field: "amount",
256
- value: amount,
257
- max: midnightWithdrawLiquidity(vaultData),
258
- });
259
- }
260
166
  const createdAt = suppliedNow ?? Time.timestamp();
261
167
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
262
- if (deadline <= createdAt)
168
+ if (deadline <= createdAt) {
263
169
  throw new ExpiredDeadlineError(deadline, createdAt);
170
+ }
264
171
  const common = normalizeBundlesCommonParams({
265
172
  deadline,
266
173
  referralFeePct: params.referralFeePct,
@@ -279,8 +186,9 @@ export class MorphoVaultV2 {
279
186
  return Object.freeze({
280
187
  getRequirements: async () => {
281
188
  const now = suppliedNow ?? Time.timestamp();
282
- if (deadline <= now)
189
+ if (deadline <= now) {
283
190
  throw new ExpiredDeadlineError(deadline, now);
191
+ }
284
192
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
285
193
  // Re-read the live share allowance on every call instead of caching the resolved requirements.
286
194
  return getVaultBundlesSharesRequirements(this.client.viemClient, {
@@ -321,12 +229,14 @@ export class MorphoVaultV2 {
321
229
  const metadata = resolveTransactionMetadata(this.client.options.metadata, suppliedNow);
322
230
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
323
231
  const { shares, userAddress } = params;
324
- if (shares <= 0n)
232
+ if (shares <= 0n) {
325
233
  throw new NonPositiveInputError("shares", shares);
234
+ }
326
235
  const createdAt = suppliedNow ?? Time.timestamp();
327
236
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
328
- if (deadline <= createdAt)
237
+ if (deadline <= createdAt) {
329
238
  throw new ExpiredDeadlineError(deadline, createdAt);
239
+ }
330
240
  const common = normalizeBundlesCommonParams({
331
241
  deadline,
332
242
  referralFeePct: params.referralFeePct,
@@ -336,24 +246,12 @@ export class MorphoVaultV2 {
336
246
  return Object.freeze({
337
247
  getRequirements: async () => {
338
248
  const now = suppliedNow ?? Time.timestamp();
339
- if (deadline <= now)
249
+ if (deadline <= now) {
340
250
  throw new ExpiredDeadlineError(deadline, now);
341
- await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
342
- const vaultData = await this.getData();
343
- if (isMidnightLiquidityAdapter(vaultData)) {
344
- // Onchain redeem accrues interest before converting shares to assets.
345
- const { vault: accrued } = vaultData.accrueInterest(now);
346
- const liquidity = midnightWithdrawLiquidity(accrued);
347
- if (accrued.toAssets(shares) > liquidity) {
348
- throw new InputExceedsMaxError({
349
- field: "shares",
350
- value: shares,
351
- max: accrued.toShares(liquidity),
352
- });
353
- }
354
251
  }
252
+ await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
355
253
  return getVaultBundlesSharesRequirements(this.client.viemClient, {
356
- vaultData,
254
+ vaultData: await this.getData(),
357
255
  version: "vaultV2",
358
256
  owner: userAddress,
359
257
  chainId: this.chainId,
@@ -393,129 +291,28 @@ export class MorphoVaultV2 {
393
291
  if (!isAddressEqual(vaultData.address, this.vault)) {
394
292
  throw new VaultAddressMismatchError(this.vault, vaultData.address);
395
293
  }
396
- if (amount <= 0n)
397
- throw new NonPositiveInputError("amount", amount);
398
- const marketParamsListSnapshot = marketParamsList.map(({ loanToken, collateralToken, oracle, irm, lltv }) => ({
399
- loanToken,
400
- collateralToken,
401
- oracle,
402
- irm,
403
- lltv,
404
- }));
405
- const marketIdListSnapshot = marketParamsListSnapshot.map((marketParams) => MarketUtils.getMarketId(marketParams));
406
- const now = suppliedNow ?? Time.timestamp();
407
- const deadline = deadlineOverride ?? now + Time.s.from.h(2n);
408
- // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
409
- // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
410
- validateDeadline(deadline);
411
- if (deadline <= now)
412
- throw new ExpiredDeadlineError(deadline, now);
413
- if (vaultData.accrualAdapters.length !== 1) {
414
- throw new VaultV2SingleAdapterRequiredError(this.vault, vaultData.accrualAdapters.length);
415
- }
416
- const soleAdapter = vaultData.accrualAdapters[0];
417
- if (soleAdapter == null) {
418
- throw new VaultV2SingleAdapterRequiredError(this.vault, 0);
419
- }
420
- const adapter = adapterOverride ?? soleAdapter.address;
421
- if (!isAddressEqual(adapter, soleAdapter.address)) {
422
- throw new AdapterNotPartOfVaultError(this.vault, adapter);
423
- }
424
- if (!(soleAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
425
- throw new VaultV2UnsupportedExitAdapterError(adapter);
426
- }
427
- const penalty = vaultData.forceDeallocatePenalties[soleAdapter.address] ?? 0n;
428
- const idleAssets = MathLib.min(vaultData.assetBalance, amount);
429
- const assetsToDeallocate = MathLib.wDivDown(amount - idleAssets, MathLib.WAD + penalty);
430
- if (idleAssets === 0n && assetsToDeallocate === 0n) {
431
- throw new InKindRedeemZeroDeallocationError({
432
- vault: this.vault,
433
- amount,
434
- penalty,
435
- });
436
- }
437
- if (assetsToDeallocate > 0n && marketParamsListSnapshot.length === 0) {
438
- throw new EmptyMarketParamsListError();
439
- }
440
- const { peak, requiredShareAllowance } = getInKindShareAllowance({
441
- soleAdapter,
442
- marketParamsListSnapshot,
443
- marketIdListSnapshot,
294
+ const { deadline, adapter, marketParamsListSnapshot, requiredShareAllowance, peak, } = computeVaultV2InKindRedeemQuote({
295
+ amount,
296
+ marketParamsList,
444
297
  vaultData,
445
- now,
446
- deadline,
447
- idleAssets,
448
- assetsToDeallocate,
449
- penalty,
298
+ deadline: deadlineOverride,
299
+ adapter: adapterOverride,
300
+ now: suppliedNow ?? Time.timestamp(),
301
+ vault: this.vault,
450
302
  });
451
303
  const vaultExitBundlesV1 = getChainAddress(this.chainId, "bundles.vaultExitBundlesV1");
452
- const blue = getChainAddress(this.chainId, "blue");
453
304
  return {
454
- getRequirements: async () => {
455
- const requirementsTimestamp = suppliedNow ?? Time.timestamp();
456
- if (deadline <= requirementsTimestamp) {
457
- throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
458
- }
459
- await validateClientChainId(this.client.viemClient, this.chainId);
460
- await this.assertWriteTargets(["bundles.vaultExitBundlesV1", "blue"]);
461
- // Vault gates are intentionally left to the final transaction. A receive gate may inspect
462
- // VaultExitBundlesV1's transient `initiator`, which is populated only during the actual
463
- // periphery call. A send-share gate is arbitrary external code and is evaluated repeatedly
464
- // after intermediate penalty share burns, so one standalone read is not execution-equivalent
465
- // either. Simulate the finalized transaction after authorization when gate compatibility
466
- // must be checked before submission.
467
- const [allowance, nonce, blueBalance] = await Promise.all([
468
- readContract(this.client.viemClient, {
469
- address: this.vault,
470
- abi: erc20Abi,
471
- functionName: "allowance",
472
- args: [userAddress, vaultExitBundlesV1],
473
- }),
474
- readContract(this.client.viemClient, {
475
- address: this.vault,
476
- abi: erc2612Abi,
477
- functionName: "nonces",
478
- args: [userAddress],
479
- }),
480
- readContract(this.client.viemClient, {
481
- address: vaultData.asset,
482
- abi: erc20Abi,
483
- functionName: "balanceOf",
484
- args: [blue],
485
- }),
486
- ]);
487
- if (blueBalance < peak) {
488
- throw new InsufficientBlueBalanceForInKindRedeemError({
489
- asset: vaultData.asset,
490
- available: blueBalance,
491
- required: peak,
492
- });
493
- }
494
- if (allowance >= requiredShareAllowance)
495
- return [];
496
- if (this.client.options.supportSignature) {
497
- return [
498
- encodeVaultSharesPermit({
499
- now: suppliedNow == null ? undefined : now,
500
- vault: vaultData,
501
- version: "vaultV2",
502
- spender: vaultExitBundlesV1,
503
- owner: userAddress,
504
- chainId: this.chainId,
505
- nonce,
506
- deadline,
507
- }),
508
- ];
509
- }
510
- return [
511
- encodeErc20Approval({
512
- token: this.vault,
513
- spender: vaultExitBundlesV1,
514
- amount: maxUint256,
515
- chainId: this.chainId,
516
- }),
517
- ];
518
- },
305
+ getRequirements: () => getVaultV2InKindRedeemRequirements(this.client.viemClient, {
306
+ vaultData,
307
+ vault: this.vault,
308
+ userAddress,
309
+ chainId: this.chainId,
310
+ deadline,
311
+ requiredShareAllowance,
312
+ supportSignature: this.client.options.supportSignature,
313
+ peak,
314
+ now: suppliedNow,
315
+ }),
519
316
  buildTx: (signatures) => {
520
317
  const permit = selectBundlesSharesPermitSignature(signatures, {
521
318
  spender: vaultExitBundlesV1,
@@ -546,195 +343,31 @@ export class MorphoVaultV2 {
546
343
  if (!isAddressEqual(vaultData.address, this.vault)) {
547
344
  throw new VaultAddressMismatchError(this.vault, vaultData.address);
548
345
  }
549
- if (exitAssets <= 0n)
550
- throw new NonPositiveInputError("exitAssets", exitAssets);
551
- validateUint256Field("exitAssets", exitAssets);
552
- validateSlippageTolerance(slippageTolerance);
553
- // Called for its throws only: the raw pair is forwarded to the action, which normalizes it
554
- // again on the encode path so a direct action caller gets the same guarantees.
555
- validateReferralFee({ referralFeePct, referralFeeRecipient });
556
- if (minSharePriceE27Override != null) {
557
- // An unbounded override reopens the exact hole this path closes: the contract reads
558
- // `minSharePriceE27 == 0` as "no bound".
559
- if (minSharePriceE27Override <= 0n) {
560
- throw new NonPositiveInputError("minSharePriceE27", minSharePriceE27Override);
561
- }
562
- // And an override the uint256 slot cannot hold must fail here rather than after
563
- // `getRequirements()` has already asked for an approval or a permit signature.
564
- validateUint256Field("minSharePriceE27", minSharePriceE27Override);
565
- }
566
- const now = suppliedNow ?? Time.timestamp();
567
- const deadline = deadlineOverride ?? now + Time.s.from.h(2n);
568
- // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
569
- // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
570
- validateDeadline(deadline);
571
- if (deadline <= now)
572
- throw new ExpiredDeadlineError(deadline, now);
573
- const maxDeadline = now + VAULT_V2_FEE_PROJECTION_HORIZON;
574
- if (deadline > maxDeadline) {
575
- throw new InputExceedsMaxError({
576
- field: "deadline",
577
- value: deadline,
578
- max: maxDeadline,
579
- });
580
- }
581
- const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData, adapterOverride);
582
- switch (eligibility.type) {
583
- case "eligible":
584
- break;
585
- case "adapterCount":
586
- throw new VaultV2SingleAdapterRequiredError(this.vault, eligibility.adapters);
587
- case "adapterMismatch":
588
- throw new AdapterNotPartOfVaultError(this.vault, eligibility.adapter);
589
- case "unsupportedAdapter":
590
- throw new VaultV2UnsupportedExitAdapterError(eligibility.adapter);
591
- case "unsupportedLiquidityAdapter":
592
- throw new VaultV2UnsupportedLiquidityAdapterError({
593
- vault: this.vault,
594
- liquidityAdapter: eligibility.liquidityAdapter,
595
- adapter: eligibility.adapter,
596
- });
597
- case "undecodableLiquidityData":
598
- throw new VaultV2UndecodableLiquidityDataError({
599
- vault: this.vault,
600
- liquidityAdapter: eligibility.liquidityAdapter,
601
- liquidityData: eligibility.liquidityData,
602
- cause: eligibility.cause,
603
- });
604
- }
605
- const { adapter: accrualAdapter, liquidityMarketId } = eligibility;
606
- const adapter = accrualAdapter.address;
607
- const plan = computeVaultV2ForceWithdrawPlan({
608
- vaultData,
609
- adapter: accrualAdapter,
610
- liquidityMarketId,
346
+ const { deadline, adapter, minSharePriceE27, requiredShareAllowance } = computeVaultV2ForceWithdrawQuote({
611
347
  exitAssets,
612
- timestamp: now,
613
- });
614
- if (plan.withdrawnAssets <= 0n) {
615
- throw new VaultV2ForceWithdrawZeroWithdrawalError({
616
- vault: this.vault,
617
- exitAssets,
618
- penalty: plan.penalty,
619
- });
620
- }
621
- // The contract's force-deallocation loop is unbounded: under-coverage panics on-chain.
622
- if (plan.coveredAssets < plan.assetsToDeallocate) {
623
- throw new VaultV2ForceWithdrawCoverageError({
624
- required: plan.assetsToDeallocate,
625
- covered: plan.coveredAssets,
626
- maxExitAssets: plan.maxExitAssets,
627
- });
628
- }
629
- const projectionTimestamp = deadline;
630
- // VaultExitBundlesV1 measures shares as `sharesBefore - balanceAfter`; its first withdrawal
631
- // accrues the vault before burning. The realized price sits between the raw snapshot price
632
- // (pending fee mints not yet diluting it) and the `now` projection (interest the chain may not
633
- // have accrued yet, e.g. when the wall clock runs ahead of the chain). Price the floor off the
634
- // larger *net* burn of the two endpoints — the raw snapshot mints no fee shares, the `now`
635
- // accrual mints `feeSharesNow` — so it never exceeds either, and use the projected deadline
636
- // accrual for the fee-mint guard.
637
- const { vault: nowVaultData } = vaultData.accrueInterest(MathLib.max(now, vaultData.lastUpdate));
638
- const { vault: projectedVaultData } = vaultData.accrueInterest(MathLib.max(projectionTimestamp, vaultData.lastUpdate));
639
- const sharesBurntRaw = computeVaultV2ForceWithdrawSharesBurnt({
640
348
  vaultData,
641
- deadlineVaultData: vaultData,
642
- plan,
643
- });
644
- const sharesBurntNow = computeVaultV2ForceWithdrawSharesBurnt({
645
- vaultData: nowVaultData,
646
- deadlineVaultData: nowVaultData,
647
- plan,
648
- });
649
- const feeSharesNow = computeVaultV2ForceWithdrawFeeSharesMinted({
650
- vaultData,
651
- owner: userAddress,
652
- timestamp: now,
653
- });
654
- const feeSharesProjected = computeVaultV2ForceWithdrawFeeSharesMinted({
655
- vaultData,
656
- owner: userAddress,
657
- timestamp: projectionTimestamp,
658
- });
659
- const minSharesBurntProjected = computeVaultV2ForceWithdrawMinSharesBurnt({
660
- vaultData: projectedVaultData,
661
- plan,
662
- });
663
- // When fee shares are minted, the projected pair bounds every execution time in the window.
664
- if (feeSharesProjected > 0n &&
665
- feeSharesProjected >= minSharesBurntProjected) {
666
- throw new VaultV2ForceWithdrawFeeSharesExceedBurnError({
667
- vault: this.vault,
668
- userAddress,
669
- sharesBurnt: minSharesBurntProjected,
670
- feeShares: feeSharesProjected,
671
- });
672
- }
673
- // sharesBurntNow ≥ minSharesBurntNow ≥ minSharesBurntProjected > feeSharesProjected ≥ feeSharesNow
674
- const sharesBurntForFloor = MathLib.max(sharesBurntRaw, sharesBurntNow - feeSharesNow);
675
- const minSharePriceE27 = getForceWithdrawSharePrice({
676
- minSharePriceE27Override,
677
- withdrawnAssets: plan.withdrawnAssets,
678
- sharesBurntForFloor,
349
+ userAddress,
350
+ adapter: adapterOverride,
351
+ deadline: deadlineOverride,
679
352
  slippageTolerance,
353
+ minSharePriceE27: minSharePriceE27Override,
354
+ referralFeePct,
355
+ referralFeeRecipient,
356
+ now: suppliedNow ?? Time.timestamp(),
357
+ vault: this.vault,
680
358
  });
681
- // This is the minimum allowance needed for successful execution, not an exit cap: the bundle
682
- // independently rejects a realized share price below `minSharePriceE27`. Include the fee
683
- // shares minted by the first withdrawal and enough headroom for the configured tolerance.
684
- const allowanceSharePriceE27 = MathLib.max(MathLib.min(MathLib.mulDivDown(minSharePriceE27, MathLib.WAD - slippageTolerance, MathLib.WAD), minSharePriceE27 - 1n), 1n);
685
- const requiredShareAllowance = MathLib.min(MathLib.max(MathLib.mulDivUp(exitAssets, MathLib.RAY, allowanceSharePriceE27), MathLib.mulDivUp(exitAssets, MathLib.RAY, minSharePriceE27) + 1n) + feeSharesProjected, maxUint256);
686
359
  const vaultExitBundlesV1 = getChainAddress(this.chainId, "bundles.vaultExitBundlesV1");
687
360
  return {
688
- getRequirements: async () => {
689
- const requirementsTimestamp = suppliedNow ?? Time.timestamp();
690
- if (deadline <= requirementsTimestamp) {
691
- throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
692
- }
693
- await validateClientChainId(this.client.viemClient, this.chainId);
694
- await this.assertWriteTargets(["bundles.vaultExitBundlesV1"]);
695
- // Vault gates are intentionally left to the final transaction: the receive-assets gate may
696
- // inspect VaultExitBundlesV1's transient `initiator`, and a send-shares gate is arbitrary
697
- // external code re-evaluated after each intermediate penalty burn, so neither is
698
- // execution-equivalent from a standalone read. Unlike in-kind redemption, this exit never
699
- // supplies into Morpho Blue, so no Blue token-balance check is needed.
700
- const [allowance, nonce] = await Promise.all([
701
- readContract(this.client.viemClient, {
702
- address: this.vault,
703
- abi: erc20Abi,
704
- functionName: "allowance",
705
- args: [userAddress, vaultExitBundlesV1],
706
- }),
707
- readContract(this.client.viemClient, {
708
- address: this.vault,
709
- abi: erc2612Abi,
710
- functionName: "nonces",
711
- args: [userAddress],
712
- }),
713
- ]);
714
- if (allowance >= requiredShareAllowance)
715
- return [];
716
- if (this.client.options.supportSignature) {
717
- const requirement = encodeVaultSharesPermit({
718
- now: suppliedNow == null ? undefined : now,
719
- vault: vaultData,
720
- version: "vaultV2",
721
- spender: vaultExitBundlesV1,
722
- owner: userAddress,
723
- chainId: this.chainId,
724
- nonce,
725
- deadline,
726
- });
727
- return [requirement];
728
- }
729
- return [
730
- encodeErc20Approval({
731
- token: this.vault,
732
- spender: vaultExitBundlesV1,
733
- amount: maxUint256,
734
- chainId: this.chainId,
735
- }),
736
- ];
737
- },
361
+ getRequirements: () => getVaultV2ForceWithdrawRequirements(this.client.viemClient, {
362
+ vaultData,
363
+ vault: this.vault,
364
+ userAddress,
365
+ chainId: this.chainId,
366
+ deadline,
367
+ requiredShareAllowance,
368
+ supportSignature: this.client.options.supportSignature,
369
+ now: suppliedNow,
370
+ }),
738
371
  buildTx: (signatures) => {
739
372
  const permit = selectBundlesSharesPermitSignature(signatures, {
740
373
  spender: vaultExitBundlesV1,
@@ -56,8 +56,7 @@ export interface InputVaultV2BlueReallocationData {
56
56
  /**
57
57
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
58
58
  *
59
- * Constructor inputs are cloned, except read-only Midnight adapter snapshots, which are
60
- * shared by reference. Every simulated reallocation returns a new
59
+ * Constructor inputs are cloned. Every simulated reallocation returns a new
61
60
  * instance. Planning keeps the transaction-scoped `firstTotalAssets`
62
61
  * denominator outside the durable snapshot while applying reallocations in
63
62
  * contract order. Penalty donations update simulated vault accounting but are
@@ -134,7 +133,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
134
133
  /**
135
134
  * Clones the complete simulation snapshot.
136
135
  *
137
- * @returns A deep clone of this simulation state; read-only Midnight adapter snapshots are shared by reference.
136
+ * @returns A deep clone of this simulation state.
138
137
  * @example
139
138
  * ```ts
140
139
  * import { markets } from "@morpho-org/morpho-test";