@morpho-org/morpho-sdk 10.0.0-next.0 → 10.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/README.md +104 -12
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +1 -5
  4. package/lib/cjs/actions/blue/common.js +4 -2
  5. package/lib/cjs/actions/blue/withdrawBuyCallback.js +2 -1
  6. package/lib/cjs/actions/bundles/common.js +20 -14
  7. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -1
  8. package/lib/cjs/actions/midnight/cancelOffers.js +2 -1
  9. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +4 -2
  10. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +2 -1
  11. package/lib/cjs/actions/midnight/takeBorrow.js +2 -1
  12. package/lib/cjs/actions/midnight/takeLend.js +2 -1
  13. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +2 -1
  14. package/lib/cjs/actions/midnight/takeWithdraw.js +2 -1
  15. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +4 -2
  16. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -11
  17. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
  18. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
  19. package/lib/cjs/actions/vaultV1/inKindRedeem.js +6 -3
  20. package/lib/cjs/actions/vaultV1/migrateToV2.js +1 -1
  21. package/lib/cjs/actions/vaultV2/forceWithdraw.js +4 -2
  22. package/lib/cjs/actions/vaultV2/inKindRedeem.js +4 -2
  23. package/lib/cjs/blue/abis.d.ts +1 -1
  24. package/lib/cjs/blue/abis.js +1 -5
  25. package/lib/cjs/blue/entities.d.ts +4 -4
  26. package/lib/cjs/blue/entities.js +1 -3
  27. package/lib/cjs/blue/errors.d.ts +2 -2
  28. package/lib/cjs/blue/errors.js +1 -5
  29. package/lib/cjs/blue/fetch.d.ts +2 -2
  30. package/lib/cjs/blue/fetch.js +1 -3
  31. package/lib/cjs/blue/utils.d.ts +1 -1
  32. package/lib/cjs/blue/utils.js +1 -2
  33. package/lib/cjs/entities/blue/blue.js +8 -4
  34. package/lib/cjs/entities/index.d.ts +4 -4
  35. package/lib/cjs/entities/index.js +1 -3
  36. package/lib/cjs/entities/midnight/deadline.js +2 -1
  37. package/lib/cjs/entities/midnight/midnight.js +14 -7
  38. package/lib/cjs/entities/midnight/publication.js +73 -44
  39. package/lib/cjs/entities/requirements/assertContractCode.js +4 -2
  40. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +9 -13
  41. package/lib/cjs/entities/requirements/getErc2612Permit.js +10 -5
  42. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -0
  43. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +7 -1
  44. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
  45. package/lib/cjs/entities/requirements/getVaultV1InKindRedeemRequirements.js +111 -0
  46. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
  47. package/lib/cjs/entities/requirements/getVaultV2ForceWithdrawRequirements.js +76 -0
  48. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
  49. package/lib/cjs/entities/requirements/getVaultV2InKindRedeemRequirements.js +93 -0
  50. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
  51. package/lib/cjs/entities/vaultV1/inKindRedeemQuote.js +85 -0
  52. package/lib/cjs/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
  53. package/lib/cjs/entities/vaultV1/migrateToV2Quote.js +37 -0
  54. package/lib/cjs/entities/vaultV1/vaultV1.js +51 -181
  55. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
  56. package/lib/cjs/entities/vaultV2/forceWithdrawQuote.js +189 -0
  57. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
  58. package/lib/cjs/entities/vaultV2/inKindRedeemQuote.js +110 -0
  59. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +8 -34
  60. package/lib/cjs/entities/vaultV2/vaultV2.js +62 -429
  61. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +2 -3
  62. package/lib/cjs/entities/vaultV2BlueReallocationData.js +346 -234
  63. package/lib/cjs/errors.d.ts +4 -4
  64. package/lib/cjs/errors.js +6 -7
  65. package/lib/cjs/fetch.d.ts +2 -2
  66. package/lib/cjs/fetch.js +1 -3
  67. package/lib/cjs/helpers/deadShares.js +34 -19
  68. package/lib/cjs/helpers/encodeMidnightCalldata.js +4 -2
  69. package/lib/cjs/helpers/metadata.js +12 -6
  70. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +10 -5
  71. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +6 -3
  72. package/lib/cjs/helpers/utilization.js +10 -5
  73. package/lib/cjs/helpers/validate.js +12 -6
  74. package/lib/cjs/helpers/validateMidnightBounds.js +2 -1
  75. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +2 -1
  76. package/lib/cjs/helpers/validateMidnightPublication.js +4 -2
  77. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +44 -22
  78. package/lib/cjs/helpers/validatePositiveInput.js +2 -1
  79. package/lib/cjs/helpers/validateTakeableOffers.js +2 -1
  80. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +14 -7
  81. package/lib/cjs/index.d.ts +2 -2
  82. package/lib/cjs/index.js +10 -1
  83. package/lib/cjs/midnight/errors.d.ts +1 -2
  84. package/lib/cjs/midnight/errors.js +4 -5
  85. package/lib/cjs/transactionPlan/approval.js +12 -1
  86. package/lib/cjs/transactionPlan/deposit.d.ts +22 -0
  87. package/lib/cjs/transactionPlan/deposit.js +139 -0
  88. package/lib/cjs/transactionPlan/error.d.ts +10 -8
  89. package/lib/cjs/transactionPlan/error.js +10 -8
  90. package/lib/cjs/transactionPlan/getTokenPermit.js +2 -1
  91. package/lib/cjs/transactionPlan/index.d.ts +18 -0
  92. package/lib/cjs/transactionPlan/index.js +23 -5
  93. package/lib/cjs/transactionPlan/intent.d.ts +3 -3
  94. package/lib/cjs/transactionPlan/intent.js +14 -7
  95. package/lib/cjs/transactionPlan/permit.d.ts +1 -1
  96. package/lib/cjs/transactionPlan/permit.js +86 -20
  97. package/lib/cjs/transactionPlan/plan.d.ts +16 -6
  98. package/lib/cjs/transactionPlan/plan.js +72 -22
  99. package/lib/cjs/transactionPlan/redeem.d.ts +18 -0
  100. package/lib/cjs/transactionPlan/redeem.js +63 -0
  101. package/lib/cjs/transactionPlan/requirements.d.ts +4 -3
  102. package/lib/cjs/transactionPlan/requirements.js +12 -6
  103. package/lib/cjs/transactionPlan/serde.d.ts +2 -2
  104. package/lib/cjs/transactionPlan/serde.js +41 -15
  105. package/lib/cjs/transactionPlan/shareSpending.d.ts +18 -0
  106. package/lib/cjs/transactionPlan/shareSpending.js +50 -0
  107. package/lib/cjs/transactionPlan/types.d.ts +117 -11
  108. package/lib/cjs/transactionPlan/validateActions.js +11 -1
  109. package/lib/cjs/transactionPlan/validation.js +6 -3
  110. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +93 -0
  111. package/lib/cjs/transactionPlan/vaultv1/deposit.js +94 -0
  112. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
  113. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +203 -0
  114. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
  115. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +217 -0
  116. package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +69 -0
  117. package/lib/cjs/transactionPlan/vaultv1/redeem.js +78 -0
  118. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +77 -0
  119. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +88 -0
  120. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +14 -31
  121. package/lib/cjs/transactionPlan/vaultv2/deposit.js +15 -141
  122. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
  123. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +155 -0
  124. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
  125. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +206 -0
  126. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
  127. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +206 -0
  128. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +84 -0
  129. package/lib/cjs/transactionPlan/vaultv2/redeem.js +86 -0
  130. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +14 -27
  131. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +17 -124
  132. package/lib/cjs/transactionPlan/version.js +2 -1
  133. package/lib/cjs/transactionPlan/withdraw.d.ts +18 -0
  134. package/lib/cjs/transactionPlan/withdraw.js +94 -0
  135. package/lib/cjs/types/action.js +16 -8
  136. package/lib/cjs/types/error.d.ts +8 -1
  137. package/lib/cjs/types/error.js +10 -1
  138. package/lib/cjs/utils.d.ts +2 -2
  139. package/lib/cjs/utils.js +2 -4
  140. package/lib/cjs/version.d.ts +1 -1
  141. package/lib/cjs/version.js +1 -1
  142. package/lib/esm/abis.d.ts +1 -1
  143. package/lib/esm/abis.js +1 -1
  144. package/lib/esm/actions/blue/common.js +4 -2
  145. package/lib/esm/actions/blue/withdrawBuyCallback.js +2 -1
  146. package/lib/esm/actions/bundles/common.js +20 -14
  147. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -1
  148. package/lib/esm/actions/midnight/cancelOffers.js +2 -1
  149. package/lib/esm/actions/midnight/supplyCollateralBatch.js +4 -2
  150. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +2 -1
  151. package/lib/esm/actions/midnight/takeBorrow.js +2 -1
  152. package/lib/esm/actions/midnight/takeLend.js +2 -1
  153. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +2 -1
  154. package/lib/esm/actions/midnight/takeWithdraw.js +2 -1
  155. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +4 -2
  156. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +4 -13
  157. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +2 -1
  158. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +2 -1
  159. package/lib/esm/actions/vaultV1/inKindRedeem.js +6 -3
  160. package/lib/esm/actions/vaultV1/migrateToV2.js +1 -1
  161. package/lib/esm/actions/vaultV2/forceWithdraw.js +4 -2
  162. package/lib/esm/actions/vaultV2/inKindRedeem.js +4 -2
  163. package/lib/esm/blue/abis.d.ts +1 -1
  164. package/lib/esm/blue/abis.js +1 -1
  165. package/lib/esm/blue/entities.d.ts +4 -4
  166. package/lib/esm/blue/entities.js +2 -2
  167. package/lib/esm/blue/errors.d.ts +2 -2
  168. package/lib/esm/blue/errors.js +2 -2
  169. package/lib/esm/blue/fetch.d.ts +2 -2
  170. package/lib/esm/blue/fetch.js +2 -2
  171. package/lib/esm/blue/utils.d.ts +1 -1
  172. package/lib/esm/blue/utils.js +1 -1
  173. package/lib/esm/entities/blue/blue.js +8 -4
  174. package/lib/esm/entities/index.d.ts +4 -4
  175. package/lib/esm/entities/index.js +2 -2
  176. package/lib/esm/entities/midnight/deadline.js +2 -1
  177. package/lib/esm/entities/midnight/midnight.js +14 -7
  178. package/lib/esm/entities/midnight/publication.js +73 -44
  179. package/lib/esm/entities/requirements/assertContractCode.js +4 -2
  180. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +10 -14
  181. package/lib/esm/entities/requirements/getErc2612Permit.js +10 -5
  182. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -0
  183. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +7 -1
  184. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.d.ts +21 -0
  185. package/lib/esm/entities/requirements/getVaultV1InKindRedeemRequirements.js +108 -0
  186. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.d.ts +20 -0
  187. package/lib/esm/entities/requirements/getVaultV2ForceWithdrawRequirements.js +73 -0
  188. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.d.ts +21 -0
  189. package/lib/esm/entities/requirements/getVaultV2InKindRedeemRequirements.js +90 -0
  190. package/lib/esm/entities/vaultV1/inKindRedeemQuote.d.ts +25 -0
  191. package/lib/esm/entities/vaultV1/inKindRedeemQuote.js +82 -0
  192. package/lib/esm/entities/vaultV1/migrateToV2Quote.d.ts +20 -0
  193. package/lib/esm/entities/vaultV1/migrateToV2Quote.js +34 -0
  194. package/lib/esm/entities/vaultV1/vaultV1.js +57 -187
  195. package/lib/esm/entities/vaultV2/forceWithdrawQuote.d.ts +25 -0
  196. package/lib/esm/entities/vaultV2/forceWithdrawQuote.js +186 -0
  197. package/lib/esm/entities/vaultV2/inKindRedeemQuote.d.ts +28 -0
  198. package/lib/esm/entities/vaultV2/inKindRedeemQuote.js +107 -0
  199. package/lib/esm/entities/vaultV2/vaultV2.d.ts +8 -34
  200. package/lib/esm/entities/vaultV2/vaultV2.js +70 -437
  201. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +2 -3
  202. package/lib/esm/entities/vaultV2BlueReallocationData.js +346 -234
  203. package/lib/esm/errors.d.ts +4 -4
  204. package/lib/esm/errors.js +4 -4
  205. package/lib/esm/fetch.d.ts +2 -2
  206. package/lib/esm/fetch.js +2 -2
  207. package/lib/esm/helpers/deadShares.js +35 -20
  208. package/lib/esm/helpers/encodeMidnightCalldata.js +4 -2
  209. package/lib/esm/helpers/metadata.js +12 -6
  210. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +10 -5
  211. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +6 -3
  212. package/lib/esm/helpers/utilization.js +10 -5
  213. package/lib/esm/helpers/validate.js +12 -6
  214. package/lib/esm/helpers/validateMidnightBounds.js +2 -1
  215. package/lib/esm/helpers/validateMidnightCollateralBatch.js +2 -1
  216. package/lib/esm/helpers/validateMidnightPublication.js +4 -2
  217. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +44 -22
  218. package/lib/esm/helpers/validatePositiveInput.js +2 -1
  219. package/lib/esm/helpers/validateTakeableOffers.js +2 -1
  220. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +14 -7
  221. package/lib/esm/index.d.ts +2 -2
  222. package/lib/esm/index.js +1 -1
  223. package/lib/esm/midnight/errors.d.ts +1 -2
  224. package/lib/esm/midnight/errors.js +1 -2
  225. package/lib/esm/transactionPlan/approval.js +13 -2
  226. package/lib/esm/transactionPlan/deposit.d.ts +22 -0
  227. package/lib/esm/transactionPlan/deposit.js +135 -0
  228. package/lib/esm/transactionPlan/error.d.ts +10 -8
  229. package/lib/esm/transactionPlan/error.js +10 -8
  230. package/lib/esm/transactionPlan/getTokenPermit.js +2 -1
  231. package/lib/esm/transactionPlan/index.d.ts +18 -0
  232. package/lib/esm/transactionPlan/index.js +9 -0
  233. package/lib/esm/transactionPlan/intent.d.ts +3 -3
  234. package/lib/esm/transactionPlan/intent.js +14 -7
  235. package/lib/esm/transactionPlan/permit.d.ts +1 -1
  236. package/lib/esm/transactionPlan/permit.js +86 -20
  237. package/lib/esm/transactionPlan/plan.d.ts +16 -6
  238. package/lib/esm/transactionPlan/plan.js +68 -18
  239. package/lib/esm/transactionPlan/redeem.d.ts +18 -0
  240. package/lib/esm/transactionPlan/redeem.js +59 -0
  241. package/lib/esm/transactionPlan/requirements.d.ts +4 -3
  242. package/lib/esm/transactionPlan/requirements.js +12 -6
  243. package/lib/esm/transactionPlan/serde.d.ts +2 -2
  244. package/lib/esm/transactionPlan/serde.js +41 -15
  245. package/lib/esm/transactionPlan/shareSpending.d.ts +18 -0
  246. package/lib/esm/transactionPlan/shareSpending.js +47 -0
  247. package/lib/esm/transactionPlan/types.d.ts +117 -11
  248. package/lib/esm/transactionPlan/validateActions.js +11 -1
  249. package/lib/esm/transactionPlan/validation.js +6 -3
  250. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +93 -0
  251. package/lib/esm/transactionPlan/vaultv1/deposit.js +90 -0
  252. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +96 -0
  253. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +198 -0
  254. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +94 -0
  255. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +212 -0
  256. package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +69 -0
  257. package/lib/esm/transactionPlan/vaultv1/redeem.js +74 -0
  258. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +77 -0
  259. package/lib/esm/transactionPlan/vaultv1/withdraw.js +84 -0
  260. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +14 -31
  261. package/lib/esm/transactionPlan/vaultv2/deposit.js +17 -142
  262. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +74 -0
  263. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +150 -0
  264. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +98 -0
  265. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +201 -0
  266. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +113 -0
  267. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +201 -0
  268. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +84 -0
  269. package/lib/esm/transactionPlan/vaultv2/redeem.js +82 -0
  270. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +14 -27
  271. package/lib/esm/transactionPlan/vaultv2/withdraw.js +19 -125
  272. package/lib/esm/transactionPlan/version.js +2 -1
  273. package/lib/esm/transactionPlan/withdraw.d.ts +18 -0
  274. package/lib/esm/transactionPlan/withdraw.js +90 -0
  275. package/lib/esm/types/action.js +16 -8
  276. package/lib/esm/types/error.d.ts +8 -1
  277. package/lib/esm/types/error.js +10 -1
  278. package/lib/esm/utils.d.ts +2 -2
  279. package/lib/esm/utils.js +2 -2
  280. package/lib/esm/version.d.ts +1 -1
  281. package/lib/esm/version.js +1 -1
  282. package/package.json +15 -15
@@ -17,8 +17,9 @@ const createCapReserveState = (markets) => ({
17
17
  });
18
18
  const cloneCapReserveState = (state) => {
19
19
  const touchedPairs = new Map();
20
- for (const [vault, pairs] of state.touchedPairs)
20
+ for (const [vault, pairs] of state.touchedPairs) {
21
21
  touchedPairs.set(vault, new Map(pairs));
22
+ }
22
23
  return {
23
24
  initialMarkets: { ...state.initialMarkets },
24
25
  marketAccruals: new Map(state.marketAccruals),
@@ -40,8 +41,9 @@ const createSimulationContext = () => ({
40
41
  * @internal
41
42
  */
42
43
  const findAddressKey = (record, address) => {
43
- if (Object.hasOwn(record, address))
44
+ if (Object.hasOwn(record, address)) {
44
45
  return address;
46
+ }
45
47
  return Object.keys(record).find((key) => (0, viem_1.isAddressEqual)(key, address));
46
48
  };
47
49
  /**
@@ -57,22 +59,25 @@ const findAddressKey = (record, address) => {
57
59
  const getAdapterIds = (cache, adapter, market) => {
58
60
  const key = `${adapter.address}:${market.id}`;
59
61
  const cached = cache.get(key);
60
- if (cached != null)
62
+ if (cached != null) {
61
63
  return cached;
64
+ }
62
65
  const ids = adapter.ids(market.params);
63
66
  cache.set(key, ids);
64
67
  return ids;
65
68
  };
66
69
  const resolveMaxPenalty = (value) => {
67
70
  const penalty = value ?? constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY;
68
- if (penalty < 0n)
71
+ if (penalty < 0n) {
69
72
  throw new index_js_1.NegativeInputError("maxPenalty", penalty);
70
- if (penalty > constant_js_1.MAX_REALLOCATION_PENALTY)
73
+ }
74
+ if (penalty > constant_js_1.MAX_REALLOCATION_PENALTY) {
71
75
  throw new index_js_1.InputExceedsMaxError({
72
76
  field: "maxPenalty",
73
77
  value: penalty,
74
78
  max: constant_js_1.MAX_REALLOCATION_PENALTY,
75
79
  });
80
+ }
76
81
  return penalty;
77
82
  };
78
83
  const getCanonicalMarket = (markets, market) => (markets[market.id] ??= new blue_sdk_1.Market({ ...market }));
@@ -90,14 +95,12 @@ const cloneAccrualVault = (vault, markets) => new blue_sdk_1.AccrualVault({
90
95
  position: clonePosition(position, markets),
91
96
  })));
92
97
  const cloneAdapter = (adapter, markets) => {
93
- if (adapter.type === "VaultV2MidnightAdapter")
94
- return adapter;
95
98
  const base = {
96
99
  address: adapter.address,
97
100
  parentVault: adapter.parentVault,
98
101
  skimRecipient: adapter.skimRecipient,
99
102
  };
100
- if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)
103
+ if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2) {
101
104
  return new blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2({
102
105
  ...base,
103
106
  marketIds: [...adapter.marketIds],
@@ -107,14 +110,17 @@ const cloneAdapter = (adapter, markets) => {
107
110
  // V2 adapters can retain the canonical instance directly, so every
108
111
  // adapter observes the same global Morpho market state.
109
112
  adapter.markets.map((market) => getCanonicalMarket(markets, market)));
110
- if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter)
113
+ }
114
+ if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter) {
111
115
  return new blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter({ ...base, marketParamsList: [...adapter.marketParamsList] }, adapter.positions.map((position) => clonePosition(position, markets)));
112
- if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter)
116
+ }
117
+ if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter) {
113
118
  return new blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter({
114
119
  ...base,
115
120
  morphoVaultV1: adapter.morphoVaultV1,
116
121
  parentAllocation: adapter.parentAllocation,
117
122
  }, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
123
+ }
118
124
  throw new blue_sdk_1.UnsupportedVaultV2AdapterError(adapter.address);
119
125
  };
120
126
  const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
@@ -140,8 +146,7 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
140
146
  /**
141
147
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
142
148
  *
143
- * Constructor inputs are cloned, except read-only Midnight adapter snapshots, which are
144
- * shared by reference. Every simulated reallocation returns a new
149
+ * Constructor inputs are cloned. Every simulated reallocation returns a new
145
150
  * instance. Planning keeps the transaction-scoped `firstTotalAssets`
146
151
  * denominator outside the durable snapshot while applying reallocations in
147
152
  * contract order. Penalty donations update simulated vault accounting but are
@@ -272,7 +277,7 @@ class VaultV2BlueReallocationData {
272
277
  /**
273
278
  * Clones the complete simulation snapshot.
274
279
  *
275
- * @returns A deep clone of this simulation state; read-only Midnight adapter snapshots are shared by reference.
280
+ * @returns A deep clone of this simulation state.
276
281
  * @example
277
282
  * ```ts
278
283
  * import { markets } from "@morpho-org/morpho-test";
@@ -328,8 +333,9 @@ class VaultV2BlueReallocationData {
328
333
  */
329
334
  getMarket(marketId) {
330
335
  const market = this.mutableMarkets[marketId];
331
- if (market == null)
336
+ if (market == null) {
332
337
  throw new index_js_1.UnknownReallocationMarketError(marketId);
338
+ }
333
339
  return market;
334
340
  }
335
341
  /**
@@ -366,8 +372,9 @@ class VaultV2BlueReallocationData {
366
372
  getMutableVault(vault) {
367
373
  const key = findAddressKey(this.mutableVaults, vault);
368
374
  const data = key == null ? undefined : this.mutableVaults[key];
369
- if (data == null)
375
+ if (data == null) {
370
376
  throw new index_js_1.UnknownReallocationVaultError(vault);
377
+ }
371
378
  return data;
372
379
  }
373
380
  /**
@@ -406,8 +413,9 @@ class VaultV2BlueReallocationData {
406
413
  getAllocation(vault, id) {
407
414
  const key = findAddressKey(this.allocations, vault);
408
415
  const allocation = key == null ? undefined : this.allocations[key]?.[id];
409
- if (allocation == null)
416
+ if (allocation == null) {
410
417
  throw new index_js_1.UnknownReallocationAllocationError(vault, id);
418
+ }
411
419
  return allocation;
412
420
  }
413
421
  /**
@@ -441,8 +449,9 @@ class VaultV2BlueReallocationData {
441
449
  */
442
450
  getPublicAllocatorConfig(vault) {
443
451
  const config = this.getOptionalPublicAllocatorConfig(vault);
444
- if (config == null)
452
+ if (config == null) {
445
453
  throw new index_js_1.UnknownReallocationPublicAllocatorConfigError(vault);
454
+ }
446
455
  return config;
447
456
  }
448
457
  /**
@@ -454,8 +463,9 @@ class VaultV2BlueReallocationData {
454
463
  */
455
464
  getOptionalPublicAllocatorConfig(vault) {
456
465
  const key = findAddressKey(this.publicAllocatorConfigs, vault);
457
- if (key == null)
466
+ if (key == null) {
458
467
  throw new index_js_1.UnknownReallocationPublicAllocatorConfigError(vault);
468
+ }
459
469
  return this.publicAllocatorConfigs[key];
460
470
  }
461
471
  /**
@@ -488,8 +498,9 @@ class VaultV2BlueReallocationData {
488
498
  getActiveAdapters(vault) {
489
499
  const key = findAddressKey(this.activeAdapters, vault);
490
500
  const adapters = key == null ? undefined : this.activeAdapters[key];
491
- if (adapters == null)
501
+ if (adapters == null) {
492
502
  throw new index_js_1.UnknownReallocationActiveAdaptersError(vault);
503
+ }
493
504
  return adapters;
494
505
  }
495
506
  /**
@@ -533,8 +544,9 @@ class VaultV2BlueReallocationData {
533
544
  const config = key == null
534
545
  ? undefined
535
546
  : this.marketPublicAllocatorConfigs[key]?.[adapterMarketCapId];
536
- if (config == null)
547
+ if (config == null) {
537
548
  throw new index_js_1.UnknownReallocationMarketPublicAllocatorConfigError(vault, adapterMarketCapId);
549
+ }
538
550
  return config;
539
551
  }
540
552
  /**
@@ -573,8 +585,9 @@ class VaultV2BlueReallocationData {
573
585
  getMutableAdapter(vault, adapter) {
574
586
  const data = this.getMutableVault(vault).accrualAdapters.find((candidate) => candidate instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2 &&
575
587
  (0, viem_1.isAddressEqual)(candidate.address, adapter));
576
- if (data == null)
588
+ if (data == null) {
577
589
  throw new index_js_1.UnknownReallocationAdapterError(vault, adapter);
590
+ }
578
591
  return data;
579
592
  }
580
593
  /**
@@ -700,8 +713,9 @@ class VaultV2BlueReallocationData {
700
713
  * ```
701
714
  */
702
715
  computeVaultV2BlueReallocations(marketId, options = {}) {
703
- if (options.enabled === false)
716
+ if (options.enabled === false) {
704
717
  return { reallocations: [], data: this };
718
+ }
705
719
  const maxWithdrawalUtilization = (0, utilization_js_1.resolveMaxWithdrawalUtilization)(options.maxWithdrawalUtilization);
706
720
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
707
721
  const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options.capAccrualBuffer);
@@ -802,7 +816,7 @@ class VaultV2BlueReallocationData {
802
816
  return { normalizedOptions, market, hasExplicitBlueBalance, blueBalance };
803
817
  }
804
818
  computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
805
- if (options.enabled === false)
819
+ if (options.enabled === false) {
806
820
  return {
807
821
  reallocations: [],
808
822
  data: this,
@@ -810,6 +824,7 @@ class VaultV2BlueReallocationData {
810
824
  allocatorCapBoundTargets: new Set(),
811
825
  idleBoundVaults: new Set(),
812
826
  };
827
+ }
813
828
  this.getMarket(marketId);
814
829
  const timestamp = options.timestamp == null
815
830
  ? this.getLatestSnapshotTimestamp()
@@ -831,56 +846,12 @@ class VaultV2BlueReallocationData {
831
846
  const idleBoundVaults = new Set();
832
847
  const initialIdleAssets = new Map();
833
848
  const idleTakenAssets = new Map();
834
- // Onchain, market interest is booked once at transaction start, on pre-plan
835
- // positions at pre-plan rates, and stays on touched positions' cap ids.
836
- // This reserve state is shared across every planner pass and leg of the plan.
837
- // biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
838
- const getPair = (vault, adapter, market) => {
839
- const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
840
- const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
841
- if (touched != null)
842
- return touched;
843
- const shares = adapter.supplyShares[market.id] ?? 0n;
844
- return {
845
- key,
846
- ids: getAdapterIds(adapterIdsCache, adapter, market),
847
- reserve: (reserveState) => {
848
- let reserve = reserveState.reserveByPairKey.get(key);
849
- if (reserve == null) {
850
- let accruals = reserveState.marketAccruals.get(market.id);
851
- if (accruals == null) {
852
- const initialMarket = reserveState.initialMarkets[market.id];
853
- if (initialMarket == null)
854
- throw new index_js_1.UnknownReallocationMarketError(market.id);
855
- accruals = [
856
- initialMarket.accrueInterest(timestamp),
857
- initialMarket.accrueInterest(timestamp + capAccrualBuffer),
858
- ];
859
- reserveState.marketAccruals.set(market.id, accruals);
860
- }
861
- const [atTimestamp, projected] = accruals;
862
- reserve = blue_sdk_1.MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
863
- reserveState.reserveByPairKey.set(key, reserve);
864
- }
865
- return reserve;
866
- },
867
- };
868
- };
869
- // biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
870
- const capReserve = (vault, id, candidatePairs) => {
871
- let reserve = 0n;
872
- const seen = new Set();
873
- for (const pair of [
874
- ...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
875
- ...candidatePairs,
876
- ]) {
877
- if (seen.has(pair.key) || !pair.ids.includes(id))
878
- continue;
879
- seen.add(pair.key);
880
- reserve += pair.reserve(reserves);
881
- }
882
- return reserve;
883
- };
849
+ const { getPair, capReserve } = createCapReserveResolvers({
850
+ reserves,
851
+ adapterIdsCache,
852
+ timestamp,
853
+ capAccrualBuffer,
854
+ });
884
855
  while (remainingAssets == null || remainingAssets > 0n) {
885
856
  const candidates = vaults
886
857
  .map((vaultAddress) => {
@@ -904,28 +875,16 @@ class VaultV2BlueReallocationData {
904
875
  setMarkets: data.setMarkets.bind(data),
905
876
  applyPublicReallocation: data.applyPublicReallocation.bind(data),
906
877
  };
907
- const idleState = resolveVaultCandidateIdleState(params);
908
- if (idleState == null)
909
- return;
910
- const { availableIdleAssets } = idleState;
911
- const vaultAddressKey = vaultAddress.toLowerCase();
912
- if (!initialIdleAssets.has(vaultAddressKey))
913
- initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
914
- let activeAdapters = activeAdaptersCache.get(vaultAddress);
915
- if (activeAdapters == null) {
916
- activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
917
- activeAdaptersCache.set(vaultAddress, activeAdapters);
918
- }
919
- return planVaultCandidate({
878
+ return planCachedVaultCandidate({
920
879
  ...params,
921
- ...idleState,
922
- activeAdapters,
880
+ initialIdleAssets,
881
+ activeAdaptersCache,
923
882
  });
924
883
  })
925
884
  .filter((candidate) => candidate != null)
926
885
  .sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"));
927
886
  const largest = candidates[0];
928
- if (largest == null)
887
+ if (largest == null) {
929
888
  return {
930
889
  reallocations,
931
890
  data,
@@ -933,6 +892,7 @@ class VaultV2BlueReallocationData {
933
892
  allocatorCapBoundTargets,
934
893
  idleBoundVaults,
935
894
  };
895
+ }
936
896
  const updates = getAcceptedCandidateUpdates({
937
897
  candidate: largest,
938
898
  idleTakenAssets,
@@ -956,8 +916,9 @@ class VaultV2BlueReallocationData {
956
916
  });
957
917
  data = transition.data;
958
918
  simulationContext = transition.context;
959
- if (remainingAssets != null)
919
+ if (remainingAssets != null) {
960
920
  remainingAssets -= acceptedReallocation.assets;
921
+ }
961
922
  }
962
923
  return {
963
924
  reallocations,
@@ -1013,8 +974,9 @@ class VaultV2BlueReallocationData {
1013
974
  * ```
1014
975
  */
1015
976
  getPublicReallocationLiquidity(marketId, options) {
1016
- if (options?.enabled === false)
977
+ if (options?.enabled === false) {
1017
978
  return 0n;
979
+ }
1018
980
  const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options?.capAccrualBuffer);
1019
981
  const maxPenalty = resolveMaxPenalty(options?.maxPenalty);
1020
982
  return this.clone()
@@ -1083,8 +1045,9 @@ class VaultV2BlueReallocationData {
1083
1045
  : BigInt(options.timestamp);
1084
1046
  const market = this.getMarket(marketId).accrueInterest(timestamp);
1085
1047
  if (options?.enabled === false ||
1086
- constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization)
1048
+ constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization) {
1087
1049
  return market.getBorrowToUtilization(utilization);
1050
+ }
1088
1051
  const availableLiquidity = this.clone()
1089
1052
  .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1090
1053
  context: createSimulationContext(),
@@ -1107,12 +1070,14 @@ class VaultV2BlueReallocationData {
1107
1070
  getLatestSnapshotTimestamp() {
1108
1071
  let timestamp = this.timestamp ?? 0n;
1109
1072
  for (const market of Object.values(this.markets)) {
1110
- if (market != null)
1073
+ if (market != null) {
1111
1074
  timestamp = blue_sdk_1.MathLib.max(timestamp, market.lastUpdate);
1075
+ }
1112
1076
  }
1113
1077
  for (const vault of Object.values(this.vaults)) {
1114
- if (vault != null)
1078
+ if (vault != null) {
1115
1079
  timestamp = blue_sdk_1.MathLib.max(timestamp, vault.lastUpdate);
1080
+ }
1116
1081
  }
1117
1082
  return timestamp;
1118
1083
  }
@@ -1168,8 +1133,9 @@ class VaultV2BlueReallocationData {
1168
1133
  });
1169
1134
  }
1170
1135
  // Idle allocations also credit the instance's explicit Blue liquidity balance.
1171
- if (reallocation.from.type === "idle")
1136
+ if (reallocation.from.type === "idle") {
1172
1137
  data.creditIdleReallocationBalance(reallocation, targetMarket);
1138
+ }
1173
1139
  if (firstTotalAssets == null) {
1174
1140
  const firstAllocation = data.accrueReallocationFirstAllocation({
1175
1141
  vault,
@@ -1204,10 +1170,12 @@ class VaultV2BlueReallocationData {
1204
1170
  const supply = currentTargetMarket.supply(reallocation.assets, 0n, timestamp);
1205
1171
  const targetSupplyShares = (targetAdapter.supplyShares[targetMarket.id] ?? 0n) + supply.shares;
1206
1172
  targetAdapter.supplyShares[targetMarket.id] = targetSupplyShares;
1207
- if (!targetAdapter.marketIds.includes(targetMarket.id))
1173
+ if (!targetAdapter.marketIds.includes(targetMarket.id)) {
1208
1174
  targetAdapter.marketIds.push(targetMarket.id);
1209
- if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id))
1175
+ }
1176
+ if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id)) {
1210
1177
  targetAdapter.markets.push(supply.market);
1178
+ }
1211
1179
  this.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1212
1180
  const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1213
1181
  // The adapter's rounded expected-assets delta can differ by one wei at inclusion,
@@ -1216,8 +1184,9 @@ class VaultV2BlueReallocationData {
1216
1184
  for (const id of targetIds) {
1217
1185
  const allocation = this.getAllocation(reallocation.vault, id);
1218
1186
  const allocations = this.mutableAllocations[allocationsKey];
1219
- if (allocations == null)
1187
+ if (allocations == null) {
1220
1188
  throw new index_js_1.UnknownReallocationAllocationError(reallocation.vault, id);
1189
+ }
1221
1190
  allocations[id] = {
1222
1191
  ...allocation,
1223
1192
  allocation: allocation.allocation + targetChange,
@@ -1227,12 +1196,14 @@ class VaultV2BlueReallocationData {
1227
1196
  /** Credits shared Blue liquidity when an idle allocation enters the target market. @internal */
1228
1197
  creditIdleReallocationBalance(reallocation, targetMarket) {
1229
1198
  const blueBalanceKey = findAddressKey(this.mutableBlueBalances, targetMarket.params.loanToken);
1230
- if (blueBalanceKey == null)
1199
+ if (blueBalanceKey == null) {
1231
1200
  return;
1201
+ }
1232
1202
  const blueBalance = this.mutableBlueBalances[blueBalanceKey];
1233
- if (blueBalance != null)
1203
+ if (blueBalance != null) {
1234
1204
  this.mutableBlueBalances[blueBalanceKey] =
1235
1205
  blueBalance + reallocation.assets;
1206
+ }
1236
1207
  }
1237
1208
  /** Builds the isolated markets, adapter views and caps used by a transition probe. @internal */
1238
1209
  cloneReallocationProbe({ reallocation, targetMarketId, adapterIdsCache, sourceVaultKey, sourceVault, sourceAllocationsKey, }) {
@@ -1247,10 +1218,12 @@ class VaultV2BlueReallocationData {
1247
1218
  const sourceMarket = this.getMarket(reallocation.from.marketParams.id);
1248
1219
  probeMarkets[sourceMarket.id] = sourceMarket;
1249
1220
  adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
1250
- for (const key of getDependentProbeAdapterKeys(sourceVault, sourceMarket.id))
1221
+ for (const key of getDependentProbeAdapterKeys(sourceVault, sourceMarket.id)) {
1251
1222
  adapterKeysToClone.add(key);
1252
- for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket))
1223
+ }
1224
+ for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket)) {
1253
1225
  allocationIdsToClone.add(id);
1226
+ }
1254
1227
  }
1255
1228
  const data = new VaultV2BlueReallocationData({
1256
1229
  chainId: this.chainId,
@@ -1269,8 +1242,9 @@ class VaultV2BlueReallocationData {
1269
1242
  if (sourceAllocationsKey != null) {
1270
1243
  const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
1271
1244
  const allocations = {};
1272
- for (const id of allocationIdsToClone)
1245
+ for (const id of allocationIdsToClone) {
1273
1246
  allocations[id] = sourceAllocations?.[id];
1247
+ }
1274
1248
  data.mutableAllocations[sourceAllocationsKey] = allocations;
1275
1249
  }
1276
1250
  return data;
@@ -1351,16 +1325,18 @@ class VaultV2BlueReallocationData {
1351
1325
  this.mutableMarkets[market.id] = market;
1352
1326
  changedMarketIds.add(market.id);
1353
1327
  }
1354
- if (changedMarketIds.size === 0)
1328
+ if (changedMarketIds.size === 0) {
1355
1329
  return;
1330
+ }
1356
1331
  const adapters = collectAdaptersToRefresh(this.mutableVaults, adaptersToRefresh);
1357
1332
  for (const adapter of adapters) {
1358
1333
  const update = refreshAdapterMarkets(adapter, {
1359
1334
  markets: this.mutableMarkets,
1360
1335
  changedMarketIds,
1361
1336
  });
1362
- if (update != null)
1337
+ if (update != null) {
1363
1338
  Object.assign(adapter, update);
1339
+ }
1364
1340
  }
1365
1341
  }
1366
1342
  }
@@ -1373,39 +1349,46 @@ function collectAdaptersToRefresh(vaults, adaptersToRefresh) {
1373
1349
  // AccrualPosition constructors copy their Market, so rebuild those adapter
1374
1350
  // views as well as repointing V2 adapters whenever the canonical state moves.
1375
1351
  for (const vault of Object.values(vaults)) {
1376
- if (vault == null)
1352
+ if (vault == null) {
1377
1353
  continue;
1378
- for (const adapter of vault.accrualAdapters)
1354
+ }
1355
+ for (const adapter of vault.accrualAdapters) {
1379
1356
  adapters.add(adapter);
1380
- if (vault.accrualLiquidityAdapter != null)
1357
+ }
1358
+ if (vault.accrualLiquidityAdapter != null) {
1381
1359
  adapters.add(vault.accrualLiquidityAdapter);
1360
+ }
1382
1361
  }
1383
1362
  }
1384
1363
  else {
1385
- for (const adapter of adaptersToRefresh)
1364
+ for (const adapter of adaptersToRefresh) {
1386
1365
  adapters.add(adapter);
1366
+ }
1387
1367
  }
1388
1368
  return adapters;
1389
1369
  }
1390
1370
  /** Computes one adapter's dependent market views after a canonical state change. @internal */
1391
1371
  function refreshAdapterMarkets(adapter, { markets, changedMarketIds, }) {
1392
1372
  if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2) {
1393
- if (!adapter.markets.some(({ id }) => changedMarketIds.has(id)))
1373
+ if (!adapter.markets.some(({ id }) => changedMarketIds.has(id))) {
1394
1374
  return;
1375
+ }
1395
1376
  return {
1396
1377
  markets: adapter.markets.map((adapterMarket) => getCanonicalMarket(markets, adapterMarket)),
1397
1378
  };
1398
1379
  }
1399
1380
  if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1Adapter) {
1400
- if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId)))
1381
+ if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId))) {
1401
1382
  return;
1383
+ }
1402
1384
  return {
1403
1385
  positions: adapter.positions.map((position) => clonePosition(position, markets)),
1404
1386
  };
1405
1387
  }
1406
1388
  if (adapter instanceof blue_sdk_1.AccrualVaultV2MorphoVaultV1Adapter) {
1407
- if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId)))
1389
+ if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId))) {
1408
1390
  return;
1391
+ }
1409
1392
  return {
1410
1393
  accrualVaultV1: cloneAccrualVault(adapter.accrualVaultV1, markets),
1411
1394
  };
@@ -1447,14 +1430,17 @@ function cloneMarketAllocatorConfigurations(configs) {
1447
1430
  /** Finds adapter views that a source-market transition must isolate for probing. @internal */
1448
1431
  function getDependentProbeAdapterKeys(sourceVault, sourceMarketId) {
1449
1432
  const keys = new Set();
1450
- if (sourceVault == null)
1433
+ if (sourceVault == null) {
1451
1434
  return keys;
1435
+ }
1452
1436
  const adapters = new Set(sourceVault.accrualAdapters);
1453
- if (sourceVault.accrualLiquidityAdapter != null)
1437
+ if (sourceVault.accrualLiquidityAdapter != null) {
1454
1438
  adapters.add(sourceVault.accrualLiquidityAdapter);
1439
+ }
1455
1440
  for (const adapter of adapters) {
1456
- if (adapterReferencesMarket(adapter, sourceMarketId))
1441
+ if (adapterReferencesMarket(adapter, sourceMarketId)) {
1457
1442
  keys.add(adapter.address.toLowerCase());
1443
+ }
1458
1444
  }
1459
1445
  return keys;
1460
1446
  }
@@ -1473,9 +1459,10 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
1473
1459
  const idleBoundVaults = [];
1474
1460
  const idleTakenEntries = [];
1475
1461
  const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1476
- if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1462
+ if (acceptedReallocation.assets >= acceptedAllocatorHeadroom) {
1477
1463
  // BluePublicAllocator caps are per vault and target adapter.
1478
1464
  allocatorCapBoundTargets.push(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1465
+ }
1479
1466
  if (acceptedReallocation.from.type === "idle") {
1480
1467
  const vaultKey = acceptedReallocation.vault.toLowerCase();
1481
1468
  const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
@@ -1483,8 +1470,9 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
1483
1470
  // Candidates always record this; a missing entry counts the vault as bound.
1484
1471
  const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1485
1472
  if (taken >=
1486
- blue_sdk_1.MathLib.zeroFloorSub(initial, blue_sdk_1.MathLib.wMulUp(initial, allocatorCapHeadroom)))
1473
+ blue_sdk_1.MathLib.zeroFloorSub(initial, blue_sdk_1.MathLib.wMulUp(initial, allocatorCapHeadroom))) {
1487
1474
  idleBoundVaults.push(vaultKey);
1475
+ }
1488
1476
  }
1489
1477
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1490
1478
  const existingPairs = reserves.touchedPairs.get(touchedVaultKey);
@@ -1493,12 +1481,14 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
1493
1481
  ? [[touchedVaultKey, touchedVaultPairs]]
1494
1482
  : [];
1495
1483
  const touchedPairEntries = [];
1496
- if (!touchedVaultPairs.has(acceptedTargetPair.key))
1484
+ if (!touchedVaultPairs.has(acceptedTargetPair.key)) {
1497
1485
  touchedPairEntries.push([acceptedTargetPair.key, acceptedTargetPair]);
1486
+ }
1498
1487
  if (acceptedSourcePair != null &&
1499
1488
  !touchedVaultPairs.has(acceptedSourcePair.key) &&
1500
- acceptedSourcePair.key !== acceptedTargetPair.key)
1489
+ acceptedSourcePair.key !== acceptedTargetPair.key) {
1501
1490
  touchedPairEntries.push([acceptedSourcePair.key, acceptedSourcePair]);
1491
+ }
1502
1492
  return {
1503
1493
  allocatorCapBoundTargets,
1504
1494
  idleTakenAssets: idleTakenEntries,
@@ -1508,26 +1498,117 @@ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, init
1508
1498
  touchedPairEntries,
1509
1499
  };
1510
1500
  }
1501
+ /**
1502
+ * Creates cap-reserve readers over the shared in-place planning caches.
1503
+ * Returned readers populate reserve caches as in the utilization pass.
1504
+ * @internal
1505
+ */
1506
+ function createCapReserveResolvers({ reserves, adapterIdsCache, timestamp, capAccrualBuffer, }) {
1507
+ // Onchain, market interest is booked once at transaction start, on pre-plan
1508
+ // positions at pre-plan rates, and stays on touched positions' cap ids.
1509
+ // This reserve state is shared across every planner pass and leg of the plan.
1510
+ // biome-ignore lint/complexity/useMaxParams: a pair is identified by its vault, adapter, and market.
1511
+ const getPair = (vault, adapter, market) => {
1512
+ const key = `${vault}:${adapter.address}:${market.id}`.toLowerCase();
1513
+ const touched = reserves.touchedPairs.get(vault.toLowerCase())?.get(key);
1514
+ if (touched != null) {
1515
+ return touched;
1516
+ }
1517
+ const shares = adapter.supplyShares[market.id] ?? 0n;
1518
+ return {
1519
+ key,
1520
+ ids: getAdapterIds(adapterIdsCache, adapter, market),
1521
+ reserve: (reserveState) => {
1522
+ let reserve = reserveState.reserveByPairKey.get(key);
1523
+ if (reserve == null) {
1524
+ let accruals = reserveState.marketAccruals.get(market.id);
1525
+ if (accruals == null) {
1526
+ const initialMarket = reserveState.initialMarkets[market.id];
1527
+ if (initialMarket == null) {
1528
+ throw new index_js_1.UnknownReallocationMarketError(market.id);
1529
+ }
1530
+ accruals = [
1531
+ initialMarket.accrueInterest(timestamp),
1532
+ initialMarket.accrueInterest(timestamp + capAccrualBuffer),
1533
+ ];
1534
+ reserveState.marketAccruals.set(market.id, accruals);
1535
+ }
1536
+ const [atTimestamp, projected] = accruals;
1537
+ reserve = blue_sdk_1.MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
1538
+ reserveState.reserveByPairKey.set(key, reserve);
1539
+ }
1540
+ return reserve;
1541
+ },
1542
+ };
1543
+ };
1544
+ // biome-ignore lint/complexity/useMaxParams: the reserve is scoped to one vault, cap id, and candidate set.
1545
+ const capReserve = (vault, id, candidatePairs) => {
1546
+ let reserve = 0n;
1547
+ const seen = new Set();
1548
+ for (const pair of [
1549
+ ...(reserves.touchedPairs.get(vault.toLowerCase())?.values() ?? []),
1550
+ ...candidatePairs,
1551
+ ]) {
1552
+ if (seen.has(pair.key) || !pair.ids.includes(id)) {
1553
+ continue;
1554
+ }
1555
+ seen.add(pair.key);
1556
+ reserve += pair.reserve(reserves);
1557
+ }
1558
+ return reserve;
1559
+ };
1560
+ return { getPair, capReserve };
1561
+ }
1562
+ /**
1563
+ * Plans one vault candidate, caching its initial idle assets and active adapters in place.
1564
+ * @internal
1565
+ */
1566
+ function planCachedVaultCandidate(params) {
1567
+ const { vaultAddress, data, initialIdleAssets, activeAdaptersCache } = params;
1568
+ const idleState = resolveVaultCandidateIdleState(params);
1569
+ if (idleState == null) {
1570
+ return;
1571
+ }
1572
+ const { availableIdleAssets } = idleState;
1573
+ const vaultAddressKey = vaultAddress.toLowerCase();
1574
+ if (!initialIdleAssets.has(vaultAddressKey)) {
1575
+ initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
1576
+ }
1577
+ let activeAdapters = activeAdaptersCache.get(vaultAddress);
1578
+ if (activeAdapters == null) {
1579
+ activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
1580
+ activeAdaptersCache.set(vaultAddress, activeAdapters);
1581
+ }
1582
+ return planVaultCandidate({
1583
+ ...params,
1584
+ ...idleState,
1585
+ activeAdapters,
1586
+ });
1587
+ }
1511
1588
  /** Resolves an eligible vault's idle balance before initializing candidate caches. @internal */
1512
1589
  function resolveVaultCandidateIdleState(params) {
1513
1590
  const { vaultAddress, data, marketId, penalty, options, simulationContext, getOptionalPublicAllocatorConfig, } = params;
1514
1591
  const targetMarket = data.getMarket(marketId);
1515
1592
  const publicAllocatorConfig = getOptionalPublicAllocatorConfig(vaultAddress);
1516
- if (publicAllocatorConfig == null)
1593
+ if (publicAllocatorConfig == null) {
1517
1594
  return;
1595
+ }
1518
1596
  const vault = data.getVault(vaultAddress);
1519
1597
  if (!(0, viem_1.isAddressEqual)(publicAllocatorConfig.vault, vaultAddress) ||
1520
1598
  publicAllocatorConfig.penalty >
1521
- (options.maxPenalty ?? constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY))
1599
+ (options.maxPenalty ?? constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY)) {
1522
1600
  return;
1523
- if (penalty != null && publicAllocatorConfig.penalty !== penalty)
1601
+ }
1602
+ if (penalty != null && publicAllocatorConfig.penalty !== penalty) {
1524
1603
  return;
1604
+ }
1525
1605
  const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
1526
1606
  const donatedPenaltyAssets = donatedPenaltyAssetsKey == null
1527
1607
  ? 0n
1528
1608
  : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey];
1529
- if (donatedPenaltyAssets == null)
1609
+ if (donatedPenaltyAssets == null) {
1530
1610
  throw new blue_sdk_1.UnknownDataError(`Missing donated penalty assets for "${vaultAddress}".`);
1611
+ }
1531
1612
  // Exclude rounded penalty dust from idle candidates so one donation
1532
1613
  // cannot replenish liquidity for another same-plan reallocation.
1533
1614
  const availableIdleAssets = blue_sdk_1.MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssets);
@@ -1541,12 +1622,17 @@ function resolveVaultCandidateIdleState(params) {
1541
1622
  function planVaultCandidate(params) {
1542
1623
  const { vault, targetMarket, publicAllocatorConfig, availableIdleAssets, activeAdapters, } = params;
1543
1624
  const targetSupplyHeadroom = blue_sdk_1.MathLib.zeroFloorSub(blue_sdk_1.MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
1625
+ if (targetSupplyHeadroom === 0n ||
1626
+ targetMarket.toSupplyShares(1n, "Down") >
1627
+ blue_sdk_1.MathLib.zeroFloorSub(blue_sdk_1.MathLib.MAX_UINT_128, targetMarket.totalSupplyShares)) {
1628
+ return;
1629
+ }
1544
1630
  const minimumSupply = targetMarket.supply(1n, 0n);
1545
1631
  const rawCandidates = [];
1546
1632
  // Missing nested allocator state means the snapshot is incomplete, so
1547
1633
  // typed getter errors below must propagate. Only explicit zero caps or
1548
1634
  // disabled permissions make an adapter ineligible.
1549
- for (const adapter of vault.accrualAdapters)
1635
+ for (const adapter of vault.accrualAdapters) {
1550
1636
  rawCandidates.push(...planTargetAdapterCandidates({
1551
1637
  ...params,
1552
1638
  vault,
@@ -1558,6 +1644,7 @@ function planVaultCandidate(params) {
1558
1644
  minimumSupply,
1559
1645
  adapter,
1560
1646
  }));
1647
+ }
1561
1648
  const capCompatibleCandidates = [];
1562
1649
  for (const candidate of rawCandidates) {
1563
1650
  const compatible = fitCandidateCaps({
@@ -1565,8 +1652,9 @@ function planVaultCandidate(params) {
1565
1652
  ...candidate,
1566
1653
  targetMarket,
1567
1654
  });
1568
- if (compatible != null)
1655
+ if (compatible != null) {
1569
1656
  capCompatibleCandidates.push(compatible);
1657
+ }
1570
1658
  }
1571
1659
  return capCompatibleCandidates.sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"))[0];
1572
1660
  }
@@ -1576,22 +1664,26 @@ function planVaultCandidate(params) {
1576
1664
  * @internal
1577
1665
  */
1578
1666
  function planTargetAdapterCandidates(params) {
1579
- const { vaultAddress, data, marketId, adapterIdsCache, getPair, capReserve, reserves, allocatorCapHeadroom, vault, targetMarket, activeAdapters, targetSupplyHeadroom, minimumSupply, adapter, } = params;
1667
+ const { vaultAddress, data, marketId, adapterIdsCache, getPair, capReserve, reserves, allocatorCapHeadroom, vault, targetMarket, activeAdapters, minimumSupply, adapter, } = params;
1580
1668
  const rawCandidates = [];
1581
- if (!(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2))
1669
+ if (!(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)) {
1582
1670
  return [];
1583
- if (!(0, viem_1.isAddressEqual)(adapter.parentVault, vaultAddress))
1671
+ }
1672
+ if (!(0, viem_1.isAddressEqual)(adapter.parentVault, vaultAddress)) {
1584
1673
  return [];
1674
+ }
1585
1675
  if (!(0, viem_1.isAddressEqual)(targetMarket.params.loanToken, vault.asset) ||
1586
- !(0, viem_1.isAddressEqual)(targetMarket.params.irm, adapter.adaptiveCurveIrm))
1676
+ !(0, viem_1.isAddressEqual)(targetMarket.params.irm, adapter.adaptiveCurveIrm)) {
1587
1677
  return [];
1678
+ }
1588
1679
  const targetPair = getPair(vaultAddress, adapter, targetMarket);
1589
1680
  const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
1590
1681
  const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
1591
1682
  if (!(0, viem_1.isAddressEqual)(marketPublicAllocatorConfig.vault, vaultAddress) ||
1592
1683
  !(0, viem_1.isAddressEqual)(marketPublicAllocatorConfig.adapter, adapter.address) ||
1593
- !activeAdapters.has(adapter.address.toLowerCase()))
1684
+ !activeAdapters.has(adapter.address.toLowerCase())) {
1594
1685
  return [];
1686
+ }
1595
1687
  const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
1596
1688
  const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
1597
1689
  const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
@@ -1600,8 +1692,9 @@ function planTargetAdapterCandidates(params) {
1600
1692
  collateralCapAllocation,
1601
1693
  adapterMarketCapAllocation,
1602
1694
  ];
1603
- if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
1695
+ if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n)) {
1604
1696
  return [];
1697
+ }
1605
1698
  const adapterShares = adapter.supplyShares[marketId] ?? 0n;
1606
1699
  const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
1607
1700
  const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
@@ -1620,12 +1713,11 @@ function planTargetAdapterCandidates(params) {
1620
1713
  })
1621
1714
  .map(({ id }) => id);
1622
1715
  // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
1623
- if (targetSupplyHeadroom === 0n ||
1624
- allocatorHeadroom === 0n ||
1716
+ if (allocatorHeadroom === 0n ||
1625
1717
  minimumSupply.shares < minimumSupply.assets ||
1626
- minimumSupply.market.totalSupplyShares > blue_sdk_1.MathLib.MAX_UINT_128 ||
1627
- blockedTargetIds.includes(adapterMarketCapId))
1718
+ blockedTargetIds.includes(adapterMarketCapId)) {
1628
1719
  return [];
1720
+ }
1629
1721
  const sourceParams = {
1630
1722
  ...params,
1631
1723
  adapter,
@@ -1634,8 +1726,9 @@ function planTargetAdapterCandidates(params) {
1634
1726
  blockedTargetIds,
1635
1727
  };
1636
1728
  const idleCandidate = planIdleCandidate(sourceParams);
1637
- if (idleCandidate != null)
1729
+ if (idleCandidate != null) {
1638
1730
  rawCandidates.push(idleCandidate);
1731
+ }
1639
1732
  rawCandidates.push(...planSourceAdapterCandidates(sourceParams));
1640
1733
  return rawCandidates;
1641
1734
  }
@@ -1670,20 +1763,24 @@ function planSourceAdapterCandidates(params) {
1670
1763
  const { vault, vaultAddress, activeAdapters } = params;
1671
1764
  const candidates = [];
1672
1765
  for (const sourceAdapter of vault.accrualAdapters) {
1673
- if (!(sourceAdapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2))
1766
+ if (!(sourceAdapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)) {
1674
1767
  continue;
1675
- if (!(0, viem_1.isAddressEqual)(sourceAdapter.parentVault, vaultAddress))
1768
+ }
1769
+ if (!(0, viem_1.isAddressEqual)(sourceAdapter.parentVault, vaultAddress)) {
1676
1770
  continue;
1677
- if (!activeAdapters.has(sourceAdapter.address.toLowerCase()))
1771
+ }
1772
+ if (!activeAdapters.has(sourceAdapter.address.toLowerCase())) {
1678
1773
  continue;
1774
+ }
1679
1775
  for (const sourceMarketReference of sourceAdapter.markets) {
1680
1776
  const candidate = planSourceMarketCandidate({
1681
1777
  ...params,
1682
1778
  sourceAdapter,
1683
1779
  sourceMarketReference,
1684
1780
  });
1685
- if (candidate != null)
1781
+ if (candidate != null) {
1686
1782
  candidates.push(candidate);
1783
+ }
1687
1784
  }
1688
1785
  }
1689
1786
  return candidates;
@@ -1698,33 +1795,40 @@ function planSourceMarketCandidate(params) {
1698
1795
  const { data, vault, vaultAddress, sourceAdapter, sourceMarketReference, normalizedMarketId, adapterIdsCache, blockedTargetIds, getPair, timestamp, setMarkets, targetSupplyHeadroom, allocatorHeadroom, maxWithdrawalUtilization, adapter, publicAllocatorConfig, targetPair, } = params;
1699
1796
  const sourceMarket = data.getMarket(sourceMarketReference.id);
1700
1797
  if (!(0, viem_1.isAddressEqual)(sourceMarket.params.loanToken, vault.asset) ||
1701
- !(0, viem_1.isAddressEqual)(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm))
1798
+ !(0, viem_1.isAddressEqual)(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm)) {
1702
1799
  return;
1703
- if (sourceMarket.id.toLowerCase() === normalizedMarketId)
1800
+ }
1801
+ if (sourceMarket.id.toLowerCase() === normalizedMarketId) {
1704
1802
  return;
1803
+ }
1705
1804
  const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1706
1805
  const [, , sourceAdapterMarketCapId] = sourceIds;
1707
1806
  const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
1708
1807
  if (!(0, viem_1.isAddressEqual)(sourceConfig.vault, vaultAddress) ||
1709
1808
  !(0, viem_1.isAddressEqual)(sourceConfig.adapter, sourceAdapter.address) ||
1710
- !sourceConfig.canPullFromMarket)
1809
+ !sourceConfig.canPullFromMarket) {
1711
1810
  return;
1811
+ }
1712
1812
  const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
1713
- if (sourceAllocations.some(({ allocation }) => allocation === 0n))
1813
+ if (sourceAllocations.some(({ allocation }) => allocation === 0n)) {
1714
1814
  return;
1815
+ }
1715
1816
  const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1716
- if (sourceSupplyShares === 0n)
1817
+ if (sourceSupplyShares === 0n) {
1717
1818
  return;
1819
+ }
1718
1820
  // A withdrawal can create target headroom only for shared cap IDs.
1719
- if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
1821
+ if (blockedTargetIds.some((id) => !sourceIds.includes(id))) {
1720
1822
  return;
1823
+ }
1721
1824
  const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
1722
1825
  const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
1723
1826
  setMarkets([accruedSourceMarket]);
1724
1827
  const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
1725
1828
  const assets = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
1726
- if (assets <= 0n)
1829
+ if (assets <= 0n) {
1727
1830
  return;
1831
+ }
1728
1832
  return {
1729
1833
  reallocation: {
1730
1834
  vault: vaultAddress,
@@ -1752,8 +1856,9 @@ function fitCandidateCaps(params) {
1752
1856
  const targetIds = targetPair.ids;
1753
1857
  const sourceIds = new Set(sourcePair?.ids ?? []);
1754
1858
  const reserveById = new Map();
1755
- for (const id of targetIds)
1859
+ for (const id of targetIds) {
1756
1860
  reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
1861
+ }
1757
1862
  const probeParams = { ...params, targetIds, sourceIds, reserveById };
1758
1863
  // Non-shared target IDs impose monotonic upper bounds. Shared IDs
1759
1864
  // can impose lower bounds and non-monotonic rounding constraints,
@@ -1776,21 +1881,23 @@ function fitCandidateCaps(params) {
1776
1881
  });
1777
1882
  }
1778
1883
  }
1779
- if (selectedAssets > 0n && probe?.withinAllCaps === true)
1884
+ if (selectedAssets > 0n && probe?.withinAllCaps === true) {
1780
1885
  return {
1781
1886
  reallocation: { ...reallocation, assets: selectedAssets },
1782
1887
  targetPair,
1783
1888
  sourcePair,
1784
1889
  allocatorHeadroom,
1785
1890
  };
1891
+ }
1786
1892
  }
1787
1893
  /** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
1788
1894
  function probeCandidateReallocation(params) {
1789
1895
  const { assets, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
1790
1896
  if (targetMarket.totalSupplyShares +
1791
1897
  targetMarket.toSupplyShares(assets, "Down") >
1792
- blue_sdk_1.MathLib.MAX_UINT_128)
1898
+ blue_sdk_1.MathLib.MAX_UINT_128) {
1793
1899
  return;
1900
+ }
1794
1901
  const postTransition = (0, morpho_ts_1._try)(() => applyPublicReallocation({
1795
1902
  context: simulationContext,
1796
1903
  reallocation: { ...reallocation, assets },
@@ -1799,8 +1906,9 @@ function probeCandidateReallocation(params) {
1799
1906
  adapterIdsCache,
1800
1907
  probe: true,
1801
1908
  }), index_js_1.ReallocationAllocationUnderflowError, index_js_1.ReallocationAdapterSupplySharesUnderflowError);
1802
- if (postTransition == null)
1909
+ if (postTransition == null) {
1803
1910
  return;
1911
+ }
1804
1912
  // Vault V2 checks relative caps against the transient firstTotalAssets,
1805
1913
  // which stays fixed after the vault's first allocation in a transaction.
1806
1914
  const { firstTotalAssets } = postTransition;
@@ -1815,8 +1923,9 @@ function probeCandidateReallocation(params) {
1815
1923
  allocation.allocation + (reserveById.get(id) ?? 0n) <= capacity;
1816
1924
  if (!withinCap) {
1817
1925
  withinAllCaps = false;
1818
- if (!sourceIds.has(id))
1926
+ if (!sourceIds.has(id)) {
1819
1927
  withinUpperBounds = false;
1928
+ }
1820
1929
  }
1821
1930
  }
1822
1931
  return { withinAllCaps, withinUpperBounds };
@@ -1830,25 +1939,30 @@ function findCandidateUpperBound(probeParams) {
1830
1939
  const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
1831
1940
  probeUpper = false;
1832
1941
  if (probeCandidateReallocation({ ...probeParams, assets })
1833
- ?.withinUpperBounds === true)
1942
+ ?.withinUpperBounds === true) {
1834
1943
  lower = assets;
1835
- else
1944
+ }
1945
+ else {
1836
1946
  upper = assets - 1n;
1947
+ }
1837
1948
  }
1838
1949
  return lower;
1839
1950
  }
1840
1951
  /** Tracks shared-Blue transfer funding in the reallocation's execution order. @internal */
1841
1952
  function getReallocationTransferShortfall(reallocations, blueBalance) {
1842
1953
  const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
1843
- if (penaltyAssets === 0n)
1954
+ if (penaltyAssets === 0n) {
1844
1955
  return 0n;
1956
+ }
1845
1957
  let shortfall = blue_sdk_1.MathLib.zeroFloorSub(penaltyAssets, blueBalance);
1846
1958
  let balance = blue_sdk_1.MathLib.zeroFloorSub(blueBalance, penaltyAssets);
1847
1959
  for (const { from, assets } of reallocations) {
1848
- if (from.type === "idle")
1960
+ if (from.type === "idle") {
1849
1961
  balance += assets;
1850
- else
1962
+ }
1963
+ else {
1851
1964
  shortfall = blue_sdk_1.MathLib.max(shortfall, blue_sdk_1.MathLib.zeroFloorSub(assets, balance));
1965
+ }
1852
1966
  }
1853
1967
  return shortfall;
1854
1968
  }
@@ -1874,8 +1988,9 @@ function planVaultOperation(params) {
1874
1988
  idleBoundVaults,
1875
1989
  };
1876
1990
  for (const penalty of penaltyTiers) {
1877
- if (type === "refinance" && penalty === blue_sdk_1.MathLib.WAD)
1991
+ if (type === "refinance" && penalty === blue_sdk_1.MathLib.WAD) {
1878
1992
  continue;
1993
+ }
1879
1994
  state = planOperationPenaltyTier({ ...params, penalty, state });
1880
1995
  }
1881
1996
  return summarizeOperationPlan({ ...params, state });
@@ -1894,8 +2009,9 @@ function planOperationPenaltyTier(params) {
1894
2009
  for (const utilization of [maxWithdrawalUtilization, blue_sdk_1.MathLib.WAD]) {
1895
2010
  const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
1896
2011
  isFriendlyPass = false;
1897
- if (state.remainingShortfall === 0n && !isFreeFriendlyPass)
2012
+ if (state.remainingShortfall === 0n && !isFreeFriendlyPass) {
1898
2013
  continue;
2014
+ }
1899
2015
  const result = planOperationUtilizationPass({
1900
2016
  ...params,
1901
2017
  state,
@@ -1917,23 +2033,25 @@ function planOperationPenaltyTier(params) {
1917
2033
  */
1918
2034
  function planOperationUtilizationPass(params) {
1919
2035
  const { penalty } = params;
1920
- let { reserves, data, context, remainingShortfall, accountingShortfall, allocatorCapBoundTargets, idleBoundVaults, } = params.state;
1921
- let reallocations = [...params.state.reallocations];
2036
+ let state = {
2037
+ ...params.state,
2038
+ reallocations: [...params.state.reallocations],
2039
+ };
1922
2040
  let triedFullCapacityAttempt = params.triedFullCapacityAttempt;
1923
2041
  let passMaxAssets = getOperationPassBudget(params);
1924
2042
  const retryPaidPass = penalty > 0n;
1925
2043
  let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
1926
2044
  let tryFullCapacityAttempt = false;
1927
2045
  let isFullCapacityRetryPath = false;
1928
- const beforePassRemainingShortfall = remainingShortfall;
1929
- const beforePassAccountingShortfall = accountingShortfall;
2046
+ const beforePassRemainingShortfall = state.remainingShortfall;
2047
+ const beforePassAccountingShortfall = state.accountingShortfall;
1930
2048
  // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
1931
2049
  const passStart = retryPaidPass
1932
2050
  ? {
1933
- data: data.clone(),
1934
- context,
1935
- reserves: cloneCapReserveState(reserves),
1936
- reallocationCount: reallocations.length,
2051
+ data: state.data.clone(),
2052
+ context: state.context,
2053
+ reserves: cloneCapReserveState(state.reserves),
2054
+ reallocationCount: state.reallocations.length,
1937
2055
  }
1938
2056
  : undefined;
1939
2057
  let previousPassReallocatedAssets = 0n;
@@ -1944,54 +2062,26 @@ function planOperationUtilizationPass(params) {
1944
2062
  const isFullCapacityAttempt = tryFullCapacityAttempt;
1945
2063
  tryFullCapacityAttempt = false;
1946
2064
  if (passStart != null) {
1947
- data = passStart.data.clone();
1948
- context = passStart.context;
1949
- reserves = cloneCapReserveState(passStart.reserves);
1950
- reallocations.length = passStart.reallocationCount;
2065
+ state = restoreOperationPassStart({ state, passStart });
1951
2066
  }
1952
2067
  const attempt = executeOperationAttempt({
1953
2068
  ...params,
1954
- state: {
1955
- reserves,
1956
- reallocations,
1957
- data,
1958
- context,
1959
- remainingShortfall,
1960
- accountingShortfall,
1961
- allocatorCapBoundTargets,
1962
- idleBoundVaults,
1963
- },
2069
+ state,
1964
2070
  isFullCapacityAttempt,
1965
2071
  passMaxAssets,
1966
2072
  isFullCapacityRetryPath,
1967
2073
  });
1968
- ({
1969
- reserves,
1970
- reallocations,
1971
- data,
1972
- context,
1973
- remainingShortfall,
1974
- accountingShortfall,
1975
- allocatorCapBoundTargets,
1976
- idleBoundVaults,
1977
- } = attempt.state);
2074
+ state = attempt.state;
1978
2075
  const { pass, physicalShortfall, attemptTransferShortfall, attemptCoversShortfall, passReallocatedAssets, } = attempt;
1979
- if (passStart == null)
2076
+ if (passStart == null) {
1980
2077
  break;
1981
- if (isFullCapacityAttempt)
2078
+ }
2079
+ if (isFullCapacityAttempt) {
1982
2080
  passMaxAssets = passReallocatedAssets;
2081
+ }
1983
2082
  bestAttempt = chooseOperationBestAttempt({
1984
2083
  ...params,
1985
- state: {
1986
- reserves,
1987
- reallocations,
1988
- data,
1989
- context,
1990
- remainingShortfall,
1991
- accountingShortfall,
1992
- allocatorCapBoundTargets,
1993
- idleBoundVaults,
1994
- },
2084
+ state,
1995
2085
  bestAttempt,
1996
2086
  beforePassAccountingShortfall,
1997
2087
  isFullCapacityRetryPath,
@@ -2011,14 +2101,15 @@ function planOperationUtilizationPass(params) {
2011
2101
  previousPassReallocatedAssets,
2012
2102
  isFullCapacityAttempt,
2013
2103
  attemptCoversShortfall,
2014
- accountingShortfall,
2104
+ accountingShortfall: state.accountingShortfall,
2015
2105
  physicalShortfall,
2016
2106
  passReallocatedAssets,
2017
- remainingShortfall,
2107
+ remainingShortfall: state.remainingShortfall,
2018
2108
  penalty,
2019
2109
  });
2020
- if (next.type === "break")
2110
+ if (next.type === "break") {
2021
2111
  break;
2112
+ }
2022
2113
  ({
2023
2114
  lo,
2024
2115
  hi,
@@ -2032,16 +2123,7 @@ function planOperationUtilizationPass(params) {
2032
2123
  }
2033
2124
  const finalState = finishOperationPass({
2034
2125
  ...params,
2035
- state: {
2036
- reserves,
2037
- reallocations,
2038
- data,
2039
- context,
2040
- remainingShortfall,
2041
- accountingShortfall,
2042
- allocatorCapBoundTargets,
2043
- idleBoundVaults,
2044
- },
2126
+ state,
2045
2127
  passStart,
2046
2128
  bestAttempt,
2047
2129
  beforePassRemainingShortfall,
@@ -2052,6 +2134,18 @@ function planOperationUtilizationPass(params) {
2052
2134
  triedFullCapacityAttempt,
2053
2135
  };
2054
2136
  }
2137
+ /**
2138
+ * Restores working data and reserves and truncates the shared reallocation array in place.
2139
+ * Other attempt results remain available to the retry search.
2140
+ * @internal
2141
+ */
2142
+ function restoreOperationPassStart({ state, passStart, }) {
2143
+ const data = passStart.data.clone();
2144
+ const context = passStart.context;
2145
+ const reserves = cloneCapReserveState(passStart.reserves);
2146
+ state.reallocations.length = passStart.reallocationCount;
2147
+ return { ...state, data, context, reserves };
2148
+ }
2055
2149
  /** Summarizes liquidity-bound legs and the accounting and physical funding result. @internal */
2056
2150
  function summarizeOperationPlan(params) {
2057
2151
  const { maxAssets, headroom, type, amount, feeAssets, blueBalance, absoluteShortfall, hasExplicitBlueBalance, } = params;
@@ -2062,8 +2156,9 @@ function summarizeOperationPlan(params) {
2062
2156
  reallocatedAssets += assets;
2063
2157
  const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
2064
2158
  if (!allocatorCapBoundTargets.has(key) &&
2065
- !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
2159
+ !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase()))) {
2066
2160
  unboundAssets += assets;
2161
+ }
2067
2162
  }
2068
2163
  const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
2069
2164
  const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
@@ -2218,7 +2313,7 @@ function chooseOperationBestAttempt(params) {
2218
2313
  }
2219
2314
  if (isBetterAttempt &&
2220
2315
  (!isFullCapacityRetryPath ||
2221
- (attemptCoversShortfall && attemptTransferShortfall === 0n)))
2316
+ (attemptCoversShortfall && attemptTransferShortfall === 0n))) {
2222
2317
  return {
2223
2318
  data,
2224
2319
  context,
@@ -2229,6 +2324,7 @@ function chooseOperationBestAttempt(params) {
2229
2324
  passReallocatedAssets,
2230
2325
  priority: attemptPriority,
2231
2326
  };
2327
+ }
2232
2328
  return bestAttempt;
2233
2329
  }
2234
2330
  /** Advances bisection or grossed-up retries, stopping on stalled physical funding. @internal */
@@ -2242,8 +2338,9 @@ function advanceOperationPassSearch(params) {
2242
2338
  attemptCoversShortfall,
2243
2339
  }));
2244
2340
  if (hi != null) {
2245
- if (hi - lo <= 1n)
2341
+ if (hi - lo <= 1n) {
2246
2342
  return { type: "break" };
2343
+ }
2247
2344
  passMaxAssets = (lo + hi) / 2n;
2248
2345
  return {
2249
2346
  type: "continue",
@@ -2257,8 +2354,9 @@ function advanceOperationPassSearch(params) {
2257
2354
  previousPassReallocatedAssets,
2258
2355
  };
2259
2356
  }
2260
- if (isFullCapacityAttempt && !attemptCoversShortfall)
2357
+ if (isFullCapacityAttempt && !attemptCoversShortfall) {
2261
2358
  return { type: "break" };
2359
+ }
2262
2360
  if (accountingShortfall === 0n &&
2263
2361
  previousPhysicalShortfall != null &&
2264
2362
  physicalShortfall >= previousPhysicalShortfall) {
@@ -2282,8 +2380,9 @@ function advanceOperationPassSearch(params) {
2282
2380
  }
2283
2381
  previousPhysicalShortfall = physicalShortfall;
2284
2382
  if (passReallocatedAssets <= previousPassReallocatedAssets ||
2285
- penalty === blue_sdk_1.MathLib.WAD)
2383
+ penalty === blue_sdk_1.MathLib.WAD) {
2286
2384
  return { type: "break" };
2385
+ }
2287
2386
  previousPassReallocatedAssets = passReallocatedAssets;
2288
2387
  passMaxAssets += blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty);
2289
2388
  return {
@@ -2348,22 +2447,27 @@ function finishOperationPass(params) {
2348
2447
  function updateOperationSearchBracket(params) {
2349
2448
  let { lo, hi } = params;
2350
2449
  const { passMaxAssets, attemptCoversShortfall } = params;
2351
- if (attemptCoversShortfall)
2450
+ if (attemptCoversShortfall) {
2352
2451
  hi = hi == null ? passMaxAssets : blue_sdk_1.MathLib.min(hi, passMaxAssets);
2353
- else
2452
+ }
2453
+ else {
2354
2454
  lo = blue_sdk_1.MathLib.max(lo, passMaxAssets);
2455
+ }
2355
2456
  return { lo, hi };
2356
2457
  }
2357
2458
  /** Validates the operation amount and fee before reading its snapshot. @internal */
2358
2459
  function resolveOperationFeeAssets(operation) {
2359
2460
  const { amount } = operation;
2360
- if (amount <= 0n)
2461
+ if (amount <= 0n) {
2361
2462
  throw new index_js_1.NonPositiveInputError("amount", amount);
2463
+ }
2362
2464
  const referralFeePct = operation.type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
2363
- if (referralFeePct < 0n)
2465
+ if (referralFeePct < 0n) {
2364
2466
  throw new index_js_1.NegativeInputError("referralFeePct", referralFeePct);
2365
- if (referralFeePct >= blue_sdk_1.MathLib.WAD)
2467
+ }
2468
+ if (referralFeePct >= blue_sdk_1.MathLib.WAD) {
2366
2469
  throw new index_js_1.ReferralFeePctExceededError(referralFeePct);
2470
+ }
2367
2471
  const feeAssets = operation.type === "refinance"
2368
2472
  ? (0, common_js_1.getBlueBundlesV1ReferralFeeAssets)(amount, referralFeePct)
2369
2473
  : 0n;
@@ -2379,10 +2483,12 @@ function getOperationMarketTotals({ market, marketId, type, amount, feeAssets, }
2379
2483
  });
2380
2484
  }
2381
2485
  let newTotalBorrowAssets = market.totalBorrowAssets;
2382
- if (type === "borrow")
2486
+ if (type === "borrow") {
2383
2487
  newTotalBorrowAssets += amount;
2384
- if (type === "refinance")
2488
+ }
2489
+ if (type === "refinance") {
2385
2490
  newTotalBorrowAssets += amount + feeAssets;
2491
+ }
2386
2492
  const newTotalSupplyAssets = type === "withdraw"
2387
2493
  ? market.totalSupplyAssets - amount
2388
2494
  : market.totalSupplyAssets;
@@ -2402,18 +2508,21 @@ function selectOperationPlan(params) {
2402
2508
  ? absoluteShortfall
2403
2509
  : target.unboundAssets, { headroom: allocatorCapHeadroom });
2404
2510
  // Shared-cap fitting is not monotonic in the budget.
2405
- if (!selected.coversShortfall && target.coversShortfall)
2511
+ if (!selected.coversShortfall && target.coversShortfall) {
2406
2512
  selected = target;
2513
+ }
2407
2514
  }
2408
2515
  let available = blue_sdk_1.MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
2409
2516
  // Without headroom, `target` already is the full-cap plan toward the target.
2410
2517
  const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
2411
2518
  for (const maxAssets of fullCapBudgets) {
2412
- if (selected.coversShortfall)
2519
+ if (selected.coversShortfall) {
2413
2520
  break;
2521
+ }
2414
2522
  selected = plan(maxAssets, { headroom: 0n });
2415
- if (selected.reallocatedAssets > available)
2523
+ if (selected.reallocatedAssets > available) {
2416
2524
  available = selected.reallocatedAssets;
2525
+ }
2417
2526
  }
2418
2527
  // Reject unfunded plans before comparing optional physical-balance alternatives.
2419
2528
  assertSelectedOperationFunding({ ...params, selected, available });
@@ -2423,8 +2532,9 @@ function selectOperationPlan(params) {
2423
2532
  /** Preserves penalty-specific error precedence when selected liquidity cannot fund the operation. @internal */
2424
2533
  function assertSelectedOperationFunding(params) {
2425
2534
  const { selected, available, hasExplicitBlueBalance, blueBalance, type, amount, absoluteShortfall, marketId, } = params;
2426
- if (selected.coversShortfall)
2535
+ if (selected.coversShortfall) {
2427
2536
  return;
2537
+ }
2428
2538
  const selectedTransferShortfall = hasExplicitBlueBalance
2429
2539
  ? getReallocationTransferShortfall(selected.reallocations, blueBalance)
2430
2540
  : 0n;
@@ -2433,12 +2543,13 @@ function assertSelectedOperationFunding(params) {
2433
2543
  selectedPenaltyAssets > amount &&
2434
2544
  selected.reallocatedAssets >= absoluteShortfall &&
2435
2545
  (!hasExplicitBlueBalance ||
2436
- (selected.physicalShortfall === 0n && selectedTransferShortfall === 0n)))
2546
+ (selected.physicalShortfall === 0n && selectedTransferShortfall === 0n))) {
2437
2547
  throw new index_js_1.InputExceedsMaxError({
2438
2548
  field: "reallocationPenaltyAssets",
2439
2549
  value: selectedPenaltyAssets,
2440
2550
  max: amount,
2441
2551
  });
2552
+ }
2442
2553
  throw new index_js_1.InsufficientSharedLiquidityError({
2443
2554
  marketId,
2444
2555
  shortfall: blue_sdk_1.MathLib.max(absoluteShortfall +
@@ -2470,8 +2581,9 @@ function choosePhysicalBalancePlan(params) {
2470
2581
  });
2471
2582
  if (alternative.coversShortfall &&
2472
2583
  (0, common_js_1.getBlueBundlesV1PenaltyAssets)(alternative.reallocations) <
2473
- (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations))
2584
+ (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations)) {
2474
2585
  selected = alternative;
2586
+ }
2475
2587
  }
2476
2588
  return selected;
2477
2589
  }