@morpho-org/morpho-sdk 6.0.0-next.1 → 6.0.0-next.3

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 (305) hide show
  1. package/MIGRATION-v5-to-v6.md +199 -34
  2. package/README.md +23 -15
  3. package/lib/cjs/abis.d.ts +3 -2829
  4. package/lib/cjs/abis.js +1 -1938
  5. package/lib/cjs/actions/blue/borrow.d.ts +3 -2
  6. package/lib/cjs/actions/blue/borrow.js +3 -2
  7. package/lib/cjs/actions/blue/common.js +6 -35
  8. package/lib/cjs/actions/blue/refinance.d.ts +2 -2
  9. package/lib/cjs/actions/blue/refinance.js +2 -2
  10. package/lib/cjs/actions/blue/repay.d.ts +1 -1
  11. package/lib/cjs/actions/blue/repay.js +1 -1
  12. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  13. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -2
  14. package/lib/cjs/actions/blue/supply.d.ts +2 -2
  15. package/lib/cjs/actions/blue/supply.js +4 -9
  16. package/lib/cjs/actions/blue/supplyCollateral.d.ts +2 -2
  17. package/lib/cjs/actions/blue/supplyCollateral.js +2 -2
  18. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +3 -2
  19. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +3 -2
  20. package/lib/cjs/actions/blue/withdraw.d.ts +3 -3
  21. package/lib/cjs/actions/blue/withdraw.js +3 -3
  22. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +2 -2
  23. package/lib/cjs/actions/blue/withdrawCollateral.js +2 -2
  24. package/lib/cjs/actions/bundles/common.d.ts +38 -4
  25. package/lib/cjs/actions/bundles/common.js +91 -35
  26. package/lib/cjs/actions/index.d.ts +0 -1
  27. package/lib/cjs/actions/index.js +0 -1
  28. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +9 -8
  29. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +17 -26
  30. package/lib/cjs/actions/requirements/blue/index.d.ts +0 -1
  31. package/lib/cjs/actions/requirements/blue/index.js +0 -1
  32. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +20 -14
  33. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +24 -25
  34. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +4 -4
  35. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +4 -5
  36. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +21 -12
  37. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +39 -38
  38. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +4 -2
  39. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +14 -9
  40. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +9 -6
  41. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +22 -17
  42. package/lib/cjs/actions/requirements/encode/index.d.ts +0 -1
  43. package/lib/cjs/actions/requirements/encode/index.js +0 -1
  44. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +5 -6
  45. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -6
  46. package/lib/cjs/actions/requirements/index.d.ts +0 -1
  47. package/lib/cjs/actions/requirements/index.js +0 -1
  48. package/lib/cjs/actions/vaultV1/deposit.d.ts +1 -2
  49. package/lib/cjs/actions/vaultV1/deposit.js +1 -2
  50. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +6 -4
  51. package/lib/cjs/actions/vaultV1/inKindRedeem.js +12 -8
  52. package/lib/cjs/actions/vaultV2/deposit.d.ts +1 -2
  53. package/lib/cjs/actions/vaultV2/deposit.js +1 -2
  54. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +58 -39
  55. package/lib/cjs/actions/vaultV2/forceWithdraw.js +87 -60
  56. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +6 -4
  57. package/lib/cjs/actions/vaultV2/inKindRedeem.js +12 -8
  58. package/lib/cjs/augment.d.ts +0 -1
  59. package/lib/cjs/augment.js +0 -1
  60. package/lib/cjs/blue/abis.d.ts +1 -1
  61. package/lib/cjs/blue/abis.js +1 -5
  62. package/lib/cjs/blue/entities.d.ts +2 -2
  63. package/lib/cjs/blue/entities.js +1 -2
  64. package/lib/cjs/blue/errors.d.ts +1 -1
  65. package/lib/cjs/blue/errors.js +2 -1
  66. package/lib/cjs/blue/fetch.d.ts +1 -1
  67. package/lib/cjs/blue/fetch.js +1 -2
  68. package/lib/cjs/blue/types.d.ts +2 -4
  69. package/lib/cjs/blue/utils.d.ts +1 -3
  70. package/lib/cjs/blue/utils.js +1 -3
  71. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  72. package/lib/cjs/client/morphoViemExtension.js +1 -1
  73. package/lib/cjs/constants.d.ts +3 -37
  74. package/lib/cjs/constants.js +1 -39
  75. package/lib/cjs/entities/blue/blue.d.ts +38 -264
  76. package/lib/cjs/entities/blue/blue.js +2 -203
  77. package/lib/cjs/entities/index.d.ts +3 -60
  78. package/lib/cjs/entities/index.js +1 -20
  79. package/lib/cjs/entities/midnight/midnight.js +20 -24
  80. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +7 -6
  81. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +19 -14
  82. package/lib/cjs/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.js +3 -3
  83. package/lib/cjs/entities/requirements/index.d.ts +1 -0
  84. package/lib/cjs/entities/requirements/index.js +1 -0
  85. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +18 -6
  86. package/lib/cjs/entities/vaultV1/vaultV1.js +25 -8
  87. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +154 -35
  88. package/lib/cjs/entities/vaultV2/vaultV2.js +249 -23
  89. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +8 -1
  90. package/lib/cjs/entities/vaultV2BlueReallocationData.js +50 -34
  91. package/lib/cjs/errors.d.ts +2 -46
  92. package/lib/cjs/errors.js +2 -46
  93. package/lib/cjs/fetch.d.ts +1 -15
  94. package/lib/cjs/fetch.js +1 -16
  95. package/lib/cjs/helpers/constant.d.ts +0 -2
  96. package/lib/cjs/helpers/constant.js +0 -2
  97. package/lib/cjs/helpers/index.d.ts +4 -3
  98. package/lib/cjs/helpers/index.js +10 -9
  99. package/lib/cjs/helpers/metadata.d.ts +3 -5
  100. package/lib/cjs/helpers/metadata.js +4 -6
  101. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.d.ts +107 -0
  102. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +164 -0
  103. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  104. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +2 -0
  105. package/lib/cjs/helpers/slippage.d.ts +34 -90
  106. package/lib/cjs/helpers/slippage.js +52 -137
  107. package/lib/cjs/helpers/utilization.d.ts +12 -10
  108. package/lib/cjs/helpers/utilization.js +27 -12
  109. package/lib/cjs/helpers/validate.d.ts +66 -32
  110. package/lib/cjs/helpers/validate.js +84 -57
  111. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  112. package/lib/cjs/helpers/validateRequirementSpender.js +1 -3
  113. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.d.ts +274 -0
  114. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +369 -0
  115. package/lib/cjs/types/action.d.ts +102 -68
  116. package/lib/cjs/types/action.js +11 -4
  117. package/lib/cjs/types/error.d.ts +332 -385
  118. package/lib/cjs/types/error.js +369 -412
  119. package/lib/cjs/types/sharedLiquidity.d.ts +1 -117
  120. package/lib/cjs/types.d.ts +2 -18
  121. package/lib/cjs/utils.d.ts +8 -35
  122. package/lib/cjs/utils.js +11 -36
  123. package/lib/esm/abis.d.ts +3 -2829
  124. package/lib/esm/abis.js +3 -1935
  125. package/lib/esm/actions/blue/borrow.d.ts +3 -2
  126. package/lib/esm/actions/blue/borrow.js +3 -2
  127. package/lib/esm/actions/blue/common.js +8 -37
  128. package/lib/esm/actions/blue/refinance.d.ts +2 -2
  129. package/lib/esm/actions/blue/refinance.js +2 -2
  130. package/lib/esm/actions/blue/repay.d.ts +1 -1
  131. package/lib/esm/actions/blue/repay.js +1 -1
  132. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +2 -2
  133. package/lib/esm/actions/blue/repayWithdrawCollateral.js +2 -2
  134. package/lib/esm/actions/blue/supply.d.ts +2 -2
  135. package/lib/esm/actions/blue/supply.js +6 -11
  136. package/lib/esm/actions/blue/supplyCollateral.d.ts +2 -2
  137. package/lib/esm/actions/blue/supplyCollateral.js +2 -2
  138. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +3 -2
  139. package/lib/esm/actions/blue/supplyCollateralBorrow.js +3 -2
  140. package/lib/esm/actions/blue/withdraw.d.ts +3 -3
  141. package/lib/esm/actions/blue/withdraw.js +3 -3
  142. package/lib/esm/actions/blue/withdrawCollateral.d.ts +2 -2
  143. package/lib/esm/actions/blue/withdrawCollateral.js +2 -2
  144. package/lib/esm/actions/bundles/common.d.ts +38 -4
  145. package/lib/esm/actions/bundles/common.js +91 -36
  146. package/lib/esm/actions/index.d.ts +0 -1
  147. package/lib/esm/actions/index.js +0 -1
  148. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +9 -8
  149. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +20 -29
  150. package/lib/esm/actions/requirements/blue/index.d.ts +0 -1
  151. package/lib/esm/actions/requirements/blue/index.js +0 -1
  152. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +20 -14
  153. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +25 -26
  154. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +4 -4
  155. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +4 -5
  156. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +21 -12
  157. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +40 -39
  158. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +4 -2
  159. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +14 -9
  160. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +9 -6
  161. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +22 -17
  162. package/lib/esm/actions/requirements/encode/index.d.ts +0 -1
  163. package/lib/esm/actions/requirements/encode/index.js +0 -1
  164. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +5 -6
  165. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -6
  166. package/lib/esm/actions/requirements/index.d.ts +0 -1
  167. package/lib/esm/actions/requirements/index.js +0 -1
  168. package/lib/esm/actions/vaultV1/deposit.d.ts +1 -2
  169. package/lib/esm/actions/vaultV1/deposit.js +1 -2
  170. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +6 -4
  171. package/lib/esm/actions/vaultV1/inKindRedeem.js +12 -8
  172. package/lib/esm/actions/vaultV2/deposit.d.ts +1 -2
  173. package/lib/esm/actions/vaultV2/deposit.js +1 -2
  174. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +58 -39
  175. package/lib/esm/actions/vaultV2/forceWithdraw.js +89 -62
  176. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +6 -4
  177. package/lib/esm/actions/vaultV2/inKindRedeem.js +12 -8
  178. package/lib/esm/augment.d.ts +0 -1
  179. package/lib/esm/augment.js +0 -1
  180. package/lib/esm/blue/abis.d.ts +1 -1
  181. package/lib/esm/blue/abis.js +1 -1
  182. package/lib/esm/blue/entities.d.ts +2 -2
  183. package/lib/esm/blue/entities.js +1 -1
  184. package/lib/esm/blue/errors.d.ts +1 -1
  185. package/lib/esm/blue/errors.js +1 -1
  186. package/lib/esm/blue/fetch.d.ts +1 -1
  187. package/lib/esm/blue/fetch.js +1 -1
  188. package/lib/esm/blue/types.d.ts +2 -4
  189. package/lib/esm/blue/utils.d.ts +1 -3
  190. package/lib/esm/blue/utils.js +1 -3
  191. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  192. package/lib/esm/client/morphoViemExtension.js +1 -1
  193. package/lib/esm/constants.d.ts +3 -37
  194. package/lib/esm/constants.js +3 -37
  195. package/lib/esm/entities/blue/blue.d.ts +38 -264
  196. package/lib/esm/entities/blue/blue.js +5 -206
  197. package/lib/esm/entities/index.d.ts +3 -60
  198. package/lib/esm/entities/index.js +1 -16
  199. package/lib/esm/entities/midnight/midnight.js +20 -24
  200. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +7 -6
  201. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +20 -15
  202. package/lib/esm/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.js +3 -3
  203. package/lib/esm/entities/requirements/index.d.ts +1 -0
  204. package/lib/esm/entities/requirements/index.js +1 -0
  205. package/lib/esm/entities/vaultV1/vaultV1.d.ts +18 -6
  206. package/lib/esm/entities/vaultV1/vaultV1.js +29 -12
  207. package/lib/esm/entities/vaultV2/vaultV2.d.ts +154 -35
  208. package/lib/esm/entities/vaultV2/vaultV2.js +256 -30
  209. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +8 -1
  210. package/lib/esm/entities/vaultV2BlueReallocationData.js +48 -32
  211. package/lib/esm/errors.d.ts +2 -46
  212. package/lib/esm/errors.js +2 -46
  213. package/lib/esm/fetch.d.ts +1 -15
  214. package/lib/esm/fetch.js +1 -15
  215. package/lib/esm/helpers/constant.d.ts +0 -2
  216. package/lib/esm/helpers/constant.js +0 -2
  217. package/lib/esm/helpers/index.d.ts +4 -3
  218. package/lib/esm/helpers/index.js +4 -3
  219. package/lib/esm/helpers/metadata.d.ts +3 -5
  220. package/lib/esm/helpers/metadata.js +4 -6
  221. package/lib/esm/helpers/previewVaultV2ForceWithdraw.d.ts +107 -0
  222. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +161 -0
  223. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  224. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +2 -0
  225. package/lib/esm/helpers/slippage.d.ts +34 -90
  226. package/lib/esm/helpers/slippage.js +52 -134
  227. package/lib/esm/helpers/utilization.d.ts +12 -10
  228. package/lib/esm/helpers/utilization.js +26 -11
  229. package/lib/esm/helpers/validate.d.ts +66 -32
  230. package/lib/esm/helpers/validate.js +83 -57
  231. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  232. package/lib/esm/helpers/validateRequirementSpender.js +1 -3
  233. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.d.ts +274 -0
  234. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +362 -0
  235. package/lib/esm/types/action.d.ts +102 -68
  236. package/lib/esm/types/action.js +12 -5
  237. package/lib/esm/types/error.d.ts +332 -385
  238. package/lib/esm/types/error.js +355 -392
  239. package/lib/esm/types/sharedLiquidity.d.ts +1 -117
  240. package/lib/esm/types.d.ts +2 -18
  241. package/lib/esm/utils.d.ts +8 -35
  242. package/lib/esm/utils.js +7 -34
  243. package/package.json +7 -15
  244. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +0 -42
  245. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.js +0 -83
  246. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirements.d.ts +0 -88
  247. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +0 -151
  248. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +0 -37
  249. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +0 -50
  250. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.d.ts +0 -57
  251. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.js +0 -74
  252. package/lib/cjs/actions/requirements/generalAdapter/index.d.ts +0 -3
  253. package/lib/cjs/actions/requirements/generalAdapter/index.js +0 -19
  254. package/lib/cjs/actions/signatures/getBlueAuthorizationAction.d.ts +0 -29
  255. package/lib/cjs/actions/signatures/getBlueAuthorizationAction.js +0 -48
  256. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +0 -58
  257. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +0 -119
  258. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +0 -44
  259. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +0 -43
  260. package/lib/cjs/actions/signatures/index.d.ts +0 -3
  261. package/lib/cjs/actions/signatures/index.js +0 -19
  262. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +0 -8
  263. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.js +0 -8
  264. package/lib/cjs/bundler/actions.d.ts +0 -797
  265. package/lib/cjs/bundler/actions.js +0 -1371
  266. package/lib/cjs/bundler/index.d.ts +0 -2
  267. package/lib/cjs/bundler/index.js +0 -18
  268. package/lib/cjs/bundler/types.d.ts +0 -235
  269. package/lib/cjs/bundler/types.js +0 -2
  270. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +0 -326
  271. package/lib/cjs/entities/vaultV1ReallocationData.js +0 -542
  272. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +0 -78
  273. package/lib/cjs/helpers/computeVaultV1Reallocations.js +0 -243
  274. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +0 -42
  275. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.js +0 -79
  276. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirements.d.ts +0 -88
  277. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +0 -147
  278. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +0 -37
  279. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +0 -46
  280. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.d.ts +0 -57
  281. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.js +0 -70
  282. package/lib/esm/actions/requirements/generalAdapter/index.d.ts +0 -3
  283. package/lib/esm/actions/requirements/generalAdapter/index.js +0 -3
  284. package/lib/esm/actions/signatures/getBlueAuthorizationAction.d.ts +0 -29
  285. package/lib/esm/actions/signatures/getBlueAuthorizationAction.js +0 -44
  286. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +0 -58
  287. package/lib/esm/actions/signatures/getTokenRequirementActions.js +0 -115
  288. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +0 -44
  289. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +0 -39
  290. package/lib/esm/actions/signatures/index.d.ts +0 -3
  291. package/lib/esm/actions/signatures/index.js +0 -3
  292. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +0 -8
  293. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +0 -5
  294. package/lib/esm/bundler/actions.d.ts +0 -797
  295. package/lib/esm/bundler/actions.js +0 -1368
  296. package/lib/esm/bundler/index.d.ts +0 -2
  297. package/lib/esm/bundler/index.js +0 -2
  298. package/lib/esm/bundler/types.d.ts +0 -235
  299. package/lib/esm/bundler/types.js +0 -1
  300. package/lib/esm/entities/vaultV1ReallocationData.d.ts +0 -326
  301. package/lib/esm/entities/vaultV1ReallocationData.js +0 -544
  302. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +0 -78
  303. package/lib/esm/helpers/computeVaultV1Reallocations.js +0 -239
  304. /package/lib/cjs/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.d.ts +0 -0
  305. /package/lib/esm/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.d.ts +0 -0
@@ -0,0 +1,274 @@
1
+ import { type AccrualVaultV2, AccrualVaultV2MorphoMarketV1AdapterV2, type Address, type MarketId } from "@morpho-org/blue-sdk";
2
+ import { type Hex } from "viem";
3
+ /**
4
+ * Outcome of resolving a Vault V2 snapshot against VaultExitBundlesV1's force-withdraw
5
+ * preconditions.
6
+ *
7
+ * Discriminated on `type`. Callers that must fail loudly map each non-`"eligible"` tag to a typed
8
+ * error; callers that only frame a UI treat every non-`"eligible"` tag as "no exit available".
9
+ */
10
+ export type VaultV2ForceWithdrawEligibility = {
11
+ readonly type: "eligible";
12
+ /** The vault's sole MorphoMarketV1AdapterV2. */
13
+ readonly adapter: AccrualVaultV2MorphoMarketV1AdapterV2;
14
+ /** Market the vault routes penalty-free liquidity through, or `undefined` when unset. */
15
+ readonly liquidityMarketId: MarketId | undefined;
16
+ } | {
17
+ readonly type: "adapterCount";
18
+ readonly adapters: number;
19
+ } | {
20
+ readonly type: "adapterMismatch";
21
+ readonly adapter: Address;
22
+ } | {
23
+ readonly type: "unsupportedAdapter";
24
+ readonly adapter: Address;
25
+ } | {
26
+ readonly type: "unsupportedLiquidityAdapter";
27
+ readonly liquidityAdapter: Address;
28
+ readonly adapter: Address;
29
+ } | {
30
+ readonly type: "undecodableLiquidityData";
31
+ readonly liquidityAdapter: Address;
32
+ /** Raw `liquidityData` that failed to decode as `MarketParams`. */
33
+ readonly liquidityData: Hex;
34
+ /** The underlying decode failure, preserved for the caller to wrap as `cause`. */
35
+ readonly cause: unknown;
36
+ };
37
+ /**
38
+ * Resolves whether a Vault V2 snapshot can be force-withdrawn through VaultExitBundlesV1.
39
+ *
40
+ * Mirrors the contract's four preconditions: `adaptersLength() == 1`, `isAdapter(adapter)`,
41
+ * `adapter.morpho() == BLUE` (implied by the adapter type, whose factory pins Blue), and a
42
+ * `liquidityAdapter` the contract can cast to `IMorphoMarketV1AdapterV2` and whose `liquidityData`
43
+ * decodes as `MarketParams`. Because the exit already requires a single adapter, the only
44
+ * resolvable liquidity configurations are unset or that same adapter.
45
+ *
46
+ * Pure: reads only the supplied snapshot and never throws.
47
+ *
48
+ * @param vaultData - Pre-fetched Vault V2 accrual snapshot.
49
+ * @param adapterOverride - Optional adapter the caller expects; defaults to the vault's sole adapter.
50
+ * @returns The `"eligible"` variant with the resolved adapter and liquidity market, or the tag
51
+ * describing which precondition failed.
52
+ * @example
53
+ * ```ts
54
+ * import { resolveVaultV2ForceWithdrawEligibility } from "@morpho-org/morpho-sdk";
55
+ *
56
+ * const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData);
57
+ * if (eligibility.type === "eligible") {
58
+ * console.log(eligibility.adapter.address, eligibility.liquidityMarketId);
59
+ * }
60
+ * ```
61
+ */
62
+ export declare function resolveVaultV2ForceWithdrawEligibility(vaultData: AccrualVaultV2, adapterOverride?: Address): VaultV2ForceWithdrawEligibility;
63
+ /**
64
+ * Computes the Vault V2 shares that accruing a vault snapshot mints to its owner as management
65
+ * and/or performance fees.
66
+ *
67
+ * Fee shares are minted to the matching recipient during the first withdrawal after accrual.
68
+ * When the owner is both recipients, both fee-share amounts are included. Timestamps before the
69
+ * snapshot's last update are clamped because Vault V2 cannot accrue backwards.
70
+ *
71
+ * @param params - Vault fee-share accrual inputs.
72
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
73
+ * @param params.owner - Account whose fee-recipient share mints are measured.
74
+ * @param params.timestamp - Target accrual timestamp, clamped to `vaultData.lastUpdate`.
75
+ * @returns Shares minted to `owner` by the management and/or performance fees, or `0n` when the
76
+ * owner is not a fee recipient.
77
+ * @example
78
+ * ```ts
79
+ * import { computeVaultV2ForceWithdrawFeeSharesMinted } from "@morpho-org/morpho-sdk";
80
+ *
81
+ * const feeShares = computeVaultV2ForceWithdrawFeeSharesMinted({
82
+ * vaultData,
83
+ * owner,
84
+ * timestamp,
85
+ * });
86
+ * ```
87
+ */
88
+ export declare function computeVaultV2ForceWithdrawFeeSharesMinted(params: {
89
+ readonly vaultData: AccrualVaultV2;
90
+ readonly owner: Address;
91
+ readonly timestamp: bigint;
92
+ }): bigint;
93
+ /** Vault V2 force-withdraw amounts derived from a vault snapshot. */
94
+ export interface VaultV2ForceWithdrawPlan {
95
+ /** WAD-scaled force-deallocation penalty the vault charges on this adapter. */
96
+ readonly penalty: bigint;
97
+ /** Penalty-inclusive amount requested from the vault. */
98
+ readonly exitAssets: bigint;
99
+ /** Penalty-free leg, withdrawn before any force deallocation. */
100
+ readonly assetsToWithdraw: bigint;
101
+ /** Penalised leg, force-deallocated from the adapter's markets. */
102
+ readonly assetsToDeallocate: bigint;
103
+ /** Upper bound of the assets burned as force-deallocation penalty. */
104
+ readonly penaltyAssets: bigint;
105
+ /** Assets the contract withdraws in total, before the referral fee. */
106
+ readonly withdrawnAssets: bigint;
107
+ /** Assets the adapter's markets can release for *this* `exitAssets`, summed across markets. */
108
+ readonly coveredAssets: bigint;
109
+ /**
110
+ * Largest penalty-inclusive `exitAssets` the snapshot supports.
111
+ *
112
+ * Independent of the requested `exitAssets`, so it is safe to use as an input ceiling. Always an
113
+ * amount the exit actually accepts: `0n` when nothing is exitable, and saturated at `maxUint256`
114
+ * rather than grossing up past the ABI slot.
115
+ */
116
+ readonly maxExitAssets: bigint;
117
+ /** Upper bound of the `forceDeallocate` calls the contract's loop performs. */
118
+ readonly penaltyLegs: number;
119
+ }
120
+ /**
121
+ * Computes every Vault V2 force-withdraw amount from a vault snapshot, without any RPC.
122
+ *
123
+ * Reproduces `vaultExitBundlesV1ForceWithdrawVaultV2` arithmetic:
124
+ *
125
+ * ```solidity
126
+ * withdrawableAssets = idle + min(liquidityAdapterAssets, liquidityMarketLiquidity);
127
+ * assetsToWithdraw = min(exitAssets, withdrawableAssets);
128
+ * assetsToDeallocate = mulDivDown(exitAssets - assetsToWithdraw, WAD, WAD + penalty);
129
+ * ```
130
+ *
131
+ * `coveredAssets` sums `min(adapterPosition, marketLiquidity)` over the adapter's markets, minus
132
+ * whatever the penalty-free leg already drained from the liquidity market. The sum is deliberately
133
+ * order-independent: the contract's loop visits every market taking `min(available, remaining)`, so
134
+ * total capacity does not depend on the adapter's storage order — which matters because a drained
135
+ * market is removed from that list mid-loop.
136
+ *
137
+ * That order-independence assumes `VaultExitBundlesV1` copies `adapter.marketIds` into memory
138
+ * *before* the loop. If it instead re-read adapter storage each iteration,
139
+ * `MorphoMarketV1AdapterV2.deallocate`'s swap-and-pop removal of a drained market would make the
140
+ * loop skip markets, and this sum would overstate real capacity — letting an exit through that
141
+ * panics on-chain. The claim is load-bearing for the coverage guard and is verified only by the
142
+ * fork suite, not by any in-repo contract source.
143
+ *
144
+ * @param params - Plan inputs.
145
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
146
+ * @param params.adapter - The vault's sole MorphoMarketV1AdapterV2, from
147
+ * {@link resolveVaultV2ForceWithdrawEligibility}.
148
+ * @param params.liquidityMarketId - Market the vault routes penalty-free liquidity through, or
149
+ * `undefined` when the vault has no liquidity adapter.
150
+ * @param params.exitAssets - Penalty-inclusive amount to exit.
151
+ * @param params.timestamp - Timestamp used to accrue every Morpho Blue market before converting
152
+ * adapter shares.
153
+ * @returns The resolved plan. `coveredAssets < assetsToDeallocate` means the exit would overrun the
154
+ * contract's unbounded loop; the caller decides how to report that.
155
+ * @throws {NonPositiveInputError} when `exitAssets` is not positive.
156
+ * @example
157
+ * ```ts
158
+ * import {
159
+ * computeVaultV2ForceWithdrawPlan,
160
+ * resolveVaultV2ForceWithdrawEligibility,
161
+ * } from "@morpho-org/morpho-sdk";
162
+ *
163
+ * const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData);
164
+ * if (eligibility.type === "eligible") {
165
+ * const plan = computeVaultV2ForceWithdrawPlan({
166
+ * vaultData,
167
+ * adapter: eligibility.adapter,
168
+ * liquidityMarketId: eligibility.liquidityMarketId,
169
+ * exitAssets: 1_000_000n,
170
+ * timestamp: 1_800_000_000n,
171
+ * });
172
+ * // plan.withdrawnAssets is what the user receives before the referral fee
173
+ * }
174
+ * ```
175
+ */
176
+ export declare function computeVaultV2ForceWithdrawPlan(params: {
177
+ readonly vaultData: AccrualVaultV2;
178
+ readonly adapter: AccrualVaultV2MorphoMarketV1AdapterV2;
179
+ readonly liquidityMarketId: MarketId | undefined;
180
+ readonly exitAssets: bigint;
181
+ readonly timestamp: bigint;
182
+ }): VaultV2ForceWithdrawPlan;
183
+ /**
184
+ * Upper-bounds the vault shares a Vault V2 force withdrawal burns.
185
+ *
186
+ * The contract splits the burn across up to `penaltyLegs + 2` separate `VaultV2.withdraw` calls (the
187
+ * penalty-free leg, one per `forceDeallocate`, and the final deallocated leg), each rounding its own
188
+ * share burn up. Converting the aggregate already spends one ceiling, so the bound adds one share
189
+ * per *additional* leg that moves a positive amount — a zero-amount leg burns `toShares(0, "Up")`
190
+ * and rounds nothing.
191
+ *
192
+ * The result is the **denominator of {@link computeMinForceWithdrawSharePrice}** — the largest share
193
+ * burn the realized exit price is measured against. It takes the max over the two supplied snapshots
194
+ * because interest lowers the burn while management fees raise it, so neither snapshot alone bounds
195
+ * execution. The entity passes both accrued to `now` (execution time): the raw `lastUpdate` snapshot
196
+ * underestimates the burn a stale fee-bearing vault realizes — the first withdrawal accrues pending
197
+ * management fees before burning shares — which lifts the floor above the faithful price and trips
198
+ * `SlippageExceeded`. Accruing to `now`, not the caller-chosen `deadline`, tracks execution without
199
+ * letting a long deadline silently weaken the guard; `slippageTolerance` absorbs the residual drift
200
+ * until inclusion. Pass distinct snapshots to bound the burn across an accrual window.
201
+ *
202
+ * This is **not** the share allowance to authorize. The price floor's denominator is this bound
203
+ * minus `computeVaultV2ForceWithdrawFeeSharesMinted({ vaultData, owner, timestamp: now })`: the
204
+ * contract measures the *net* burn, which fee mints to `owner` shrink. The allowance is
205
+ * `min(mulDivUp(exitAssets, RAY, minSharePriceE27) + computeVaultV2ForceWithdrawFeeSharesMinted({
206
+ * vaultData, owner, timestamp: deadline }), maxUint256)`: the permit pays for the *gross* burn.
207
+ *
208
+ * @param params - Share-bound inputs.
209
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
210
+ * @param params.deadlineVaultData - The same vault accrued to a second timestamp; the max of the two
211
+ * share burns is returned. The entity passes the `now`-accrued snapshot for both.
212
+ * @param params.plan - Plan from {@link computeVaultV2ForceWithdrawPlan}.
213
+ * @returns An upper bound, in vault shares, of what the exit burns.
214
+ * @example
215
+ * ```ts
216
+ * import { MathLib } from "@morpho-org/blue-sdk";
217
+ * import {
218
+ * computeVaultV2ForceWithdrawFeeSharesMinted,
219
+ * computeVaultV2ForceWithdrawSharesBurnt,
220
+ * } from "@morpho-org/morpho-sdk";
221
+ *
222
+ * const { vault: nowVaultData } = vaultData.accrueInterest(now);
223
+ * const sharesBurnt = computeVaultV2ForceWithdrawSharesBurnt({
224
+ * vaultData: nowVaultData,
225
+ * deadlineVaultData: nowVaultData,
226
+ * plan,
227
+ * });
228
+ * const feeSharesNow = computeVaultV2ForceWithdrawFeeSharesMinted({
229
+ * vaultData,
230
+ * owner,
231
+ * timestamp: now,
232
+ * });
233
+ * const sharesBurntForFloor = sharesBurnt - feeSharesNow;
234
+ * const requiredShareAllowance = MathLib.min(
235
+ * MathLib.mulDivUp(exitAssets, MathLib.RAY, minSharePriceE27) +
236
+ * computeVaultV2ForceWithdrawFeeSharesMinted({
237
+ * vaultData,
238
+ * owner,
239
+ * timestamp: deadline,
240
+ * }),
241
+ * maxUint256,
242
+ * );
243
+ * ```
244
+ */
245
+ export declare function computeVaultV2ForceWithdrawSharesBurnt(params: {
246
+ readonly vaultData: AccrualVaultV2;
247
+ readonly deadlineVaultData: AccrualVaultV2;
248
+ readonly plan: VaultV2ForceWithdrawPlan;
249
+ }): bigint;
250
+ /**
251
+ * Computes a lower bound of the Vault V2 shares that a force withdrawal burns.
252
+ *
253
+ * The penalty-free/penalised split can move as liquidity accrues between planning and inclusion.
254
+ * This lower bound is used to reject fee-recipient exits whose fee mints could reach the burn
255
+ * measured by VaultExitBundlesV1, independently of that split.
256
+ *
257
+ * @param params - Lower-bound inputs.
258
+ * @param params.vaultData - Vault V2 snapshot already accrued to the execution timestamp.
259
+ * @param params.plan - Plan from {@link computeVaultV2ForceWithdrawPlan}.
260
+ * @returns A lower bound, in vault shares, of the burn measured by the contract.
261
+ * @example
262
+ * ```ts
263
+ * import { computeVaultV2ForceWithdrawMinSharesBurnt } from "@morpho-org/morpho-sdk";
264
+ *
265
+ * const minSharesBurnt = computeVaultV2ForceWithdrawMinSharesBurnt({
266
+ * vaultData,
267
+ * plan,
268
+ * });
269
+ * ```
270
+ */
271
+ export declare function computeVaultV2ForceWithdrawMinSharesBurnt(params: {
272
+ readonly vaultData: AccrualVaultV2;
273
+ readonly plan: VaultV2ForceWithdrawPlan;
274
+ }): bigint;
@@ -0,0 +1,362 @@
1
+ import { AccrualVaultV2MorphoMarketV1AdapterV2, MarketParams, MathLib, } from "@morpho-org/blue-sdk";
2
+ import { isAddressEqual, maxUint256, zeroAddress } from "viem";
3
+ import { NonPositiveInputError } from "../types/index.js";
4
+ /**
5
+ * Resolves whether a Vault V2 snapshot can be force-withdrawn through VaultExitBundlesV1.
6
+ *
7
+ * Mirrors the contract's four preconditions: `adaptersLength() == 1`, `isAdapter(adapter)`,
8
+ * `adapter.morpho() == BLUE` (implied by the adapter type, whose factory pins Blue), and a
9
+ * `liquidityAdapter` the contract can cast to `IMorphoMarketV1AdapterV2` and whose `liquidityData`
10
+ * decodes as `MarketParams`. Because the exit already requires a single adapter, the only
11
+ * resolvable liquidity configurations are unset or that same adapter.
12
+ *
13
+ * Pure: reads only the supplied snapshot and never throws.
14
+ *
15
+ * @param vaultData - Pre-fetched Vault V2 accrual snapshot.
16
+ * @param adapterOverride - Optional adapter the caller expects; defaults to the vault's sole adapter.
17
+ * @returns The `"eligible"` variant with the resolved adapter and liquidity market, or the tag
18
+ * describing which precondition failed.
19
+ * @example
20
+ * ```ts
21
+ * import { resolveVaultV2ForceWithdrawEligibility } from "@morpho-org/morpho-sdk";
22
+ *
23
+ * const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData);
24
+ * if (eligibility.type === "eligible") {
25
+ * console.log(eligibility.adapter.address, eligibility.liquidityMarketId);
26
+ * }
27
+ * ```
28
+ */
29
+ export function resolveVaultV2ForceWithdrawEligibility(vaultData, adapterOverride) {
30
+ const [soleAdapter] = vaultData.accrualAdapters;
31
+ if (vaultData.accrualAdapters.length !== 1 || soleAdapter == null) {
32
+ return { type: "adapterCount", adapters: vaultData.accrualAdapters.length };
33
+ }
34
+ const adapter = adapterOverride ?? soleAdapter.address;
35
+ if (!isAddressEqual(adapter, soleAdapter.address)) {
36
+ return { type: "adapterMismatch", adapter };
37
+ }
38
+ if (!(soleAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
39
+ return { type: "unsupportedAdapter", adapter };
40
+ }
41
+ const { liquidityAdapter } = vaultData;
42
+ if (isAddressEqual(liquidityAdapter, zeroAddress)) {
43
+ return {
44
+ type: "eligible",
45
+ adapter: soleAdapter,
46
+ liquidityMarketId: undefined,
47
+ };
48
+ }
49
+ if (!isAddressEqual(liquidityAdapter, soleAdapter.address)) {
50
+ return { type: "unsupportedLiquidityAdapter", liquidityAdapter, adapter };
51
+ }
52
+ let liquidityMarketId;
53
+ try {
54
+ liquidityMarketId = MarketParams.fromHex(vaultData.liquidityData).id;
55
+ }
56
+ catch (cause) {
57
+ // Undecodable `liquidityData` reverts the contract's `abi.decode`. Reported separately from a
58
+ // foreign adapter: the adapter here is the right one, only its stored market params are unusable.
59
+ return {
60
+ type: "undecodableLiquidityData",
61
+ liquidityAdapter,
62
+ liquidityData: vaultData.liquidityData,
63
+ cause,
64
+ };
65
+ }
66
+ return { type: "eligible", adapter: soleAdapter, liquidityMarketId };
67
+ }
68
+ /**
69
+ * Computes the Vault V2 shares that accruing a vault snapshot mints to its owner as management
70
+ * and/or performance fees.
71
+ *
72
+ * Fee shares are minted to the matching recipient during the first withdrawal after accrual.
73
+ * When the owner is both recipients, both fee-share amounts are included. Timestamps before the
74
+ * snapshot's last update are clamped because Vault V2 cannot accrue backwards.
75
+ *
76
+ * @param params - Vault fee-share accrual inputs.
77
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
78
+ * @param params.owner - Account whose fee-recipient share mints are measured.
79
+ * @param params.timestamp - Target accrual timestamp, clamped to `vaultData.lastUpdate`.
80
+ * @returns Shares minted to `owner` by the management and/or performance fees, or `0n` when the
81
+ * owner is not a fee recipient.
82
+ * @example
83
+ * ```ts
84
+ * import { computeVaultV2ForceWithdrawFeeSharesMinted } from "@morpho-org/morpho-sdk";
85
+ *
86
+ * const feeShares = computeVaultV2ForceWithdrawFeeSharesMinted({
87
+ * vaultData,
88
+ * owner,
89
+ * timestamp,
90
+ * });
91
+ * ```
92
+ */
93
+ export function computeVaultV2ForceWithdrawFeeSharesMinted(params) {
94
+ const { vault: accruedVault, managementFeeShares, performanceFeeShares, } = params.vaultData.accrueInterest(MathLib.max(params.timestamp, params.vaultData.lastUpdate));
95
+ return ((isAddressEqual(accruedVault.managementFeeRecipient, params.owner)
96
+ ? managementFeeShares
97
+ : 0n) +
98
+ (isAddressEqual(accruedVault.performanceFeeRecipient, params.owner)
99
+ ? performanceFeeShares
100
+ : 0n));
101
+ }
102
+ /**
103
+ * Computes every Vault V2 force-withdraw amount from a vault snapshot, without any RPC.
104
+ *
105
+ * Reproduces `vaultExitBundlesV1ForceWithdrawVaultV2` arithmetic:
106
+ *
107
+ * ```solidity
108
+ * withdrawableAssets = idle + min(liquidityAdapterAssets, liquidityMarketLiquidity);
109
+ * assetsToWithdraw = min(exitAssets, withdrawableAssets);
110
+ * assetsToDeallocate = mulDivDown(exitAssets - assetsToWithdraw, WAD, WAD + penalty);
111
+ * ```
112
+ *
113
+ * `coveredAssets` sums `min(adapterPosition, marketLiquidity)` over the adapter's markets, minus
114
+ * whatever the penalty-free leg already drained from the liquidity market. The sum is deliberately
115
+ * order-independent: the contract's loop visits every market taking `min(available, remaining)`, so
116
+ * total capacity does not depend on the adapter's storage order — which matters because a drained
117
+ * market is removed from that list mid-loop.
118
+ *
119
+ * That order-independence assumes `VaultExitBundlesV1` copies `adapter.marketIds` into memory
120
+ * *before* the loop. If it instead re-read adapter storage each iteration,
121
+ * `MorphoMarketV1AdapterV2.deallocate`'s swap-and-pop removal of a drained market would make the
122
+ * loop skip markets, and this sum would overstate real capacity — letting an exit through that
123
+ * panics on-chain. The claim is load-bearing for the coverage guard and is verified only by the
124
+ * fork suite, not by any in-repo contract source.
125
+ *
126
+ * @param params - Plan inputs.
127
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
128
+ * @param params.adapter - The vault's sole MorphoMarketV1AdapterV2, from
129
+ * {@link resolveVaultV2ForceWithdrawEligibility}.
130
+ * @param params.liquidityMarketId - Market the vault routes penalty-free liquidity through, or
131
+ * `undefined` when the vault has no liquidity adapter.
132
+ * @param params.exitAssets - Penalty-inclusive amount to exit.
133
+ * @param params.timestamp - Timestamp used to accrue every Morpho Blue market before converting
134
+ * adapter shares.
135
+ * @returns The resolved plan. `coveredAssets < assetsToDeallocate` means the exit would overrun the
136
+ * contract's unbounded loop; the caller decides how to report that.
137
+ * @throws {NonPositiveInputError} when `exitAssets` is not positive.
138
+ * @example
139
+ * ```ts
140
+ * import {
141
+ * computeVaultV2ForceWithdrawPlan,
142
+ * resolveVaultV2ForceWithdrawEligibility,
143
+ * } from "@morpho-org/morpho-sdk";
144
+ *
145
+ * const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData);
146
+ * if (eligibility.type === "eligible") {
147
+ * const plan = computeVaultV2ForceWithdrawPlan({
148
+ * vaultData,
149
+ * adapter: eligibility.adapter,
150
+ * liquidityMarketId: eligibility.liquidityMarketId,
151
+ * exitAssets: 1_000_000n,
152
+ * timestamp: 1_800_000_000n,
153
+ * });
154
+ * // plan.withdrawnAssets is what the user receives before the referral fee
155
+ * }
156
+ * ```
157
+ */
158
+ export function computeVaultV2ForceWithdrawPlan(params) {
159
+ const { vaultData, adapter, liquidityMarketId, exitAssets, timestamp } = params;
160
+ // Guard the exported planner: a non-positive `exitAssets` would flow a negative through
161
+ // `min(exitAssets, withdrawable)` and return a plan with negative amounts. The entity and preview
162
+ // reject it upstream; this protects direct importers of the advertised helper.
163
+ if (exitAssets <= 0n)
164
+ throw new NonPositiveInputError("exitAssets", exitAssets);
165
+ const penalty = vaultData.forceDeallocatePenalties[adapter.address] ?? 0n;
166
+ const idleAssets = vaultData.assetBalance;
167
+ // `min(adapterPosition, marketLiquidity)` per market, on interest-accrued market state — the
168
+ // contract reads `expectedMarketBalances`, so the un-accrued `maxWithdraw` helpers on
169
+ // `AccrualVaultV2` would understate capacity.
170
+ const availableByMarket = new Map(adapter.markets.map((market) => {
171
+ const accrued = market.accrueInterest(MathLib.max(timestamp, market.lastUpdate));
172
+ return [
173
+ market.id,
174
+ MathLib.min(accrued.toSupplyAssets(adapter.supplyShares[market.id] ?? 0n), accrued.liquidity),
175
+ ];
176
+ }));
177
+ const liquidityCapacity = liquidityMarketId == null
178
+ ? 0n
179
+ : (availableByMarket.get(liquidityMarketId) ?? 0n);
180
+ const withdrawableAssets = idleAssets + liquidityCapacity;
181
+ const assetsToWithdraw = MathLib.min(exitAssets, withdrawableAssets);
182
+ const assetsToDeallocate = MathLib.mulDivDown(exitAssets - assetsToWithdraw, MathLib.WAD, MathLib.WAD + penalty);
183
+ // The penalty-free leg pulls its shortfall through the liquidity adapter, draining that market
184
+ // before the force-deallocation loop reaches it.
185
+ const drainedFromLiquidityMarket = MathLib.zeroFloorSub(assetsToWithdraw, idleAssets);
186
+ if (liquidityMarketId != null && drainedFromLiquidityMarket > 0n) {
187
+ availableByMarket.set(liquidityMarketId, MathLib.zeroFloorSub(liquidityCapacity, drainedFromLiquidityMarket));
188
+ }
189
+ let coveredAssets = 0n;
190
+ const nonEmpty = [];
191
+ for (const available of availableByMarket.values()) {
192
+ if (available <= 0n)
193
+ continue;
194
+ coveredAssets += available;
195
+ nonEmpty.push(available);
196
+ }
197
+ // `maxExitAssets` must not depend on the requested amount. At the ceiling the penalty-free leg
198
+ // always drains the liquidity market completely, so that market contributes nothing to the
199
+ // force-deallocation loop — whereas a small request leaves part of it, which would overstate the
200
+ // ceiling for callers using it to cap an input.
201
+ let saturatedCoveredAssets = 0n;
202
+ for (const [marketId, available] of availableByMarket) {
203
+ if (marketId === liquidityMarketId)
204
+ continue;
205
+ if (available > 0n)
206
+ saturatedCoveredAssets += available;
207
+ }
208
+ // Worst-case leg count is the ascending walk: the most markets the loop can touch is the number
209
+ // of smallest positions that together reach `assetsToDeallocate`. Deliberately an upper bound, not
210
+ // a replay of the contract's prefetched `marketIds` order (where an earlier market may cover the
211
+ // whole request in one leg): this count feeds the share-burn *upper* bound behind the slippage
212
+ // floor, so it must hold for any execution order. Replaying a snapshot order that then diverges at
213
+ // inclusion (a market added or drained between `getData()` and execution) would under-count legs,
214
+ // over-state the floor, and false-revert a valid distressed exit — a worse failure than the
215
+ // bounded looseness (≤ `penaltyLegs - 1` asset-units, absorbed by `slippageTolerance`) the
216
+ // ascending walk leaves. Tightening it to the exact walk is a separate change needing fork
217
+ // coverage of the snapshot-vs-execution divergence.
218
+ let penaltyLegs = 0;
219
+ let remaining = assetsToDeallocate;
220
+ for (const available of nonEmpty.toSorted((a, b) => a === b ? 0 : a > b ? 1 : -1)) {
221
+ if (remaining <= 0n)
222
+ break;
223
+ penaltyLegs += 1;
224
+ remaining -= MathLib.min(available, remaining);
225
+ }
226
+ return {
227
+ penalty,
228
+ exitAssets,
229
+ assetsToWithdraw,
230
+ assetsToDeallocate,
231
+ // `sum(ceil(assetsᵢ·penalty/WAD)) <= ceil(sum(assetsᵢ)·penalty/WAD) + legs - 1`. The per-leg
232
+ // slack only exists because each chunk rounds its own charge up; at a zero penalty every chunk
233
+ // charges exactly nothing, so carrying the slack would invent penalty assets the contract never
234
+ // debits — inflating the share-burn denominator and weakening the derived bound.
235
+ penaltyAssets: penaltyLegs === 0 || penalty === 0n
236
+ ? 0n
237
+ : MathLib.wMulUp(assetsToDeallocate, penalty) + BigInt(penaltyLegs - 1),
238
+ withdrawnAssets: assetsToWithdraw + assetsToDeallocate,
239
+ coveredAssets,
240
+ // Both bounds keep the ceiling *actionable*, since callers cap an input field with it and the
241
+ // coverage error tells them to reduce to it. A vault with nothing to give reports zero: the
242
+ // inversion rounds up to `1n` at a positive penalty, and `1n` withdraws nothing, which the
243
+ // entity rejects. And the gross-up can exceed the ABI slot on an enormous snapshot, which the
244
+ // entity also rejects — so it saturates rather than advertising an unusable amount.
245
+ maxExitAssets: withdrawableAssets === 0n && saturatedCoveredAssets === 0n
246
+ ? 0n
247
+ : MathLib.min(withdrawableAssets +
248
+ MathLib.wMulUp(saturatedCoveredAssets + 1n, MathLib.WAD + penalty) -
249
+ 1n, maxUint256),
250
+ penaltyLegs,
251
+ };
252
+ }
253
+ /**
254
+ * Upper-bounds the vault shares a Vault V2 force withdrawal burns.
255
+ *
256
+ * The contract splits the burn across up to `penaltyLegs + 2` separate `VaultV2.withdraw` calls (the
257
+ * penalty-free leg, one per `forceDeallocate`, and the final deallocated leg), each rounding its own
258
+ * share burn up. Converting the aggregate already spends one ceiling, so the bound adds one share
259
+ * per *additional* leg that moves a positive amount — a zero-amount leg burns `toShares(0, "Up")`
260
+ * and rounds nothing.
261
+ *
262
+ * The result is the **denominator of {@link computeMinForceWithdrawSharePrice}** — the largest share
263
+ * burn the realized exit price is measured against. It takes the max over the two supplied snapshots
264
+ * because interest lowers the burn while management fees raise it, so neither snapshot alone bounds
265
+ * execution. The entity passes both accrued to `now` (execution time): the raw `lastUpdate` snapshot
266
+ * underestimates the burn a stale fee-bearing vault realizes — the first withdrawal accrues pending
267
+ * management fees before burning shares — which lifts the floor above the faithful price and trips
268
+ * `SlippageExceeded`. Accruing to `now`, not the caller-chosen `deadline`, tracks execution without
269
+ * letting a long deadline silently weaken the guard; `slippageTolerance` absorbs the residual drift
270
+ * until inclusion. Pass distinct snapshots to bound the burn across an accrual window.
271
+ *
272
+ * This is **not** the share allowance to authorize. The price floor's denominator is this bound
273
+ * minus `computeVaultV2ForceWithdrawFeeSharesMinted({ vaultData, owner, timestamp: now })`: the
274
+ * contract measures the *net* burn, which fee mints to `owner` shrink. The allowance is
275
+ * `min(mulDivUp(exitAssets, RAY, minSharePriceE27) + computeVaultV2ForceWithdrawFeeSharesMinted({
276
+ * vaultData, owner, timestamp: deadline }), maxUint256)`: the permit pays for the *gross* burn.
277
+ *
278
+ * @param params - Share-bound inputs.
279
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
280
+ * @param params.deadlineVaultData - The same vault accrued to a second timestamp; the max of the two
281
+ * share burns is returned. The entity passes the `now`-accrued snapshot for both.
282
+ * @param params.plan - Plan from {@link computeVaultV2ForceWithdrawPlan}.
283
+ * @returns An upper bound, in vault shares, of what the exit burns.
284
+ * @example
285
+ * ```ts
286
+ * import { MathLib } from "@morpho-org/blue-sdk";
287
+ * import {
288
+ * computeVaultV2ForceWithdrawFeeSharesMinted,
289
+ * computeVaultV2ForceWithdrawSharesBurnt,
290
+ * } from "@morpho-org/morpho-sdk";
291
+ *
292
+ * const { vault: nowVaultData } = vaultData.accrueInterest(now);
293
+ * const sharesBurnt = computeVaultV2ForceWithdrawSharesBurnt({
294
+ * vaultData: nowVaultData,
295
+ * deadlineVaultData: nowVaultData,
296
+ * plan,
297
+ * });
298
+ * const feeSharesNow = computeVaultV2ForceWithdrawFeeSharesMinted({
299
+ * vaultData,
300
+ * owner,
301
+ * timestamp: now,
302
+ * });
303
+ * const sharesBurntForFloor = sharesBurnt - feeSharesNow;
304
+ * const requiredShareAllowance = MathLib.min(
305
+ * MathLib.mulDivUp(exitAssets, MathLib.RAY, minSharePriceE27) +
306
+ * computeVaultV2ForceWithdrawFeeSharesMinted({
307
+ * vaultData,
308
+ * owner,
309
+ * timestamp: deadline,
310
+ * }),
311
+ * maxUint256,
312
+ * );
313
+ * ```
314
+ */
315
+ export function computeVaultV2ForceWithdrawSharesBurnt(params) {
316
+ const { vaultData, deadlineVaultData, plan } = params;
317
+ // `penaltyAssets` already carries the per-market ceil accumulation, so this is the full
318
+ // penalty-inclusive amount debited from the user's position.
319
+ const grossDebited = plan.withdrawnAssets + plan.penaltyAssets;
320
+ // Only withdrawals that move a positive amount round anything: `toShares(0, "Up")` is `0`. So the
321
+ // penalty-free leg counts only when it pays out, the `forceDeallocate` burns count only at a
322
+ // positive penalty, and the deallocated leg counts only when the loop deallocated something.
323
+ const positiveLegs = (plan.assetsToWithdraw > 0n ? 1 : 0) +
324
+ (plan.penalty > 0n ? plan.penaltyLegs : 0) +
325
+ (plan.assetsToDeallocate > 0n ? 1 : 0);
326
+ return (MathLib.max(vaultData.toShares(grossDebited, "Up"), deadlineVaultData.toShares(grossDebited, "Up")) +
327
+ // `sum(ceil(sharesᵢ)) <= ceil(sum(sharesᵢ)) + (positiveLegs - 1)`: the aggregate conversion above
328
+ // already spends one ceiling, so only the *additional* positive legs can each cost one more
329
+ // share. A fixed `penaltyLegs + 2` overcounts every zero-amount leg, and because this value is
330
+ // the slippage denominator an overcount silently widens the price drop the bound accepts —
331
+ // worst on a dust exit, where two phantom shares can dominate the real burn.
332
+ BigInt(positiveLegs > 0 ? positiveLegs - 1 : 0));
333
+ }
334
+ /**
335
+ * Computes a lower bound of the Vault V2 shares that a force withdrawal burns.
336
+ *
337
+ * The penalty-free/penalised split can move as liquidity accrues between planning and inclusion.
338
+ * This lower bound is used to reject fee-recipient exits whose fee mints could reach the burn
339
+ * measured by VaultExitBundlesV1, independently of that split.
340
+ *
341
+ * @param params - Lower-bound inputs.
342
+ * @param params.vaultData - Vault V2 snapshot already accrued to the execution timestamp.
343
+ * @param params.plan - Plan from {@link computeVaultV2ForceWithdrawPlan}.
344
+ * @returns A lower bound, in vault shares, of the burn measured by the contract.
345
+ * @example
346
+ * ```ts
347
+ * import { computeVaultV2ForceWithdrawMinSharesBurnt } from "@morpho-org/morpho-sdk";
348
+ *
349
+ * const minSharesBurnt = computeVaultV2ForceWithdrawMinSharesBurnt({
350
+ * vaultData,
351
+ * plan,
352
+ * });
353
+ * ```
354
+ */
355
+ export function computeVaultV2ForceWithdrawMinSharesBurnt(params) {
356
+ const { vaultData, plan } = params;
357
+ // The penalty-free/penalised split moves as the liquidity market accrues, but any split debits
358
+ // within `1 + penalty` (< 2 asset units) of `exitAssets`, so `exitAssets - 1` lower-bounds every
359
+ // execution-time split.
360
+ return vaultData.toShares(MathLib.min(plan.withdrawnAssets +
361
+ MathLib.wMulUp(plan.assetsToDeallocate, plan.penalty), MathLib.zeroFloorSub(plan.exitAssets, 1n)), "Down");
362
+ }