@morpho-org/morpho-sdk 9.8.0 → 10.0.0-next.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 (181) hide show
  1. package/MIGRATION-v9-to-v10.md +114 -0
  2. package/README.md +5 -1
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +5 -1
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -1
  7. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -1
  8. package/lib/cjs/actions/midnight/cancelAndMake.js +2 -1
  9. package/lib/cjs/actions/midnight/cancelOffers.d.ts +54 -0
  10. package/lib/cjs/actions/midnight/cancelOffers.js +107 -0
  11. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  12. package/lib/cjs/actions/midnight/index.js +1 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  14. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +1 -1
  15. package/lib/cjs/actions/midnight/takeBorrow.d.ts +1 -1
  16. package/lib/cjs/actions/midnight/takeBorrow.js +1 -1
  17. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -1
  18. package/lib/cjs/actions/midnight/takeLend.js +1 -1
  19. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  20. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -1
  21. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +1 -1
  22. package/lib/cjs/actions/midnight/takeWithdraw.js +1 -1
  23. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  25. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  26. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +3 -3
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +3 -2
  31. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  32. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  33. package/lib/cjs/blue/abis.d.ts +1 -1
  34. package/lib/cjs/blue/abis.js +5 -1
  35. package/lib/cjs/blue/entities.d.ts +4 -4
  36. package/lib/cjs/blue/entities.js +3 -1
  37. package/lib/cjs/blue/errors.d.ts +2 -2
  38. package/lib/cjs/blue/errors.js +5 -1
  39. package/lib/cjs/blue/fetch.d.ts +2 -2
  40. package/lib/cjs/blue/fetch.js +3 -1
  41. package/lib/cjs/blue/utils.d.ts +1 -1
  42. package/lib/cjs/blue/utils.js +2 -1
  43. package/lib/cjs/entities/blue/blue.d.ts +34 -28
  44. package/lib/cjs/entities/blue/blue.js +99 -73
  45. package/lib/cjs/entities/index.d.ts +4 -4
  46. package/lib/cjs/entities/index.js +3 -1
  47. package/lib/cjs/entities/midnight/deadline.d.ts +2 -2
  48. package/lib/cjs/entities/midnight/deadline.js +2 -2
  49. package/lib/cjs/entities/midnight/midnight.d.ts +49 -51
  50. package/lib/cjs/entities/midnight/midnight.js +144 -131
  51. package/lib/cjs/entities/midnight/publication.d.ts +2 -0
  52. package/lib/cjs/entities/midnight/publication.js +126 -100
  53. package/lib/cjs/entities/midnight/types.d.ts +4 -4
  54. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  55. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +17 -17
  56. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +3 -4
  57. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +1 -1
  58. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +12 -12
  59. package/lib/cjs/entities/vaultV1/vaultV1.js +83 -57
  60. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +50 -24
  61. package/lib/cjs/entities/vaultV2/vaultV2.js +166 -90
  62. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +17 -2
  63. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1410 -806
  64. package/lib/cjs/errors.d.ts +4 -4
  65. package/lib/cjs/errors.js +7 -5
  66. package/lib/cjs/fetch.d.ts +2 -2
  67. package/lib/cjs/fetch.js +3 -1
  68. package/lib/cjs/helpers/deadShares.js +55 -34
  69. package/lib/cjs/helpers/metadata.d.ts +14 -2
  70. package/lib/cjs/helpers/metadata.js +39 -4
  71. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +34 -22
  72. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +7 -1
  73. package/lib/cjs/helpers/validate.js +76 -61
  74. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +154 -103
  75. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +31 -20
  76. package/lib/cjs/midnight/errors.d.ts +2 -1
  77. package/lib/cjs/midnight/errors.js +5 -4
  78. package/lib/cjs/transactionPlan/plan.js +6 -3
  79. package/lib/cjs/transactionPlan/serde.js +7 -7
  80. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +6 -4
  81. package/lib/cjs/transactionPlan/vaultv2/deposit.js +5 -3
  82. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  83. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +5 -3
  84. package/lib/cjs/types/action.d.ts +26 -2
  85. package/lib/cjs/types/action.js +1 -1
  86. package/lib/cjs/types/error.js +11 -5
  87. package/lib/cjs/types/metadata.d.ts +12 -2
  88. package/lib/cjs/utils.d.ts +2 -2
  89. package/lib/cjs/utils.js +4 -2
  90. package/lib/cjs/version.d.ts +1 -1
  91. package/lib/cjs/version.js +1 -1
  92. package/lib/esm/abis.d.ts +1 -1
  93. package/lib/esm/abis.js +1 -1
  94. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +3 -4
  95. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +1 -1
  96. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -1
  97. package/lib/esm/actions/midnight/cancelAndMake.js +2 -1
  98. package/lib/esm/actions/midnight/cancelOffers.d.ts +54 -0
  99. package/lib/esm/actions/midnight/cancelOffers.js +103 -0
  100. package/lib/esm/actions/midnight/index.d.ts +1 -0
  101. package/lib/esm/actions/midnight/index.js +1 -0
  102. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +1 -1
  103. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +1 -1
  104. package/lib/esm/actions/midnight/takeBorrow.d.ts +1 -1
  105. package/lib/esm/actions/midnight/takeBorrow.js +1 -1
  106. package/lib/esm/actions/midnight/takeLend.d.ts +1 -1
  107. package/lib/esm/actions/midnight/takeLend.js +1 -1
  108. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -1
  109. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -1
  110. package/lib/esm/actions/midnight/takeWithdraw.d.ts +1 -1
  111. package/lib/esm/actions/midnight/takeWithdraw.js +1 -1
  112. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -4
  113. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +1 -1
  114. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +4 -6
  115. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +3 -3
  116. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -6
  117. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +3 -3
  118. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +5 -6
  119. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +3 -2
  120. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +3 -5
  121. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +26 -23
  122. package/lib/esm/blue/abis.d.ts +1 -1
  123. package/lib/esm/blue/abis.js +1 -1
  124. package/lib/esm/blue/entities.d.ts +4 -4
  125. package/lib/esm/blue/entities.js +2 -2
  126. package/lib/esm/blue/errors.d.ts +2 -2
  127. package/lib/esm/blue/errors.js +2 -2
  128. package/lib/esm/blue/fetch.d.ts +2 -2
  129. package/lib/esm/blue/fetch.js +2 -2
  130. package/lib/esm/blue/utils.d.ts +1 -1
  131. package/lib/esm/blue/utils.js +1 -1
  132. package/lib/esm/entities/blue/blue.d.ts +34 -28
  133. package/lib/esm/entities/blue/blue.js +99 -73
  134. package/lib/esm/entities/index.d.ts +4 -4
  135. package/lib/esm/entities/index.js +2 -2
  136. package/lib/esm/entities/midnight/deadline.d.ts +2 -2
  137. package/lib/esm/entities/midnight/deadline.js +2 -2
  138. package/lib/esm/entities/midnight/midnight.d.ts +49 -51
  139. package/lib/esm/entities/midnight/midnight.js +145 -132
  140. package/lib/esm/entities/midnight/publication.d.ts +2 -0
  141. package/lib/esm/entities/midnight/publication.js +126 -100
  142. package/lib/esm/entities/midnight/types.d.ts +4 -4
  143. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +3 -5
  144. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +17 -17
  145. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +3 -4
  146. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +1 -1
  147. package/lib/esm/entities/vaultV1/vaultV1.d.ts +12 -12
  148. package/lib/esm/entities/vaultV1/vaultV1.js +83 -57
  149. package/lib/esm/entities/vaultV2/vaultV2.d.ts +50 -24
  150. package/lib/esm/entities/vaultV2/vaultV2.js +166 -90
  151. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +17 -2
  152. package/lib/esm/entities/vaultV2BlueReallocationData.js +1410 -806
  153. package/lib/esm/errors.d.ts +4 -4
  154. package/lib/esm/errors.js +4 -4
  155. package/lib/esm/fetch.d.ts +2 -2
  156. package/lib/esm/fetch.js +2 -2
  157. package/lib/esm/helpers/deadShares.js +56 -35
  158. package/lib/esm/helpers/metadata.d.ts +14 -2
  159. package/lib/esm/helpers/metadata.js +38 -4
  160. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +34 -22
  161. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +7 -1
  162. package/lib/esm/helpers/validate.js +76 -61
  163. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +153 -102
  164. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +31 -20
  165. package/lib/esm/midnight/errors.d.ts +2 -1
  166. package/lib/esm/midnight/errors.js +2 -1
  167. package/lib/esm/transactionPlan/plan.js +6 -3
  168. package/lib/esm/transactionPlan/serde.js +7 -7
  169. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +6 -4
  170. package/lib/esm/transactionPlan/vaultv2/deposit.js +5 -3
  171. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +6 -4
  172. package/lib/esm/transactionPlan/vaultv2/withdraw.js +5 -3
  173. package/lib/esm/types/action.d.ts +26 -2
  174. package/lib/esm/types/action.js +1 -1
  175. package/lib/esm/types/error.js +11 -5
  176. package/lib/esm/types/metadata.d.ts +12 -2
  177. package/lib/esm/utils.d.ts +2 -2
  178. package/lib/esm/utils.js +2 -2
  179. package/lib/esm/version.d.ts +1 -1
  180. package/lib/esm/version.js +1 -1
  181. package/package.json +8 -7
@@ -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";
@@ -87,6 +87,8 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
87
87
  position: clonePosition(position, markets),
88
88
  })));
89
89
  const cloneAdapter = (adapter, markets) => {
90
+ if (adapter.type === "VaultV2MidnightAdapter")
91
+ return adapter;
90
92
  const base = {
91
93
  address: adapter.address,
92
94
  parentVault: adapter.parentVault,
@@ -117,13 +119,14 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
117
119
  adapterKeysToClone.has(adapter.address.toLowerCase())
118
120
  ? cloneAdapter(adapter, markets)
119
121
  : adapter);
120
- const liquidityAdapter = vault.accrualLiquidityAdapter == null
122
+ const accrualLiquidityAdapter = vault.accrualLiquidityAdapter;
123
+ const liquidityAdapter = accrualLiquidityAdapter == null
121
124
  ? undefined
122
- : (adapters.find((adapter) => isAddressEqual(adapter.address, vault.accrualLiquidityAdapter.address)) ??
125
+ : (adapters.find((adapter) => isAddressEqual(adapter.address, accrualLiquidityAdapter.address)) ??
123
126
  (adapterKeysToClone == null ||
124
- adapterKeysToClone.has(vault.accrualLiquidityAdapter.address.toLowerCase())
125
- ? cloneAdapter(vault.accrualLiquidityAdapter, markets)
126
- : vault.accrualLiquidityAdapter));
127
+ adapterKeysToClone.has(accrualLiquidityAdapter.address.toLowerCase())
128
+ ? cloneAdapter(accrualLiquidityAdapter, markets)
129
+ : accrualLiquidityAdapter));
127
130
  return new AccrualVaultV2({
128
131
  ...vault,
129
132
  liquidityAllocations: vault.liquidityAllocations?.map((allocation) => ({
@@ -134,7 +137,8 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
134
137
  /**
135
138
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
136
139
  *
137
- * Constructor inputs are cloned. Every simulated reallocation returns a new
140
+ * Constructor inputs are cloned, except read-only Midnight adapter snapshots, which are
141
+ * shared by reference. Every simulated reallocation returns a new
138
142
  * instance. Planning keeps the transaction-scoped `firstTotalAssets`
139
143
  * denominator outside the durable snapshot while applying reallocations in
140
144
  * contract order. Penalty donations update simulated vault accounting but are
@@ -224,31 +228,11 @@ export class VaultV2BlueReallocationData {
224
228
  this.marketPublicAllocatorConfigs = input.marketPublicAllocatorConfigs;
225
229
  }
226
230
  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
- }
231
+ const configurations = cloneAllocatorConfigurations(input);
232
+ this.publicAllocatorConfigs = configurations.publicAllocatorConfigs;
233
+ this.activeAdapters = configurations.activeAdapters;
234
+ this.marketPublicAllocatorConfigs =
235
+ configurations.marketPublicAllocatorConfigs;
252
236
  }
253
237
  for (const [marketId, market] of Object.entries(input.markets ?? {})) {
254
238
  this.mutableMarkets[marketId] =
@@ -264,14 +248,20 @@ export class VaultV2BlueReallocationData {
264
248
  : cloneVault(vault, { markets: this.mutableMarkets });
265
249
  this.mutableVaults[address] = clonedVault;
266
250
  }
251
+ // Populate the instance's allocation snapshots after cloning vault views.
252
+ this.copyAllocationSnapshots(input, isClone);
253
+ }
254
+ /** Copies allocation entries, retaining the clone path's shallow-copy semantics. @internal */
255
+ copyAllocationSnapshots(input, isClone) {
267
256
  for (const [vault, allocations] of Object.entries(input.allocations ?? {})) {
268
257
  if (isClone) {
269
258
  this.mutableAllocations[vault] = { ...allocations };
270
259
  continue;
271
260
  }
272
- this.mutableAllocations[vault] = {};
261
+ const clonedAllocations = {};
262
+ this.mutableAllocations[vault] = clonedAllocations;
273
263
  for (const [id, allocation] of Object.entries(allocations ?? {})) {
274
- this.mutableAllocations[vault][id] =
264
+ clonedAllocations[id] =
275
265
  allocation == null ? undefined : { ...allocation };
276
266
  }
277
267
  }
@@ -279,7 +269,7 @@ export class VaultV2BlueReallocationData {
279
269
  /**
280
270
  * Clones the complete simulation snapshot.
281
271
  *
282
- * @returns A deep clone of this simulation state.
272
+ * @returns A deep clone of this simulation state; read-only Midnight adapter snapshots are shared by reference.
283
273
  * @example
284
274
  * ```ts
285
275
  * import { markets } from "@morpho-org/morpho-test";
@@ -727,16 +717,63 @@ export class VaultV2BlueReallocationData {
727
717
  return { reallocations, data };
728
718
  }
729
719
  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)
720
+ const feeAssets = resolveOperationFeeAssets(operation);
721
+ const { normalizedOptions, market, hasExplicitBlueBalance, blueBalance } = this.resolveOperationSnapshot({ marketId, options, resolvedOptions });
722
+ const { newTotalBorrowAssets, newTotalSupplyAssets } = getOperationMarketTotals({ market, marketId, type, amount, feeAssets });
723
+ const requiredAssets = MathLib.wDivUp(newTotalBorrowAssets, DEFAULT_SUPPLY_TARGET_UTILIZATION) -
724
+ newTotalSupplyAssets;
725
+ if (MarketUtils.getUtilization({
726
+ totalSupplyAssets: newTotalSupplyAssets,
727
+ totalBorrowAssets: newTotalBorrowAssets,
728
+ }) <= DEFAULT_SUPPLY_TARGET_UTILIZATION ||
729
+ requiredAssets <= 0n) {
730
+ const data = this.clone();
731
+ data.setMarkets([market]);
732
+ return { reallocations: [], data };
733
+ }
734
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
735
+ ? newTotalBorrowAssets - newTotalSupplyAssets
739
736
  : 0n;
737
+ const penaltyTiers = [
738
+ 0n,
739
+ ...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
740
+ ? [config.penalty]
741
+ : [])),
742
+ ].sort(bigIntComparator((tier) => tier));
743
+ const plan = (maxAssets, { headroom, usePhysicalBalance = false, }) => planVaultOperation({
744
+ maxAssets,
745
+ headroom,
746
+ usePhysicalBalance,
747
+ absoluteShortfall,
748
+ penaltyTiers,
749
+ type,
750
+ maxWithdrawalUtilization,
751
+ amount,
752
+ feeAssets,
753
+ blueBalance,
754
+ capAccrualBuffer,
755
+ normalizedOptions,
756
+ hasExplicitBlueBalance,
757
+ marketId,
758
+ initialData: this,
759
+ initialMarkets: this.mutableMarkets,
760
+ runUtilizationPass: (data, args) => data.computeVaultV2BlueReallocationsAtUtilizationInPlace(args),
761
+ });
762
+ return selectOperationPlan({
763
+ plan,
764
+ requiredAssets,
765
+ allocatorCapHeadroom,
766
+ absoluteShortfall,
767
+ hasExplicitBlueBalance,
768
+ marketId,
769
+ type,
770
+ amount,
771
+ blueBalance,
772
+ feeAssets,
773
+ });
774
+ }
775
+ /** Resolves the operation's accrued market and shared-Blue liquidity snapshot. @internal */
776
+ resolveOperationSnapshot({ marketId, options, resolvedOptions, }) {
740
777
  const timestamp = options.timestamp == null
741
778
  ? this.getLatestSnapshotTimestamp()
742
779
  : BigInt(options.timestamp);
@@ -759,367 +796,7 @@ export class VaultV2BlueReallocationData {
759
796
  ? total +
760
797
  MathLib.zeroFloorSub(snapshotMarket.totalSupplyAssets, snapshotMarket.totalBorrowAssets)
761
798
  : 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 };
799
+ return { normalizedOptions, market, hasExplicitBlueBalance, blueBalance };
1123
800
  }
1124
801
  computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
1125
802
  if (options.enabled === false)
@@ -1204,23 +881,30 @@ export class VaultV2BlueReallocationData {
1204
881
  while (remainingAssets == null || remainingAssets > 0n) {
1205
882
  const candidates = vaults
1206
883
  .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)
884
+ const params = {
885
+ vaultAddress,
886
+ data,
887
+ marketId,
888
+ penalty,
889
+ options,
890
+ simulationContext,
891
+ normalizedMarketId,
892
+ adapterIdsCache,
893
+ getPair,
894
+ capReserve,
895
+ reserves,
896
+ allocatorCapHeadroom,
897
+ timestamp,
898
+ maxWithdrawalUtilization,
899
+ remainingAssets,
900
+ getOptionalPublicAllocatorConfig: data.getOptionalPublicAllocatorConfig.bind(data),
901
+ setMarkets: data.setMarkets.bind(data),
902
+ applyPublicReallocation: data.applyPublicReallocation.bind(data),
903
+ };
904
+ const idleState = resolveVaultCandidateIdleState(params);
905
+ if (idleState == null)
1217
906
  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]);
907
+ const { availableIdleAssets } = idleState;
1224
908
  const vaultAddressKey = vaultAddress.toLowerCase();
1225
909
  if (!initialIdleAssets.has(vaultAddressKey))
1226
910
  initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
@@ -1229,215 +913,11 @@ export class VaultV2BlueReallocationData {
1229
913
  activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
1230
914
  activeAdaptersCache.set(vaultAddress, activeAdapters);
1231
915
  }
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];
916
+ return planVaultCandidate({
917
+ ...params,
918
+ ...idleState,
919
+ activeAdapters,
920
+ });
1441
921
  })
1442
922
  .filter((candidate) => candidate != null)
1443
923
  .sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"));
@@ -1450,31 +930,19 @@ export class VaultV2BlueReallocationData {
1450
930
  allocatorCapBoundTargets,
1451
931
  idleBoundVaults,
1452
932
  };
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
- }
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);
933
+ const updates = getAcceptedCandidateUpdates({
934
+ candidate: largest,
935
+ idleTakenAssets,
936
+ initialIdleAssets,
937
+ allocatorCapHeadroom,
938
+ reserves,
939
+ });
940
+ updates.allocatorCapBoundTargets.forEach((key) => allocatorCapBoundTargets.add(key));
941
+ updates.idleTakenAssets.forEach(([key, assets]) => idleTakenAssets.set(key, assets));
942
+ updates.idleBoundVaults.forEach((key) => idleBoundVaults.add(key));
943
+ updates.touchedVaultEntries.forEach(([key, pairs]) => reserves.touchedPairs.set(key, pairs));
944
+ updates.touchedPairEntries.forEach(([key, pair]) => updates.touchedVaultPairs.set(key, pair));
945
+ const { reallocation: acceptedReallocation } = largest;
1478
946
  reallocations.push(acceptedReallocation);
1479
947
  const transition = data.applyPublicReallocation({
1480
948
  context: simulationContext,
@@ -1651,53 +1119,14 @@ export class VaultV2BlueReallocationData {
1651
1119
  const sourceVault = sourceVaultKey == null ? undefined : this.mutableVaults[sourceVaultKey];
1652
1120
  let data = this;
1653
1121
  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,
1122
+ data = this.cloneReallocationProbe({
1123
+ reallocation,
1124
+ targetMarketId,
1125
+ adapterIdsCache,
1126
+ sourceVaultKey,
1127
+ sourceVault,
1128
+ sourceAllocationsKey,
1684
1129
  });
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
1130
  }
1702
1131
  const vaultKey = findAddressKey(data.mutableVaults, reallocation.vault) ??
1703
1132
  reallocation.vault;
@@ -1725,80 +1154,50 @@ export class VaultV2BlueReallocationData {
1725
1154
  };
1726
1155
  }
1727
1156
  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;
1766
- }
1767
- 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;
1157
+ // Book the source withdrawal and cap deltas before supplying the target.
1158
+ data.withdrawReallocationSource({
1159
+ reallocation,
1160
+ source: reallocation.from,
1161
+ timestamp,
1162
+ adapterIdsCache,
1163
+ allocationsKey,
1164
+ vault,
1165
+ });
1772
1166
  }
1167
+ // Idle allocations also credit the instance's explicit Blue liquidity balance.
1168
+ if (reallocation.from.type === "idle")
1169
+ data.creditIdleReallocationBalance(reallocation, targetMarket);
1773
1170
  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
- };
1171
+ const firstAllocation = data.accrueReallocationFirstAllocation({
1172
+ vault,
1173
+ vaultKey,
1174
+ timestamp,
1175
+ context: nextContext,
1176
+ firstTotalAssetsKey,
1177
+ });
1178
+ vault = firstAllocation.vault;
1179
+ firstTotalAssets = firstAllocation.firstTotalAssets;
1180
+ nextContext = firstAllocation.context;
1796
1181
  }
1797
- const targetAdapter = data.getMutableAdapter(reallocation.vault, reallocation.to.adapter);
1182
+ // Book the target shares and cap deltas in the working state.
1183
+ data.supplyReallocationTarget({
1184
+ reallocation,
1185
+ adapterIdsCache,
1186
+ targetMarket,
1187
+ timestamp,
1188
+ probe,
1189
+ allocationsKey,
1190
+ });
1191
+ vault.assetBalance -= reallocation.assets;
1192
+ return { data, context: nextContext, firstTotalAssets };
1193
+ }
1194
+ /** Supplies the target position and books its rounded allocation changes. @internal */
1195
+ supplyReallocationTarget({ reallocation, adapterIdsCache, targetMarket, timestamp, probe, allocationsKey, }) {
1196
+ const targetAdapter = this.getMutableAdapter(reallocation.vault, reallocation.to.adapter);
1798
1197
  const targetIds = getAdapterIds(adapterIdsCache, targetAdapter, targetMarket);
1799
1198
  const [, , targetAdapterMarketCapId] = targetIds;
1800
- const currentTargetMarket = data.getMarket(targetMarket.id);
1801
- const oldTargetAllocation = data.getAllocation(reallocation.vault, targetAdapterMarketCapId).allocation;
1199
+ const currentTargetMarket = this.getMarket(targetMarket.id);
1200
+ const oldTargetAllocation = this.getAllocation(reallocation.vault, targetAdapterMarketCapId).allocation;
1802
1201
  const supply = currentTargetMarket.supply(reallocation.assets, 0n, timestamp);
1803
1202
  const targetSupplyShares = (targetAdapter.supplyShares[targetMarket.id] ?? 0n) + supply.shares;
1804
1203
  targetAdapter.supplyShares[targetMarket.id] = targetSupplyShares;
@@ -1806,20 +1205,141 @@ export class VaultV2BlueReallocationData {
1806
1205
  targetAdapter.marketIds.push(targetMarket.id);
1807
1206
  if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id))
1808
1207
  targetAdapter.markets.push(supply.market);
1809
- data.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1208
+ this.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1810
1209
  const simulatedChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1811
1210
  // The adapter's rounded expected-assets delta can differ by one wei at inclusion,
1812
1211
  // so cap tracking assumes each accepted leg adds at least its requested assets.
1813
1212
  const targetChange = MathLib.max(simulatedChange, reallocation.assets);
1814
1213
  for (const id of targetIds) {
1815
- const allocation = data.getAllocation(reallocation.vault, id);
1816
- data.mutableAllocations[allocationsKey][id] = {
1214
+ const allocation = this.getAllocation(reallocation.vault, id);
1215
+ const allocations = this.mutableAllocations[allocationsKey];
1216
+ if (allocations == null)
1217
+ throw new UnknownReallocationAllocationError(reallocation.vault, id);
1218
+ allocations[id] = {
1817
1219
  ...allocation,
1818
1220
  allocation: allocation.allocation + targetChange,
1819
1221
  };
1820
1222
  }
1821
- vault.assetBalance -= reallocation.assets;
1822
- return { data, context: nextContext, firstTotalAssets };
1223
+ }
1224
+ /** Credits shared Blue liquidity when an idle allocation enters the target market. @internal */
1225
+ creditIdleReallocationBalance(reallocation, targetMarket) {
1226
+ const blueBalanceKey = findAddressKey(this.mutableBlueBalances, targetMarket.params.loanToken);
1227
+ if (blueBalanceKey == null)
1228
+ return;
1229
+ const blueBalance = this.mutableBlueBalances[blueBalanceKey];
1230
+ if (blueBalance != null)
1231
+ this.mutableBlueBalances[blueBalanceKey] =
1232
+ blueBalance + reallocation.assets;
1233
+ }
1234
+ /** Builds the isolated markets, adapter views and caps used by a transition probe. @internal */
1235
+ cloneReallocationProbe({ reallocation, targetMarketId, adapterIdsCache, sourceVaultKey, sourceVault, sourceAllocationsKey, }) {
1236
+ const probeMarkets = {
1237
+ [targetMarketId]: this.getMarket(targetMarketId),
1238
+ };
1239
+ const adapterKeysToClone = new Set([
1240
+ reallocation.to.adapter.toLowerCase(),
1241
+ ]);
1242
+ const allocationIdsToClone = new Set(getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.to.adapter), this.getMarket(targetMarketId)));
1243
+ if (reallocation.from.type === "market") {
1244
+ const sourceMarket = this.getMarket(reallocation.from.marketParams.id);
1245
+ probeMarkets[sourceMarket.id] = sourceMarket;
1246
+ adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
1247
+ for (const key of getDependentProbeAdapterKeys(sourceVault, sourceMarket.id))
1248
+ adapterKeysToClone.add(key);
1249
+ for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket))
1250
+ allocationIdsToClone.add(id);
1251
+ }
1252
+ const data = new VaultV2BlueReallocationData({
1253
+ chainId: this.chainId,
1254
+ timestamp: this.timestamp,
1255
+ markets: probeMarkets,
1256
+ });
1257
+ if (sourceVaultKey != null) {
1258
+ data.mutableVaults[sourceVaultKey] =
1259
+ sourceVault == null
1260
+ ? undefined
1261
+ : cloneVault(sourceVault, {
1262
+ markets: data.mutableMarkets,
1263
+ adapterKeysToClone,
1264
+ });
1265
+ }
1266
+ if (sourceAllocationsKey != null) {
1267
+ const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
1268
+ const allocations = {};
1269
+ for (const id of allocationIdsToClone)
1270
+ allocations[id] = sourceAllocations?.[id];
1271
+ data.mutableAllocations[sourceAllocationsKey] = allocations;
1272
+ }
1273
+ return data;
1274
+ }
1275
+ /** Withdraws the source market position and books its cap changes before target supply. @internal */
1276
+ withdrawReallocationSource({ reallocation, source, timestamp, adapterIdsCache, allocationsKey, vault, }) {
1277
+ const sourceAdapter = this.getMutableAdapter(reallocation.vault, source.adapter);
1278
+ const sourceMarket = this.getMarket(source.marketParams.id);
1279
+ const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1280
+ const [, , sourceAdapterMarketCapId] = sourceIds;
1281
+ const currentSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1282
+ const withdrawal = sourceMarket.withdraw(reallocation.assets, 0n, timestamp);
1283
+ if (withdrawal.shares > currentSupplyShares) {
1284
+ throw new ReallocationAdapterSupplySharesUnderflowError({
1285
+ vault: reallocation.vault,
1286
+ adapter: sourceAdapter.address,
1287
+ marketId: sourceMarket.id,
1288
+ supplyShares: currentSupplyShares,
1289
+ withdrawnShares: withdrawal.shares,
1290
+ });
1291
+ }
1292
+ sourceAdapter.supplyShares[sourceMarket.id] =
1293
+ currentSupplyShares - withdrawal.shares;
1294
+ this.setMarkets([withdrawal.market]);
1295
+ const sourceChange = withdrawal.market.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n) -
1296
+ this.getAllocation(reallocation.vault, sourceAdapterMarketCapId)
1297
+ .allocation;
1298
+ for (const id of sourceIds) {
1299
+ const allocation = this.getAllocation(reallocation.vault, id);
1300
+ const nextAllocation = allocation.allocation + sourceChange;
1301
+ if (nextAllocation < 0n) {
1302
+ throw new ReallocationAllocationUnderflowError({
1303
+ vault: reallocation.vault,
1304
+ id,
1305
+ allocation: allocation.allocation,
1306
+ change: sourceChange,
1307
+ });
1308
+ }
1309
+ const allocations = this.mutableAllocations[allocationsKey];
1310
+ allocations[id] = {
1311
+ ...allocation,
1312
+ allocation: nextAllocation,
1313
+ };
1314
+ }
1315
+ vault.assetBalance += reallocation.assets;
1316
+ }
1317
+ /** Books the vault's first-allocation denominator once per simulated transaction. @internal */
1318
+ accrueReallocationFirstAllocation({ vault: initialVault, vaultKey, timestamp, context, firstTotalAssetsKey, }) {
1319
+ let vault = initialVault;
1320
+ // Vault V2's transient firstTotalAssets tracks the first allocation in a
1321
+ // transaction independently from elapsed time. Later allocations must not
1322
+ // recompute the denominator, even if their simulated balances have changed.
1323
+ if (timestamp === vault.lastUpdate) {
1324
+ // AccrualVaultV2 skips zero-elapsed accruals, but the contract's first
1325
+ // touch still reads real adapter assets. With zero elapsed time, its
1326
+ // growth clamp leaves only existing losses to recognize.
1327
+ const realAssets = vault.accrualAdapters.reduce((assets, adapter) => assets + adapter.realAssets(timestamp), vault.assetBalance);
1328
+ vault._totalAssets = MathLib.min(realAssets, vault._totalAssets);
1329
+ }
1330
+ else {
1331
+ vault = vault.accrueInterest(timestamp).vault;
1332
+ }
1333
+ this.mutableVaults[vaultKey] = vault;
1334
+ const firstTotalAssets = vault._totalAssets;
1335
+ const nextContext = {
1336
+ ...context,
1337
+ firstTotalAssets: {
1338
+ ...context.firstTotalAssets,
1339
+ [firstTotalAssetsKey]: firstTotalAssets,
1340
+ },
1341
+ };
1342
+ return { vault, firstTotalAssets, context: nextContext };
1823
1343
  }
1824
1344
  /** Updates canonical markets in bulk and refreshes only dependent adapter views. */
1825
1345
  setMarkets(markets, adaptersToRefresh) {
@@ -1830,40 +1350,1124 @@ export class VaultV2BlueReallocationData {
1830
1350
  }
1831
1351
  if (changedMarketIds.size === 0)
1832
1352
  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);
1845
- }
1353
+ const adapters = collectAdaptersToRefresh(this.mutableVaults, adaptersToRefresh);
1354
+ for (const adapter of adapters) {
1355
+ const update = refreshAdapterMarkets(adapter, {
1356
+ markets: this.mutableMarkets,
1357
+ changedMarketIds,
1358
+ });
1359
+ if (update != null)
1360
+ Object.assign(adapter, update);
1846
1361
  }
1847
- else {
1848
- for (const adapter of adaptersToRefresh)
1362
+ }
1363
+ }
1364
+ /** Collects the adapters whose views may depend on changed canonical markets. @internal */
1365
+ function collectAdaptersToRefresh(vaults, adaptersToRefresh) {
1366
+ const adapters = new Set();
1367
+ if (adaptersToRefresh == null) {
1368
+ // A Morpho market is global state shared by every vault position. Legacy
1369
+ // AccrualPosition constructors copy their Market, so rebuild those adapter
1370
+ // views as well as repointing V2 adapters whenever the canonical state moves.
1371
+ for (const vault of Object.values(vaults)) {
1372
+ if (vault == null)
1373
+ continue;
1374
+ for (const adapter of vault.accrualAdapters)
1849
1375
  adapters.add(adapter);
1376
+ if (vault.accrualLiquidityAdapter != null)
1377
+ adapters.add(vault.accrualLiquidityAdapter);
1850
1378
  }
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));
1856
- }
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));
1861
- }
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);
1866
- }
1379
+ }
1380
+ else {
1381
+ for (const adapter of adaptersToRefresh)
1382
+ adapters.add(adapter);
1383
+ }
1384
+ return adapters;
1385
+ }
1386
+ /** Computes one adapter's dependent market views after a canonical state change. @internal */
1387
+ function refreshAdapterMarkets(adapter, { markets, changedMarketIds, }) {
1388
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2) {
1389
+ if (!adapter.markets.some(({ id }) => changedMarketIds.has(id)))
1390
+ return;
1391
+ return {
1392
+ markets: adapter.markets.map((adapterMarket) => getCanonicalMarket(markets, adapterMarket)),
1393
+ };
1394
+ }
1395
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter) {
1396
+ if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId)))
1397
+ return;
1398
+ return {
1399
+ positions: adapter.positions.map((position) => clonePosition(position, markets)),
1400
+ };
1401
+ }
1402
+ if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
1403
+ if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId)))
1404
+ return;
1405
+ return {
1406
+ accrualVaultV1: cloneAccrualVault(adapter.accrualVaultV1, markets),
1407
+ };
1408
+ }
1409
+ }
1410
+ /** Clones allocator authorization records without sharing caller-owned iterables. @internal */
1411
+ function cloneAllocatorConfigurations(input) {
1412
+ const publicAllocatorConfigs = {};
1413
+ const activeAdapters = {};
1414
+ const marketPublicAllocatorConfigs = {};
1415
+ for (const [vault, config] of Object.entries(input.publicAllocatorConfigs ?? {})) {
1416
+ publicAllocatorConfigs[vault] =
1417
+ config == null ? undefined : new VaultV2BluePublicAllocatorConfig(config);
1418
+ }
1419
+ for (const [vault, adapters] of Object.entries(input.activeAdapters ?? {})) {
1420
+ activeAdapters[vault] = adapters == null ? undefined : new Set(adapters);
1421
+ }
1422
+ for (const [vault, configs] of Object.entries(input.marketPublicAllocatorConfigs ?? {})) {
1423
+ marketPublicAllocatorConfigs[vault] =
1424
+ cloneMarketAllocatorConfigurations(configs);
1425
+ }
1426
+ return {
1427
+ publicAllocatorConfigs,
1428
+ activeAdapters,
1429
+ marketPublicAllocatorConfigs,
1430
+ };
1431
+ }
1432
+ /** Clones one vault's adapter-market allocator configurations. @internal */
1433
+ function cloneMarketAllocatorConfigurations(configs) {
1434
+ const cloned = {};
1435
+ for (const [id, config] of Object.entries(configs ?? {})) {
1436
+ cloned[id] =
1437
+ config == null
1438
+ ? undefined
1439
+ : new VaultV2BlueMarketPublicAllocatorConfig(config);
1440
+ }
1441
+ return cloned;
1442
+ }
1443
+ /** Finds adapter views that a source-market transition must isolate for probing. @internal */
1444
+ function getDependentProbeAdapterKeys(sourceVault, sourceMarketId) {
1445
+ const keys = new Set();
1446
+ if (sourceVault == null)
1447
+ return keys;
1448
+ const adapters = new Set(sourceVault.accrualAdapters);
1449
+ if (sourceVault.accrualLiquidityAdapter != null)
1450
+ adapters.add(sourceVault.accrualLiquidityAdapter);
1451
+ for (const adapter of adapters) {
1452
+ if (adapterReferencesMarket(adapter, sourceMarketId))
1453
+ keys.add(adapter.address.toLowerCase());
1454
+ }
1455
+ return keys;
1456
+ }
1457
+ /** Tests whether an adapter view depends on one canonical Blue market. @internal */
1458
+ function adapterReferencesMarket(adapter, marketId) {
1459
+ return ((adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2 &&
1460
+ adapter.markets.some(({ id }) => id === marketId)) ||
1461
+ (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter &&
1462
+ adapter.positions.some((position) => position.marketId === marketId)) ||
1463
+ (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter &&
1464
+ adapter.accrualVaultV1.allocations.has(marketId)));
1465
+ }
1466
+ /** Computes the accepted leg's liquidity bounds and shared cap reserve entries. @internal */
1467
+ function getAcceptedCandidateUpdates({ candidate: largest, idleTakenAssets, initialIdleAssets, allocatorCapHeadroom, reserves, }) {
1468
+ const allocatorCapBoundTargets = [];
1469
+ const idleBoundVaults = [];
1470
+ const idleTakenEntries = [];
1471
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1472
+ if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1473
+ // BluePublicAllocator caps are per vault and target adapter.
1474
+ allocatorCapBoundTargets.push(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1475
+ if (acceptedReallocation.from.type === "idle") {
1476
+ const vaultKey = acceptedReallocation.vault.toLowerCase();
1477
+ const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
1478
+ idleTakenEntries.push([vaultKey, taken]);
1479
+ // Candidates always record this; a missing entry counts the vault as bound.
1480
+ const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1481
+ if (taken >=
1482
+ MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom)))
1483
+ idleBoundVaults.push(vaultKey);
1484
+ }
1485
+ const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1486
+ const existingPairs = reserves.touchedPairs.get(touchedVaultKey);
1487
+ const touchedVaultPairs = existingPairs ?? new Map();
1488
+ const touchedVaultEntries = existingPairs == null
1489
+ ? [[touchedVaultKey, touchedVaultPairs]]
1490
+ : [];
1491
+ const touchedPairEntries = [];
1492
+ if (!touchedVaultPairs.has(acceptedTargetPair.key))
1493
+ touchedPairEntries.push([acceptedTargetPair.key, acceptedTargetPair]);
1494
+ if (acceptedSourcePair != null &&
1495
+ !touchedVaultPairs.has(acceptedSourcePair.key) &&
1496
+ acceptedSourcePair.key !== acceptedTargetPair.key)
1497
+ touchedPairEntries.push([acceptedSourcePair.key, acceptedSourcePair]);
1498
+ return {
1499
+ allocatorCapBoundTargets,
1500
+ idleTakenAssets: idleTakenEntries,
1501
+ idleBoundVaults,
1502
+ touchedVaultPairs,
1503
+ touchedVaultEntries,
1504
+ touchedPairEntries,
1505
+ };
1506
+ }
1507
+ /** Resolves an eligible vault's idle balance before initializing candidate caches. @internal */
1508
+ function resolveVaultCandidateIdleState(params) {
1509
+ const { vaultAddress, data, marketId, penalty, options, simulationContext, getOptionalPublicAllocatorConfig, } = params;
1510
+ const targetMarket = data.getMarket(marketId);
1511
+ const publicAllocatorConfig = getOptionalPublicAllocatorConfig(vaultAddress);
1512
+ if (publicAllocatorConfig == null)
1513
+ return;
1514
+ const vault = data.getVault(vaultAddress);
1515
+ if (!isAddressEqual(publicAllocatorConfig.vault, vaultAddress) ||
1516
+ publicAllocatorConfig.penalty >
1517
+ (options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY))
1518
+ return;
1519
+ if (penalty != null && publicAllocatorConfig.penalty !== penalty)
1520
+ return;
1521
+ const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
1522
+ const donatedPenaltyAssets = donatedPenaltyAssetsKey == null
1523
+ ? 0n
1524
+ : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey];
1525
+ if (donatedPenaltyAssets == null)
1526
+ throw new UnknownDataError(`Missing donated penalty assets for "${vaultAddress}".`);
1527
+ // Exclude rounded penalty dust from idle candidates so one donation
1528
+ // cannot replenish liquidity for another same-plan reallocation.
1529
+ const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssets);
1530
+ return { vault, targetMarket, publicAllocatorConfig, availableIdleAssets };
1531
+ }
1532
+ /**
1533
+ * Plans the highest-asset cap-compatible candidate for one configured vault.
1534
+ * Candidate planning updates shared working data/reserves in place; do not reuse a prior state.
1535
+ * @internal
1536
+ */
1537
+ function planVaultCandidate(params) {
1538
+ const { vault, targetMarket, publicAllocatorConfig, availableIdleAssets, activeAdapters, } = params;
1539
+ const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
1540
+ const minimumSupply = targetMarket.supply(1n, 0n);
1541
+ const rawCandidates = [];
1542
+ // Missing nested allocator state means the snapshot is incomplete, so
1543
+ // typed getter errors below must propagate. Only explicit zero caps or
1544
+ // disabled permissions make an adapter ineligible.
1545
+ for (const adapter of vault.accrualAdapters)
1546
+ rawCandidates.push(...planTargetAdapterCandidates({
1547
+ ...params,
1548
+ vault,
1549
+ targetMarket,
1550
+ publicAllocatorConfig,
1551
+ availableIdleAssets,
1552
+ activeAdapters,
1553
+ targetSupplyHeadroom,
1554
+ minimumSupply,
1555
+ adapter,
1556
+ }));
1557
+ const capCompatibleCandidates = [];
1558
+ for (const candidate of rawCandidates) {
1559
+ const compatible = fitCandidateCaps({
1560
+ ...params,
1561
+ ...candidate,
1562
+ targetMarket,
1563
+ });
1564
+ if (compatible != null)
1565
+ capCompatibleCandidates.push(compatible);
1566
+ }
1567
+ return capCompatibleCandidates.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"))[0];
1568
+ }
1569
+ /**
1570
+ * Builds idle and market-source candidates for one eligible target adapter.
1571
+ * Updates shared working data/reserves through candidate steps; do not reuse a prior state.
1572
+ * @internal
1573
+ */
1574
+ function planTargetAdapterCandidates(params) {
1575
+ const { vaultAddress, data, marketId, adapterIdsCache, getPair, capReserve, reserves, allocatorCapHeadroom, vault, targetMarket, activeAdapters, targetSupplyHeadroom, minimumSupply, adapter, } = params;
1576
+ const rawCandidates = [];
1577
+ if (!(adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
1578
+ return [];
1579
+ if (!isAddressEqual(adapter.parentVault, vaultAddress))
1580
+ return [];
1581
+ if (!isAddressEqual(targetMarket.params.loanToken, vault.asset) ||
1582
+ !isAddressEqual(targetMarket.params.irm, adapter.adaptiveCurveIrm))
1583
+ return [];
1584
+ const targetPair = getPair(vaultAddress, adapter, targetMarket);
1585
+ const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
1586
+ const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
1587
+ if (!isAddressEqual(marketPublicAllocatorConfig.vault, vaultAddress) ||
1588
+ !isAddressEqual(marketPublicAllocatorConfig.adapter, adapter.address) ||
1589
+ !activeAdapters.has(adapter.address.toLowerCase()))
1590
+ return [];
1591
+ const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
1592
+ const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
1593
+ const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
1594
+ const targetAllocations = [
1595
+ adapterCapAllocation,
1596
+ collateralCapAllocation,
1597
+ adapterMarketCapAllocation,
1598
+ ];
1599
+ if (targetAllocations.some(({ absoluteCap }) => absoluteCap === 0n))
1600
+ return [];
1601
+ const adapterShares = adapter.supplyShares[marketId] ?? 0n;
1602
+ const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
1603
+ const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
1604
+ const allocatorHeadroom = MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
1605
+ untracked +
1606
+ targetPair.reserve(reserves)), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
1607
+ const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
1608
+ const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
1609
+ const blockedTargetIds = targetAllocations
1610
+ .filter(({ allocation, absoluteCap, relativeCap, id }) => {
1611
+ const nextAllocation = allocation +
1612
+ capReserve(vaultAddress, id, [targetPair]) +
1613
+ minimumAllocationChange;
1614
+ return (nextAllocation > absoluteCap ||
1615
+ (relativeCap === 0n && nextAllocation > 0n));
1616
+ })
1617
+ .map(({ id }) => id);
1618
+ // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
1619
+ if (targetSupplyHeadroom === 0n ||
1620
+ allocatorHeadroom === 0n ||
1621
+ minimumSupply.shares < minimumSupply.assets ||
1622
+ minimumSupply.market.totalSupplyShares > MathLib.MAX_UINT_128 ||
1623
+ blockedTargetIds.includes(adapterMarketCapId))
1624
+ return [];
1625
+ const sourceParams = {
1626
+ ...params,
1627
+ adapter,
1628
+ targetPair,
1629
+ allocatorHeadroom,
1630
+ blockedTargetIds,
1631
+ };
1632
+ const idleCandidate = planIdleCandidate(sourceParams);
1633
+ if (idleCandidate != null)
1634
+ rawCandidates.push(idleCandidate);
1635
+ rawCandidates.push(...planSourceAdapterCandidates(sourceParams));
1636
+ return rawCandidates;
1637
+ }
1638
+ /** Builds a vault-idle leg when permissions and target caps allow it. @internal */
1639
+ function planIdleCandidate(params) {
1640
+ const { vaultAddress, adapter, publicAllocatorConfig, availableIdleAssets, blockedTargetIds, targetSupplyHeadroom, allocatorHeadroom, targetPair, } = params;
1641
+ if (publicAllocatorConfig.canPullFromIdle &&
1642
+ availableIdleAssets > 0n &&
1643
+ blockedTargetIds.length === 0) {
1644
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
1645
+ if (assets > 0n) {
1646
+ return {
1647
+ reallocation: {
1648
+ vault: vaultAddress,
1649
+ from: { type: "idle" },
1650
+ to: { adapter: adapter.address },
1651
+ assets,
1652
+ penalty: publicAllocatorConfig.penalty,
1653
+ },
1654
+ targetPair,
1655
+ allocatorHeadroom,
1656
+ };
1657
+ }
1658
+ }
1659
+ }
1660
+ /**
1661
+ * Walks authorized source adapters in snapshot order for one target position.
1662
+ * Source steps update the shared working data in place; do not reuse a prior state.
1663
+ * @internal
1664
+ */
1665
+ function planSourceAdapterCandidates(params) {
1666
+ const { vault, vaultAddress, activeAdapters } = params;
1667
+ const candidates = [];
1668
+ for (const sourceAdapter of vault.accrualAdapters) {
1669
+ if (!(sourceAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
1670
+ continue;
1671
+ if (!isAddressEqual(sourceAdapter.parentVault, vaultAddress))
1672
+ continue;
1673
+ if (!activeAdapters.has(sourceAdapter.address.toLowerCase()))
1674
+ continue;
1675
+ for (const sourceMarketReference of sourceAdapter.markets) {
1676
+ const candidate = planSourceMarketCandidate({
1677
+ ...params,
1678
+ sourceAdapter,
1679
+ sourceMarketReference,
1680
+ });
1681
+ if (candidate != null)
1682
+ candidates.push(candidate);
1683
+ }
1684
+ }
1685
+ return candidates;
1686
+ }
1687
+ /**
1688
+ * Plans a source-market withdrawal, accruing the same working market state.
1689
+ * Updates the working data clone in place via setMarkets; the caller retains that same
1690
+ * object, even when no candidate is returned. Do not reuse a prior state after this step.
1691
+ * @internal
1692
+ */
1693
+ function planSourceMarketCandidate(params) {
1694
+ const { data, vault, vaultAddress, sourceAdapter, sourceMarketReference, normalizedMarketId, adapterIdsCache, blockedTargetIds, getPair, timestamp, setMarkets, targetSupplyHeadroom, allocatorHeadroom, maxWithdrawalUtilization, adapter, publicAllocatorConfig, targetPair, } = params;
1695
+ const sourceMarket = data.getMarket(sourceMarketReference.id);
1696
+ if (!isAddressEqual(sourceMarket.params.loanToken, vault.asset) ||
1697
+ !isAddressEqual(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm))
1698
+ return;
1699
+ if (sourceMarket.id.toLowerCase() === normalizedMarketId)
1700
+ return;
1701
+ const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1702
+ const [, , sourceAdapterMarketCapId] = sourceIds;
1703
+ const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
1704
+ if (!isAddressEqual(sourceConfig.vault, vaultAddress) ||
1705
+ !isAddressEqual(sourceConfig.adapter, sourceAdapter.address) ||
1706
+ !sourceConfig.canPullFromMarket)
1707
+ return;
1708
+ const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
1709
+ if (sourceAllocations.some(({ allocation }) => allocation === 0n))
1710
+ return;
1711
+ const sourceSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1712
+ if (sourceSupplyShares === 0n)
1713
+ return;
1714
+ // A withdrawal can create target headroom only for shared cap IDs.
1715
+ if (blockedTargetIds.some((id) => !sourceIds.includes(id)))
1716
+ return;
1717
+ const sourcePair = getPair(vaultAddress, sourceAdapter, sourceMarket);
1718
+ const accruedSourceMarket = sourceMarket.accrueInterest(timestamp);
1719
+ setMarkets([accruedSourceMarket]);
1720
+ const expectedSourceSupplyAssets = accruedSourceMarket.toSupplyAssets(sourceSupplyShares);
1721
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, accruedSourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
1722
+ if (assets <= 0n)
1723
+ return;
1724
+ return {
1725
+ reallocation: {
1726
+ vault: vaultAddress,
1727
+ from: {
1728
+ type: "market",
1729
+ adapter: sourceAdapter.address,
1730
+ marketParams: sourceMarket.params,
1731
+ },
1732
+ to: { adapter: adapter.address },
1733
+ assets,
1734
+ penalty: publicAllocatorConfig.penalty,
1735
+ },
1736
+ targetPair,
1737
+ sourcePair,
1738
+ allocatorHeadroom,
1739
+ };
1740
+ }
1741
+ /**
1742
+ * Fits a raw candidate to non-shared upper bounds and shared-cap rounding.
1743
+ * Cap reserve reads populate shared working reserve caches; do not reuse a prior state.
1744
+ * @internal
1745
+ */
1746
+ function fitCandidateCaps(params) {
1747
+ const { reallocation, targetPair, sourcePair, allocatorHeadroom, capReserve, remainingAssets, } = params;
1748
+ const targetIds = targetPair.ids;
1749
+ const sourceIds = new Set(sourcePair?.ids ?? []);
1750
+ const reserveById = new Map();
1751
+ for (const id of targetIds)
1752
+ reserveById.set(id, capReserve(reallocation.vault, id, sourcePair == null ? [targetPair] : [targetPair, sourcePair]));
1753
+ const probeParams = { ...params, targetIds, sourceIds, reserveById };
1754
+ // Non-shared target IDs impose monotonic upper bounds. Shared IDs
1755
+ // can impose lower bounds and non-monotonic rounding constraints,
1756
+ // so validate them after selecting the non-shared maximum.
1757
+ const lower = findCandidateUpperBound(probeParams);
1758
+ let selectedAssets = MathLib.min(lower, remainingAssets ?? reallocation.assets);
1759
+ let probe = selectedAssets > 0n
1760
+ ? probeCandidateReallocation({ ...probeParams, assets: selectedAssets })
1761
+ : undefined;
1762
+ if (remainingAssets != null && probe?.withinAllCaps !== true) {
1763
+ // Bound the base-unit scan; expose a caller ceiling if wider searches become necessary.
1764
+ const searchUpper = MathLib.min(lower, selectedAssets + MAX_SHARED_CAP_SEARCH_STEPS);
1765
+ while (selectedAssets > 0n &&
1766
+ selectedAssets < searchUpper &&
1767
+ probe?.withinAllCaps !== true) {
1768
+ selectedAssets += 1n;
1769
+ probe = probeCandidateReallocation({
1770
+ ...probeParams,
1771
+ assets: selectedAssets,
1772
+ });
1773
+ }
1774
+ }
1775
+ if (selectedAssets > 0n && probe?.withinAllCaps === true)
1776
+ return {
1777
+ reallocation: { ...reallocation, assets: selectedAssets },
1778
+ targetPair,
1779
+ sourcePair,
1780
+ allocatorHeadroom,
1781
+ };
1782
+ }
1783
+ /** Simulates one candidate amount and tests its reserved target-cap headroom. @internal */
1784
+ function probeCandidateReallocation(params) {
1785
+ const { assets, targetMarket, applyPublicReallocation, simulationContext, reallocation, marketId, adapterIdsCache, targetIds, sourceIds, reserveById, } = params;
1786
+ if (targetMarket.totalSupplyShares +
1787
+ targetMarket.toSupplyShares(assets, "Down") >
1788
+ MathLib.MAX_UINT_128)
1789
+ return;
1790
+ const postTransition = _try(() => applyPublicReallocation({
1791
+ context: simulationContext,
1792
+ reallocation: { ...reallocation, assets },
1793
+ targetMarketId: marketId,
1794
+ timestamp: targetMarket.lastUpdate,
1795
+ adapterIdsCache,
1796
+ probe: true,
1797
+ }), ReallocationAllocationUnderflowError, ReallocationAdapterSupplySharesUnderflowError);
1798
+ if (postTransition == null)
1799
+ return;
1800
+ // Vault V2 checks relative caps against the transient firstTotalAssets,
1801
+ // which stays fixed after the vault's first allocation in a transaction.
1802
+ const { firstTotalAssets } = postTransition;
1803
+ let withinUpperBounds = true;
1804
+ let withinAllCaps = true;
1805
+ for (const id of targetIds) {
1806
+ const allocation = postTransition.data.getAllocation(reallocation.vault, id);
1807
+ const capacity = VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
1808
+ // The reserve covers interest accrued before inclusion by every
1809
+ // position the plan touched on this cap id, as booked onchain.
1810
+ const withinCap = allocation.absoluteCap > 0n &&
1811
+ allocation.allocation + (reserveById.get(id) ?? 0n) <= capacity;
1812
+ if (!withinCap) {
1813
+ withinAllCaps = false;
1814
+ if (!sourceIds.has(id))
1815
+ withinUpperBounds = false;
1816
+ }
1817
+ }
1818
+ return { withinAllCaps, withinUpperBounds };
1819
+ }
1820
+ /** Bisects the monotonic non-shared target-cap upper bound. @internal */
1821
+ function findCandidateUpperBound(probeParams) {
1822
+ let lower = 0n;
1823
+ let upper = probeParams.reallocation.assets;
1824
+ let probeUpper = true;
1825
+ while (lower < upper) {
1826
+ const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
1827
+ probeUpper = false;
1828
+ if (probeCandidateReallocation({ ...probeParams, assets })
1829
+ ?.withinUpperBounds === true)
1830
+ lower = assets;
1831
+ else
1832
+ upper = assets - 1n;
1833
+ }
1834
+ return lower;
1835
+ }
1836
+ /** Tracks shared-Blue transfer funding in the reallocation's execution order. @internal */
1837
+ function getReallocationTransferShortfall(reallocations, blueBalance) {
1838
+ const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
1839
+ if (penaltyAssets === 0n)
1840
+ return 0n;
1841
+ let shortfall = MathLib.zeroFloorSub(penaltyAssets, blueBalance);
1842
+ let balance = MathLib.zeroFloorSub(blueBalance, penaltyAssets);
1843
+ for (const { from, assets } of reallocations) {
1844
+ if (from.type === "idle")
1845
+ balance += assets;
1846
+ else
1847
+ shortfall = MathLib.max(shortfall, MathLib.zeroFloorSub(assets, balance));
1848
+ }
1849
+ return shortfall;
1850
+ }
1851
+ /** Plans one operation budget across penalty tiers and utilization passes. @internal */
1852
+ function planVaultOperation(params) {
1853
+ const { initialMarkets, initialData, absoluteShortfall, penaltyTiers, type } = params;
1854
+ const reserves = createCapReserveState(initialMarkets);
1855
+ const reallocations = [];
1856
+ const data = initialData.clone();
1857
+ const context = createSimulationContext();
1858
+ const remainingShortfall = absoluteShortfall;
1859
+ const accountingShortfall = absoluteShortfall;
1860
+ const allocatorCapBoundTargets = new Set();
1861
+ const idleBoundVaults = new Set();
1862
+ let state = {
1863
+ reserves,
1864
+ reallocations,
1865
+ data,
1866
+ context,
1867
+ remainingShortfall,
1868
+ accountingShortfall,
1869
+ allocatorCapBoundTargets,
1870
+ idleBoundVaults,
1871
+ };
1872
+ for (const penalty of penaltyTiers) {
1873
+ if (type === "refinance" && penalty === MathLib.WAD)
1874
+ continue;
1875
+ state = planOperationPenaltyTier({ ...params, penalty, state });
1876
+ }
1877
+ return summarizeOperationPlan({ ...params, state });
1878
+ }
1879
+ /**
1880
+ * Runs friendly then full-utilization passes at one allocator penalty.
1881
+ * Passes update working data/reserves in place, which the returned state may share.
1882
+ * Do not reuse a prior state after this step.
1883
+ * @internal
1884
+ */
1885
+ function planOperationPenaltyTier(params) {
1886
+ const { penalty, maxWithdrawalUtilization } = params;
1887
+ let state = params.state;
1888
+ let isFriendlyPass = true;
1889
+ let triedFullCapacityAttempt = false;
1890
+ for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
1891
+ const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
1892
+ isFriendlyPass = false;
1893
+ if (state.remainingShortfall === 0n && !isFreeFriendlyPass)
1894
+ continue;
1895
+ const result = planOperationUtilizationPass({
1896
+ ...params,
1897
+ state,
1898
+ utilization,
1899
+ penalty,
1900
+ isFreeFriendlyPass,
1901
+ triedFullCapacityAttempt,
1902
+ });
1903
+ state = result.state;
1904
+ triedFullCapacityAttempt = result.triedFullCapacityAttempt;
1905
+ }
1906
+ return state;
1907
+ }
1908
+ /**
1909
+ * Executes and, for paid passes, retries one utilization budget.
1910
+ * Updates working data/reserves in place; the returned state may share those objects
1911
+ * rather than an isolated snapshot. Do not reuse a prior state after this step.
1912
+ * @internal
1913
+ */
1914
+ function planOperationUtilizationPass(params) {
1915
+ const { penalty } = params;
1916
+ let { reserves, data, context, remainingShortfall, accountingShortfall, allocatorCapBoundTargets, idleBoundVaults, } = params.state;
1917
+ let reallocations = [...params.state.reallocations];
1918
+ let triedFullCapacityAttempt = params.triedFullCapacityAttempt;
1919
+ let passMaxAssets = getOperationPassBudget(params);
1920
+ const retryPaidPass = penalty > 0n;
1921
+ let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
1922
+ let tryFullCapacityAttempt = false;
1923
+ let isFullCapacityRetryPath = false;
1924
+ const beforePassRemainingShortfall = remainingShortfall;
1925
+ const beforePassAccountingShortfall = accountingShortfall;
1926
+ // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
1927
+ const passStart = retryPaidPass
1928
+ ? {
1929
+ data: data.clone(),
1930
+ context,
1931
+ reserves: cloneCapReserveState(reserves),
1932
+ reallocationCount: reallocations.length,
1933
+ }
1934
+ : undefined;
1935
+ let previousPassReallocatedAssets = 0n;
1936
+ let previousPhysicalShortfall;
1937
+ let hi;
1938
+ let bestAttempt;
1939
+ while (true) {
1940
+ const isFullCapacityAttempt = tryFullCapacityAttempt;
1941
+ tryFullCapacityAttempt = false;
1942
+ if (passStart != null) {
1943
+ data = passStart.data.clone();
1944
+ context = passStart.context;
1945
+ reserves = cloneCapReserveState(passStart.reserves);
1946
+ reallocations.length = passStart.reallocationCount;
1947
+ }
1948
+ const attempt = executeOperationAttempt({
1949
+ ...params,
1950
+ state: {
1951
+ reserves,
1952
+ reallocations,
1953
+ data,
1954
+ context,
1955
+ remainingShortfall,
1956
+ accountingShortfall,
1957
+ allocatorCapBoundTargets,
1958
+ idleBoundVaults,
1959
+ },
1960
+ isFullCapacityAttempt,
1961
+ passMaxAssets,
1962
+ isFullCapacityRetryPath,
1963
+ });
1964
+ ({
1965
+ reserves,
1966
+ reallocations,
1967
+ data,
1968
+ context,
1969
+ remainingShortfall,
1970
+ accountingShortfall,
1971
+ allocatorCapBoundTargets,
1972
+ idleBoundVaults,
1973
+ } = attempt.state);
1974
+ const { pass, physicalShortfall, attemptTransferShortfall, attemptCoversShortfall, passReallocatedAssets, } = attempt;
1975
+ if (passStart == null)
1976
+ break;
1977
+ if (isFullCapacityAttempt)
1978
+ passMaxAssets = passReallocatedAssets;
1979
+ bestAttempt = chooseOperationBestAttempt({
1980
+ ...params,
1981
+ state: {
1982
+ reserves,
1983
+ reallocations,
1984
+ data,
1985
+ context,
1986
+ remainingShortfall,
1987
+ accountingShortfall,
1988
+ allocatorCapBoundTargets,
1989
+ idleBoundVaults,
1990
+ },
1991
+ bestAttempt,
1992
+ beforePassAccountingShortfall,
1993
+ isFullCapacityRetryPath,
1994
+ attemptCoversShortfall,
1995
+ attemptTransferShortfall,
1996
+ passReallocatedAssets,
1997
+ passReallocations: pass.reallocations,
1998
+ });
1999
+ const next = advanceOperationPassSearch({
2000
+ lo,
2001
+ hi,
2002
+ passMaxAssets,
2003
+ triedFullCapacityAttempt,
2004
+ tryFullCapacityAttempt,
2005
+ isFullCapacityRetryPath,
2006
+ previousPhysicalShortfall,
2007
+ previousPassReallocatedAssets,
2008
+ isFullCapacityAttempt,
2009
+ attemptCoversShortfall,
2010
+ accountingShortfall,
2011
+ physicalShortfall,
2012
+ passReallocatedAssets,
2013
+ remainingShortfall,
2014
+ penalty,
2015
+ });
2016
+ if (next.type === "break")
2017
+ break;
2018
+ ({
2019
+ lo,
2020
+ hi,
2021
+ passMaxAssets,
2022
+ triedFullCapacityAttempt,
2023
+ tryFullCapacityAttempt,
2024
+ isFullCapacityRetryPath,
2025
+ previousPhysicalShortfall,
2026
+ previousPassReallocatedAssets,
2027
+ } = next);
2028
+ }
2029
+ const finalState = finishOperationPass({
2030
+ ...params,
2031
+ state: {
2032
+ reserves,
2033
+ reallocations,
2034
+ data,
2035
+ context,
2036
+ remainingShortfall,
2037
+ accountingShortfall,
2038
+ allocatorCapBoundTargets,
2039
+ idleBoundVaults,
2040
+ },
2041
+ passStart,
2042
+ bestAttempt,
2043
+ beforePassRemainingShortfall,
2044
+ beforePassAccountingShortfall,
2045
+ });
2046
+ return {
2047
+ state: finalState,
2048
+ triedFullCapacityAttempt,
2049
+ };
2050
+ }
2051
+ /** Summarizes liquidity-bound legs and the accounting and physical funding result. @internal */
2052
+ function summarizeOperationPlan(params) {
2053
+ const { maxAssets, headroom, type, amount, feeAssets, blueBalance, absoluteShortfall, hasExplicitBlueBalance, } = params;
2054
+ const { reallocations, data, allocatorCapBoundTargets, idleBoundVaults } = params.state;
2055
+ let reallocatedAssets = 0n;
2056
+ let unboundAssets = 0n;
2057
+ for (const { vault, from, to, assets } of reallocations) {
2058
+ reallocatedAssets += assets;
2059
+ const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
2060
+ if (!allocatorCapBoundTargets.has(key) &&
2061
+ !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
2062
+ unboundAssets += assets;
2063
+ }
2064
+ const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
2065
+ const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
2066
+ const physicalShortfall = penaltyAssets === 0n
2067
+ ? 0n
2068
+ : MathLib.zeroFloorSub((type === "refinance" ? amount + feeAssets + penaltyAssets : amount) +
2069
+ penaltyAssets, blueBalance + idleAssets);
2070
+ const transferShortfall = getReallocationTransferShortfall(reallocations, blueBalance);
2071
+ const coversAccountingShortfall = type === "refinance"
2072
+ ? reallocatedAssets >= absoluteShortfall + penaltyAssets
2073
+ : reallocatedAssets >= absoluteShortfall;
2074
+ return {
2075
+ maxAssets,
2076
+ headroom,
2077
+ reallocations,
2078
+ data,
2079
+ liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
2080
+ reallocatedAssets,
2081
+ unboundAssets,
2082
+ physicalShortfall,
2083
+ coversShortfall: coversAccountingShortfall &&
2084
+ (type === "refinance" || penaltyAssets <= amount) &&
2085
+ (!hasExplicitBlueBalance ||
2086
+ (physicalShortfall === 0n && transferShortfall === 0n)),
2087
+ };
2088
+ }
2089
+ /** Sizes a pass for its accounting gap and optional physical penalty funding. @internal */
2090
+ function getOperationPassBudget(params) {
2091
+ const { type, penalty, isFreeFriendlyPass, maxAssets, usePhysicalBalance, amount, feeAssets, blueBalance, } = params;
2092
+ const { remainingShortfall, reallocations } = params.state;
2093
+ let passMaxAssets = remainingShortfall;
2094
+ if (type === "refinance" && penalty > 0n) {
2095
+ passMaxAssets = MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
2096
+ }
2097
+ else if (isFreeFriendlyPass) {
2098
+ passMaxAssets = maxAssets;
2099
+ }
2100
+ if (usePhysicalBalance && penalty > 0n) {
2101
+ const penaltyMultiplier = type === "refinance" ? 2n : 1n;
2102
+ const physicalPenalty = penaltyMultiplier * penalty;
2103
+ if (physicalPenalty < MathLib.WAD) {
2104
+ const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
2105
+ // Idle must fund both the operation and its penalty flash loan.
2106
+ const physicalShortfall = MathLib.zeroFloorSub(amount +
2107
+ feeAssets +
2108
+ penaltyMultiplier * getBlueBundlesV1PenaltyAssets(reallocations), blueBalance + idleAssets);
2109
+ passMaxAssets = MathLib.max(passMaxAssets, MathLib.mulDivUp(physicalShortfall, MathLib.WAD, MathLib.WAD - physicalPenalty));
2110
+ }
2111
+ }
2112
+ return passMaxAssets;
2113
+ }
2114
+ /**
2115
+ * Executes one pass attempt and returns its updated state and funding gaps.
2116
+ * Updates working data/reserves in place via runUtilizationPass; the returned state
2117
+ * shares those objects. Callers must not reuse a prior state after this step.
2118
+ * @internal
2119
+ */
2120
+ function executeOperationAttempt(params) {
2121
+ const { type, amount, feeAssets, blueBalance, capAccrualBuffer, normalizedOptions, hasExplicitBlueBalance, marketId, headroom, utilization, penalty, isFreeFriendlyPass, runUtilizationPass, isFullCapacityAttempt, passMaxAssets, isFullCapacityRetryPath, } = params;
2122
+ let { reserves, data, context, remainingShortfall, accountingShortfall, allocatorCapBoundTargets, idleBoundVaults, } = params.state;
2123
+ const reallocations = [...params.state.reallocations];
2124
+ const pass = runUtilizationPass(data, {
2125
+ context,
2126
+ reserves,
2127
+ marketId,
2128
+ maxWithdrawalUtilization: utilization,
2129
+ maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
2130
+ capAccrualBuffer,
2131
+ allocatorCapHeadroom: headroom,
2132
+ penalty,
2133
+ options: normalizedOptions,
2134
+ });
2135
+ reallocations.push(...pass.reallocations);
2136
+ data = pass.data;
2137
+ context = pass.context;
2138
+ if (isFreeFriendlyPass) {
2139
+ allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
2140
+ idleBoundVaults = pass.idleBoundVaults;
2141
+ }
2142
+ const currentMarket = data.getMarket(marketId);
2143
+ const penaltyAssets = type === "refinance" ? getBlueBundlesV1PenaltyAssets(reallocations) : 0n;
2144
+ let borrow;
2145
+ switch (type) {
2146
+ case "borrow":
2147
+ borrow = currentMarket.totalBorrowAssets + amount;
2148
+ break;
2149
+ case "refinance":
2150
+ borrow =
2151
+ currentMarket.totalBorrowAssets + amount + feeAssets + penaltyAssets;
2152
+ break;
2153
+ default:
2154
+ borrow = currentMarket.totalBorrowAssets;
2155
+ }
2156
+ const supply = type === "withdraw"
2157
+ ? currentMarket.totalSupplyAssets - amount
2158
+ : currentMarket.totalSupplyAssets;
2159
+ accountingShortfall = borrow > supply ? borrow - supply : 0n;
2160
+ const penaltyForPhysicalShortfall = getBlueBundlesV1PenaltyAssets(reallocations);
2161
+ const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
2162
+ const physicalShortfall = penaltyForPhysicalShortfall === 0n
2163
+ ? 0n
2164
+ : MathLib.zeroFloorSub((type === "refinance"
2165
+ ? amount + feeAssets + penaltyForPhysicalShortfall
2166
+ : amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
2167
+ remainingShortfall = MathLib.max(accountingShortfall, physicalShortfall);
2168
+ const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
2169
+ ? getReallocationTransferShortfall(reallocations, blueBalance)
2170
+ : 0n;
2171
+ const attemptCoversShortfall = remainingShortfall === 0n;
2172
+ const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
2173
+ return {
2174
+ state: {
2175
+ reserves,
2176
+ reallocations,
2177
+ data,
2178
+ context,
2179
+ remainingShortfall,
2180
+ accountingShortfall,
2181
+ allocatorCapBoundTargets,
2182
+ idleBoundVaults,
2183
+ },
2184
+ pass,
2185
+ physicalShortfall,
2186
+ attemptTransferShortfall,
2187
+ attemptCoversShortfall,
2188
+ passReallocatedAssets,
2189
+ };
2190
+ }
2191
+ /** Retains the best feasible paid-pass attempt with the original priority ordering. @internal */
2192
+ function chooseOperationBestAttempt(params) {
2193
+ const { hasExplicitBlueBalance, bestAttempt, beforePassAccountingShortfall, isFullCapacityRetryPath, attemptCoversShortfall, attemptTransferShortfall, passReallocatedAssets, passReallocations, } = params;
2194
+ const { data, context, reserves, remainingShortfall, accountingShortfall } = params.state;
2195
+ const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
2196
+ const attemptPriority = hasExplicitBlueBalance
2197
+ ? [0n, remainingShortfall, 0n, passReallocatedAssets]
2198
+ : [
2199
+ improvesAccounting ? 0n : 1n,
2200
+ improvesAccounting ? accountingShortfall : 0n,
2201
+ remainingShortfall,
2202
+ passReallocatedAssets,
2203
+ ];
2204
+ const previousBestAttempt = bestAttempt;
2205
+ let isBetterAttempt = previousBestAttempt == null;
2206
+ if (previousBestAttempt != null) {
2207
+ const firstDifference = attemptPriority.findIndex((candidatePriority, index) => candidatePriority !== previousBestAttempt.priority[index]);
2208
+ const priority = attemptPriority[firstDifference];
2209
+ const previousPriority = previousBestAttempt.priority[firstDifference];
2210
+ isBetterAttempt =
2211
+ priority != null &&
2212
+ previousPriority != null &&
2213
+ priority < previousPriority;
2214
+ }
2215
+ if (isBetterAttempt &&
2216
+ (!isFullCapacityRetryPath ||
2217
+ (attemptCoversShortfall && attemptTransferShortfall === 0n)))
2218
+ return {
2219
+ data,
2220
+ context,
2221
+ reserves: cloneCapReserveState(reserves),
2222
+ reallocations: passReallocations,
2223
+ remainingShortfall,
2224
+ accountingShortfall,
2225
+ passReallocatedAssets,
2226
+ priority: attemptPriority,
2227
+ };
2228
+ return bestAttempt;
2229
+ }
2230
+ /** Advances bisection or grossed-up retries, stopping on stalled physical funding. @internal */
2231
+ function advanceOperationPassSearch(params) {
2232
+ let { lo, hi, passMaxAssets, triedFullCapacityAttempt, tryFullCapacityAttempt, isFullCapacityRetryPath, previousPhysicalShortfall, previousPassReallocatedAssets, } = params;
2233
+ const { isFullCapacityAttempt, attemptCoversShortfall, accountingShortfall, physicalShortfall, passReallocatedAssets, remainingShortfall, penalty, } = params;
2234
+ ({ lo, hi } = updateOperationSearchBracket({
2235
+ lo,
2236
+ hi,
2237
+ passMaxAssets,
2238
+ attemptCoversShortfall,
2239
+ }));
2240
+ if (hi != null) {
2241
+ if (hi - lo <= 1n)
2242
+ return { type: "break" };
2243
+ passMaxAssets = (lo + hi) / 2n;
2244
+ return {
2245
+ type: "continue",
2246
+ lo,
2247
+ hi,
2248
+ passMaxAssets,
2249
+ triedFullCapacityAttempt,
2250
+ tryFullCapacityAttempt,
2251
+ isFullCapacityRetryPath,
2252
+ previousPhysicalShortfall,
2253
+ previousPassReallocatedAssets,
2254
+ };
2255
+ }
2256
+ if (isFullCapacityAttempt && !attemptCoversShortfall)
2257
+ return { type: "break" };
2258
+ if (accountingShortfall === 0n &&
2259
+ previousPhysicalShortfall != null &&
2260
+ physicalShortfall >= previousPhysicalShortfall) {
2261
+ if (!triedFullCapacityAttempt && passReallocatedAssets === passMaxAssets) {
2262
+ triedFullCapacityAttempt = true;
2263
+ tryFullCapacityAttempt = true;
2264
+ isFullCapacityRetryPath = true;
2265
+ return {
2266
+ type: "continue",
2267
+ lo,
2268
+ hi,
2269
+ passMaxAssets,
2270
+ triedFullCapacityAttempt,
2271
+ tryFullCapacityAttempt,
2272
+ isFullCapacityRetryPath,
2273
+ previousPhysicalShortfall,
2274
+ previousPassReallocatedAssets,
2275
+ };
2276
+ }
2277
+ return { type: "break" };
2278
+ }
2279
+ previousPhysicalShortfall = physicalShortfall;
2280
+ if (passReallocatedAssets <= previousPassReallocatedAssets ||
2281
+ penalty === MathLib.WAD)
2282
+ return { type: "break" };
2283
+ previousPassReallocatedAssets = passReallocatedAssets;
2284
+ passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
2285
+ return {
2286
+ type: "continue",
2287
+ lo,
2288
+ hi,
2289
+ passMaxAssets,
2290
+ triedFullCapacityAttempt,
2291
+ tryFullCapacityAttempt,
2292
+ isFullCapacityRetryPath,
2293
+ previousPhysicalShortfall,
2294
+ previousPassReallocatedAssets,
2295
+ };
2296
+ }
2297
+ /**
2298
+ * Commits the best improving paid attempt or restores the pre-pass checkpoint.
2299
+ * Returns working data by reference and may retain shared reserves; this does not
2300
+ * isolate earlier in-place updates. Do not reuse a prior state for further planning.
2301
+ * @internal
2302
+ */
2303
+ function finishOperationPass(params) {
2304
+ const { passStart, bestAttempt, beforePassRemainingShortfall, beforePassAccountingShortfall, hasExplicitBlueBalance, } = params;
2305
+ let { reserves, data, context, remainingShortfall, accountingShortfall } = params.state;
2306
+ const { allocatorCapBoundTargets, idleBoundVaults } = params.state;
2307
+ const reallocations = [...params.state.reallocations];
2308
+ if (passStart != null) {
2309
+ const improved = bestAttempt != null &&
2310
+ (hasExplicitBlueBalance
2311
+ ? bestAttempt.remainingShortfall < beforePassRemainingShortfall
2312
+ : bestAttempt.accountingShortfall < beforePassAccountingShortfall ||
2313
+ bestAttempt.remainingShortfall < beforePassRemainingShortfall);
2314
+ if (improved && bestAttempt != null) {
2315
+ data = bestAttempt.data;
2316
+ context = bestAttempt.context;
2317
+ reserves = cloneCapReserveState(bestAttempt.reserves);
2318
+ reallocations.length = passStart.reallocationCount;
2319
+ reallocations.push(...bestAttempt.reallocations);
2320
+ remainingShortfall = bestAttempt.remainingShortfall;
2321
+ accountingShortfall = bestAttempt.accountingShortfall;
1867
2322
  }
2323
+ else {
2324
+ data = passStart.data;
2325
+ context = passStart.context;
2326
+ reserves = cloneCapReserveState(passStart.reserves);
2327
+ reallocations.length = passStart.reallocationCount;
2328
+ remainingShortfall = beforePassRemainingShortfall;
2329
+ accountingShortfall = beforePassAccountingShortfall;
2330
+ }
2331
+ }
2332
+ return {
2333
+ reserves,
2334
+ reallocations,
2335
+ data,
2336
+ context,
2337
+ remainingShortfall,
2338
+ accountingShortfall,
2339
+ allocatorCapBoundTargets,
2340
+ idleBoundVaults,
2341
+ };
2342
+ }
2343
+ /** Tightens a paid-pass bisection bracket from the attempt's coverage result. @internal */
2344
+ function updateOperationSearchBracket(params) {
2345
+ let { lo, hi } = params;
2346
+ const { passMaxAssets, attemptCoversShortfall } = params;
2347
+ if (attemptCoversShortfall)
2348
+ hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
2349
+ else
2350
+ lo = MathLib.max(lo, passMaxAssets);
2351
+ return { lo, hi };
2352
+ }
2353
+ /** Validates the operation amount and fee before reading its snapshot. @internal */
2354
+ function resolveOperationFeeAssets(operation) {
2355
+ const { amount } = operation;
2356
+ if (amount <= 0n)
2357
+ throw new NonPositiveInputError("amount", amount);
2358
+ const referralFeePct = operation.type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
2359
+ if (referralFeePct < 0n)
2360
+ throw new NegativeInputError("referralFeePct", referralFeePct);
2361
+ if (referralFeePct >= MathLib.WAD)
2362
+ throw new ReferralFeePctExceededError(referralFeePct);
2363
+ const feeAssets = operation.type === "refinance"
2364
+ ? getBlueBundlesV1ReferralFeeAssets(amount, referralFeePct)
2365
+ : 0n;
2366
+ return feeAssets;
2367
+ }
2368
+ /** Computes post-operation accounting totals, rejecting withdrawals above supply. @internal */
2369
+ function getOperationMarketTotals({ market, marketId, type, amount, feeAssets, }) {
2370
+ if (type === "withdraw" && amount > market.totalSupplyAssets) {
2371
+ throw new ReallocationWithdrawExceedsMarketSupplyError({
2372
+ marketId,
2373
+ withdrawAmount: amount,
2374
+ totalSupplyAssets: market.totalSupplyAssets,
2375
+ });
2376
+ }
2377
+ let newTotalBorrowAssets = market.totalBorrowAssets;
2378
+ if (type === "borrow")
2379
+ newTotalBorrowAssets += amount;
2380
+ if (type === "refinance")
2381
+ newTotalBorrowAssets += amount + feeAssets;
2382
+ const newTotalSupplyAssets = type === "withdraw"
2383
+ ? market.totalSupplyAssets - amount
2384
+ : market.totalSupplyAssets;
2385
+ return { newTotalBorrowAssets, newTotalSupplyAssets };
2386
+ }
2387
+ /** Chooses a headroom or full-cap budget before testing physical-balance alternatives. @internal */
2388
+ function selectOperationPlan(params) {
2389
+ const { plan, requiredAssets, allocatorCapHeadroom, absoluteShortfall } = params;
2390
+ // A leg that fills an allocator cap, or idle legs that together take
2391
+ // (nearly) all of a source vault's starting idle, revert once another
2392
+ // allocation lands first. A bound plan therefore moves only the operation's
2393
+ // shortfall, or what unbound legs moved.
2394
+ const target = plan(requiredAssets, { headroom: allocatorCapHeadroom });
2395
+ let selected = target;
2396
+ if (allocatorCapHeadroom > 0n && target.liquidityBound) {
2397
+ selected = plan(absoluteShortfall > target.unboundAssets
2398
+ ? absoluteShortfall
2399
+ : target.unboundAssets, { headroom: allocatorCapHeadroom });
2400
+ // Shared-cap fitting is not monotonic in the budget.
2401
+ if (!selected.coversShortfall && target.coversShortfall)
2402
+ selected = target;
2403
+ }
2404
+ let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
2405
+ // Without headroom, `target` already is the full-cap plan toward the target.
2406
+ const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
2407
+ for (const maxAssets of fullCapBudgets) {
2408
+ if (selected.coversShortfall)
2409
+ break;
2410
+ selected = plan(maxAssets, { headroom: 0n });
2411
+ if (selected.reallocatedAssets > available)
2412
+ available = selected.reallocatedAssets;
2413
+ }
2414
+ // Reject unfunded plans before comparing optional physical-balance alternatives.
2415
+ assertSelectedOperationFunding({ ...params, selected, available });
2416
+ const funded = choosePhysicalBalancePlan({ ...params, selected });
2417
+ return { reallocations: funded.reallocations, data: funded.data };
2418
+ }
2419
+ /** Preserves penalty-specific error precedence when selected liquidity cannot fund the operation. @internal */
2420
+ function assertSelectedOperationFunding(params) {
2421
+ const { selected, available, hasExplicitBlueBalance, blueBalance, type, amount, absoluteShortfall, marketId, } = params;
2422
+ if (selected.coversShortfall)
2423
+ return;
2424
+ const selectedTransferShortfall = hasExplicitBlueBalance
2425
+ ? getReallocationTransferShortfall(selected.reallocations, blueBalance)
2426
+ : 0n;
2427
+ const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
2428
+ if (type !== "refinance" &&
2429
+ selectedPenaltyAssets > amount &&
2430
+ selected.reallocatedAssets >= absoluteShortfall &&
2431
+ (!hasExplicitBlueBalance ||
2432
+ (selected.physicalShortfall === 0n && selectedTransferShortfall === 0n)))
2433
+ throw new InputExceedsMaxError({
2434
+ field: "reallocationPenaltyAssets",
2435
+ value: selectedPenaltyAssets,
2436
+ max: amount,
2437
+ });
2438
+ throw new InsufficientSharedLiquidityError({
2439
+ marketId,
2440
+ shortfall: MathLib.max(absoluteShortfall +
2441
+ (type === "refinance"
2442
+ ? getBlueBundlesV1PenaltyAssets(selected.reallocations)
2443
+ : 0n), selected.reallocatedAssets +
2444
+ (hasExplicitBlueBalance
2445
+ ? MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
2446
+ : 0n)),
2447
+ available,
2448
+ });
2449
+ }
2450
+ /** Retains the selected plan unless a physical-balance seed is funded and strictly cheaper. @internal */
2451
+ function choosePhysicalBalancePlan(params) {
2452
+ const { hasExplicitBlueBalance, blueBalance, amount, feeAssets, type, plan } = params;
2453
+ let { selected } = params;
2454
+ const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
2455
+ if (hasExplicitBlueBalance &&
2456
+ selectedPenaltyAssets > 1n &&
2457
+ blueBalance <
2458
+ amount +
2459
+ feeAssets +
2460
+ (type === "refinance" ? 2n : 1n) * selectedPenaltyAssets) {
2461
+ // Amount feasibility is not monotonic: retain the original plan unless
2462
+ // the physical-balance seed finds a fully funded, strictly cheaper one.
2463
+ const alternative = plan(selected.maxAssets, {
2464
+ headroom: selected.headroom,
2465
+ usePhysicalBalance: true,
2466
+ });
2467
+ if (alternative.coversShortfall &&
2468
+ getBlueBundlesV1PenaltyAssets(alternative.reallocations) <
2469
+ getBlueBundlesV1PenaltyAssets(selected.reallocations))
2470
+ selected = alternative;
1868
2471
  }
2472
+ return selected;
1869
2473
  }