@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
@@ -1,15 +1,18 @@
1
- import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, getChainAddresses, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
1
+ import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
- import { getChainAddress, Time } from "@morpho-org/morpho-ts";
4
- import { erc20Abi, isAddressEqual } from "viem";
3
+ import { _try, getChainAddress, Time } from "@morpho-org/morpho-ts";
4
+ import { erc20Abi, isAddressEqual, maxUint256 } from "viem";
5
5
  import { multicall } from "viem/actions";
6
- import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesRequirementSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
6
+ import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundlesFunding, selectBundlesSharesPermitSignature, selectBundlesSharesRequirementSignature, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
7
7
  import { encodeErc20Approval, encodeVaultSharesPermit, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
8
- import { computeVaultMaxShareAllowance, computeVaultMaxSharePrice, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
9
- import { validateNativeVaultAsset, validateUint256Field, } from "../../helpers/validate.js";
10
- import { AdapterNotPartOfVaultError, ChainIdMismatchError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemRequiresSingleAdapterError, InKindRedeemZeroDeallocationError, InsufficientBlueBalanceForInKindRedeemError, isRequirementSignature, NonPositiveInputError, selectRequirementSignatures, UnsupportedInKindAdapterError, VaultAddressMismatchError, } from "../../types/index.js";
8
+ import { computeMinForceWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, MAX_SLIPPAGE_TOLERANCE, resolveVaultV2ForceWithdrawEligibility, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
9
+ import { validateDeadline, validateNativeVaultAsset, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
10
+ import { AdapterNotPartOfVaultError, ChainIdMismatchError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemZeroDeallocationError, InputExceedsMaxError, InsufficientBlueBalanceForInKindRedeemError, isRequirementSignature, NonPositiveInputError, VaultAddressMismatchError, VaultV2ForceWithdrawCoverageError, VaultV2ForceWithdrawFeeSharesExceedBurnError, VaultV2ForceWithdrawSharePriceBelowFloorError, VaultV2ForceWithdrawZeroSharePriceError, VaultV2ForceWithdrawZeroWithdrawalError, VaultV2SingleAdapterRequiredError, VaultV2UndecodableLiquidityDataError, VaultV2UnsupportedExitAdapterError, VaultV2UnsupportedLiquidityAdapterError, } from "../../types/index.js";
11
11
  import { getVaultBundlesSharesRequirements } from "../requirements/getVaultBundlesSharesRequirements.js";
12
12
  import { getBundlesTokenRequirements } from "../requirements/index.js";
13
+ // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
14
+ // accrual model stays well-defined inside it.
15
+ const VAULT_V2_FEE_PROJECTION_HORIZON = Time.s.from.y(1n);
13
16
  export class MorphoVaultV2 {
14
17
  client;
15
18
  vault;
@@ -27,7 +30,6 @@ export class MorphoVaultV2 {
27
30
  }
28
31
  return fetchAccrualVaultV2(this.vault, this.client.viemClient, {
29
32
  ...parameters,
30
- chainId: this.chainId,
31
33
  deployless: this.client.options.supportDeployless,
32
34
  });
33
35
  }
@@ -286,21 +288,24 @@ export class MorphoVaultV2 {
286
288
  const marketIdListSnapshot = marketParamsListSnapshot.map((marketParams) => MarketUtils.getMarketId(marketParams));
287
289
  const now = Time.timestamp();
288
290
  const deadline = deadlineOverride ?? now + Time.s.from.h(2n);
291
+ // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
292
+ // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
293
+ validateDeadline(deadline);
289
294
  if (deadline <= now)
290
295
  throw new ExpiredDeadlineError(deadline, now);
291
296
  if (vaultData.accrualAdapters.length !== 1) {
292
- throw new InKindRedeemRequiresSingleAdapterError(this.vault, vaultData.accrualAdapters.length);
297
+ throw new VaultV2SingleAdapterRequiredError(this.vault, vaultData.accrualAdapters.length);
293
298
  }
294
299
  const soleAdapter = vaultData.accrualAdapters[0];
295
300
  if (soleAdapter == null) {
296
- throw new InKindRedeemRequiresSingleAdapterError(this.vault, 0);
301
+ throw new VaultV2SingleAdapterRequiredError(this.vault, 0);
297
302
  }
298
303
  const adapter = adapterOverride ?? soleAdapter.address;
299
304
  if (!isAddressEqual(adapter, soleAdapter.address)) {
300
305
  throw new AdapterNotPartOfVaultError(this.vault, adapter);
301
306
  }
302
307
  if (!(soleAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
303
- throw new UnsupportedInKindAdapterError(adapter);
308
+ throw new VaultV2UnsupportedExitAdapterError(adapter);
304
309
  }
305
310
  const penalty = vaultData.forceDeallocatePenalties[soleAdapter.address] ?? 0n;
306
311
  const idleAssets = MathLib.min(vaultData.assetBalance, amount);
@@ -315,7 +320,9 @@ export class MorphoVaultV2 {
315
320
  if (assetsToDeallocate > 0n && marketParamsListSnapshot.length === 0) {
316
321
  throw new EmptyMarketParamsListError();
317
322
  }
318
- const assetsByMarket = new Map(soleAdapter.markets.map((market) => [
323
+ const assetsByMarket = new Map(soleAdapter.markets
324
+ .filter((market) => (soleAdapter.supplyShares[market.id] ?? 0n) !== 0n)
325
+ .map((market) => [
319
326
  market.id,
320
327
  market
321
328
  .accrueInterest(now)
@@ -358,8 +365,7 @@ export class MorphoVaultV2 {
358
365
  remaining -= chunk;
359
366
  }
360
367
  const vaultExitBundlesV1 = getChainAddress(this.chainId, "bundles.vaultExitBundlesV1");
361
- const addresses = getChainAddresses(this.chainId);
362
- const blue = addresses.blue ?? addresses.morpho;
368
+ const blue = getChainAddress(this.chainId, "blue");
363
369
  return {
364
370
  getRequirements: async () => {
365
371
  const requirementsTimestamp = Time.timestamp();
@@ -402,9 +408,14 @@ export class MorphoVaultV2 {
402
408
  required: peak,
403
409
  });
404
410
  }
405
- if (allowance >= requiredShareAllowance)
411
+ // In-kind withdrawals carry no onchain share cap, so the allowance itself is the cap. A
412
+ // larger leftover allowance would let a share-price loss burn past `requiredShareAllowance`.
413
+ if (allowance === requiredShareAllowance)
406
414
  return [];
407
- if (this.client.options.supportSignature) {
415
+ // A lowering permit can be skipped after its nonce is consumed, so oversized allowances
416
+ // must be reset with an onchain approval.
417
+ if (allowance < requiredShareAllowance &&
418
+ this.client.options.supportSignature) {
408
419
  return [
409
420
  encodeVaultSharesPermit({
410
421
  vault: vaultData,
@@ -428,8 +439,10 @@ export class MorphoVaultV2 {
428
439
  ];
429
440
  },
430
441
  buildTx: (signatures) => {
431
- const { permit } = selectRequirementSignatures(signatures, {
432
- permit: true,
442
+ const permit = selectBundlesSharesPermitSignature(signatures, {
443
+ spender: vaultExitBundlesV1,
444
+ amount: requiredShareAllowance,
445
+ deadline,
433
446
  });
434
447
  return vaultV2InKindRedeem({
435
448
  vault: { chainId: this.chainId, address: this.vault },
@@ -446,21 +459,234 @@ export class MorphoVaultV2 {
446
459
  },
447
460
  };
448
461
  }
449
- forceWithdraw({ deallocations, withdraw, userAddress, }) {
462
+ /** {@inheritDoc VaultV2Actions.forceWithdraw} */
463
+ forceWithdraw({ exitAssets, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, minSharePriceE27: minSharePriceE27Override, referralFeePct = 0n, referralFeeRecipient, }) {
450
464
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
465
+ if (!isAddressEqual(vaultData.address, this.vault)) {
466
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
467
+ }
468
+ if (exitAssets <= 0n)
469
+ throw new NonPositiveInputError("exitAssets", exitAssets);
470
+ validateUint256Field("exitAssets", exitAssets);
471
+ validateSlippageTolerance(slippageTolerance);
472
+ // Called for its throws only: the raw pair is forwarded to the action, which normalizes it
473
+ // again on the encode path so a direct action caller gets the same guarantees.
474
+ validateReferralFee({ referralFeePct, referralFeeRecipient });
475
+ if (minSharePriceE27Override != null) {
476
+ // An unbounded override reopens the exact hole this path closes: the contract reads
477
+ // `minSharePriceE27 == 0` as "no bound".
478
+ if (minSharePriceE27Override <= 0n) {
479
+ throw new NonPositiveInputError("minSharePriceE27", minSharePriceE27Override);
480
+ }
481
+ // And an override the uint256 slot cannot hold must fail here rather than after
482
+ // `getRequirements()` has already asked for an approval or a permit signature.
483
+ validateUint256Field("minSharePriceE27", minSharePriceE27Override);
484
+ }
485
+ const now = Time.timestamp();
486
+ const deadline = deadlineOverride ?? now + Time.s.from.h(2n);
487
+ // Reject the same bounds the action enforces, before `getRequirements()` can walk the caller
488
+ // through a vault-share approval or an EIP-712 permit for a deadline `buildTx()` cannot encode.
489
+ validateDeadline(deadline);
490
+ if (deadline <= now)
491
+ throw new ExpiredDeadlineError(deadline, now);
492
+ const maxDeadline = now + VAULT_V2_FEE_PROJECTION_HORIZON;
493
+ if (deadline > maxDeadline) {
494
+ throw new InputExceedsMaxError({
495
+ field: "deadline",
496
+ value: deadline,
497
+ max: maxDeadline,
498
+ });
499
+ }
500
+ const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData, adapterOverride);
501
+ switch (eligibility.type) {
502
+ case "eligible":
503
+ break;
504
+ case "adapterCount":
505
+ throw new VaultV2SingleAdapterRequiredError(this.vault, eligibility.adapters);
506
+ case "adapterMismatch":
507
+ throw new AdapterNotPartOfVaultError(this.vault, eligibility.adapter);
508
+ case "unsupportedAdapter":
509
+ throw new VaultV2UnsupportedExitAdapterError(eligibility.adapter);
510
+ case "unsupportedLiquidityAdapter":
511
+ throw new VaultV2UnsupportedLiquidityAdapterError({
512
+ vault: this.vault,
513
+ liquidityAdapter: eligibility.liquidityAdapter,
514
+ adapter: eligibility.adapter,
515
+ });
516
+ case "undecodableLiquidityData":
517
+ throw new VaultV2UndecodableLiquidityDataError({
518
+ vault: this.vault,
519
+ liquidityAdapter: eligibility.liquidityAdapter,
520
+ liquidityData: eligibility.liquidityData,
521
+ cause: eligibility.cause,
522
+ });
523
+ }
524
+ const { adapter: accrualAdapter, liquidityMarketId } = eligibility;
525
+ const adapter = accrualAdapter.address;
526
+ const plan = computeVaultV2ForceWithdrawPlan({
527
+ vaultData,
528
+ adapter: accrualAdapter,
529
+ liquidityMarketId,
530
+ exitAssets,
531
+ timestamp: now,
532
+ });
533
+ if (plan.withdrawnAssets <= 0n) {
534
+ throw new VaultV2ForceWithdrawZeroWithdrawalError({
535
+ vault: this.vault,
536
+ exitAssets,
537
+ penalty: plan.penalty,
538
+ });
539
+ }
540
+ // The contract's force-deallocation loop is unbounded: under-coverage panics on-chain.
541
+ if (plan.coveredAssets < plan.assetsToDeallocate) {
542
+ throw new VaultV2ForceWithdrawCoverageError({
543
+ required: plan.assetsToDeallocate,
544
+ covered: plan.coveredAssets,
545
+ maxExitAssets: plan.maxExitAssets,
546
+ });
547
+ }
548
+ const projectionTimestamp = deadline;
549
+ // VaultExitBundlesV1 measures shares as `sharesBefore - balanceAfter`; its first withdrawal
550
+ // accrues the vault before burning. Use the `now` accrual for the floor and the projected
551
+ // deadline accrual for the fee-mint guard.
552
+ const { vault: nowVaultData } = vaultData.accrueInterest(MathLib.max(now, vaultData.lastUpdate));
553
+ const { vault: projectedVaultData } = vaultData.accrueInterest(MathLib.max(projectionTimestamp, vaultData.lastUpdate));
554
+ const sharesBurntNow = computeVaultV2ForceWithdrawSharesBurnt({
555
+ vaultData: nowVaultData,
556
+ deadlineVaultData: nowVaultData,
557
+ plan,
558
+ });
559
+ const feeSharesNow = computeVaultV2ForceWithdrawFeeSharesMinted({
560
+ vaultData,
561
+ owner: userAddress,
562
+ timestamp: now,
563
+ });
564
+ const feeSharesProjected = computeVaultV2ForceWithdrawFeeSharesMinted({
565
+ vaultData,
566
+ owner: userAddress,
567
+ timestamp: projectionTimestamp,
568
+ });
569
+ const minSharesBurntProjected = computeVaultV2ForceWithdrawMinSharesBurnt({
570
+ vaultData: projectedVaultData,
571
+ plan,
572
+ });
573
+ // When fee shares are minted, the projected pair bounds every execution time in the window.
574
+ if (feeSharesProjected > 0n &&
575
+ feeSharesProjected >= minSharesBurntProjected) {
576
+ throw new VaultV2ForceWithdrawFeeSharesExceedBurnError({
577
+ vault: this.vault,
578
+ userAddress,
579
+ sharesBurnt: minSharesBurntProjected,
580
+ feeShares: feeSharesProjected,
581
+ });
582
+ }
583
+ // sharesBurntNow ≥ minSharesBurntNow ≥ minSharesBurntProjected > feeSharesProjected ≥ feeSharesNow
584
+ const netSharesBurntNow = sharesBurntNow - feeSharesNow;
585
+ if (minSharePriceE27Override != null) {
586
+ // The maximum-slippage threshold only bounds the override; unlike the transaction floor it
587
+ // may round to zero, in which case every positive override is acceptable.
588
+ const minAllowedSharePriceE27 = _try(() => computeMinForceWithdrawSharePrice({
589
+ withdrawnAssets: plan.withdrawnAssets,
590
+ sharesBurnt: netSharesBurntNow,
591
+ slippageTolerance: MAX_SLIPPAGE_TOLERANCE,
592
+ }), VaultV2ForceWithdrawZeroSharePriceError) ?? 1n;
593
+ if (minSharePriceE27Override < minAllowedSharePriceE27) {
594
+ throw new VaultV2ForceWithdrawSharePriceBelowFloorError({
595
+ minSharePriceE27: minSharePriceE27Override,
596
+ floorE27: minAllowedSharePriceE27,
597
+ });
598
+ }
599
+ }
600
+ const minSharePriceE27 = minSharePriceE27Override ??
601
+ computeMinForceWithdrawSharePrice({
602
+ withdrawnAssets: plan.withdrawnAssets,
603
+ sharesBurnt: netSharesBurntNow,
604
+ slippageTolerance,
605
+ });
606
+ // The floor is deliberately *not* capped at `MAX_ABSOLUTE_SHARE_PRICE` (100 assets/share):
607
+ // lowering a lower bound weakens it, so any vault whose share price grew past that would be left
608
+ // with no real protection. Its two sibling `computeMin*SharePrice` helpers cap nothing either —
609
+ // only the `computeMax*` ones do, where capping relaxes an upper bound and is safe.
610
+ validateUint256Field("minSharePriceE27", minSharePriceE27);
611
+ // VaultExitBundlesV1's burn bound includes fee shares minted by the first withdrawal. Add the
612
+ // projected fee shares to the price-floor ceiling so the approval covers that mint.
613
+ // Saturated at `maxUint256` as an ABI-slot guard for an otherwise valid extreme share burn.
614
+ const requiredShareAllowance = MathLib.min(MathLib.mulDivUp(exitAssets, MathLib.RAY, minSharePriceE27) +
615
+ feeSharesProjected, maxUint256);
616
+ const vaultExitBundlesV1 = getChainAddress(this.chainId, "bundles.vaultExitBundlesV1");
451
617
  return {
452
- buildTx: () => vaultV2ForceWithdraw({
453
- vault: { address: this.vault },
454
- args: {
455
- deallocations,
456
- withdraw: {
457
- amount: withdraw.amount,
458
- recipient: userAddress,
618
+ getRequirements: async () => {
619
+ const requirementsTimestamp = Time.timestamp();
620
+ if (deadline <= requirementsTimestamp) {
621
+ throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
622
+ }
623
+ // Vault gates are intentionally left to the final transaction: the receive-assets gate may
624
+ // inspect VaultExitBundlesV1's transient `initiator`, and a send-shares gate is arbitrary
625
+ // external code re-evaluated after each intermediate penalty burn, so neither is
626
+ // execution-equivalent from a standalone read. Unlike in-kind redemption, this exit never
627
+ // supplies into Morpho Blue, so no Blue token-balance check is needed.
628
+ const [allowance, nonce] = await multicall(this.client.viemClient, {
629
+ allowFailure: false,
630
+ contracts: [
631
+ {
632
+ address: this.vault,
633
+ abi: erc20Abi,
634
+ functionName: "allowance",
635
+ args: [userAddress, vaultExitBundlesV1],
636
+ },
637
+ {
638
+ address: this.vault,
639
+ abi: erc2612Abi,
640
+ functionName: "nonces",
641
+ args: [userAddress],
642
+ },
643
+ ],
644
+ });
645
+ if (allowance >= requiredShareAllowance)
646
+ return [];
647
+ if (this.client.options.supportSignature) {
648
+ const requirement = encodeVaultSharesPermit({
649
+ vault: vaultData,
650
+ version: "vaultV2",
651
+ spender: vaultExitBundlesV1,
652
+ owner: userAddress,
653
+ chainId: this.chainId,
654
+ nonce,
655
+ amount: requiredShareAllowance,
656
+ deadline,
657
+ });
658
+ return [requirement];
659
+ }
660
+ return [
661
+ encodeErc20Approval({
662
+ token: this.vault,
663
+ spender: vaultExitBundlesV1,
664
+ amount: requiredShareAllowance,
665
+ chainId: this.chainId,
666
+ }),
667
+ ];
668
+ },
669
+ buildTx: (signatures) => {
670
+ const permit = selectBundlesSharesPermitSignature(signatures, {
671
+ spender: vaultExitBundlesV1,
672
+ amount: requiredShareAllowance,
673
+ deadline,
674
+ });
675
+ return vaultV2ForceWithdraw({
676
+ vault: { chainId: this.chainId, address: this.vault },
677
+ args: {
678
+ adapter,
679
+ exitAssets,
680
+ minSharePriceE27,
681
+ userAddress,
682
+ deadline,
683
+ referralFeePct,
684
+ referralFeeRecipient,
685
+ requirementSignature: permit,
459
686
  },
460
- onBehalf: userAddress,
461
- },
462
- metadata: this.client.options.metadata,
463
- }),
687
+ metadata: this.client.options.metadata,
688
+ });
689
+ },
464
690
  };
465
691
  }
466
692
  forceRedeem({ deallocations, redeem, userAddress, }) {
@@ -363,7 +363,11 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
363
363
  * utilization defaults to 90% and is configurable through
364
364
  * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
365
365
  * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
366
- * considered.
366
+ * considered. Targets with no remaining supply or allocator capacity are skipped before
367
+ * projecting source interest. The adapter's minimum share minting requirement, supply-share
368
+ * limits, and target absolute or zero relative caps are checked against a one-asset deposit.
369
+ * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
370
+ * allocation does not increase after rounding.
367
371
  *
368
372
  * Shared-cap discovery is conservative. Operation planning searches at most
369
373
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -374,6 +378,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
374
378
  * @param marketId - Target Blue market id.
375
379
  * @param options - Optional discovery controls and operation to support.
376
380
  * @returns Flat action-ready reallocations and their post-simulation state.
381
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
377
382
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
378
383
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
379
384
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
@@ -430,6 +435,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
430
435
  * @param marketId - Target Blue market id.
431
436
  * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
432
437
  * @returns Reallocatable market and idle assets, or `0n` when none are available; rounding-only shared-cap fits may be conservatively omitted.
438
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
433
439
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
434
440
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
435
441
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -470,6 +476,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
470
476
  * @param utilization - Desired utilization, scaled by WAD. Defaults to 90%.
471
477
  * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
472
478
  * @returns Borrowable assets while remaining at or below `utilization`; rounding-only shared-cap fits may be conservatively omitted.
479
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
473
480
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
474
481
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
475
482
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -1,7 +1,8 @@
1
1
  import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, Market, MarketUtils, MathLib, UnsupportedVaultV2AdapterError, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
2
2
  import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
3
3
  import { isAddressEqual } from "viem";
4
- import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
4
+ import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
5
+ import { resolveMaxWithdrawalUtilization } from "../helpers/utilization.js";
5
6
  import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
6
7
  const MAX_SHARED_CAP_SEARCH_STEPS = 1024n;
7
8
  /** Creates isolated transaction-scoped state for one simulation. @internal */
@@ -41,18 +42,6 @@ const getAdapterIds = (cache, adapter, market) => {
41
42
  cache.set(key, ids);
42
43
  return ids;
43
44
  };
44
- const resolveMaxWithdrawalUtilization = (value) => {
45
- const utilization = value ?? DEFAULT_WITHDRAWAL_TARGET_UTILIZATION;
46
- if (utilization < 0n)
47
- throw new NegativeInputError("maxWithdrawalUtilization", utilization);
48
- if (utilization > MathLib.WAD)
49
- throw new InputExceedsMaxError({
50
- field: "maxWithdrawalUtilization",
51
- value: utilization,
52
- max: MathLib.WAD,
53
- });
54
- return utilization;
55
- };
56
45
  const resolveMaxPenalty = (value) => {
57
46
  const penalty = value ?? DEFAULT_MAX_REALLOCATION_PENALTY;
58
47
  if (penalty < 0n)
@@ -72,16 +61,10 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
72
61
  pendingTimelock: { ...vault.pendingTimelock },
73
62
  pendingGuardian: { ...vault.pendingGuardian },
74
63
  supplyQueue: [...vault.supplyQueue],
75
- publicAllocatorConfig: vault.publicAllocatorConfig == null
76
- ? undefined
77
- : { ...vault.publicAllocatorConfig },
78
64
  }, [...vault.allocations.values()].map(({ config, position }) => ({
79
65
  config: {
80
66
  ...config,
81
67
  pendingCap: { ...config.pendingCap },
82
- publicAllocatorConfig: config.publicAllocatorConfig == null
83
- ? undefined
84
- : { ...config.publicAllocatorConfig },
85
68
  },
86
69
  position: clonePosition(position, markets),
87
70
  })));
@@ -104,7 +87,11 @@ const cloneAdapter = (adapter, markets) => {
104
87
  if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter)
105
88
  return new AccrualVaultV2MorphoMarketV1Adapter({ ...base, marketParamsList: [...adapter.marketParamsList] }, adapter.positions.map((position) => clonePosition(position, markets)));
106
89
  if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter)
107
- return new AccrualVaultV2MorphoVaultV1Adapter({ ...base, morphoVaultV1: adapter.morphoVaultV1 }, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
90
+ return new AccrualVaultV2MorphoVaultV1Adapter({
91
+ ...base,
92
+ morphoVaultV1: adapter.morphoVaultV1,
93
+ parentAllocation: adapter.parentAllocation,
94
+ }, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
108
95
  throw new UnsupportedVaultV2AdapterError(adapter.address);
109
96
  };
110
97
  const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
@@ -568,7 +555,11 @@ export class VaultV2BlueReallocationData {
568
555
  * utilization defaults to 90% and is configurable through
569
556
  * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
570
557
  * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
571
- * considered.
558
+ * considered. Targets with no remaining supply or allocator capacity are skipped before
559
+ * projecting source interest. The adapter's minimum share minting requirement, supply-share
560
+ * limits, and target absolute or zero relative caps are checked against a one-asset deposit.
561
+ * Shared cap IDs that a source withdrawal can reduce remain eligible, as do deposits whose
562
+ * allocation does not increase after rounding.
572
563
  *
573
564
  * Shared-cap discovery is conservative. Operation planning searches at most
574
565
  * 1,024 base units above its targeted amount for the nearest executable fit.
@@ -579,6 +570,7 @@ export class VaultV2BlueReallocationData {
579
570
  * @param marketId - Target Blue market id.
580
571
  * @param options - Optional discovery controls and operation to support.
581
572
  * @returns Flat action-ready reallocations and their post-simulation state.
573
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
582
574
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
583
575
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
584
576
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
@@ -719,9 +711,7 @@ export class VaultV2BlueReallocationData {
719
711
  : BigInt(options.timestamp);
720
712
  let data = this;
721
713
  let simulationContext = context;
722
- data.setMarkets(Object.values(data.markets)
723
- .filter((market) => market != null)
724
- .map((market) => market.accrueInterest(timestamp)));
714
+ data.setMarkets([data.getMarket(marketId).accrueInterest(timestamp)]);
725
715
  const reallocations = [];
726
716
  const configuredVaults = Object.keys(data.vaults);
727
717
  const vaultKeyByLower = new Map(configuredVaults.map((vault) => [vault.toLowerCase(), vault]));
@@ -756,6 +746,7 @@ export class VaultV2BlueReallocationData {
756
746
  activeAdaptersCache.set(vaultAddress, activeAdapters);
757
747
  }
758
748
  const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
749
+ const minimumSupply = targetMarket.supply(1n, 0n);
759
750
  const rawCandidates = [];
760
751
  // Missing nested allocator state means the snapshot is incomplete, so
761
752
  // typed getter errors below must propagate. Only explicit zero caps or
@@ -777,17 +768,35 @@ export class VaultV2BlueReallocationData {
777
768
  const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
778
769
  const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
779
770
  const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
780
- if ([
771
+ const targetAllocations = [
781
772
  adapterCapAllocation,
782
773
  collateralCapAllocation,
783
774
  adapterMarketCapAllocation,
784
- ].some(({ absoluteCap }) => absoluteCap === 0n))
775
+ ];
776
+ if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
785
777
  continue;
786
778
  const expectedSupplyAssets = targetMarket.toSupplyAssets(adapter.supplyShares[marketId] ?? 0n);
787
779
  const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
788
780
  const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation + untracked);
781
+ const minimumAllocation = minimumSupply.market.toSupplyAssets((adapter.supplyShares[marketId] ?? 0n) + minimumSupply.shares);
782
+ const minimumAllocationChange = minimumAllocation - adapterMarketCapAllocation.allocation;
783
+ const blockedTargetIds = targetAllocations
784
+ .filter(({ allocation, absoluteCap, relativeCap }) => {
785
+ const nextAllocation = allocation + minimumAllocationChange;
786
+ return (nextAllocation > absoluteCap ||
787
+ (relativeCap === 0n && nextAllocation > 0n));
788
+ })
789
+ .map(({ id }) => id);
790
+ // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
791
+ if (targetSupplyHeadroom === 0n ||
792
+ allocatorHeadroom === 0n ||
793
+ minimumSupply.shares < minimumSupply.assets ||
794
+ minimumSupply.market.totalSupplyShares > MathLib.MAX_UINT_128 ||
795
+ blockedTargetIds.includes(adapterMarketCapId))
796
+ continue;
789
797
  if (publicAllocatorConfig.canPullFromIdle &&
790
- availableIdleAssets > 0n) {
798
+ availableIdleAssets > 0n &&
799
+ blockedTargetIds.length === 0) {
791
800
  const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
792
801
  if (assets > 0n) {
793
802
  rawCandidates.push({
@@ -823,8 +832,16 @@ export class VaultV2BlueReallocationData {
823
832
  const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
824
833
  if (sourceAllocations.some(({ allocation }) => allocation === 0n))
825
834
  continue;
826
- const expectedSourceSupplyAssets = sourceMarket.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n);
827
- const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, sourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
835
+ const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
836
+ if (sourceSupplyShares === 0n)
837
+ continue;
838
+ // A withdrawal can create target headroom only for shared cap IDs.
839
+ if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
840
+ continue;
841
+ const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
842
+ data.setMarkets([accruedSourceMarket]);
843
+ const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
844
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
828
845
  if (assets <= 0n)
829
846
  continue;
830
847
  rawCandidates.push({
@@ -845,9 +862,6 @@ export class VaultV2BlueReallocationData {
845
862
  for (const reallocation of rawCandidates) {
846
863
  let lower = 0n;
847
864
  let upper = reallocation.assets;
848
- // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
849
- if (targetMarket.toSupplyShares(upper, "Down") < upper)
850
- continue;
851
865
  const reallocationAdapter = data.getAdapter(reallocation.vault, reallocation.to.adapter);
852
866
  const targetIds = getAdapterIds(adapterIdsCache, reallocationAdapter, targetMarket);
853
867
  const sourceIds = new Set();
@@ -951,6 +965,7 @@ export class VaultV2BlueReallocationData {
951
965
  * @param marketId - Target Blue market id.
952
966
  * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
953
967
  * @returns Reallocatable market and idle assets, or `0n` when none are available; rounding-only shared-cap fits may be conservatively omitted.
968
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
954
969
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
955
970
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
956
971
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -1003,6 +1018,7 @@ export class VaultV2BlueReallocationData {
1003
1018
  * @param utilization - Desired utilization, scaled by WAD. Defaults to 90%.
1004
1019
  * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
1005
1020
  * @returns Borrowable assets while remaining at or below `utilization`; rounding-only shared-cap fits may be conservatively omitted.
1021
+ * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
1006
1022
  * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
1007
1023
  * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
1008
1024
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -1,49 +1,5 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError,
2
- /** @deprecated Use InvalidBlueMarketParamsError or the raw protocol subpath. */
3
- InvalidMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError,
4
- /** @deprecated Use UnknownBlueDataError or the raw protocol subpath. */
5
- UnknownDataError, UnknownFactory as UnknownBlueFactory,
6
- /** @deprecated Use UnknownBlueFactory or the raw protocol subpath. */
7
- UnknownFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError,
8
- /** @deprecated Use UnknownBlueMarketParamsError or the raw protocol subpath. */
9
- UnknownMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory,
10
- /** @deprecated Use UnknownBlueOfFactory or the raw protocol subpath. */
11
- UnknownOfFactory, UnknownTokenError as UnknownBlueTokenError,
12
- /** @deprecated Use UnknownBlueTokenError or the raw protocol subpath. */
13
- UnknownTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError,
14
- /** @deprecated Use UnknownBlueTokenPriceError or the raw protocol subpath. */
15
- UnknownTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError,
16
- /** @deprecated Use UnknownBlueVaultConfigError or the raw protocol subpath. */
17
- UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError,
18
- /** @deprecated Use UnsupportedBluePreLiquidationParamsError or the raw protocol subpath. */
19
- UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError,
20
- /** @deprecated Use UnsupportedBlueVaultV2AdapterError or the raw protocol subpath. */
21
- UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError, UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
22
2
  export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
23
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError,
24
- /** @deprecated Use InvalidMidnightOfferGroupError or the raw protocol subpath. */
25
- InvalidOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError,
26
- /** @deprecated Use InvalidMidnightOfferParameterError or the raw protocol subpath. */
27
- InvalidOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError,
28
- /** @deprecated Use InvalidMidnightPositionAccrualStateError or the raw protocol subpath. */
29
- InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError,
30
- /** @deprecated Use InvalidMidnightPositionAccrualTimestampError or the raw protocol subpath. */
31
- InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError,
32
- /** @deprecated Use InvalidMidnightPositionLossFactorError or the raw protocol subpath. */
33
- InvalidPositionLossFactorError, InvalidTickSpacingError as InvalidMidnightTickSpacingError,
34
- /** @deprecated Use InvalidMidnightTickSpacingError or the raw protocol subpath. */
35
- InvalidTickSpacingError, InvalidTreeError as InvalidMidnightTreeError,
36
- /** @deprecated Use InvalidMidnightTreeError or the raw protocol subpath. */
37
- InvalidTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError,
38
- /** @deprecated Use InvalidMidnightTreeHeightError or the raw protocol subpath. */
39
- InvalidTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError,
40
- /** @deprecated Use MidnightPriceGreaterThanOneError or the raw protocol subpath. */
41
- PriceGreaterThanOneError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError,
42
- /** @deprecated Use MidnightSettlementFeeExceedsPriceError or the raw protocol subpath. */
43
- SettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError,
44
- /** @deprecated Use MidnightTickOutOfRangeError or the raw protocol subpath. */
45
- TickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError,
46
- /** @deprecated Use UnknownMidnightCollateralIndexError or the raw protocol subpath. */
47
- UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
3
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
48
4
  export type { ErrorClass } from "@morpho-org/morpho-ts";
49
5
  export { _try, DivisionByZeroError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";