@morpho-org/morpho-sdk 9.8.0 → 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (303) hide show
  1. package/MIGRATION-v9-to-v10.md +114 -0
  2. package/README.md +109 -13
  3. package/lib/cjs/actions/blue/common.js +4 -2
  4. package/lib/cjs/actions/blue/withdrawBuyCallback.js +2 -1
  5. package/lib/cjs/actions/bundles/common.js +20 -14
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  7. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +3 -2
  8. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -1
  9. package/lib/cjs/actions/midnight/cancelAndMake.js +2 -1
  10. package/lib/cjs/actions/midnight/cancelOffers.d.ts +54 -0
  11. package/lib/cjs/actions/midnight/cancelOffers.js +108 -0
  12. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  13. package/lib/cjs/actions/midnight/index.js +1 -0
  14. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +4 -2
  15. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  16. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +3 -2
  17. package/lib/cjs/actions/midnight/takeBorrow.d.ts +1 -1
  18. package/lib/cjs/actions/midnight/takeBorrow.js +3 -2
  19. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -1
  20. package/lib/cjs/actions/midnight/takeLend.js +3 -2
  21. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  22. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +3 -2
  23. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +1 -1
  24. package/lib/cjs/actions/midnight/takeWithdraw.js +3 -2
  25. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +4 -2
  26. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  27. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  28. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  29. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  31. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +3 -3
  32. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  33. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +5 -13
  34. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  35. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  36. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
  37. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
  38. package/lib/cjs/actions/vaultV1/inKindRedeem.js +6 -3
  39. package/lib/cjs/actions/vaultV1/migrateToV2.js +1 -1
  40. package/lib/cjs/actions/vaultV2/forceWithdraw.js +4 -2
  41. package/lib/cjs/actions/vaultV2/inKindRedeem.js +4 -2
  42. package/lib/cjs/entities/blue/blue.d.ts +34 -28
  43. package/lib/cjs/entities/blue/blue.js +107 -77
  44. package/lib/cjs/entities/midnight/deadline.d.ts +2 -2
  45. package/lib/cjs/entities/midnight/deadline.js +4 -3
  46. package/lib/cjs/entities/midnight/midnight.d.ts +49 -51
  47. package/lib/cjs/entities/midnight/midnight.js +158 -138
  48. package/lib/cjs/entities/midnight/publication.d.ts +2 -0
  49. package/lib/cjs/entities/midnight/publication.js +193 -138
  50. package/lib/cjs/entities/midnight/types.d.ts +4 -4
  51. package/lib/cjs/entities/requirements/assertContractCode.js +4 -2
  52. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  53. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +24 -28
  54. package/lib/cjs/entities/requirements/getErc2612Permit.js +10 -5
  55. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -4
  56. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  57. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
  58. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.js +111 -0
  59. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
  60. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.js +76 -0
  61. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
  62. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.js +93 -0
  63. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
  64. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.js +85 -0
  65. package/lib/cjs/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
  66. package/lib/cjs/entities/vaultV1/migrateToV2Quote.js +37 -0
  67. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +12 -12
  68. package/lib/cjs/entities/vaultV1/vaultV1.js +90 -194
  69. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
  70. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.js +189 -0
  71. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
  72. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.js +110 -0
  73. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +16 -16
  74. package/lib/cjs/entities/vaultV2/vaultV2.js +94 -385
  75. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +14 -0
  76. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1599 -883
  77. package/lib/cjs/errors.d.ts +1 -1
  78. package/lib/cjs/errors.js +2 -1
  79. package/lib/cjs/helpers/deadShares.js +83 -47
  80. package/lib/cjs/helpers/encodeMidnightCalldata.js +4 -2
  81. package/lib/cjs/helpers/metadata.d.ts +14 -2
  82. package/lib/cjs/helpers/metadata.js +49 -8
  83. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +44 -27
  84. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +11 -2
  85. package/lib/cjs/helpers/utilization.js +10 -5
  86. package/lib/cjs/helpers/validate.js +88 -67
  87. package/lib/cjs/helpers/validateMidnightBounds.js +2 -1
  88. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +2 -1
  89. package/lib/cjs/helpers/validateMidnightPublication.js +4 -2
  90. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +177 -104
  91. package/lib/cjs/helpers/validatePositiveInput.js +2 -1
  92. package/lib/cjs/helpers/validateTakeableOffers.js +2 -1
  93. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +40 -22
  94. package/lib/cjs/index.d.ts +2 -2
  95. package/lib/cjs/index.js +10 -1
  96. package/lib/cjs/transactionPlan/approval.js +12 -1
  97. package/lib/cjs/transactionPlan/deposit.d.ts +22 -0
  98. package/lib/cjs/transactionPlan/deposit.js +139 -0
  99. package/lib/cjs/transactionPlan/error.d.ts +10 -8
  100. package/lib/cjs/transactionPlan/error.js +10 -8
  101. package/lib/cjs/transactionPlan/getTokenPermit.js +2 -1
  102. package/lib/cjs/transactionPlan/index.d.ts +18 -0
  103. package/lib/cjs/transactionPlan/index.js +23 -5
  104. package/lib/cjs/transactionPlan/intent.d.ts +3 -3
  105. package/lib/cjs/transactionPlan/intent.js +14 -7
  106. package/lib/cjs/transactionPlan/permit.d.ts +1 -1
  107. package/lib/cjs/transactionPlan/permit.js +86 -20
  108. package/lib/cjs/transactionPlan/plan.d.ts +16 -6
  109. package/lib/cjs/transactionPlan/plan.js +77 -24
  110. package/lib/cjs/transactionPlan/redeem.d.ts +18 -0
  111. package/lib/cjs/transactionPlan/redeem.js +63 -0
  112. package/lib/cjs/transactionPlan/requirements.d.ts +4 -3
  113. package/lib/cjs/transactionPlan/requirements.js +12 -6
  114. package/lib/cjs/transactionPlan/serde.d.ts +2 -2
  115. package/lib/cjs/transactionPlan/serde.js +45 -19
  116. package/lib/cjs/transactionPlan/shareSpending.d.ts +18 -0
  117. package/lib/cjs/transactionPlan/shareSpending.js +50 -0
  118. package/lib/cjs/transactionPlan/types.d.ts +117 -11
  119. package/lib/cjs/transactionPlan/validateActions.js +11 -1
  120. package/lib/cjs/transactionPlan/validation.js +6 -3
  121. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +93 -0
  122. package/lib/cjs/transactionPlan/vaultv1/deposit.js +94 -0
  123. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
  124. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +203 -0
  125. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
  126. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +217 -0
  127. package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +69 -0
  128. package/lib/cjs/transactionPlan/vaultv1/redeem.js +78 -0
  129. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +77 -0
  130. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +88 -0
  131. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +18 -33
  132. package/lib/cjs/transactionPlan/vaultv2/deposit.js +19 -143
  133. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
  134. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +155 -0
  135. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
  136. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +206 -0
  137. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
  138. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +206 -0
  139. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +84 -0
  140. package/lib/cjs/transactionPlan/vaultv2/redeem.js +86 -0
  141. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +18 -29
  142. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +21 -126
  143. package/lib/cjs/transactionPlan/version.js +2 -1
  144. package/lib/cjs/transactionPlan/withdraw.d.ts +18 -0
  145. package/lib/cjs/transactionPlan/withdraw.js +94 -0
  146. package/lib/cjs/types/action.d.ts +26 -2
  147. package/lib/cjs/types/action.js +17 -9
  148. package/lib/cjs/types/error.d.ts +8 -1
  149. package/lib/cjs/types/error.js +21 -6
  150. package/lib/cjs/types/metadata.d.ts +12 -2
  151. package/lib/cjs/version.d.ts +1 -1
  152. package/lib/cjs/version.js +1 -1
  153. package/lib/esm/actions/blue/common.js +4 -2
  154. package/lib/esm/actions/blue/withdrawBuyCallback.js +2 -1
  155. package/lib/esm/actions/bundles/common.js +20 -14
  156. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  157. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +3 -2
  158. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -1
  159. package/lib/esm/actions/midnight/cancelAndMake.js +2 -1
  160. package/lib/esm/actions/midnight/cancelOffers.d.ts +54 -0
  161. package/lib/esm/actions/midnight/cancelOffers.js +104 -0
  162. package/lib/esm/actions/midnight/index.d.ts +1 -0
  163. package/lib/esm/actions/midnight/index.js +1 -0
  164. package/lib/esm/actions/midnight/supplyCollateralBatch.js +4 -2
  165. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  166. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +3 -2
  167. package/lib/esm/actions/midnight/takeBorrow.d.ts +1 -1
  168. package/lib/esm/actions/midnight/takeBorrow.js +3 -2
  169. package/lib/esm/actions/midnight/takeLend.d.ts +1 -1
  170. package/lib/esm/actions/midnight/takeLend.js +3 -2
  171. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  172. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +3 -2
  173. package/lib/esm/actions/midnight/takeWithdraw.d.ts +1 -1
  174. package/lib/esm/actions/midnight/takeWithdraw.js +3 -2
  175. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +4 -2
  176. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  177. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  178. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  179. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  180. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  181. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +3 -3
  182. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  183. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +7 -15
  184. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  185. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  186. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
  187. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
  188. package/lib/esm/actions/vaultV1/inKindRedeem.js +6 -3
  189. package/lib/esm/actions/vaultV1/migrateToV2.js +1 -1
  190. package/lib/esm/actions/vaultV2/forceWithdraw.js +4 -2
  191. package/lib/esm/actions/vaultV2/inKindRedeem.js +4 -2
  192. package/lib/esm/entities/blue/blue.d.ts +34 -28
  193. package/lib/esm/entities/blue/blue.js +107 -77
  194. package/lib/esm/entities/midnight/deadline.d.ts +2 -2
  195. package/lib/esm/entities/midnight/deadline.js +4 -3
  196. package/lib/esm/entities/midnight/midnight.d.ts +49 -51
  197. package/lib/esm/entities/midnight/midnight.js +159 -139
  198. package/lib/esm/entities/midnight/publication.d.ts +2 -0
  199. package/lib/esm/entities/midnight/publication.js +193 -138
  200. package/lib/esm/entities/midnight/types.d.ts +4 -4
  201. package/lib/esm/entities/requirements/assertContractCode.js +4 -2
  202. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  203. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +25 -29
  204. package/lib/esm/entities/requirements/getErc2612Permit.js +10 -5
  205. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -4
  206. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  207. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
  208. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.js +108 -0
  209. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
  210. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.js +73 -0
  211. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
  212. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.js +90 -0
  213. package/lib/esm/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
  214. package/lib/esm/entities/vaultV1/inKindRedeemQuote.js +82 -0
  215. package/lib/esm/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
  216. package/lib/esm/entities/vaultV1/migrateToV2Quote.js +34 -0
  217. package/lib/esm/entities/vaultV1/vaultV1.d.ts +12 -12
  218. package/lib/esm/entities/vaultV1/vaultV1.js +96 -200
  219. package/lib/esm/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
  220. package/lib/esm/entities/vaultV2/forceWithdrawQuote.js +186 -0
  221. package/lib/esm/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
  222. package/lib/esm/entities/vaultV2/inKindRedeemQuote.js +107 -0
  223. package/lib/esm/entities/vaultV2/vaultV2.d.ts +16 -16
  224. package/lib/esm/entities/vaultV2/vaultV2.js +102 -393
  225. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +14 -0
  226. package/lib/esm/entities/vaultV2BlueReallocationData.js +1599 -883
  227. package/lib/esm/errors.d.ts +1 -1
  228. package/lib/esm/errors.js +1 -1
  229. package/lib/esm/helpers/deadShares.js +83 -47
  230. package/lib/esm/helpers/encodeMidnightCalldata.js +4 -2
  231. package/lib/esm/helpers/metadata.d.ts +14 -2
  232. package/lib/esm/helpers/metadata.js +48 -8
  233. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +44 -27
  234. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +11 -2
  235. package/lib/esm/helpers/utilization.js +10 -5
  236. package/lib/esm/helpers/validate.js +88 -67
  237. package/lib/esm/helpers/validateMidnightBounds.js +2 -1
  238. package/lib/esm/helpers/validateMidnightCollateralBatch.js +2 -1
  239. package/lib/esm/helpers/validateMidnightPublication.js +4 -2
  240. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +176 -103
  241. package/lib/esm/helpers/validatePositiveInput.js +2 -1
  242. package/lib/esm/helpers/validateTakeableOffers.js +2 -1
  243. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +40 -22
  244. package/lib/esm/index.d.ts +2 -2
  245. package/lib/esm/index.js +1 -1
  246. package/lib/esm/transactionPlan/approval.js +13 -2
  247. package/lib/esm/transactionPlan/deposit.d.ts +22 -0
  248. package/lib/esm/transactionPlan/deposit.js +135 -0
  249. package/lib/esm/transactionPlan/error.d.ts +10 -8
  250. package/lib/esm/transactionPlan/error.js +10 -8
  251. package/lib/esm/transactionPlan/getTokenPermit.js +2 -1
  252. package/lib/esm/transactionPlan/index.d.ts +18 -0
  253. package/lib/esm/transactionPlan/index.js +9 -0
  254. package/lib/esm/transactionPlan/intent.d.ts +3 -3
  255. package/lib/esm/transactionPlan/intent.js +14 -7
  256. package/lib/esm/transactionPlan/permit.d.ts +1 -1
  257. package/lib/esm/transactionPlan/permit.js +86 -20
  258. package/lib/esm/transactionPlan/plan.d.ts +16 -6
  259. package/lib/esm/transactionPlan/plan.js +73 -20
  260. package/lib/esm/transactionPlan/redeem.d.ts +18 -0
  261. package/lib/esm/transactionPlan/redeem.js +59 -0
  262. package/lib/esm/transactionPlan/requirements.d.ts +4 -3
  263. package/lib/esm/transactionPlan/requirements.js +12 -6
  264. package/lib/esm/transactionPlan/serde.d.ts +2 -2
  265. package/lib/esm/transactionPlan/serde.js +45 -19
  266. package/lib/esm/transactionPlan/shareSpending.d.ts +18 -0
  267. package/lib/esm/transactionPlan/shareSpending.js +47 -0
  268. package/lib/esm/transactionPlan/types.d.ts +117 -11
  269. package/lib/esm/transactionPlan/validateActions.js +11 -1
  270. package/lib/esm/transactionPlan/validation.js +6 -3
  271. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +93 -0
  272. package/lib/esm/transactionPlan/vaultv1/deposit.js +90 -0
  273. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
  274. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +198 -0
  275. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
  276. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +212 -0
  277. package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +69 -0
  278. package/lib/esm/transactionPlan/vaultv1/redeem.js +74 -0
  279. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +77 -0
  280. package/lib/esm/transactionPlan/vaultv1/withdraw.js +84 -0
  281. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +18 -33
  282. package/lib/esm/transactionPlan/vaultv2/deposit.js +21 -144
  283. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
  284. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +150 -0
  285. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
  286. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +201 -0
  287. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
  288. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +201 -0
  289. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +84 -0
  290. package/lib/esm/transactionPlan/vaultv2/redeem.js +82 -0
  291. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +18 -29
  292. package/lib/esm/transactionPlan/vaultv2/withdraw.js +23 -127
  293. package/lib/esm/transactionPlan/version.js +2 -1
  294. package/lib/esm/transactionPlan/withdraw.d.ts +18 -0
  295. package/lib/esm/transactionPlan/withdraw.js +90 -0
  296. package/lib/esm/types/action.d.ts +26 -2
  297. package/lib/esm/types/action.js +17 -9
  298. package/lib/esm/types/error.d.ts +8 -1
  299. package/lib/esm/types/error.js +21 -6
  300. package/lib/esm/types/metadata.d.ts +12 -2
  301. package/lib/esm/version.d.ts +1 -1
  302. package/lib/esm/version.js +1 -1
  303. package/package.json +15 -14
@@ -1,4 +1,4 @@
1
- import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, Market, MarketUtils, MathLib, UnsupportedVaultV2AdapterError, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
1
+ import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, Market, MarketUtils, MathLib, UnknownDataError, 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
4
  import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1ReferralFeeAssets, } from "../actions/blue/common.js";
@@ -14,8 +14,9 @@ const createCapReserveState = (markets) => ({
14
14
  });
15
15
  const cloneCapReserveState = (state) => {
16
16
  const touchedPairs = new Map();
17
- for (const [vault, pairs] of state.touchedPairs)
17
+ for (const [vault, pairs] of state.touchedPairs) {
18
18
  touchedPairs.set(vault, new Map(pairs));
19
+ }
19
20
  return {
20
21
  initialMarkets: { ...state.initialMarkets },
21
22
  marketAccruals: new Map(state.marketAccruals),
@@ -37,8 +38,9 @@ const createSimulationContext = () => ({
37
38
  * @internal
38
39
  */
39
40
  const findAddressKey = (record, address) => {
40
- if (Object.hasOwn(record, address))
41
+ if (Object.hasOwn(record, address)) {
41
42
  return address;
43
+ }
42
44
  return Object.keys(record).find((key) => isAddressEqual(key, address));
43
45
  };
44
46
  /**
@@ -54,22 +56,25 @@ const findAddressKey = (record, address) => {
54
56
  const getAdapterIds = (cache, adapter, market) => {
55
57
  const key = `${adapter.address}:${market.id}`;
56
58
  const cached = cache.get(key);
57
- if (cached != null)
59
+ if (cached != null) {
58
60
  return cached;
61
+ }
59
62
  const ids = adapter.ids(market.params);
60
63
  cache.set(key, ids);
61
64
  return ids;
62
65
  };
63
66
  const resolveMaxPenalty = (value) => {
64
67
  const penalty = value ?? DEFAULT_MAX_REALLOCATION_PENALTY;
65
- if (penalty < 0n)
68
+ if (penalty < 0n) {
66
69
  throw new NegativeInputError("maxPenalty", penalty);
67
- if (penalty > MAX_REALLOCATION_PENALTY)
70
+ }
71
+ if (penalty > MAX_REALLOCATION_PENALTY) {
68
72
  throw new InputExceedsMaxError({
69
73
  field: "maxPenalty",
70
74
  value: penalty,
71
75
  max: MAX_REALLOCATION_PENALTY,
72
76
  });
77
+ }
73
78
  return penalty;
74
79
  };
75
80
  const getCanonicalMarket = (markets, market) => (markets[market.id] ??= new Market({ ...market }));
@@ -92,7 +97,7 @@ const cloneAdapter = (adapter, markets) => {
92
97
  parentVault: adapter.parentVault,
93
98
  skimRecipient: adapter.skimRecipient,
94
99
  };
95
- if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)
100
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2) {
96
101
  return new AccrualVaultV2MorphoMarketV1AdapterV2({
97
102
  ...base,
98
103
  marketIds: [...adapter.marketIds],
@@ -102,14 +107,17 @@ const cloneAdapter = (adapter, markets) => {
102
107
  // V2 adapters can retain the canonical instance directly, so every
103
108
  // adapter observes the same global Morpho market state.
104
109
  adapter.markets.map((market) => getCanonicalMarket(markets, market)));
105
- if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter)
110
+ }
111
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter) {
106
112
  return new AccrualVaultV2MorphoMarketV1Adapter({ ...base, marketParamsList: [...adapter.marketParamsList] }, adapter.positions.map((position) => clonePosition(position, markets)));
107
- if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter)
113
+ }
114
+ if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
108
115
  return new AccrualVaultV2MorphoVaultV1Adapter({
109
116
  ...base,
110
117
  morphoVaultV1: adapter.morphoVaultV1,
111
118
  parentAllocation: adapter.parentAllocation,
112
119
  }, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
120
+ }
113
121
  throw new UnsupportedVaultV2AdapterError(adapter.address);
114
122
  };
115
123
  const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
@@ -117,13 +125,14 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
117
125
  adapterKeysToClone.has(adapter.address.toLowerCase())
118
126
  ? cloneAdapter(adapter, markets)
119
127
  : adapter);
120
- const liquidityAdapter = vault.accrualLiquidityAdapter == null
128
+ const accrualLiquidityAdapter = vault.accrualLiquidityAdapter;
129
+ const liquidityAdapter = accrualLiquidityAdapter == null
121
130
  ? undefined
122
- : (adapters.find((adapter) => isAddressEqual(adapter.address, vault.accrualLiquidityAdapter.address)) ??
131
+ : (adapters.find((adapter) => isAddressEqual(adapter.address, accrualLiquidityAdapter.address)) ??
123
132
  (adapterKeysToClone == null ||
124
- adapterKeysToClone.has(vault.accrualLiquidityAdapter.address.toLowerCase())
125
- ? cloneAdapter(vault.accrualLiquidityAdapter, markets)
126
- : vault.accrualLiquidityAdapter));
133
+ adapterKeysToClone.has(accrualLiquidityAdapter.address.toLowerCase())
134
+ ? cloneAdapter(accrualLiquidityAdapter, markets)
135
+ : accrualLiquidityAdapter));
127
136
  return new AccrualVaultV2({
128
137
  ...vault,
129
138
  liquidityAllocations: vault.liquidityAllocations?.map((allocation) => ({
@@ -224,31 +233,11 @@ export class VaultV2BlueReallocationData {
224
233
  this.marketPublicAllocatorConfigs = input.marketPublicAllocatorConfigs;
225
234
  }
226
235
  else {
227
- const publicAllocatorConfigs = {};
228
- this.publicAllocatorConfigs = publicAllocatorConfigs;
229
- const activeAdapters = {};
230
- this.activeAdapters = activeAdapters;
231
- const marketPublicAllocatorConfigs = {};
232
- this.marketPublicAllocatorConfigs = marketPublicAllocatorConfigs;
233
- for (const [vault, config] of Object.entries(input.publicAllocatorConfigs ?? {})) {
234
- publicAllocatorConfigs[vault] =
235
- config == null
236
- ? undefined
237
- : new VaultV2BluePublicAllocatorConfig(config);
238
- }
239
- for (const [vault, adapters] of Object.entries(input.activeAdapters ?? {})) {
240
- activeAdapters[vault] =
241
- adapters == null ? undefined : new Set(adapters);
242
- }
243
- for (const [vault, configs] of Object.entries(input.marketPublicAllocatorConfigs ?? {})) {
244
- marketPublicAllocatorConfigs[vault] = {};
245
- for (const [id, config] of Object.entries(configs ?? {})) {
246
- marketPublicAllocatorConfigs[vault][id] =
247
- config == null
248
- ? undefined
249
- : new VaultV2BlueMarketPublicAllocatorConfig(config);
250
- }
251
- }
236
+ const configurations = cloneAllocatorConfigurations(input);
237
+ this.publicAllocatorConfigs = configurations.publicAllocatorConfigs;
238
+ this.activeAdapters = configurations.activeAdapters;
239
+ this.marketPublicAllocatorConfigs =
240
+ configurations.marketPublicAllocatorConfigs;
252
241
  }
253
242
  for (const [marketId, market] of Object.entries(input.markets ?? {})) {
254
243
  this.mutableMarkets[marketId] =
@@ -264,14 +253,20 @@ export class VaultV2BlueReallocationData {
264
253
  : cloneVault(vault, { markets: this.mutableMarkets });
265
254
  this.mutableVaults[address] = clonedVault;
266
255
  }
256
+ // Populate the instance's allocation snapshots after cloning vault views.
257
+ this.copyAllocationSnapshots(input, isClone);
258
+ }
259
+ /** Copies allocation entries, retaining the clone path's shallow-copy semantics. @internal */
260
+ copyAllocationSnapshots(input, isClone) {
267
261
  for (const [vault, allocations] of Object.entries(input.allocations ?? {})) {
268
262
  if (isClone) {
269
263
  this.mutableAllocations[vault] = { ...allocations };
270
264
  continue;
271
265
  }
272
- this.mutableAllocations[vault] = {};
266
+ const clonedAllocations = {};
267
+ this.mutableAllocations[vault] = clonedAllocations;
273
268
  for (const [id, allocation] of Object.entries(allocations ?? {})) {
274
- this.mutableAllocations[vault][id] =
269
+ clonedAllocations[id] =
275
270
  allocation == null ? undefined : { ...allocation };
276
271
  }
277
272
  }
@@ -335,8 +330,9 @@ export class VaultV2BlueReallocationData {
335
330
  */
336
331
  getMarket(marketId) {
337
332
  const market = this.mutableMarkets[marketId];
338
- if (market == null)
333
+ if (market == null) {
339
334
  throw new UnknownReallocationMarketError(marketId);
335
+ }
340
336
  return market;
341
337
  }
342
338
  /**
@@ -373,8 +369,9 @@ export class VaultV2BlueReallocationData {
373
369
  getMutableVault(vault) {
374
370
  const key = findAddressKey(this.mutableVaults, vault);
375
371
  const data = key == null ? undefined : this.mutableVaults[key];
376
- if (data == null)
372
+ if (data == null) {
377
373
  throw new UnknownReallocationVaultError(vault);
374
+ }
378
375
  return data;
379
376
  }
380
377
  /**
@@ -413,8 +410,9 @@ export class VaultV2BlueReallocationData {
413
410
  getAllocation(vault, id) {
414
411
  const key = findAddressKey(this.allocations, vault);
415
412
  const allocation = key == null ? undefined : this.allocations[key]?.[id];
416
- if (allocation == null)
413
+ if (allocation == null) {
417
414
  throw new UnknownReallocationAllocationError(vault, id);
415
+ }
418
416
  return allocation;
419
417
  }
420
418
  /**
@@ -448,8 +446,9 @@ export class VaultV2BlueReallocationData {
448
446
  */
449
447
  getPublicAllocatorConfig(vault) {
450
448
  const config = this.getOptionalPublicAllocatorConfig(vault);
451
- if (config == null)
449
+ if (config == null) {
452
450
  throw new UnknownReallocationPublicAllocatorConfigError(vault);
451
+ }
453
452
  return config;
454
453
  }
455
454
  /**
@@ -461,8 +460,9 @@ export class VaultV2BlueReallocationData {
461
460
  */
462
461
  getOptionalPublicAllocatorConfig(vault) {
463
462
  const key = findAddressKey(this.publicAllocatorConfigs, vault);
464
- if (key == null)
463
+ if (key == null) {
465
464
  throw new UnknownReallocationPublicAllocatorConfigError(vault);
465
+ }
466
466
  return this.publicAllocatorConfigs[key];
467
467
  }
468
468
  /**
@@ -495,8 +495,9 @@ export class VaultV2BlueReallocationData {
495
495
  getActiveAdapters(vault) {
496
496
  const key = findAddressKey(this.activeAdapters, vault);
497
497
  const adapters = key == null ? undefined : this.activeAdapters[key];
498
- if (adapters == null)
498
+ if (adapters == null) {
499
499
  throw new UnknownReallocationActiveAdaptersError(vault);
500
+ }
500
501
  return adapters;
501
502
  }
502
503
  /**
@@ -540,8 +541,9 @@ export class VaultV2BlueReallocationData {
540
541
  const config = key == null
541
542
  ? undefined
542
543
  : this.marketPublicAllocatorConfigs[key]?.[adapterMarketCapId];
543
- if (config == null)
544
+ if (config == null) {
544
545
  throw new UnknownReallocationMarketPublicAllocatorConfigError(vault, adapterMarketCapId);
546
+ }
545
547
  return config;
546
548
  }
547
549
  /**
@@ -580,8 +582,9 @@ export class VaultV2BlueReallocationData {
580
582
  getMutableAdapter(vault, adapter) {
581
583
  const data = this.getMutableVault(vault).accrualAdapters.find((candidate) => candidate instanceof AccrualVaultV2MorphoMarketV1AdapterV2 &&
582
584
  isAddressEqual(candidate.address, adapter));
583
- if (data == null)
585
+ if (data == null) {
584
586
  throw new UnknownReallocationAdapterError(vault, adapter);
587
+ }
585
588
  return data;
586
589
  }
587
590
  /**
@@ -707,8 +710,9 @@ export class VaultV2BlueReallocationData {
707
710
  * ```
708
711
  */
709
712
  computeVaultV2BlueReallocations(marketId, options = {}) {
710
- if (options.enabled === false)
713
+ if (options.enabled === false) {
711
714
  return { reallocations: [], data: this };
715
+ }
712
716
  const maxWithdrawalUtilization = resolveMaxWithdrawalUtilization(options.maxWithdrawalUtilization);
713
717
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
714
718
  const capAccrualBuffer = resolveCapAccrualBuffer(options.capAccrualBuffer);
@@ -727,16 +731,63 @@ export class VaultV2BlueReallocationData {
727
731
  return { reallocations, data };
728
732
  }
729
733
  const { amount, type } = operation;
730
- if (amount <= 0n)
731
- throw new NonPositiveInputError("amount", amount);
732
- const referralFeePct = type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
733
- if (referralFeePct < 0n)
734
- throw new NegativeInputError("referralFeePct", referralFeePct);
735
- if (referralFeePct >= MathLib.WAD)
736
- throw new ReferralFeePctExceededError(referralFeePct);
737
- const feeAssets = type === "refinance"
738
- ? getBlueBundlesV1ReferralFeeAssets(amount, referralFeePct)
734
+ const feeAssets = resolveOperationFeeAssets(operation);
735
+ const { normalizedOptions, market, hasExplicitBlueBalance, blueBalance } = this.resolveOperationSnapshot({ marketId, options, resolvedOptions });
736
+ const { newTotalBorrowAssets, newTotalSupplyAssets } = getOperationMarketTotals({ market, marketId, type, amount, feeAssets });
737
+ const requiredAssets = MathLib.wDivUp(newTotalBorrowAssets, DEFAULT_SUPPLY_TARGET_UTILIZATION) -
738
+ newTotalSupplyAssets;
739
+ if (MarketUtils.getUtilization({
740
+ totalSupplyAssets: newTotalSupplyAssets,
741
+ totalBorrowAssets: newTotalBorrowAssets,
742
+ }) <= DEFAULT_SUPPLY_TARGET_UTILIZATION ||
743
+ requiredAssets <= 0n) {
744
+ const data = this.clone();
745
+ data.setMarkets([market]);
746
+ return { reallocations: [], data };
747
+ }
748
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
749
+ ? newTotalBorrowAssets - newTotalSupplyAssets
739
750
  : 0n;
751
+ const penaltyTiers = [
752
+ 0n,
753
+ ...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
754
+ ? [config.penalty]
755
+ : [])),
756
+ ].sort(bigIntComparator((tier) => tier));
757
+ const plan = (maxAssets, { headroom, usePhysicalBalance = false, }) => planVaultOperation({
758
+ maxAssets,
759
+ headroom,
760
+ usePhysicalBalance,
761
+ absoluteShortfall,
762
+ penaltyTiers,
763
+ type,
764
+ maxWithdrawalUtilization,
765
+ amount,
766
+ feeAssets,
767
+ blueBalance,
768
+ capAccrualBuffer,
769
+ normalizedOptions,
770
+ hasExplicitBlueBalance,
771
+ marketId,
772
+ initialData: this,
773
+ initialMarkets: this.mutableMarkets,
774
+ runUtilizationPass: (data, args) => data.computeVaultV2BlueReallocationsAtUtilizationInPlace(args),
775
+ });
776
+ return selectOperationPlan({
777
+ plan,
778
+ requiredAssets,
779
+ allocatorCapHeadroom,
780
+ absoluteShortfall,
781
+ hasExplicitBlueBalance,
782
+ marketId,
783
+ type,
784
+ amount,
785
+ blueBalance,
786
+ feeAssets,
787
+ });
788
+ }
789
+ /** Resolves the operation's accrued market and shared-Blue liquidity snapshot. @internal */
790
+ resolveOperationSnapshot({ marketId, options, resolvedOptions, }) {
740
791
  const timestamp = options.timestamp == null
741
792
  ? this.getLatestSnapshotTimestamp()
742
793
  : BigInt(options.timestamp);
@@ -759,370 +810,10 @@ export class VaultV2BlueReallocationData {
759
810
  ? total +
760
811
  MathLib.zeroFloorSub(snapshotMarket.totalSupplyAssets, snapshotMarket.totalBorrowAssets)
761
812
  : total, 0n);
762
- const getTransferShortfall = (reallocations) => {
763
- const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
764
- if (penaltyAssets === 0n)
765
- return 0n;
766
- let shortfall = MathLib.zeroFloorSub(penaltyAssets, blueBalance);
767
- let balance = MathLib.zeroFloorSub(blueBalance, penaltyAssets);
768
- for (const { from, assets } of reallocations) {
769
- if (from.type === "idle")
770
- balance += assets;
771
- else
772
- shortfall = MathLib.max(shortfall, MathLib.zeroFloorSub(assets, balance));
773
- }
774
- return shortfall;
775
- };
776
- if (type === "withdraw" && amount > market.totalSupplyAssets) {
777
- throw new ReallocationWithdrawExceedsMarketSupplyError({
778
- marketId,
779
- withdrawAmount: amount,
780
- totalSupplyAssets: market.totalSupplyAssets,
781
- });
782
- }
783
- const newTotalBorrowAssets = type === "borrow"
784
- ? market.totalBorrowAssets + amount
785
- : type === "refinance"
786
- ? market.totalBorrowAssets + amount + feeAssets
787
- : market.totalBorrowAssets;
788
- const newTotalSupplyAssets = type === "withdraw"
789
- ? market.totalSupplyAssets - amount
790
- : market.totalSupplyAssets;
791
- const requiredAssets = MathLib.wDivUp(newTotalBorrowAssets, DEFAULT_SUPPLY_TARGET_UTILIZATION) -
792
- newTotalSupplyAssets;
793
- if (MarketUtils.getUtilization({
794
- totalSupplyAssets: newTotalSupplyAssets,
795
- totalBorrowAssets: newTotalBorrowAssets,
796
- }) <= DEFAULT_SUPPLY_TARGET_UTILIZATION ||
797
- requiredAssets <= 0n) {
798
- const data = this.clone();
799
- data.setMarkets([market]);
800
- return { reallocations: [], data };
801
- }
802
- const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
803
- ? newTotalBorrowAssets - newTotalSupplyAssets
804
- : 0n;
805
- const penaltyTiers = [
806
- 0n,
807
- ...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
808
- ? [config.penalty]
809
- : [])),
810
- ].sort(bigIntComparator((tier) => tier));
811
- const plan = (maxAssets, { headroom, usePhysicalBalance = false, }) => {
812
- let reserves = createCapReserveState(this.mutableMarkets);
813
- const reallocations = [];
814
- let data = this.clone();
815
- let context = createSimulationContext();
816
- let remainingShortfall = absoluteShortfall;
817
- let accountingShortfall = absoluteShortfall;
818
- let allocatorCapBoundTargets = new Set();
819
- let idleBoundVaults = new Set();
820
- for (const penalty of penaltyTiers) {
821
- if (type === "refinance" && penalty === MathLib.WAD)
822
- continue;
823
- let isFriendlyPass = true;
824
- let triedFullCapacityAttempt = false;
825
- for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
826
- const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
827
- isFriendlyPass = false;
828
- if (remainingShortfall === 0n && !isFreeFriendlyPass)
829
- continue;
830
- let passMaxAssets = type === "refinance" && penalty > 0n
831
- ? MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty)
832
- : isFreeFriendlyPass
833
- ? maxAssets
834
- : remainingShortfall;
835
- if (usePhysicalBalance && penalty > 0n) {
836
- const penaltyMultiplier = type === "refinance" ? 2n : 1n;
837
- const physicalPenalty = penaltyMultiplier * penalty;
838
- if (physicalPenalty < MathLib.WAD) {
839
- const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
840
- // Idle must fund both the operation and its penalty flash loan.
841
- const physicalShortfall = MathLib.zeroFloorSub(amount +
842
- feeAssets +
843
- penaltyMultiplier *
844
- getBlueBundlesV1PenaltyAssets(reallocations), blueBalance + idleAssets);
845
- passMaxAssets = MathLib.max(passMaxAssets, MathLib.mulDivUp(physicalShortfall, MathLib.WAD, MathLib.WAD - physicalPenalty));
846
- }
847
- }
848
- const retryPaidPass = penalty > 0n;
849
- let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
850
- let tryFullCapacityAttempt = false;
851
- let isFullCapacityRetryPath = false;
852
- const beforePassRemainingShortfall = remainingShortfall;
853
- const beforePassAccountingShortfall = accountingShortfall;
854
- // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
855
- const passStart = retryPaidPass
856
- ? {
857
- data: data.clone(),
858
- context,
859
- reserves: cloneCapReserveState(reserves),
860
- reallocationCount: reallocations.length,
861
- }
862
- : undefined;
863
- let previousPassReallocatedAssets = 0n;
864
- let previousPhysicalShortfall;
865
- let hi;
866
- let bestAttempt;
867
- while (true) {
868
- const isFullCapacityAttempt = tryFullCapacityAttempt;
869
- tryFullCapacityAttempt = false;
870
- if (passStart != null) {
871
- data = passStart.data.clone();
872
- context = passStart.context;
873
- reserves = cloneCapReserveState(passStart.reserves);
874
- reallocations.length = passStart.reallocationCount;
875
- }
876
- const pass = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
877
- context,
878
- reserves,
879
- marketId,
880
- maxWithdrawalUtilization: utilization,
881
- maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
882
- capAccrualBuffer,
883
- allocatorCapHeadroom: headroom,
884
- penalty,
885
- options: normalizedOptions,
886
- });
887
- reallocations.push(...pass.reallocations);
888
- data = pass.data;
889
- context = pass.context;
890
- if (isFreeFriendlyPass) {
891
- allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
892
- idleBoundVaults = pass.idleBoundVaults;
893
- }
894
- const currentMarket = data.getMarket(marketId);
895
- const penaltyAssets = type === "refinance"
896
- ? getBlueBundlesV1PenaltyAssets(reallocations)
897
- : 0n;
898
- const borrow = type === "borrow"
899
- ? currentMarket.totalBorrowAssets + amount
900
- : type === "refinance"
901
- ? currentMarket.totalBorrowAssets +
902
- amount +
903
- feeAssets +
904
- penaltyAssets
905
- : currentMarket.totalBorrowAssets;
906
- const supply = type === "withdraw"
907
- ? currentMarket.totalSupplyAssets - amount
908
- : currentMarket.totalSupplyAssets;
909
- accountingShortfall = borrow > supply ? borrow - supply : 0n;
910
- const penaltyForPhysicalShortfall = getBlueBundlesV1PenaltyAssets(reallocations);
911
- const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
912
- const physicalShortfall = penaltyForPhysicalShortfall === 0n
913
- ? 0n
914
- : MathLib.zeroFloorSub((type === "refinance"
915
- ? amount + feeAssets + penaltyForPhysicalShortfall
916
- : amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
917
- remainingShortfall = MathLib.max(accountingShortfall, physicalShortfall);
918
- const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
919
- ? getTransferShortfall(reallocations)
920
- : 0n;
921
- const attemptCoversShortfall = remainingShortfall === 0n;
922
- const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
923
- if (passStart == null)
924
- break;
925
- if (isFullCapacityAttempt)
926
- passMaxAssets = passReallocatedAssets;
927
- const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
928
- const attemptPriority = hasExplicitBlueBalance
929
- ? [0n, remainingShortfall, 0n, passReallocatedAssets]
930
- : [
931
- improvesAccounting ? 0n : 1n,
932
- improvesAccounting ? accountingShortfall : 0n,
933
- remainingShortfall,
934
- passReallocatedAssets,
935
- ];
936
- const previousBestAttempt = bestAttempt;
937
- let isBetterAttempt = previousBestAttempt == null;
938
- if (previousBestAttempt != null) {
939
- const firstDifference = attemptPriority.findIndex((priority, index) => priority !== previousBestAttempt.priority[index]);
940
- isBetterAttempt =
941
- firstDifference !== -1 &&
942
- attemptPriority[firstDifference] <
943
- previousBestAttempt.priority[firstDifference];
944
- }
945
- if (isBetterAttempt &&
946
- (!isFullCapacityRetryPath ||
947
- (attemptCoversShortfall && attemptTransferShortfall === 0n)))
948
- bestAttempt = {
949
- data,
950
- context,
951
- reserves: cloneCapReserveState(reserves),
952
- reallocations: pass.reallocations,
953
- remainingShortfall,
954
- accountingShortfall,
955
- passReallocatedAssets,
956
- priority: attemptPriority,
957
- };
958
- if (attemptCoversShortfall)
959
- hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
960
- else
961
- lo = MathLib.max(lo, passMaxAssets);
962
- if (hi != null) {
963
- if (hi - lo <= 1n)
964
- break;
965
- passMaxAssets = (lo + hi) / 2n;
966
- continue;
967
- }
968
- if (isFullCapacityAttempt && !attemptCoversShortfall)
969
- break;
970
- if (accountingShortfall === 0n &&
971
- previousPhysicalShortfall != null &&
972
- physicalShortfall >= previousPhysicalShortfall) {
973
- if (!triedFullCapacityAttempt &&
974
- passReallocatedAssets === passMaxAssets) {
975
- triedFullCapacityAttempt = true;
976
- tryFullCapacityAttempt = true;
977
- isFullCapacityRetryPath = true;
978
- continue;
979
- }
980
- break;
981
- }
982
- previousPhysicalShortfall = physicalShortfall;
983
- if (passReallocatedAssets <= previousPassReallocatedAssets ||
984
- penalty === MathLib.WAD)
985
- break;
986
- previousPassReallocatedAssets = passReallocatedAssets;
987
- passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
988
- }
989
- if (passStart != null) {
990
- const improved = bestAttempt != null &&
991
- (hasExplicitBlueBalance
992
- ? bestAttempt.remainingShortfall < beforePassRemainingShortfall
993
- : bestAttempt.accountingShortfall <
994
- beforePassAccountingShortfall ||
995
- bestAttempt.remainingShortfall <
996
- beforePassRemainingShortfall);
997
- if (improved && bestAttempt != null) {
998
- data = bestAttempt.data;
999
- context = bestAttempt.context;
1000
- reserves = cloneCapReserveState(bestAttempt.reserves);
1001
- reallocations.length = passStart.reallocationCount;
1002
- reallocations.push(...bestAttempt.reallocations);
1003
- remainingShortfall = bestAttempt.remainingShortfall;
1004
- accountingShortfall = bestAttempt.accountingShortfall;
1005
- }
1006
- else {
1007
- data = passStart.data;
1008
- context = passStart.context;
1009
- reserves = cloneCapReserveState(passStart.reserves);
1010
- reallocations.length = passStart.reallocationCount;
1011
- remainingShortfall = beforePassRemainingShortfall;
1012
- accountingShortfall = beforePassAccountingShortfall;
1013
- }
1014
- }
1015
- }
1016
- }
1017
- let reallocatedAssets = 0n;
1018
- let unboundAssets = 0n;
1019
- for (const { vault, from, to, assets } of reallocations) {
1020
- reallocatedAssets += assets;
1021
- const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
1022
- if (!allocatorCapBoundTargets.has(key) &&
1023
- !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
1024
- unboundAssets += assets;
1025
- }
1026
- const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
1027
- const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
1028
- const physicalShortfall = penaltyAssets === 0n
1029
- ? 0n
1030
- : MathLib.zeroFloorSub((type === "refinance"
1031
- ? amount + feeAssets + penaltyAssets
1032
- : amount) + penaltyAssets, blueBalance + idleAssets);
1033
- const transferShortfall = getTransferShortfall(reallocations);
1034
- const coversAccountingShortfall = type === "refinance"
1035
- ? reallocatedAssets >= absoluteShortfall + penaltyAssets
1036
- : reallocatedAssets >= absoluteShortfall;
1037
- return {
1038
- maxAssets,
1039
- headroom,
1040
- reallocations,
1041
- data,
1042
- liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
1043
- reallocatedAssets,
1044
- unboundAssets,
1045
- physicalShortfall,
1046
- coversShortfall: coversAccountingShortfall &&
1047
- (type === "refinance" || penaltyAssets <= amount) &&
1048
- (!hasExplicitBlueBalance ||
1049
- (physicalShortfall === 0n && transferShortfall === 0n)),
1050
- };
1051
- };
1052
- // A leg that fills an allocator cap, or idle legs that together take
1053
- // (nearly) all of a source vault's starting idle, revert once another
1054
- // allocation lands first. A bound plan therefore moves only the operation's
1055
- // shortfall, or what unbound legs moved.
1056
- const target = plan(requiredAssets, { headroom: allocatorCapHeadroom });
1057
- let selected = target;
1058
- if (allocatorCapHeadroom > 0n && target.liquidityBound) {
1059
- selected = plan(absoluteShortfall > target.unboundAssets
1060
- ? absoluteShortfall
1061
- : target.unboundAssets, { headroom: allocatorCapHeadroom });
1062
- // Shared-cap fitting is not monotonic in the budget.
1063
- if (!selected.coversShortfall && target.coversShortfall)
1064
- selected = target;
1065
- }
1066
- let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
1067
- // Without headroom, `target` already is the full-cap plan toward the target.
1068
- const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
1069
- for (const maxAssets of fullCapBudgets) {
1070
- if (selected.coversShortfall)
1071
- break;
1072
- selected = plan(maxAssets, { headroom: 0n });
1073
- if (selected.reallocatedAssets > available)
1074
- available = selected.reallocatedAssets;
1075
- }
1076
- if (!selected.coversShortfall) {
1077
- const selectedTransferShortfall = hasExplicitBlueBalance
1078
- ? getTransferShortfall(selected.reallocations)
1079
- : 0n;
1080
- const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
1081
- if (type !== "refinance" &&
1082
- selectedPenaltyAssets > amount &&
1083
- selected.reallocatedAssets >= absoluteShortfall &&
1084
- (!hasExplicitBlueBalance ||
1085
- (selected.physicalShortfall === 0n &&
1086
- selectedTransferShortfall === 0n)))
1087
- throw new InputExceedsMaxError({
1088
- field: "reallocationPenaltyAssets",
1089
- value: selectedPenaltyAssets,
1090
- max: amount,
1091
- });
1092
- throw new InsufficientSharedLiquidityError({
1093
- marketId,
1094
- shortfall: MathLib.max(absoluteShortfall +
1095
- (type === "refinance"
1096
- ? getBlueBundlesV1PenaltyAssets(selected.reallocations)
1097
- : 0n), selected.reallocatedAssets +
1098
- (hasExplicitBlueBalance
1099
- ? MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
1100
- : 0n)),
1101
- available,
1102
- });
1103
- }
1104
- const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
1105
- if (hasExplicitBlueBalance &&
1106
- selectedPenaltyAssets > 1n &&
1107
- blueBalance <
1108
- amount +
1109
- feeAssets +
1110
- (type === "refinance" ? 2n : 1n) * selectedPenaltyAssets) {
1111
- // Amount feasibility is not monotonic: retain the original plan unless
1112
- // the physical-balance seed finds a fully funded, strictly cheaper one.
1113
- const alternative = plan(selected.maxAssets, {
1114
- headroom: selected.headroom,
1115
- usePhysicalBalance: true,
1116
- });
1117
- if (alternative.coversShortfall &&
1118
- getBlueBundlesV1PenaltyAssets(alternative.reallocations) <
1119
- getBlueBundlesV1PenaltyAssets(selected.reallocations))
1120
- selected = alternative;
1121
- }
1122
- return { reallocations: selected.reallocations, data: selected.data };
813
+ return { normalizedOptions, market, hasExplicitBlueBalance, blueBalance };
1123
814
  }
1124
815
  computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
1125
- if (options.enabled === false)
816
+ if (options.enabled === false) {
1126
817
  return {
1127
818
  reallocations: [],
1128
819
  data: this,
@@ -1130,6 +821,7 @@ export class VaultV2BlueReallocationData {
1130
821
  allocatorCapBoundTargets: new Set(),
1131
822
  idleBoundVaults: new Set(),
1132
823
  };
824
+ }
1133
825
  this.getMarket(marketId);
1134
826
  const timestamp = options.timestamp == null
1135
827
  ? this.getLatestSnapshotTimestamp()
@@ -1151,298 +843,45 @@ export class VaultV2BlueReallocationData {
1151
843
  const idleBoundVaults = new Set();
1152
844
  const initialIdleAssets = new Map();
1153
845
  const idleTakenAssets = new Map();
1154
- // Onchain, market interest is booked once at transaction start, on pre-plan
1155
- // positions at pre-plan rates, and stays on touched positions' cap ids.
1156
- // This reserve state is shared across every planner pass and leg of the plan.
1157
- // biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
1158
- const getPair = (vault, adapter, market) => {
1159
- const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
1160
- const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
1161
- if (touched != null)
1162
- return touched;
1163
- const shares = adapter.supplyShares[market.id] ?? 0n;
1164
- return {
1165
- key,
1166
- ids: getAdapterIds(adapterIdsCache, adapter, market),
1167
- reserve: (reserveState) => {
1168
- let reserve = reserveState.reserveByPairKey.get(key);
1169
- if (reserve == null) {
1170
- let accruals = reserveState.marketAccruals.get(market.id);
1171
- if (accruals == null) {
1172
- const initialMarket = reserveState.initialMarkets[market.id];
1173
- if (initialMarket == null)
1174
- throw new UnknownReallocationMarketError(market.id);
1175
- accruals = [
1176
- initialMarket.accrueInterest(timestamp),
1177
- initialMarket.accrueInterest(timestamp + capAccrualBuffer),
1178
- ];
1179
- reserveState.marketAccruals.set(market.id, accruals);
1180
- }
1181
- const [atTimestamp, projected] = accruals;
1182
- reserve = MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
1183
- reserveState.reserveByPairKey.set(key, reserve);
1184
- }
1185
- return reserve;
1186
- },
1187
- };
1188
- };
1189
- // biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
1190
- const capReserve = (vault, id, candidatePairs) => {
1191
- let reserve = 0n;
1192
- const seen = new Set();
1193
- for (const pair of [
1194
- ...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
1195
- ...candidatePairs,
1196
- ]) {
1197
- if (seen.has(pair.key) || !pair.ids.includes(id))
1198
- continue;
1199
- seen.add(pair.key);
1200
- reserve += pair.reserve(reserves);
1201
- }
1202
- return reserve;
1203
- };
846
+ const { getPair, capReserve } = createCapReserveResolvers({
847
+ reserves,
848
+ adapterIdsCache,
849
+ timestamp,
850
+ capAccrualBuffer,
851
+ });
1204
852
  while (remainingAssets == null || remainingAssets > 0n) {
1205
853
  const candidates = vaults
1206
854
  .map((vaultAddress) => {
1207
- const targetMarket = data.getMarket(marketId);
1208
- const publicAllocatorConfig = data.getOptionalPublicAllocatorConfig(vaultAddress);
1209
- if (publicAllocatorConfig == null)
1210
- return;
1211
- const vault = data.getVault(vaultAddress);
1212
- if (!isAddressEqual(publicAllocatorConfig.vault, vaultAddress) ||
1213
- publicAllocatorConfig.penalty >
1214
- (options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY))
1215
- return;
1216
- if (penalty != null && publicAllocatorConfig.penalty !== penalty)
1217
- return;
1218
- const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
1219
- // Exclude rounded penalty dust from idle candidates so one donation
1220
- // cannot replenish liquidity for another same-plan reallocation.
1221
- const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssetsKey == null
1222
- ? 0n
1223
- : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey]);
1224
- const vaultAddressKey = vaultAddress.toLowerCase();
1225
- if (!initialIdleAssets.has(vaultAddressKey))
1226
- initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
1227
- let activeAdapters = activeAdaptersCache.get(vaultAddress);
1228
- if (activeAdapters == null) {
1229
- activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
1230
- activeAdaptersCache.set(vaultAddress, activeAdapters);
1231
- }
1232
- const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
1233
- const minimumSupply = targetMarket.supply(1n, 0n);
1234
- const rawCandidates = [];
1235
- // Missing nested allocator state means the snapshot is incomplete, so
1236
- // typed getter errors below must propagate. Only explicit zero caps or
1237
- // disabled permissions make an adapter ineligible.
1238
- for (const adapter of vault.accrualAdapters) {
1239
- if (!(adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
1240
- continue;
1241
- if (!isAddressEqual(adapter.parentVault, vaultAddress))
1242
- continue;
1243
- if (!isAddressEqual(targetMarket.params.loanToken, vault.asset) ||
1244
- !isAddressEqual(targetMarket.params.irm, adapter.adaptiveCurveIrm))
1245
- continue;
1246
- const targetPair = getPair(vaultAddress, adapter, targetMarket);
1247
- const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
1248
- const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
1249
- if (!isAddressEqual(marketPublicAllocatorConfig.vault, vaultAddress) ||
1250
- !isAddressEqual(marketPublicAllocatorConfig.adapter, adapter.address) ||
1251
- !activeAdapters.has(adapter.address.toLowerCase()))
1252
- continue;
1253
- const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
1254
- const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
1255
- const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
1256
- const targetAllocations = [
1257
- adapterCapAllocation,
1258
- collateralCapAllocation,
1259
- adapterMarketCapAllocation,
1260
- ];
1261
- if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
1262
- continue;
1263
- const adapterShares = adapter.supplyShares[marketId] ?? 0n;
1264
- const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
1265
- const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
1266
- const allocatorHeadroom = MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
1267
- untracked +
1268
- targetPair.reserve(reserves)), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
1269
- const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
1270
- const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
1271
- const blockedTargetIds = targetAllocations
1272
- .filter(({ allocation, absoluteCap, relativeCap, id }) => {
1273
- const nextAllocation = allocation +
1274
- capReserve(vaultAddress, id, [targetPair]) +
1275
- minimumAllocationChange;
1276
- return (nextAllocation > absoluteCap ||
1277
- (relativeCap === 0n && nextAllocation > 0n));
1278
- })
1279
- .map(({ id }) => id);
1280
- // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
1281
- if (targetSupplyHeadroom === 0n ||
1282
- allocatorHeadroom === 0n ||
1283
- minimumSupply.shares < minimumSupply.assets ||
1284
- minimumSupply.market.totalSupplyShares > MathLib.MAX_UINT_128 ||
1285
- blockedTargetIds.includes(adapterMarketCapId))
1286
- continue;
1287
- if (publicAllocatorConfig.canPullFromIdle &&
1288
- availableIdleAssets > 0n &&
1289
- blockedTargetIds.length === 0) {
1290
- const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
1291
- if (assets > 0n) {
1292
- rawCandidates.push({
1293
- reallocation: {
1294
- vault: vaultAddress,
1295
- from: { type: "idle" },
1296
- to: { adapter: adapter.address },
1297
- assets,
1298
- penalty: publicAllocatorConfig.penalty,
1299
- },
1300
- targetPair,
1301
- allocatorHeadroom,
1302
- });
1303
- }
1304
- }
1305
- for (const sourceAdapter of vault.accrualAdapters) {
1306
- if (!(sourceAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
1307
- continue;
1308
- if (!isAddressEqual(sourceAdapter.parentVault, vaultAddress))
1309
- continue;
1310
- if (!activeAdapters.has(sourceAdapter.address.toLowerCase()))
1311
- continue;
1312
- for (const sourceMarketReference of sourceAdapter.markets) {
1313
- const sourceMarket = data.getMarket(sourceMarketReference.id);
1314
- if (!isAddressEqual(sourceMarket.params.loanToken, vault.asset) ||
1315
- !isAddressEqual(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm))
1316
- continue;
1317
- if (sourceMarket.id.toLowerCase() === normalizedMarketId)
1318
- continue;
1319
- const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1320
- const [, , sourceAdapterMarketCapId] = sourceIds;
1321
- const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
1322
- if (!isAddressEqual(sourceConfig.vault, vaultAddress) ||
1323
- !isAddressEqual(sourceConfig.adapter, sourceAdapter.address) ||
1324
- !sourceConfig.canPullFromMarket)
1325
- continue;
1326
- const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
1327
- if (sourceAllocations.some(({ allocation }) => allocation === 0n))
1328
- continue;
1329
- const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1330
- if (sourceSupplyShares === 0n)
1331
- continue;
1332
- // A withdrawal can create target headroom only for shared cap IDs.
1333
- if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
1334
- continue;
1335
- const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
1336
- const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
1337
- data.setMarkets([accruedSourceMarket]);
1338
- const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
1339
- const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
1340
- if (assets <= 0n)
1341
- continue;
1342
- rawCandidates.push({
1343
- reallocation: {
1344
- vault: vaultAddress,
1345
- from: {
1346
- type: "market",
1347
- adapter: sourceAdapter.address,
1348
- marketParams: sourceMarket.params,
1349
- },
1350
- to: { adapter: adapter.address },
1351
- assets,
1352
- penalty: publicAllocatorConfig.penalty,
1353
- },
1354
- targetPair,
1355
- sourcePair,
1356
- allocatorHeadroom,
1357
- });
1358
- }
1359
- }
1360
- }
1361
- const capCompatibleCandidates = [];
1362
- for (const { reallocation, targetPair, sourcePair, allocatorHeadroom, } of rawCandidates) {
1363
- let lower = 0n;
1364
- let upper = reallocation.assets;
1365
- const targetIds = targetPair.ids;
1366
- const sourceIds = new Set(sourcePair?.ids ?? []);
1367
- const reserveById = new Map();
1368
- for (const id of targetIds)
1369
- reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
1370
- const probeReallocation = (assets) => {
1371
- if (targetMarket.totalSupplyShares +
1372
- targetMarket.toSupplyShares(assets, "Down") >
1373
- MathLib.MAX_UINT_128)
1374
- return;
1375
- const postTransition = _try(() => data.applyPublicReallocation({
1376
- context: simulationContext,
1377
- reallocation: { ...reallocation, assets },
1378
- targetMarketId: marketId,
1379
- timestamp: targetMarket.lastUpdate,
1380
- adapterIdsCache,
1381
- probe: true,
1382
- }), ReallocationAllocationUnderflowError, ReallocationAdapterSupplySharesUnderflowError);
1383
- if (postTransition == null)
1384
- return;
1385
- // Vault V2 checks relative caps against the transient firstTotalAssets,
1386
- // which stays fixed after the vault's first allocation in a transaction.
1387
- const { firstTotalAssets } = postTransition;
1388
- let withinUpperBounds = true;
1389
- let withinAllCaps = true;
1390
- for (const id of targetIds) {
1391
- const allocation = postTransition.data.getAllocation(reallocation.vault, id);
1392
- const capacity = VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
1393
- // The reserve covers interest accrued before inclusion by every
1394
- // position the plan touched on this cap id, as booked onchain.
1395
- const withinCap = allocation.absoluteCap > 0n &&
1396
- allocation.allocation + (reserveById.get(id) ?? 0n) <=
1397
- capacity;
1398
- if (!withinCap) {
1399
- withinAllCaps = false;
1400
- if (!sourceIds.has(id))
1401
- withinUpperBounds = false;
1402
- }
1403
- }
1404
- return { withinAllCaps, withinUpperBounds };
1405
- };
1406
- // Non-shared target IDs impose monotonic upper bounds. Shared IDs
1407
- // can impose lower bounds and non-monotonic rounding constraints,
1408
- // so validate them after selecting the non-shared maximum.
1409
- let probeUpper = true;
1410
- while (lower < upper) {
1411
- const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
1412
- probeUpper = false;
1413
- if (probeReallocation(assets)?.withinUpperBounds === true)
1414
- lower = assets;
1415
- else
1416
- upper = assets - 1n;
1417
- }
1418
- let selectedAssets = MathLib.min(lower, remainingAssets ?? reallocation.assets);
1419
- let probe = selectedAssets > 0n
1420
- ? probeReallocation(selectedAssets)
1421
- : undefined;
1422
- if (remainingAssets != null && probe?.withinAllCaps !== true) {
1423
- // Bound the base-unit scan; expose a caller ceiling if wider searches become necessary.
1424
- const searchUpper = MathLib.min(lower, selectedAssets + MAX_SHARED_CAP_SEARCH_STEPS);
1425
- while (selectedAssets > 0n &&
1426
- selectedAssets < searchUpper &&
1427
- probe?.withinAllCaps !== true) {
1428
- selectedAssets += 1n;
1429
- probe = probeReallocation(selectedAssets);
1430
- }
1431
- }
1432
- if (selectedAssets > 0n && probe?.withinAllCaps === true)
1433
- capCompatibleCandidates.push({
1434
- reallocation: { ...reallocation, assets: selectedAssets },
1435
- targetPair,
1436
- sourcePair,
1437
- allocatorHeadroom,
1438
- });
1439
- }
1440
- return capCompatibleCandidates.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"))[0];
855
+ const params = {
856
+ vaultAddress,
857
+ data,
858
+ marketId,
859
+ penalty,
860
+ options,
861
+ simulationContext,
862
+ normalizedMarketId,
863
+ adapterIdsCache,
864
+ getPair,
865
+ capReserve,
866
+ reserves,
867
+ allocatorCapHeadroom,
868
+ timestamp,
869
+ maxWithdrawalUtilization,
870
+ remainingAssets,
871
+ getOptionalPublicAllocatorConfig: data.getOptionalPublicAllocatorConfig.bind(data),
872
+ setMarkets: data.setMarkets.bind(data),
873
+ applyPublicReallocation: data.applyPublicReallocation.bind(data),
874
+ };
875
+ return planCachedVaultCandidate({
876
+ ...params,
877
+ initialIdleAssets,
878
+ activeAdaptersCache,
879
+ });
1441
880
  })
1442
881
  .filter((candidate) => candidate != null)
1443
882
  .sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"));
1444
883
  const largest = candidates[0];
1445
- if (largest == null)
884
+ if (largest == null) {
1446
885
  return {
1447
886
  reallocations,
1448
887
  data,
@@ -1450,31 +889,20 @@ export class VaultV2BlueReallocationData {
1450
889
  allocatorCapBoundTargets,
1451
890
  idleBoundVaults,
1452
891
  };
1453
- const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1454
- if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1455
- // BluePublicAllocator caps are per vault and target adapter.
1456
- allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1457
- if (acceptedReallocation.from.type === "idle") {
1458
- const vaultKey = acceptedReallocation.vault.toLowerCase();
1459
- const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
1460
- idleTakenAssets.set(vaultKey, taken);
1461
- // Candidates always record this; a missing entry counts the vault as bound.
1462
- const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1463
- if (taken >=
1464
- MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom)))
1465
- idleBoundVaults.add(vaultKey);
1466
- }
1467
- const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1468
- let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1469
- if (touchedVaultPairs == null) {
1470
- touchedVaultPairs = new Map();
1471
- reserves.touchedPairs.set(touchedVaultKey, touchedVaultPairs);
1472
892
  }
1473
- if (!touchedVaultPairs.has(acceptedTargetPair.key))
1474
- touchedVaultPairs.set(acceptedTargetPair.key, acceptedTargetPair);
1475
- if (acceptedSourcePair != null &&
1476
- !touchedVaultPairs.has(acceptedSourcePair.key))
1477
- touchedVaultPairs.set(acceptedSourcePair.key, acceptedSourcePair);
893
+ const updates = getAcceptedCandidateUpdates({
894
+ candidate: largest,
895
+ idleTakenAssets,
896
+ initialIdleAssets,
897
+ allocatorCapHeadroom,
898
+ reserves,
899
+ });
900
+ updates.allocatorCapBoundTargets.forEach((key) => allocatorCapBoundTargets.add(key));
901
+ updates.idleTakenAssets.forEach(([key, assets]) => idleTakenAssets.set(key, assets));
902
+ updates.idleBoundVaults.forEach((key) => idleBoundVaults.add(key));
903
+ updates.touchedVaultEntries.forEach(([key, pairs]) => reserves.touchedPairs.set(key, pairs));
904
+ updates.touchedPairEntries.forEach(([key, pair]) => updates.touchedVaultPairs.set(key, pair));
905
+ const { reallocation: acceptedReallocation } = largest;
1478
906
  reallocations.push(acceptedReallocation);
1479
907
  const transition = data.applyPublicReallocation({
1480
908
  context: simulationContext,
@@ -1485,8 +913,9 @@ export class VaultV2BlueReallocationData {
1485
913
  });
1486
914
  data = transition.data;
1487
915
  simulationContext = transition.context;
1488
- if (remainingAssets != null)
916
+ if (remainingAssets != null) {
1489
917
  remainingAssets -= acceptedReallocation.assets;
918
+ }
1490
919
  }
1491
920
  return {
1492
921
  reallocations,
@@ -1542,8 +971,9 @@ export class VaultV2BlueReallocationData {
1542
971
  * ```
1543
972
  */
1544
973
  getPublicReallocationLiquidity(marketId, options) {
1545
- if (options?.enabled === false)
974
+ if (options?.enabled === false) {
1546
975
  return 0n;
976
+ }
1547
977
  const capAccrualBuffer = resolveCapAccrualBuffer(options?.capAccrualBuffer);
1548
978
  const maxPenalty = resolveMaxPenalty(options?.maxPenalty);
1549
979
  return this.clone()
@@ -1612,8 +1042,9 @@ export class VaultV2BlueReallocationData {
1612
1042
  : BigInt(options.timestamp);
1613
1043
  const market = this.getMarket(marketId).accrueInterest(timestamp);
1614
1044
  if (options?.enabled === false ||
1615
- DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization)
1045
+ DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization) {
1616
1046
  return market.getBorrowToUtilization(utilization);
1047
+ }
1617
1048
  const availableLiquidity = this.clone()
1618
1049
  .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1619
1050
  context: createSimulationContext(),
@@ -1636,12 +1067,14 @@ export class VaultV2BlueReallocationData {
1636
1067
  getLatestSnapshotTimestamp() {
1637
1068
  let timestamp = this.timestamp ?? 0n;
1638
1069
  for (const market of Object.values(this.markets)) {
1639
- if (market != null)
1070
+ if (market != null) {
1640
1071
  timestamp = MathLib.max(timestamp, market.lastUpdate);
1072
+ }
1641
1073
  }
1642
1074
  for (const vault of Object.values(this.vaults)) {
1643
- if (vault != null)
1075
+ if (vault != null) {
1644
1076
  timestamp = MathLib.max(timestamp, vault.lastUpdate);
1077
+ }
1645
1078
  }
1646
1079
  return timestamp;
1647
1080
  }
@@ -1651,53 +1084,14 @@ export class VaultV2BlueReallocationData {
1651
1084
  const sourceVault = sourceVaultKey == null ? undefined : this.mutableVaults[sourceVaultKey];
1652
1085
  let data = this;
1653
1086
  if (probe) {
1654
- const probeMarkets = { [targetMarketId]: this.getMarket(targetMarketId) };
1655
- const adapterKeysToClone = new Set([
1656
- reallocation.to.adapter.toLowerCase(),
1657
- ]);
1658
- const allocationIdsToClone = new Set(getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.to.adapter), this.getMarket(targetMarketId)));
1659
- if (reallocation.from.type === "market") {
1660
- const sourceMarket = this.getMarket(reallocation.from.marketParams.id);
1661
- probeMarkets[sourceMarket.id] = sourceMarket;
1662
- adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
1663
- if (sourceVault != null) {
1664
- const adaptersToRefresh = new Set(sourceVault.accrualAdapters);
1665
- if (sourceVault.accrualLiquidityAdapter != null)
1666
- adaptersToRefresh.add(sourceVault.accrualLiquidityAdapter);
1667
- for (const adapter of adaptersToRefresh) {
1668
- if ((adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2 &&
1669
- adapter.markets.some(({ id }) => id === sourceMarket.id)) ||
1670
- (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter &&
1671
- adapter.positions.some(({ marketId }) => marketId === sourceMarket.id)) ||
1672
- (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter &&
1673
- adapter.accrualVaultV1.allocations.has(sourceMarket.id)))
1674
- adapterKeysToClone.add(adapter.address.toLowerCase());
1675
- }
1676
- }
1677
- for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket))
1678
- allocationIdsToClone.add(id);
1679
- }
1680
- data = new VaultV2BlueReallocationData({
1681
- chainId: this.chainId,
1682
- timestamp: this.timestamp,
1683
- markets: probeMarkets,
1087
+ data = this.cloneReallocationProbe({
1088
+ reallocation,
1089
+ targetMarketId,
1090
+ adapterIdsCache,
1091
+ sourceVaultKey,
1092
+ sourceVault,
1093
+ sourceAllocationsKey,
1684
1094
  });
1685
- if (sourceVaultKey != null) {
1686
- data.mutableVaults[sourceVaultKey] =
1687
- sourceVault == null
1688
- ? undefined
1689
- : cloneVault(sourceVault, {
1690
- markets: data.mutableMarkets,
1691
- adapterKeysToClone,
1692
- });
1693
- }
1694
- if (sourceAllocationsKey != null) {
1695
- const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
1696
- const allocations = {};
1697
- for (const id of allocationIdsToClone)
1698
- allocations[id] = sourceAllocations?.[id];
1699
- data.mutableAllocations[sourceAllocationsKey] = allocations;
1700
- }
1701
1095
  }
1702
1096
  const vaultKey = findAddressKey(data.mutableVaults, reallocation.vault) ??
1703
1097
  reallocation.vault;
@@ -1725,101 +1119,201 @@ export class VaultV2BlueReallocationData {
1725
1119
  };
1726
1120
  }
1727
1121
  if (reallocation.from.type === "market") {
1728
- const sourceAdapter = data.getMutableAdapter(reallocation.vault, reallocation.from.adapter);
1729
- const sourceMarket = data.getMarket(reallocation.from.marketParams.id);
1730
- const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1731
- const [, , sourceAdapterMarketCapId] = sourceIds;
1732
- const currentSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1733
- const withdrawal = sourceMarket.withdraw(reallocation.assets, 0n, timestamp);
1734
- if (withdrawal.shares > currentSupplyShares) {
1735
- throw new ReallocationAdapterSupplySharesUnderflowError({
1736
- vault: reallocation.vault,
1737
- adapter: sourceAdapter.address,
1738
- marketId: sourceMarket.id,
1739
- supplyShares: currentSupplyShares,
1740
- withdrawnShares: withdrawal.shares,
1741
- });
1742
- }
1743
- sourceAdapter.supplyShares[sourceMarket.id] =
1744
- currentSupplyShares - withdrawal.shares;
1745
- data.setMarkets([withdrawal.market]);
1746
- const sourceChange = withdrawal.market.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n) -
1747
- data.getAllocation(reallocation.vault, sourceAdapterMarketCapId)
1748
- .allocation;
1749
- for (const id of sourceIds) {
1750
- const allocation = data.getAllocation(reallocation.vault, id);
1751
- const nextAllocation = allocation.allocation + sourceChange;
1752
- if (nextAllocation < 0n) {
1753
- throw new ReallocationAllocationUnderflowError({
1754
- vault: reallocation.vault,
1755
- id,
1756
- allocation: allocation.allocation,
1757
- change: sourceChange,
1758
- });
1759
- }
1760
- data.mutableAllocations[allocationsKey][id] = {
1761
- ...allocation,
1762
- allocation: nextAllocation,
1763
- };
1764
- }
1765
- vault.assetBalance += reallocation.assets;
1122
+ // Book the source withdrawal and cap deltas before supplying the target.
1123
+ data.withdrawReallocationSource({
1124
+ reallocation,
1125
+ source: reallocation.from,
1126
+ timestamp,
1127
+ adapterIdsCache,
1128
+ allocationsKey,
1129
+ vault,
1130
+ });
1766
1131
  }
1132
+ // Idle allocations also credit the instance's explicit Blue liquidity balance.
1767
1133
  if (reallocation.from.type === "idle") {
1768
- const blueBalanceKey = findAddressKey(data.mutableBlueBalances, targetMarket.params.loanToken);
1769
- if (blueBalanceKey != null &&
1770
- data.mutableBlueBalances[blueBalanceKey] != null)
1771
- data.mutableBlueBalances[blueBalanceKey] += reallocation.assets;
1134
+ data.creditIdleReallocationBalance(reallocation, targetMarket);
1772
1135
  }
1773
1136
  if (firstTotalAssets == null) {
1774
- // Vault V2's transient firstTotalAssets tracks the first allocation in a
1775
- // transaction independently from elapsed time. Later allocations must not
1776
- // recompute the denominator, even if their simulated balances have changed.
1777
- if (timestamp === vault.lastUpdate) {
1778
- // AccrualVaultV2 skips zero-elapsed accruals, but the contract's first
1779
- // touch still reads real adapter assets. With zero elapsed time, its
1780
- // growth clamp leaves only existing losses to recognize.
1781
- const realAssets = vault.accrualAdapters.reduce((assets, adapter) => assets + adapter.realAssets(timestamp), vault.assetBalance);
1782
- vault._totalAssets = MathLib.min(realAssets, vault._totalAssets);
1783
- }
1784
- else {
1785
- vault = vault.accrueInterest(timestamp).vault;
1786
- }
1787
- data.mutableVaults[vaultKey] = vault;
1788
- firstTotalAssets = vault._totalAssets;
1789
- nextContext = {
1790
- ...nextContext,
1791
- firstTotalAssets: {
1792
- ...nextContext.firstTotalAssets,
1793
- [firstTotalAssetsKey]: firstTotalAssets,
1794
- },
1795
- };
1137
+ const firstAllocation = data.accrueReallocationFirstAllocation({
1138
+ vault,
1139
+ vaultKey,
1140
+ timestamp,
1141
+ context: nextContext,
1142
+ firstTotalAssetsKey,
1143
+ });
1144
+ vault = firstAllocation.vault;
1145
+ firstTotalAssets = firstAllocation.firstTotalAssets;
1146
+ nextContext = firstAllocation.context;
1796
1147
  }
1797
- const targetAdapter = data.getMutableAdapter(reallocation.vault, reallocation.to.adapter);
1148
+ // Book the target shares and cap deltas in the working state.
1149
+ data.supplyReallocationTarget({
1150
+ reallocation,
1151
+ adapterIdsCache,
1152
+ targetMarket,
1153
+ timestamp,
1154
+ probe,
1155
+ allocationsKey,
1156
+ });
1157
+ vault.assetBalance -= reallocation.assets;
1158
+ return { data, context: nextContext, firstTotalAssets };
1159
+ }
1160
+ /** Supplies the target position and books its rounded allocation changes. @internal */
1161
+ supplyReallocationTarget({ reallocation, adapterIdsCache, targetMarket, timestamp, probe, allocationsKey, }) {
1162
+ const targetAdapter = this.getMutableAdapter(reallocation.vault, reallocation.to.adapter);
1798
1163
  const targetIds = getAdapterIds(adapterIdsCache, targetAdapter, targetMarket);
1799
1164
  const [, , targetAdapterMarketCapId] = targetIds;
1800
- const currentTargetMarket = data.getMarket(targetMarket.id);
1801
- const oldTargetAllocation = data.getAllocation(reallocation.vault, targetAdapterMarketCapId).allocation;
1165
+ const currentTargetMarket = this.getMarket(targetMarket.id);
1166
+ const oldTargetAllocation = this.getAllocation(reallocation.vault, targetAdapterMarketCapId).allocation;
1802
1167
  const supply = currentTargetMarket.supply(reallocation.assets, 0n, timestamp);
1803
1168
  const targetSupplyShares = (targetAdapter.supplyShares[targetMarket.id] ?? 0n) + supply.shares;
1804
1169
  targetAdapter.supplyShares[targetMarket.id] = targetSupplyShares;
1805
- if (!targetAdapter.marketIds.includes(targetMarket.id))
1170
+ if (!targetAdapter.marketIds.includes(targetMarket.id)) {
1806
1171
  targetAdapter.marketIds.push(targetMarket.id);
1807
- if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id))
1172
+ }
1173
+ if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id)) {
1808
1174
  targetAdapter.markets.push(supply.market);
1809
- data.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1175
+ }
1176
+ this.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1810
1177
  const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1811
1178
  // The adapter's rounded expected-assets delta can differ by one wei at inclusion,
1812
1179
  // so cap tracking assumes each accepted leg adds at least its requested assets.
1813
1180
  const targetChange = MathLib.max(simulatedChange, reallocation.assets);
1814
1181
  for (const id of targetIds) {
1815
- const allocation = data.getAllocation(reallocation.vault, id);
1816
- data.mutableAllocations[allocationsKey][id] = {
1182
+ const allocation = this.getAllocation(reallocation.vault, id);
1183
+ const allocations = this.mutableAllocations[allocationsKey];
1184
+ if (allocations == null) {
1185
+ throw new UnknownReallocationAllocationError(reallocation.vault, id);
1186
+ }
1187
+ allocations[id] = {
1817
1188
  ...allocation,
1818
1189
  allocation: allocation.allocation + targetChange,
1819
1190
  };
1820
1191
  }
1821
- vault.assetBalance -= reallocation.assets;
1822
- return { data, context: nextContext, firstTotalAssets };
1192
+ }
1193
+ /** Credits shared Blue liquidity when an idle allocation enters the target market. @internal */
1194
+ creditIdleReallocationBalance(reallocation, targetMarket) {
1195
+ const blueBalanceKey = findAddressKey(this.mutableBlueBalances, targetMarket.params.loanToken);
1196
+ if (blueBalanceKey == null) {
1197
+ return;
1198
+ }
1199
+ const blueBalance = this.mutableBlueBalances[blueBalanceKey];
1200
+ if (blueBalance != null) {
1201
+ this.mutableBlueBalances[blueBalanceKey] =
1202
+ blueBalance + reallocation.assets;
1203
+ }
1204
+ }
1205
+ /** Builds the isolated markets, adapter views and caps used by a transition probe. @internal */
1206
+ cloneReallocationProbe({ reallocation, targetMarketId, adapterIdsCache, sourceVaultKey, sourceVault, sourceAllocationsKey, }) {
1207
+ const probeMarkets = {
1208
+ [targetMarketId]: this.getMarket(targetMarketId),
1209
+ };
1210
+ const adapterKeysToClone = new Set([
1211
+ reallocation.to.adapter.toLowerCase(),
1212
+ ]);
1213
+ const allocationIdsToClone = new Set(getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.to.adapter), this.getMarket(targetMarketId)));
1214
+ if (reallocation.from.type === "market") {
1215
+ const sourceMarket = this.getMarket(reallocation.from.marketParams.id);
1216
+ probeMarkets[sourceMarket.id] = sourceMarket;
1217
+ adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
1218
+ for (const key of getDependentProbeAdapterKeys(sourceVault, sourceMarket.id)) {
1219
+ adapterKeysToClone.add(key);
1220
+ }
1221
+ for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket)) {
1222
+ allocationIdsToClone.add(id);
1223
+ }
1224
+ }
1225
+ const data = new VaultV2BlueReallocationData({
1226
+ chainId: this.chainId,
1227
+ timestamp: this.timestamp,
1228
+ markets: probeMarkets,
1229
+ });
1230
+ if (sourceVaultKey != null) {
1231
+ data.mutableVaults[sourceVaultKey] =
1232
+ sourceVault == null
1233
+ ? undefined
1234
+ : cloneVault(sourceVault, {
1235
+ markets: data.mutableMarkets,
1236
+ adapterKeysToClone,
1237
+ });
1238
+ }
1239
+ if (sourceAllocationsKey != null) {
1240
+ const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
1241
+ const allocations = {};
1242
+ for (const id of allocationIdsToClone) {
1243
+ allocations[id] = sourceAllocations?.[id];
1244
+ }
1245
+ data.mutableAllocations[sourceAllocationsKey] = allocations;
1246
+ }
1247
+ return data;
1248
+ }
1249
+ /** Withdraws the source market position and books its cap changes before target supply. @internal */
1250
+ withdrawReallocationSource({ reallocation, source, timestamp, adapterIdsCache, allocationsKey, vault, }) {
1251
+ const sourceAdapter = this.getMutableAdapter(reallocation.vault, source.adapter);
1252
+ const sourceMarket = this.getMarket(source.marketParams.id);
1253
+ const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1254
+ const [, , sourceAdapterMarketCapId] = sourceIds;
1255
+ const currentSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1256
+ const withdrawal = sourceMarket.withdraw(reallocation.assets, 0n, timestamp);
1257
+ if (withdrawal.shares > currentSupplyShares) {
1258
+ throw new ReallocationAdapterSupplySharesUnderflowError({
1259
+ vault: reallocation.vault,
1260
+ adapter: sourceAdapter.address,
1261
+ marketId: sourceMarket.id,
1262
+ supplyShares: currentSupplyShares,
1263
+ withdrawnShares: withdrawal.shares,
1264
+ });
1265
+ }
1266
+ sourceAdapter.supplyShares[sourceMarket.id] =
1267
+ currentSupplyShares - withdrawal.shares;
1268
+ this.setMarkets([withdrawal.market]);
1269
+ const sourceChange = withdrawal.market.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n) -
1270
+ this.getAllocation(reallocation.vault, sourceAdapterMarketCapId)
1271
+ .allocation;
1272
+ for (const id of sourceIds) {
1273
+ const allocation = this.getAllocation(reallocation.vault, id);
1274
+ const nextAllocation = allocation.allocation + sourceChange;
1275
+ if (nextAllocation < 0n) {
1276
+ throw new ReallocationAllocationUnderflowError({
1277
+ vault: reallocation.vault,
1278
+ id,
1279
+ allocation: allocation.allocation,
1280
+ change: sourceChange,
1281
+ });
1282
+ }
1283
+ const allocations = this.mutableAllocations[allocationsKey];
1284
+ allocations[id] = {
1285
+ ...allocation,
1286
+ allocation: nextAllocation,
1287
+ };
1288
+ }
1289
+ vault.assetBalance += reallocation.assets;
1290
+ }
1291
+ /** Books the vault's first-allocation denominator once per simulated transaction. @internal */
1292
+ accrueReallocationFirstAllocation({ vault: initialVault, vaultKey, timestamp, context, firstTotalAssetsKey, }) {
1293
+ let vault = initialVault;
1294
+ // Vault V2's transient firstTotalAssets tracks the first allocation in a
1295
+ // transaction independently from elapsed time. Later allocations must not
1296
+ // recompute the denominator, even if their simulated balances have changed.
1297
+ if (timestamp === vault.lastUpdate) {
1298
+ // AccrualVaultV2 skips zero-elapsed accruals, but the contract's first
1299
+ // touch still reads real adapter assets. With zero elapsed time, its
1300
+ // growth clamp leaves only existing losses to recognize.
1301
+ const realAssets = vault.accrualAdapters.reduce((assets, adapter) => assets + adapter.realAssets(timestamp), vault.assetBalance);
1302
+ vault._totalAssets = MathLib.min(realAssets, vault._totalAssets);
1303
+ }
1304
+ else {
1305
+ vault = vault.accrueInterest(timestamp).vault;
1306
+ }
1307
+ this.mutableVaults[vaultKey] = vault;
1308
+ const firstTotalAssets = vault._totalAssets;
1309
+ const nextContext = {
1310
+ ...context,
1311
+ firstTotalAssets: {
1312
+ ...context.firstTotalAssets,
1313
+ [firstTotalAssetsKey]: firstTotalAssets,
1314
+ },
1315
+ };
1316
+ return { vault, firstTotalAssets, context: nextContext };
1823
1317
  }
1824
1318
  /** Updates canonical markets in bulk and refreshes only dependent adapter views. */
1825
1319
  setMarkets(markets, adaptersToRefresh) {
@@ -1828,42 +1322,1264 @@ export class VaultV2BlueReallocationData {
1828
1322
  this.mutableMarkets[market.id] = market;
1829
1323
  changedMarketIds.add(market.id);
1830
1324
  }
1831
- if (changedMarketIds.size === 0)
1325
+ if (changedMarketIds.size === 0) {
1832
1326
  return;
1833
- const adapters = new Set();
1834
- if (adaptersToRefresh == null) {
1835
- // A Morpho market is global state shared by every vault position. Legacy
1836
- // AccrualPosition constructors copy their Market, so rebuild those adapter
1837
- // views as well as repointing V2 adapters whenever the canonical state moves.
1838
- for (const vault of Object.values(this.mutableVaults)) {
1839
- if (vault == null)
1840
- continue;
1841
- for (const adapter of vault.accrualAdapters)
1842
- adapters.add(adapter);
1843
- if (vault.accrualLiquidityAdapter != null)
1844
- adapters.add(vault.accrualLiquidityAdapter);
1327
+ }
1328
+ const adapters = collectAdaptersToRefresh(this.mutableVaults, adaptersToRefresh);
1329
+ for (const adapter of adapters) {
1330
+ const update = refreshAdapterMarkets(adapter, {
1331
+ markets: this.mutableMarkets,
1332
+ changedMarketIds,
1333
+ });
1334
+ if (update != null) {
1335
+ Object.assign(adapter, update);
1845
1336
  }
1846
1337
  }
1847
- else {
1848
- for (const adapter of adaptersToRefresh)
1338
+ }
1339
+ }
1340
+ /** Collects the adapters whose views may depend on changed canonical markets. @internal */
1341
+ function collectAdaptersToRefresh(vaults, adaptersToRefresh) {
1342
+ const adapters = new Set();
1343
+ if (adaptersToRefresh == null) {
1344
+ // A Morpho market is global state shared by every vault position. Legacy
1345
+ // AccrualPosition constructors copy their Market, so rebuild those adapter
1346
+ // views as well as repointing V2 adapters whenever the canonical state moves.
1347
+ for (const vault of Object.values(vaults)) {
1348
+ if (vault == null) {
1349
+ continue;
1350
+ }
1351
+ for (const adapter of vault.accrualAdapters) {
1849
1352
  adapters.add(adapter);
1353
+ }
1354
+ if (vault.accrualLiquidityAdapter != null) {
1355
+ adapters.add(vault.accrualLiquidityAdapter);
1356
+ }
1850
1357
  }
1851
- for (const adapter of adapters) {
1852
- if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2) {
1853
- if (!adapter.markets.some(({ id }) => changedMarketIds.has(id)))
1854
- continue;
1855
- adapter.markets = adapter.markets.map((adapterMarket) => getCanonicalMarket(this.mutableMarkets, adapterMarket));
1358
+ }
1359
+ else {
1360
+ for (const adapter of adaptersToRefresh) {
1361
+ adapters.add(adapter);
1362
+ }
1363
+ }
1364
+ return adapters;
1365
+ }
1366
+ /** Computes one adapter's dependent market views after a canonical state change. @internal */
1367
+ function refreshAdapterMarkets(adapter, { markets, changedMarketIds, }) {
1368
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2) {
1369
+ if (!adapter.markets.some(({ id }) => changedMarketIds.has(id))) {
1370
+ return;
1371
+ }
1372
+ return {
1373
+ markets: adapter.markets.map((adapterMarket) => getCanonicalMarket(markets, adapterMarket)),
1374
+ };
1375
+ }
1376
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter) {
1377
+ if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId))) {
1378
+ return;
1379
+ }
1380
+ return {
1381
+ positions: adapter.positions.map((position) => clonePosition(position, markets)),
1382
+ };
1383
+ }
1384
+ if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
1385
+ if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId))) {
1386
+ return;
1387
+ }
1388
+ return {
1389
+ accrualVaultV1: cloneAccrualVault(adapter.accrualVaultV1, markets),
1390
+ };
1391
+ }
1392
+ }
1393
+ /** Clones allocator authorization records without sharing caller-owned iterables. @internal */
1394
+ function cloneAllocatorConfigurations(input) {
1395
+ const publicAllocatorConfigs = {};
1396
+ const activeAdapters = {};
1397
+ const marketPublicAllocatorConfigs = {};
1398
+ for (const [vault, config] of Object.entries(input.publicAllocatorConfigs ?? {})) {
1399
+ publicAllocatorConfigs[vault] =
1400
+ config == null ? undefined : new VaultV2BluePublicAllocatorConfig(config);
1401
+ }
1402
+ for (const [vault, adapters] of Object.entries(input.activeAdapters ?? {})) {
1403
+ activeAdapters[vault] = adapters == null ? undefined : new Set(adapters);
1404
+ }
1405
+ for (const [vault, configs] of Object.entries(input.marketPublicAllocatorConfigs ?? {})) {
1406
+ marketPublicAllocatorConfigs[vault] =
1407
+ cloneMarketAllocatorConfigurations(configs);
1408
+ }
1409
+ return {
1410
+ publicAllocatorConfigs,
1411
+ activeAdapters,
1412
+ marketPublicAllocatorConfigs,
1413
+ };
1414
+ }
1415
+ /** Clones one vault's adapter-market allocator configurations. @internal */
1416
+ function cloneMarketAllocatorConfigurations(configs) {
1417
+ const cloned = {};
1418
+ for (const [id, config] of Object.entries(configs ?? {})) {
1419
+ cloned[id] =
1420
+ config == null
1421
+ ? undefined
1422
+ : new VaultV2BlueMarketPublicAllocatorConfig(config);
1423
+ }
1424
+ return cloned;
1425
+ }
1426
+ /** Finds adapter views that a source-market transition must isolate for probing. @internal */
1427
+ function getDependentProbeAdapterKeys(sourceVault, sourceMarketId) {
1428
+ const keys = new Set();
1429
+ if (sourceVault == null) {
1430
+ return keys;
1431
+ }
1432
+ const adapters = new Set(sourceVault.accrualAdapters);
1433
+ if (sourceVault.accrualLiquidityAdapter != null) {
1434
+ adapters.add(sourceVault.accrualLiquidityAdapter);
1435
+ }
1436
+ for (const adapter of adapters) {
1437
+ if (adapterReferencesMarket(adapter, sourceMarketId)) {
1438
+ keys.add(adapter.address.toLowerCase());
1439
+ }
1440
+ }
1441
+ return keys;
1442
+ }
1443
+ /** Tests whether an adapter view depends on one canonical Blue market. @internal */
1444
+ function adapterReferencesMarket(adapter, marketId) {
1445
+ return ((adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2 &&
1446
+ adapter.markets.some(({ id }) => id === marketId)) ||
1447
+ (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter &&
1448
+ adapter.positions.some((position) => position.marketId === marketId)) ||
1449
+ (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter &&
1450
+ adapter.accrualVaultV1.allocations.has(marketId)));
1451
+ }
1452
+ /** Computes the accepted leg's liquidity bounds and shared cap reserve entries. @internal */
1453
+ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, initialIdleAssets, allocatorCapHeadroom, reserves, }) {
1454
+ const allocatorCapBoundTargets = [];
1455
+ const idleBoundVaults = [];
1456
+ const idleTakenEntries = [];
1457
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1458
+ if (acceptedReallocation.assets >= acceptedAllocatorHeadroom) {
1459
+ // BluePublicAllocator caps are per vault and target adapter.
1460
+ allocatorCapBoundTargets.push(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1461
+ }
1462
+ if (acceptedReallocation.from.type === "idle") {
1463
+ const vaultKey = acceptedReallocation.vault.toLowerCase();
1464
+ const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
1465
+ idleTakenEntries.push([vaultKey, taken]);
1466
+ // Candidates always record this; a missing entry counts the vault as bound.
1467
+ const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1468
+ if (taken >=
1469
+ MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom))) {
1470
+ idleBoundVaults.push(vaultKey);
1471
+ }
1472
+ }
1473
+ const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1474
+ const existingPairs = reserves.touchedPairs.get(touchedVaultKey);
1475
+ const touchedVaultPairs = existingPairs ?? new Map();
1476
+ const touchedVaultEntries = existingPairs == null
1477
+ ? [[touchedVaultKey, touchedVaultPairs]]
1478
+ : [];
1479
+ const touchedPairEntries = [];
1480
+ if (!touchedVaultPairs.has(acceptedTargetPair.key)) {
1481
+ touchedPairEntries.push([acceptedTargetPair.key, acceptedTargetPair]);
1482
+ }
1483
+ if (acceptedSourcePair != null &&
1484
+ !touchedVaultPairs.has(acceptedSourcePair.key) &&
1485
+ acceptedSourcePair.key !== acceptedTargetPair.key) {
1486
+ touchedPairEntries.push([acceptedSourcePair.key, acceptedSourcePair]);
1487
+ }
1488
+ return {
1489
+ allocatorCapBoundTargets,
1490
+ idleTakenAssets: idleTakenEntries,
1491
+ idleBoundVaults,
1492
+ touchedVaultPairs,
1493
+ touchedVaultEntries,
1494
+ touchedPairEntries,
1495
+ };
1496
+ }
1497
+ /**
1498
+ * Creates cap-reserve readers over the shared in-place planning caches.
1499
+ * Returned readers populate reserve caches as in the utilization pass.
1500
+ * @internal
1501
+ */
1502
+ function createCapReserveResolvers({ reserves, adapterIdsCache, timestamp, capAccrualBuffer, }) {
1503
+ // Onchain, market interest is booked once at transaction start, on pre-plan
1504
+ // positions at pre-plan rates, and stays on touched positions' cap ids.
1505
+ // This reserve state is shared across every planner pass and leg of the plan.
1506
+ // biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
1507
+ const getPair = (vault, adapter, market) => {
1508
+ const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
1509
+ const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
1510
+ if (touched != null) {
1511
+ return touched;
1512
+ }
1513
+ const shares = adapter.supplyShares[market.id] ?? 0n;
1514
+ return {
1515
+ key,
1516
+ ids: getAdapterIds(adapterIdsCache, adapter, market),
1517
+ reserve: (reserveState) => {
1518
+ let reserve = reserveState.reserveByPairKey.get(key);
1519
+ if (reserve == null) {
1520
+ let accruals = reserveState.marketAccruals.get(market.id);
1521
+ if (accruals == null) {
1522
+ const initialMarket = reserveState.initialMarkets[market.id];
1523
+ if (initialMarket == null) {
1524
+ throw new UnknownReallocationMarketError(market.id);
1525
+ }
1526
+ accruals = [
1527
+ initialMarket.accrueInterest(timestamp),
1528
+ initialMarket.accrueInterest(timestamp + capAccrualBuffer),
1529
+ ];
1530
+ reserveState.marketAccruals.set(market.id, accruals);
1531
+ }
1532
+ const [atTimestamp, projected] = accruals;
1533
+ reserve = MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
1534
+ reserveState.reserveByPairKey.set(key, reserve);
1535
+ }
1536
+ return reserve;
1537
+ },
1538
+ };
1539
+ };
1540
+ // biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
1541
+ const capReserve = (vault, id, candidatePairs) => {
1542
+ let reserve = 0n;
1543
+ const seen = new Set();
1544
+ for (const pair of [
1545
+ ...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
1546
+ ...candidatePairs,
1547
+ ]) {
1548
+ if (seen.has(pair.key) || !pair.ids.includes(id)) {
1549
+ continue;
1856
1550
  }
1857
- else if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter) {
1858
- if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId)))
1859
- continue;
1860
- adapter.positions = adapter.positions.map((position) => clonePosition(position, this.mutableMarkets));
1551
+ seen.add(pair.key);
1552
+ reserve += pair.reserve(reserves);
1553
+ }
1554
+ return reserve;
1555
+ };
1556
+ return { getPair, capReserve };
1557
+ }
1558
+ /**
1559
+ * Plans one vault candidate, caching its initial idle assets and active adapters in place.
1560
+ * @internal
1561
+ */
1562
+ function planCachedVaultCandidate(params) {
1563
+ const { vaultAddress, data, initialIdleAssets, activeAdaptersCache } = params;
1564
+ const idleState = resolveVaultCandidateIdleState(params);
1565
+ if (idleState == null) {
1566
+ return;
1567
+ }
1568
+ const { availableIdleAssets } = idleState;
1569
+ const vaultAddressKey = vaultAddress.toLowerCase();
1570
+ if (!initialIdleAssets.has(vaultAddressKey)) {
1571
+ initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
1572
+ }
1573
+ let activeAdapters = activeAdaptersCache.get(vaultAddress);
1574
+ if (activeAdapters == null) {
1575
+ activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
1576
+ activeAdaptersCache.set(vaultAddress, activeAdapters);
1577
+ }
1578
+ return planVaultCandidate({
1579
+ ...params,
1580
+ ...idleState,
1581
+ activeAdapters,
1582
+ });
1583
+ }
1584
+ /** Resolves an eligible vault's idle balance before initializing candidate caches. @internal */
1585
+ function resolveVaultCandidateIdleState(params) {
1586
+ const { vaultAddress, data, marketId, penalty, options, simulationContext, getOptionalPublicAllocatorConfig, } = params;
1587
+ const targetMarket = data.getMarket(marketId);
1588
+ const publicAllocatorConfig = getOptionalPublicAllocatorConfig(vaultAddress);
1589
+ if (publicAllocatorConfig == null) {
1590
+ return;
1591
+ }
1592
+ const vault = data.getVault(vaultAddress);
1593
+ if (!isAddressEqual(publicAllocatorConfig.vault, vaultAddress) ||
1594
+ publicAllocatorConfig.penalty >
1595
+ (options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY)) {
1596
+ return;
1597
+ }
1598
+ if (penalty != null && publicAllocatorConfig.penalty !== penalty) {
1599
+ return;
1600
+ }
1601
+ const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
1602
+ const donatedPenaltyAssets = donatedPenaltyAssetsKey == null
1603
+ ? 0n
1604
+ : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey];
1605
+ if (donatedPenaltyAssets == null) {
1606
+ throw new UnknownDataError(`Missing donated penalty assets for "${vaultAddress}".`);
1607
+ }
1608
+ // Exclude rounded penalty dust from idle candidates so one donation
1609
+ // cannot replenish liquidity for another same-plan reallocation.
1610
+ const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssets);
1611
+ return { vault, targetMarket, publicAllocatorConfig, availableIdleAssets };
1612
+ }
1613
+ /**
1614
+ * Plans the highest-asset cap-compatible candidate for one configured vault.
1615
+ * Candidate planning updates shared working data/reserves in place; do not reuse a prior state.
1616
+ * @internal
1617
+ */
1618
+ function planVaultCandidate(params) {
1619
+ const { vault, targetMarket, publicAllocatorConfig, availableIdleAssets, activeAdapters, } = params;
1620
+ const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
1621
+ if (targetSupplyHeadroom === 0n ||
1622
+ targetMarket.toSupplyShares(1n, "Down") >
1623
+ MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyShares)) {
1624
+ return;
1625
+ }
1626
+ const minimumSupply = targetMarket.supply(1n, 0n);
1627
+ const rawCandidates = [];
1628
+ // Missing nested allocator state means the snapshot is incomplete, so
1629
+ // typed getter errors below must propagate. Only explicit zero caps or
1630
+ // disabled permissions make an adapter ineligible.
1631
+ for (const adapter of vault.accrualAdapters) {
1632
+ rawCandidates.push(...planTargetAdapterCandidates({
1633
+ ...params,
1634
+ vault,
1635
+ targetMarket,
1636
+ publicAllocatorConfig,
1637
+ availableIdleAssets,
1638
+ activeAdapters,
1639
+ targetSupplyHeadroom,
1640
+ minimumSupply,
1641
+ adapter,
1642
+ }));
1643
+ }
1644
+ const capCompatibleCandidates = [];
1645
+ for (const candidate of rawCandidates) {
1646
+ const compatible = fitCandidateCaps({
1647
+ ...params,
1648
+ ...candidate,
1649
+ targetMarket,
1650
+ });
1651
+ if (compatible != null) {
1652
+ capCompatibleCandidates.push(compatible);
1653
+ }
1654
+ }
1655
+ return capCompatibleCandidates.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"))[0];
1656
+ }
1657
+ /**
1658
+ * Builds idle and market-source candidates for one eligible target adapter.
1659
+ * Updates shared working data/reserves through candidate steps; do not reuse a prior state.
1660
+ * @internal
1661
+ */
1662
+ function planTargetAdapterCandidates(params) {
1663
+ const { vaultAddress, data, marketId, adapterIdsCache, getPair, capReserve, reserves, allocatorCapHeadroom, vault, targetMarket, activeAdapters, minimumSupply, adapter, } = params;
1664
+ const rawCandidates = [];
1665
+ if (!(adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
1666
+ return [];
1667
+ }
1668
+ if (!isAddressEqual(adapter.parentVault, vaultAddress)) {
1669
+ return [];
1670
+ }
1671
+ if (!isAddressEqual(targetMarket.params.loanToken, vault.asset) ||
1672
+ !isAddressEqual(targetMarket.params.irm, adapter.adaptiveCurveIrm)) {
1673
+ return [];
1674
+ }
1675
+ const targetPair = getPair(vaultAddress, adapter, targetMarket);
1676
+ const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
1677
+ const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
1678
+ if (!isAddressEqual(marketPublicAllocatorConfig.vault, vaultAddress) ||
1679
+ !isAddressEqual(marketPublicAllocatorConfig.adapter, adapter.address) ||
1680
+ !activeAdapters.has(adapter.address.toLowerCase())) {
1681
+ return [];
1682
+ }
1683
+ const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
1684
+ const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
1685
+ const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
1686
+ const targetAllocations = [
1687
+ adapterCapAllocation,
1688
+ collateralCapAllocation,
1689
+ adapterMarketCapAllocation,
1690
+ ];
1691
+ if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n)) {
1692
+ return [];
1693
+ }
1694
+ const adapterShares = adapter.supplyShares[marketId] ?? 0n;
1695
+ const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
1696
+ const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
1697
+ const allocatorHeadroom = MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
1698
+ untracked +
1699
+ targetPair.reserve(reserves)), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
1700
+ const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
1701
+ const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
1702
+ const blockedTargetIds = targetAllocations
1703
+ .filter(({ allocation, absoluteCap, relativeCap, id }) => {
1704
+ const nextAllocation = allocation +
1705
+ capReserve(vaultAddress, id, [targetPair]) +
1706
+ minimumAllocationChange;
1707
+ return (nextAllocation > absoluteCap ||
1708
+ (relativeCap === 0n && nextAllocation > 0n));
1709
+ })
1710
+ .map(({ id }) => id);
1711
+ // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
1712
+ if (allocatorHeadroom === 0n ||
1713
+ minimumSupply.shares < minimumSupply.assets ||
1714
+ blockedTargetIds.includes(adapterMarketCapId)) {
1715
+ return [];
1716
+ }
1717
+ const sourceParams = {
1718
+ ...params,
1719
+ adapter,
1720
+ targetPair,
1721
+ allocatorHeadroom,
1722
+ blockedTargetIds,
1723
+ };
1724
+ const idleCandidate = planIdleCandidate(sourceParams);
1725
+ if (idleCandidate != null) {
1726
+ rawCandidates.push(idleCandidate);
1727
+ }
1728
+ rawCandidates.push(...planSourceAdapterCandidates(sourceParams));
1729
+ return rawCandidates;
1730
+ }
1731
+ /** Builds a vault-idle leg when permissions and target caps allow it. @internal */
1732
+ function planIdleCandidate(params) {
1733
+ const { vaultAddress, adapter, publicAllocatorConfig, availableIdleAssets, blockedTargetIds, targetSupplyHeadroom, allocatorHeadroom, targetPair, } = params;
1734
+ if (publicAllocatorConfig.canPullFromIdle &&
1735
+ availableIdleAssets > 0n &&
1736
+ blockedTargetIds.length === 0) {
1737
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
1738
+ if (assets > 0n) {
1739
+ return {
1740
+ reallocation: {
1741
+ vault: vaultAddress,
1742
+ from: { type: "idle" },
1743
+ to: { adapter: adapter.address },
1744
+ assets,
1745
+ penalty: publicAllocatorConfig.penalty,
1746
+ },
1747
+ targetPair,
1748
+ allocatorHeadroom,
1749
+ };
1750
+ }
1751
+ }
1752
+ }
1753
+ /**
1754
+ * Walks authorized source adapters in snapshot order for one target position.
1755
+ * Source steps update the shared working data in place; do not reuse a prior state.
1756
+ * @internal
1757
+ */
1758
+ function planSourceAdapterCandidates(params) {
1759
+ const { vault, vaultAddress, activeAdapters } = params;
1760
+ const candidates = [];
1761
+ for (const sourceAdapter of vault.accrualAdapters) {
1762
+ if (!(sourceAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
1763
+ continue;
1764
+ }
1765
+ if (!isAddressEqual(sourceAdapter.parentVault, vaultAddress)) {
1766
+ continue;
1767
+ }
1768
+ if (!activeAdapters.has(sourceAdapter.address.toLowerCase())) {
1769
+ continue;
1770
+ }
1771
+ for (const sourceMarketReference of sourceAdapter.markets) {
1772
+ const candidate = planSourceMarketCandidate({
1773
+ ...params,
1774
+ sourceAdapter,
1775
+ sourceMarketReference,
1776
+ });
1777
+ if (candidate != null) {
1778
+ candidates.push(candidate);
1861
1779
  }
1862
- else if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
1863
- if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId)))
1864
- continue;
1865
- adapter.accrualVaultV1 = cloneAccrualVault(adapter.accrualVaultV1, this.mutableMarkets);
1780
+ }
1781
+ }
1782
+ return candidates;
1783
+ }
1784
+ /**
1785
+ * Plans a source-market withdrawal, accruing the same working market state.
1786
+ * Updates the working data clone in place via setMarkets; the caller retains that same
1787
+ * object, even when no candidate is returned. Do not reuse a prior state after this step.
1788
+ * @internal
1789
+ */
1790
+ function planSourceMarketCandidate(params) {
1791
+ const { data, vault, vaultAddress, sourceAdapter, sourceMarketReference, normalizedMarketId, adapterIdsCache, blockedTargetIds, getPair, timestamp, setMarkets, targetSupplyHeadroom, allocatorHeadroom, maxWithdrawalUtilization, adapter, publicAllocatorConfig, targetPair, } = params;
1792
+ const sourceMarket = data.getMarket(sourceMarketReference.id);
1793
+ if (!isAddressEqual(sourceMarket.params.loanToken, vault.asset) ||
1794
+ !isAddressEqual(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm)) {
1795
+ return;
1796
+ }
1797
+ if (sourceMarket.id.toLowerCase() === normalizedMarketId) {
1798
+ return;
1799
+ }
1800
+ const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1801
+ const [, , sourceAdapterMarketCapId] = sourceIds;
1802
+ const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
1803
+ if (!isAddressEqual(sourceConfig.vault, vaultAddress) ||
1804
+ !isAddressEqual(sourceConfig.adapter, sourceAdapter.address) ||
1805
+ !sourceConfig.canPullFromMarket) {
1806
+ return;
1807
+ }
1808
+ const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
1809
+ if (sourceAllocations.some(({ allocation }) => allocation === 0n)) {
1810
+ return;
1811
+ }
1812
+ const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1813
+ if (sourceSupplyShares === 0n) {
1814
+ return;
1815
+ }
1816
+ // A withdrawal can create target headroom only for shared cap IDs.
1817
+ if (blockedTargetIds.some((id) => !sourceIds.includes(id))) {
1818
+ return;
1819
+ }
1820
+ const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
1821
+ const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
1822
+ setMarkets([accruedSourceMarket]);
1823
+ const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
1824
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
1825
+ if (assets <= 0n) {
1826
+ return;
1827
+ }
1828
+ return {
1829
+ reallocation: {
1830
+ vault: vaultAddress,
1831
+ from: {
1832
+ type: "market",
1833
+ adapter: sourceAdapter.address,
1834
+ marketParams: sourceMarket.params,
1835
+ },
1836
+ to: { adapter: adapter.address },
1837
+ assets,
1838
+ penalty: publicAllocatorConfig.penalty,
1839
+ },
1840
+ targetPair,
1841
+ sourcePair,
1842
+ allocatorHeadroom,
1843
+ };
1844
+ }
1845
+ /**
1846
+ * Fits a raw candidate to non-shared upper bounds and shared-cap rounding.
1847
+ * Cap reserve reads populate shared working reserve caches; do not reuse a prior state.
1848
+ * @internal
1849
+ */
1850
+ function fitCandidateCaps(params) {
1851
+ const { reallocation, targetPair, sourcePair, allocatorHeadroom, capReserve, remainingAssets, } = params;
1852
+ const targetIds = targetPair.ids;
1853
+ const sourceIds = new Set(sourcePair?.ids ?? []);
1854
+ const reserveById = new Map();
1855
+ for (const id of targetIds) {
1856
+ reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
1857
+ }
1858
+ const probeParams = { ...params, targetIds, sourceIds, reserveById };
1859
+ // Non-shared target IDs impose monotonic upper bounds. Shared IDs
1860
+ // can impose lower bounds and non-monotonic rounding constraints,
1861
+ // so validate them after selecting the non-shared maximum.
1862
+ const lower = findCandidateUpperBound(probeParams);
1863
+ let selectedAssets = MathLib.min(lower, remainingAssets ?? reallocation.assets);
1864
+ let probe = selectedAssets > 0n
1865
+ ? probeCandidateReallocation({ ...probeParams, assets: selectedAssets })
1866
+ : undefined;
1867
+ if (remainingAssets != null && probe?.withinAllCaps !== true) {
1868
+ // Bound the base-unit scan; expose a caller ceiling if wider searches become necessary.
1869
+ const searchUpper = MathLib.min(lower, selectedAssets + MAX_SHARED_CAP_SEARCH_STEPS);
1870
+ while (selectedAssets > 0n &&
1871
+ selectedAssets < searchUpper &&
1872
+ probe?.withinAllCaps !== true) {
1873
+ selectedAssets += 1n;
1874
+ probe = probeCandidateReallocation({
1875
+ ...probeParams,
1876
+ assets: selectedAssets,
1877
+ });
1878
+ }
1879
+ }
1880
+ if (selectedAssets > 0n && probe?.withinAllCaps === true) {
1881
+ return {
1882
+ reallocation: { ...reallocation, assets: selectedAssets },
1883
+ targetPair,
1884
+ sourcePair,
1885
+ allocatorHeadroom,
1886
+ };
1887
+ }
1888
+ }
1889
+ /** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
1890
+ function probeCandidateReallocation(params) {
1891
+ const { assets, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
1892
+ if (targetMarket.totalSupplyShares +
1893
+ targetMarket.toSupplyShares(assets, "Down") >
1894
+ MathLib.MAX_UINT_128) {
1895
+ return;
1896
+ }
1897
+ const postTransition = _try(() => applyPublicReallocation({
1898
+ context: simulationContext,
1899
+ reallocation: { ...reallocation, assets },
1900
+ targetMarketId: marketId,
1901
+ timestamp: targetMarket.lastUpdate,
1902
+ adapterIdsCache,
1903
+ probe: true,
1904
+ }), ReallocationAllocationUnderflowError, ReallocationAdapterSupplySharesUnderflowError);
1905
+ if (postTransition == null) {
1906
+ return;
1907
+ }
1908
+ // Vault V2 checks relative caps against the transient firstTotalAssets,
1909
+ // which stays fixed after the vault's first allocation in a transaction.
1910
+ const { firstTotalAssets } = postTransition;
1911
+ let withinUpperBounds = true;
1912
+ let withinAllCaps = true;
1913
+ for (const id of targetIds) {
1914
+ const allocation = postTransition.data.getAllocation(reallocation.vault, id);
1915
+ const capacity = VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
1916
+ // The reserve covers interest accrued before inclusion by every
1917
+ // position the plan touched on this cap id, as booked onchain.
1918
+ const withinCap = allocation.absoluteCap > 0n &&
1919
+ allocation.allocation + (reserveById.get(id) ?? 0n) <= capacity;
1920
+ if (!withinCap) {
1921
+ withinAllCaps = false;
1922
+ if (!sourceIds.has(id)) {
1923
+ withinUpperBounds = false;
1866
1924
  }
1867
1925
  }
1868
1926
  }
1927
+ return { withinAllCaps, withinUpperBounds };
1928
+ }
1929
+ /** Bisects the monotonic non-shared target-cap upper bound. @internal */
1930
+ function findCandidateUpperBound(probeParams) {
1931
+ let lower = 0n;
1932
+ let upper = probeParams.reallocation.assets;
1933
+ let probeUpper = true;
1934
+ while (lower < upper) {
1935
+ const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
1936
+ probeUpper = false;
1937
+ if (probeCandidateReallocation({ ...probeParams, assets })
1938
+ ?.withinUpperBounds === true) {
1939
+ lower = assets;
1940
+ }
1941
+ else {
1942
+ upper = assets - 1n;
1943
+ }
1944
+ }
1945
+ return lower;
1946
+ }
1947
+ /** Tracks shared-Blue transfer funding in the reallocation's execution order. @internal */
1948
+ function getReallocationTransferShortfall(reallocations, blueBalance) {
1949
+ const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
1950
+ if (penaltyAssets === 0n) {
1951
+ return 0n;
1952
+ }
1953
+ let shortfall = MathLib.zeroFloorSub(penaltyAssets, blueBalance);
1954
+ let balance = MathLib.zeroFloorSub(blueBalance, penaltyAssets);
1955
+ for (const { from, assets } of reallocations) {
1956
+ if (from.type === "idle") {
1957
+ balance += assets;
1958
+ }
1959
+ else {
1960
+ shortfall = MathLib.max(shortfall, MathLib.zeroFloorSub(assets, balance));
1961
+ }
1962
+ }
1963
+ return shortfall;
1964
+ }
1965
+ /** Plans one operation budget across penalty tiers and utilization passes. @internal */
1966
+ function planVaultOperation(params) {
1967
+ const { initialMarkets, initialData, absoluteShortfall, penaltyTiers, type } = params;
1968
+ const reserves = createCapReserveState(initialMarkets);
1969
+ const reallocations = [];
1970
+ const data = initialData.clone();
1971
+ const context = createSimulationContext();
1972
+ const remainingShortfall = absoluteShortfall;
1973
+ const accountingShortfall = absoluteShortfall;
1974
+ const allocatorCapBoundTargets = new Set();
1975
+ const idleBoundVaults = new Set();
1976
+ let state = {
1977
+ reserves,
1978
+ reallocations,
1979
+ data,
1980
+ context,
1981
+ remainingShortfall,
1982
+ accountingShortfall,
1983
+ allocatorCapBoundTargets,
1984
+ idleBoundVaults,
1985
+ };
1986
+ for (const penalty of penaltyTiers) {
1987
+ if (type === "refinance" && penalty === MathLib.WAD) {
1988
+ continue;
1989
+ }
1990
+ state = planOperationPenaltyTier({ ...params, penalty, state });
1991
+ }
1992
+ return summarizeOperationPlan({ ...params, state });
1993
+ }
1994
+ /**
1995
+ * Runs friendly then full-utilization passes at one allocator penalty.
1996
+ * Passes update working data/reserves in place, which the returned state may share.
1997
+ * Do not reuse a prior state after this step.
1998
+ * @internal
1999
+ */
2000
+ function planOperationPenaltyTier(params) {
2001
+ const { penalty, maxWithdrawalUtilization } = params;
2002
+ let state = params.state;
2003
+ let isFriendlyPass = true;
2004
+ let triedFullCapacityAttempt = false;
2005
+ for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
2006
+ const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
2007
+ isFriendlyPass = false;
2008
+ if (state.remainingShortfall === 0n && !isFreeFriendlyPass) {
2009
+ continue;
2010
+ }
2011
+ const result = planOperationUtilizationPass({
2012
+ ...params,
2013
+ state,
2014
+ utilization,
2015
+ penalty,
2016
+ isFreeFriendlyPass,
2017
+ triedFullCapacityAttempt,
2018
+ });
2019
+ state = result.state;
2020
+ triedFullCapacityAttempt = result.triedFullCapacityAttempt;
2021
+ }
2022
+ return state;
2023
+ }
2024
+ /**
2025
+ * Executes and, for paid passes, retries one utilization budget.
2026
+ * Updates working data/reserves in place; the returned state may share those objects
2027
+ * rather than an isolated snapshot. Do not reuse a prior state after this step.
2028
+ * @internal
2029
+ */
2030
+ function planOperationUtilizationPass(params) {
2031
+ const { penalty } = params;
2032
+ let state = {
2033
+ ...params.state,
2034
+ reallocations: [...params.state.reallocations],
2035
+ };
2036
+ let triedFullCapacityAttempt = params.triedFullCapacityAttempt;
2037
+ let passMaxAssets = getOperationPassBudget(params);
2038
+ const retryPaidPass = penalty > 0n;
2039
+ let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
2040
+ let tryFullCapacityAttempt = false;
2041
+ let isFullCapacityRetryPath = false;
2042
+ const beforePassRemainingShortfall = state.remainingShortfall;
2043
+ const beforePassAccountingShortfall = state.accountingShortfall;
2044
+ // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
2045
+ const passStart = retryPaidPass
2046
+ ? {
2047
+ data: state.data.clone(),
2048
+ context: state.context,
2049
+ reserves: cloneCapReserveState(state.reserves),
2050
+ reallocationCount: state.reallocations.length,
2051
+ }
2052
+ : undefined;
2053
+ let previousPassReallocatedAssets = 0n;
2054
+ let previousPhysicalShortfall;
2055
+ let hi;
2056
+ let bestAttempt;
2057
+ while (true) {
2058
+ const isFullCapacityAttempt = tryFullCapacityAttempt;
2059
+ tryFullCapacityAttempt = false;
2060
+ if (passStart != null) {
2061
+ state = restoreOperationPassStart({ state, passStart });
2062
+ }
2063
+ const attempt = executeOperationAttempt({
2064
+ ...params,
2065
+ state,
2066
+ isFullCapacityAttempt,
2067
+ passMaxAssets,
2068
+ isFullCapacityRetryPath,
2069
+ });
2070
+ state = attempt.state;
2071
+ const { pass, physicalShortfall, attemptTransferShortfall, attemptCoversShortfall, passReallocatedAssets, } = attempt;
2072
+ if (passStart == null) {
2073
+ break;
2074
+ }
2075
+ if (isFullCapacityAttempt) {
2076
+ passMaxAssets = passReallocatedAssets;
2077
+ }
2078
+ bestAttempt = chooseOperationBestAttempt({
2079
+ ...params,
2080
+ state,
2081
+ bestAttempt,
2082
+ beforePassAccountingShortfall,
2083
+ isFullCapacityRetryPath,
2084
+ attemptCoversShortfall,
2085
+ attemptTransferShortfall,
2086
+ passReallocatedAssets,
2087
+ passReallocations: pass.reallocations,
2088
+ });
2089
+ const next = advanceOperationPassSearch({
2090
+ lo,
2091
+ hi,
2092
+ passMaxAssets,
2093
+ triedFullCapacityAttempt,
2094
+ tryFullCapacityAttempt,
2095
+ isFullCapacityRetryPath,
2096
+ previousPhysicalShortfall,
2097
+ previousPassReallocatedAssets,
2098
+ isFullCapacityAttempt,
2099
+ attemptCoversShortfall,
2100
+ accountingShortfall: state.accountingShortfall,
2101
+ physicalShortfall,
2102
+ passReallocatedAssets,
2103
+ remainingShortfall: state.remainingShortfall,
2104
+ penalty,
2105
+ });
2106
+ if (next.type === "break") {
2107
+ break;
2108
+ }
2109
+ ({
2110
+ lo,
2111
+ hi,
2112
+ passMaxAssets,
2113
+ triedFullCapacityAttempt,
2114
+ tryFullCapacityAttempt,
2115
+ isFullCapacityRetryPath,
2116
+ previousPhysicalShortfall,
2117
+ previousPassReallocatedAssets,
2118
+ } = next);
2119
+ }
2120
+ const finalState = finishOperationPass({
2121
+ ...params,
2122
+ state,
2123
+ passStart,
2124
+ bestAttempt,
2125
+ beforePassRemainingShortfall,
2126
+ beforePassAccountingShortfall,
2127
+ });
2128
+ return {
2129
+ state: finalState,
2130
+ triedFullCapacityAttempt,
2131
+ };
2132
+ }
2133
+ /**
2134
+ * Restores working data and reserves and truncates the shared reallocation array in place.
2135
+ * Other attempt results remain available to the retry search.
2136
+ * @internal
2137
+ */
2138
+ function restoreOperationPassStart({ state, passStart, }) {
2139
+ const data = passStart.data.clone();
2140
+ const context = passStart.context;
2141
+ const reserves = cloneCapReserveState(passStart.reserves);
2142
+ state.reallocations.length = passStart.reallocationCount;
2143
+ return { ...state, data, context, reserves };
2144
+ }
2145
+ /** Summarizes liquidity-bound legs and the accounting and physical funding result. @internal */
2146
+ function summarizeOperationPlan(params) {
2147
+ const { maxAssets, headroom, type, amount, feeAssets, blueBalance, absoluteShortfall, hasExplicitBlueBalance, } = params;
2148
+ const { reallocations, data, allocatorCapBoundTargets, idleBoundVaults } = params.state;
2149
+ let reallocatedAssets = 0n;
2150
+ let unboundAssets = 0n;
2151
+ for (const { vault, from, to, assets } of reallocations) {
2152
+ reallocatedAssets += assets;
2153
+ const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
2154
+ if (!allocatorCapBoundTargets.has(key) &&
2155
+ !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase()))) {
2156
+ unboundAssets += assets;
2157
+ }
2158
+ }
2159
+ const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
2160
+ const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
2161
+ const physicalShortfall = penaltyAssets === 0n
2162
+ ? 0n
2163
+ : MathLib.zeroFloorSub((type === "refinance" ? amount + feeAssets + penaltyAssets : amount) +
2164
+ penaltyAssets, blueBalance + idleAssets);
2165
+ const transferShortfall = getReallocationTransferShortfall(reallocations, blueBalance);
2166
+ const coversAccountingShortfall = type === "refinance"
2167
+ ? reallocatedAssets >= absoluteShortfall + penaltyAssets
2168
+ : reallocatedAssets >= absoluteShortfall;
2169
+ return {
2170
+ maxAssets,
2171
+ headroom,
2172
+ reallocations,
2173
+ data,
2174
+ liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
2175
+ reallocatedAssets,
2176
+ unboundAssets,
2177
+ physicalShortfall,
2178
+ coversShortfall: coversAccountingShortfall &&
2179
+ (type === "refinance" || penaltyAssets <= amount) &&
2180
+ (!hasExplicitBlueBalance ||
2181
+ (physicalShortfall === 0n && transferShortfall === 0n)),
2182
+ };
2183
+ }
2184
+ /** Sizes a pass for its accounting gap and optional physical penalty funding. @internal */
2185
+ function getOperationPassBudget(params) {
2186
+ const { type, penalty, isFreeFriendlyPass, maxAssets, usePhysicalBalance, amount, feeAssets, blueBalance, } = params;
2187
+ const { remainingShortfall, reallocations } = params.state;
2188
+ let passMaxAssets = remainingShortfall;
2189
+ if (type === "refinance" && penalty > 0n) {
2190
+ passMaxAssets = MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
2191
+ }
2192
+ else if (isFreeFriendlyPass) {
2193
+ passMaxAssets = maxAssets;
2194
+ }
2195
+ if (usePhysicalBalance && penalty > 0n) {
2196
+ const penaltyMultiplier = type === "refinance" ? 2n : 1n;
2197
+ const physicalPenalty = penaltyMultiplier * penalty;
2198
+ if (physicalPenalty < MathLib.WAD) {
2199
+ const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
2200
+ // Idle must fund both the operation and its penalty flash loan.
2201
+ const physicalShortfall = MathLib.zeroFloorSub(amount +
2202
+ feeAssets +
2203
+ penaltyMultiplier * getBlueBundlesV1PenaltyAssets(reallocations), blueBalance + idleAssets);
2204
+ passMaxAssets = MathLib.max(passMaxAssets, MathLib.mulDivUp(physicalShortfall, MathLib.WAD, MathLib.WAD - physicalPenalty));
2205
+ }
2206
+ }
2207
+ return passMaxAssets;
2208
+ }
2209
+ /**
2210
+ * Executes one pass attempt and returns its updated state and funding gaps.
2211
+ * Updates working data/reserves in place via runUtilizationPass; the returned state
2212
+ * shares those objects. Callers must not reuse a prior state after this step.
2213
+ * @internal
2214
+ */
2215
+ function executeOperationAttempt(params) {
2216
+ const { type, amount, feeAssets, blueBalance, capAccrualBuffer, normalizedOptions, hasExplicitBlueBalance, marketId, headroom, utilization, penalty, isFreeFriendlyPass, runUtilizationPass, isFullCapacityAttempt, passMaxAssets, isFullCapacityRetryPath, } = params;
2217
+ let { reserves, data, context, remainingShortfall, accountingShortfall, allocatorCapBoundTargets, idleBoundVaults, } = params.state;
2218
+ const reallocations = [...params.state.reallocations];
2219
+ const pass = runUtilizationPass(data, {
2220
+ context,
2221
+ reserves,
2222
+ marketId,
2223
+ maxWithdrawalUtilization: utilization,
2224
+ maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
2225
+ capAccrualBuffer,
2226
+ allocatorCapHeadroom: headroom,
2227
+ penalty,
2228
+ options: normalizedOptions,
2229
+ });
2230
+ reallocations.push(...pass.reallocations);
2231
+ data = pass.data;
2232
+ context = pass.context;
2233
+ if (isFreeFriendlyPass) {
2234
+ allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
2235
+ idleBoundVaults = pass.idleBoundVaults;
2236
+ }
2237
+ const currentMarket = data.getMarket(marketId);
2238
+ const penaltyAssets = type === "refinance" ? getBlueBundlesV1PenaltyAssets(reallocations) : 0n;
2239
+ let borrow;
2240
+ switch (type) {
2241
+ case "borrow":
2242
+ borrow = currentMarket.totalBorrowAssets + amount;
2243
+ break;
2244
+ case "refinance":
2245
+ borrow =
2246
+ currentMarket.totalBorrowAssets + amount + feeAssets + penaltyAssets;
2247
+ break;
2248
+ default:
2249
+ borrow = currentMarket.totalBorrowAssets;
2250
+ }
2251
+ const supply = type === "withdraw"
2252
+ ? currentMarket.totalSupplyAssets - amount
2253
+ : currentMarket.totalSupplyAssets;
2254
+ accountingShortfall = borrow > supply ? borrow - supply : 0n;
2255
+ const penaltyForPhysicalShortfall = getBlueBundlesV1PenaltyAssets(reallocations);
2256
+ const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
2257
+ const physicalShortfall = penaltyForPhysicalShortfall === 0n
2258
+ ? 0n
2259
+ : MathLib.zeroFloorSub((type === "refinance"
2260
+ ? amount + feeAssets + penaltyForPhysicalShortfall
2261
+ : amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
2262
+ remainingShortfall = MathLib.max(accountingShortfall, physicalShortfall);
2263
+ const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
2264
+ ? getReallocationTransferShortfall(reallocations, blueBalance)
2265
+ : 0n;
2266
+ const attemptCoversShortfall = remainingShortfall === 0n;
2267
+ const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
2268
+ return {
2269
+ state: {
2270
+ reserves,
2271
+ reallocations,
2272
+ data,
2273
+ context,
2274
+ remainingShortfall,
2275
+ accountingShortfall,
2276
+ allocatorCapBoundTargets,
2277
+ idleBoundVaults,
2278
+ },
2279
+ pass,
2280
+ physicalShortfall,
2281
+ attemptTransferShortfall,
2282
+ attemptCoversShortfall,
2283
+ passReallocatedAssets,
2284
+ };
2285
+ }
2286
+ /** Retains the best feasible paid-pass attempt with the original priority ordering. @internal */
2287
+ function chooseOperationBestAttempt(params) {
2288
+ const { hasExplicitBlueBalance, bestAttempt, beforePassAccountingShortfall, isFullCapacityRetryPath, attemptCoversShortfall, attemptTransferShortfall, passReallocatedAssets, passReallocations, } = params;
2289
+ const { data, context, reserves, remainingShortfall, accountingShortfall } = params.state;
2290
+ const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
2291
+ const attemptPriority = hasExplicitBlueBalance
2292
+ ? [0n, remainingShortfall, 0n, passReallocatedAssets]
2293
+ : [
2294
+ improvesAccounting ? 0n : 1n,
2295
+ improvesAccounting ? accountingShortfall : 0n,
2296
+ remainingShortfall,
2297
+ passReallocatedAssets,
2298
+ ];
2299
+ const previousBestAttempt = bestAttempt;
2300
+ let isBetterAttempt = previousBestAttempt == null;
2301
+ if (previousBestAttempt != null) {
2302
+ const firstDifference = attemptPriority.findIndex((candidatePriority, index) => candidatePriority !== previousBestAttempt.priority[index]);
2303
+ const priority = attemptPriority[firstDifference];
2304
+ const previousPriority = previousBestAttempt.priority[firstDifference];
2305
+ isBetterAttempt =
2306
+ priority != null &&
2307
+ previousPriority != null &&
2308
+ priority < previousPriority;
2309
+ }
2310
+ if (isBetterAttempt &&
2311
+ (!isFullCapacityRetryPath ||
2312
+ (attemptCoversShortfall && attemptTransferShortfall === 0n))) {
2313
+ return {
2314
+ data,
2315
+ context,
2316
+ reserves: cloneCapReserveState(reserves),
2317
+ reallocations: passReallocations,
2318
+ remainingShortfall,
2319
+ accountingShortfall,
2320
+ passReallocatedAssets,
2321
+ priority: attemptPriority,
2322
+ };
2323
+ }
2324
+ return bestAttempt;
2325
+ }
2326
+ /** Advances bisection or grossed-up retries, stopping on stalled physical funding. @internal */
2327
+ function advanceOperationPassSearch(params) {
2328
+ let { lo, hi, passMaxAssets, triedFullCapacityAttempt, tryFullCapacityAttempt, isFullCapacityRetryPath, previousPhysicalShortfall, previousPassReallocatedAssets, } = params;
2329
+ const { isFullCapacityAttempt, attemptCoversShortfall, accountingShortfall, physicalShortfall, passReallocatedAssets, remainingShortfall, penalty, } = params;
2330
+ ({ lo, hi } = updateOperationSearchBracket({
2331
+ lo,
2332
+ hi,
2333
+ passMaxAssets,
2334
+ attemptCoversShortfall,
2335
+ }));
2336
+ if (hi != null) {
2337
+ if (hi - lo <= 1n) {
2338
+ return { type: "break" };
2339
+ }
2340
+ passMaxAssets = (lo + hi) / 2n;
2341
+ return {
2342
+ type: "continue",
2343
+ lo,
2344
+ hi,
2345
+ passMaxAssets,
2346
+ triedFullCapacityAttempt,
2347
+ tryFullCapacityAttempt,
2348
+ isFullCapacityRetryPath,
2349
+ previousPhysicalShortfall,
2350
+ previousPassReallocatedAssets,
2351
+ };
2352
+ }
2353
+ if (isFullCapacityAttempt && !attemptCoversShortfall) {
2354
+ return { type: "break" };
2355
+ }
2356
+ if (accountingShortfall === 0n &&
2357
+ previousPhysicalShortfall != null &&
2358
+ physicalShortfall >= previousPhysicalShortfall) {
2359
+ if (!triedFullCapacityAttempt && passReallocatedAssets === passMaxAssets) {
2360
+ triedFullCapacityAttempt = true;
2361
+ tryFullCapacityAttempt = true;
2362
+ isFullCapacityRetryPath = true;
2363
+ return {
2364
+ type: "continue",
2365
+ lo,
2366
+ hi,
2367
+ passMaxAssets,
2368
+ triedFullCapacityAttempt,
2369
+ tryFullCapacityAttempt,
2370
+ isFullCapacityRetryPath,
2371
+ previousPhysicalShortfall,
2372
+ previousPassReallocatedAssets,
2373
+ };
2374
+ }
2375
+ return { type: "break" };
2376
+ }
2377
+ previousPhysicalShortfall = physicalShortfall;
2378
+ if (passReallocatedAssets <= previousPassReallocatedAssets ||
2379
+ penalty === MathLib.WAD) {
2380
+ return { type: "break" };
2381
+ }
2382
+ previousPassReallocatedAssets = passReallocatedAssets;
2383
+ passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
2384
+ return {
2385
+ type: "continue",
2386
+ lo,
2387
+ hi,
2388
+ passMaxAssets,
2389
+ triedFullCapacityAttempt,
2390
+ tryFullCapacityAttempt,
2391
+ isFullCapacityRetryPath,
2392
+ previousPhysicalShortfall,
2393
+ previousPassReallocatedAssets,
2394
+ };
2395
+ }
2396
+ /**
2397
+ * Commits the best improving paid attempt or restores the pre-pass checkpoint.
2398
+ * Returns working data by reference and may retain shared reserves; this does not
2399
+ * isolate earlier in-place updates. Do not reuse a prior state for further planning.
2400
+ * @internal
2401
+ */
2402
+ function finishOperationPass(params) {
2403
+ const { passStart, bestAttempt, beforePassRemainingShortfall, beforePassAccountingShortfall, hasExplicitBlueBalance, } = params;
2404
+ let { reserves, data, context, remainingShortfall, accountingShortfall } = params.state;
2405
+ const { allocatorCapBoundTargets, idleBoundVaults } = params.state;
2406
+ const reallocations = [...params.state.reallocations];
2407
+ if (passStart != null) {
2408
+ const improved = bestAttempt != null &&
2409
+ (hasExplicitBlueBalance
2410
+ ? bestAttempt.remainingShortfall < beforePassRemainingShortfall
2411
+ : bestAttempt.accountingShortfall < beforePassAccountingShortfall ||
2412
+ bestAttempt.remainingShortfall < beforePassRemainingShortfall);
2413
+ if (improved && bestAttempt != null) {
2414
+ data = bestAttempt.data;
2415
+ context = bestAttempt.context;
2416
+ reserves = cloneCapReserveState(bestAttempt.reserves);
2417
+ reallocations.length = passStart.reallocationCount;
2418
+ reallocations.push(...bestAttempt.reallocations);
2419
+ remainingShortfall = bestAttempt.remainingShortfall;
2420
+ accountingShortfall = bestAttempt.accountingShortfall;
2421
+ }
2422
+ else {
2423
+ data = passStart.data;
2424
+ context = passStart.context;
2425
+ reserves = cloneCapReserveState(passStart.reserves);
2426
+ reallocations.length = passStart.reallocationCount;
2427
+ remainingShortfall = beforePassRemainingShortfall;
2428
+ accountingShortfall = beforePassAccountingShortfall;
2429
+ }
2430
+ }
2431
+ return {
2432
+ reserves,
2433
+ reallocations,
2434
+ data,
2435
+ context,
2436
+ remainingShortfall,
2437
+ accountingShortfall,
2438
+ allocatorCapBoundTargets,
2439
+ idleBoundVaults,
2440
+ };
2441
+ }
2442
+ /** Tightens a paid-pass bisection bracket from the attempt's coverage result. @internal */
2443
+ function updateOperationSearchBracket(params) {
2444
+ let { lo, hi } = params;
2445
+ const { passMaxAssets, attemptCoversShortfall } = params;
2446
+ if (attemptCoversShortfall) {
2447
+ hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
2448
+ }
2449
+ else {
2450
+ lo = MathLib.max(lo, passMaxAssets);
2451
+ }
2452
+ return { lo, hi };
2453
+ }
2454
+ /** Validates the operation amount and fee before reading its snapshot. @internal */
2455
+ function resolveOperationFeeAssets(operation) {
2456
+ const { amount } = operation;
2457
+ if (amount <= 0n) {
2458
+ throw new NonPositiveInputError("amount", amount);
2459
+ }
2460
+ const referralFeePct = operation.type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
2461
+ if (referralFeePct < 0n) {
2462
+ throw new NegativeInputError("referralFeePct", referralFeePct);
2463
+ }
2464
+ if (referralFeePct >= MathLib.WAD) {
2465
+ throw new ReferralFeePctExceededError(referralFeePct);
2466
+ }
2467
+ const feeAssets = operation.type === "refinance"
2468
+ ? getBlueBundlesV1ReferralFeeAssets(amount, referralFeePct)
2469
+ : 0n;
2470
+ return feeAssets;
2471
+ }
2472
+ /** Computes post-operation accounting totals, rejecting withdrawals above supply. @internal */
2473
+ function getOperationMarketTotals({ market, marketId, type, amount, feeAssets, }) {
2474
+ if (type === "withdraw" && amount > market.totalSupplyAssets) {
2475
+ throw new ReallocationWithdrawExceedsMarketSupplyError({
2476
+ marketId,
2477
+ withdrawAmount: amount,
2478
+ totalSupplyAssets: market.totalSupplyAssets,
2479
+ });
2480
+ }
2481
+ let newTotalBorrowAssets = market.totalBorrowAssets;
2482
+ if (type === "borrow") {
2483
+ newTotalBorrowAssets += amount;
2484
+ }
2485
+ if (type === "refinance") {
2486
+ newTotalBorrowAssets += amount + feeAssets;
2487
+ }
2488
+ const newTotalSupplyAssets = type === "withdraw"
2489
+ ? market.totalSupplyAssets - amount
2490
+ : market.totalSupplyAssets;
2491
+ return { newTotalBorrowAssets, newTotalSupplyAssets };
2492
+ }
2493
+ /** Chooses a headroom or full-cap budget before testing physical-balance alternatives. @internal */
2494
+ function selectOperationPlan(params) {
2495
+ const { plan, requiredAssets, allocatorCapHeadroom, absoluteShortfall } = params;
2496
+ // A leg that fills an allocator cap, or idle legs that together take
2497
+ // (nearly) all of a source vault's starting idle, revert once another
2498
+ // allocation lands first. A bound plan therefore moves only the operation's
2499
+ // shortfall, or what unbound legs moved.
2500
+ const target = plan(requiredAssets, { headroom: allocatorCapHeadroom });
2501
+ let selected = target;
2502
+ if (allocatorCapHeadroom > 0n && target.liquidityBound) {
2503
+ selected = plan(absoluteShortfall > target.unboundAssets
2504
+ ? absoluteShortfall
2505
+ : target.unboundAssets, { headroom: allocatorCapHeadroom });
2506
+ // Shared-cap fitting is not monotonic in the budget.
2507
+ if (!selected.coversShortfall && target.coversShortfall) {
2508
+ selected = target;
2509
+ }
2510
+ }
2511
+ let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
2512
+ // Without headroom, `target` already is the full-cap plan toward the target.
2513
+ const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
2514
+ for (const maxAssets of fullCapBudgets) {
2515
+ if (selected.coversShortfall) {
2516
+ break;
2517
+ }
2518
+ selected = plan(maxAssets, { headroom: 0n });
2519
+ if (selected.reallocatedAssets > available) {
2520
+ available = selected.reallocatedAssets;
2521
+ }
2522
+ }
2523
+ // Reject unfunded plans before comparing optional physical-balance alternatives.
2524
+ assertSelectedOperationFunding({ ...params, selected, available });
2525
+ const funded = choosePhysicalBalancePlan({ ...params, selected });
2526
+ return { reallocations: funded.reallocations, data: funded.data };
2527
+ }
2528
+ /** Preserves penalty-specific error precedence when selected liquidity cannot fund the operation. @internal */
2529
+ function assertSelectedOperationFunding(params) {
2530
+ const { selected, available, hasExplicitBlueBalance, blueBalance, type, amount, absoluteShortfall, marketId, } = params;
2531
+ if (selected.coversShortfall) {
2532
+ return;
2533
+ }
2534
+ const selectedTransferShortfall = hasExplicitBlueBalance
2535
+ ? getReallocationTransferShortfall(selected.reallocations, blueBalance)
2536
+ : 0n;
2537
+ const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
2538
+ if (type !== "refinance" &&
2539
+ selectedPenaltyAssets > amount &&
2540
+ selected.reallocatedAssets >= absoluteShortfall &&
2541
+ (!hasExplicitBlueBalance ||
2542
+ (selected.physicalShortfall === 0n && selectedTransferShortfall === 0n))) {
2543
+ throw new InputExceedsMaxError({
2544
+ field: "reallocationPenaltyAssets",
2545
+ value: selectedPenaltyAssets,
2546
+ max: amount,
2547
+ });
2548
+ }
2549
+ throw new InsufficientSharedLiquidityError({
2550
+ marketId,
2551
+ shortfall: MathLib.max(absoluteShortfall +
2552
+ (type === "refinance"
2553
+ ? getBlueBundlesV1PenaltyAssets(selected.reallocations)
2554
+ : 0n), selected.reallocatedAssets +
2555
+ (hasExplicitBlueBalance
2556
+ ? MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
2557
+ : 0n)),
2558
+ available,
2559
+ });
2560
+ }
2561
+ /** Retains the selected plan unless a physical-balance seed is funded and strictly cheaper. @internal */
2562
+ function choosePhysicalBalancePlan(params) {
2563
+ const { hasExplicitBlueBalance, blueBalance, amount, feeAssets, type, plan } = params;
2564
+ let { selected } = params;
2565
+ const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
2566
+ if (hasExplicitBlueBalance &&
2567
+ selectedPenaltyAssets > 1n &&
2568
+ blueBalance <
2569
+ amount +
2570
+ feeAssets +
2571
+ (type === "refinance" ? 2n : 1n) * selectedPenaltyAssets) {
2572
+ // Amount feasibility is not monotonic: retain the original plan unless
2573
+ // the physical-balance seed finds a fully funded, strictly cheaper one.
2574
+ const alternative = plan(selected.maxAssets, {
2575
+ headroom: selected.headroom,
2576
+ usePhysicalBalance: true,
2577
+ });
2578
+ if (alternative.coversShortfall &&
2579
+ getBlueBundlesV1PenaltyAssets(alternative.reallocations) <
2580
+ getBlueBundlesV1PenaltyAssets(selected.reallocations)) {
2581
+ selected = alternative;
2582
+ }
2583
+ }
2584
+ return selected;
1869
2585
  }