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