@morpho-org/morpho-sdk 9.1.0-next.0 → 9.2.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 (154) hide show
  1. package/README.md +7 -1
  2. package/lib/cjs/abis.d.ts +2 -2
  3. package/lib/cjs/abis.js +3 -5
  4. package/lib/cjs/actions/blue/borrow.d.ts +1 -0
  5. package/lib/cjs/actions/blue/borrow.js +1 -0
  6. package/lib/cjs/actions/blue/refinance.d.ts +1 -0
  7. package/lib/cjs/actions/blue/refinance.js +3 -0
  8. package/lib/cjs/actions/blue/repay.d.ts +1 -0
  9. package/lib/cjs/actions/blue/repay.js +1 -0
  10. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  11. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -0
  12. package/lib/cjs/actions/blue/supply.d.ts +1 -0
  13. package/lib/cjs/actions/blue/supply.js +2 -0
  14. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -0
  15. package/lib/cjs/actions/blue/supplyCollateral.js +1 -0
  16. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  17. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +2 -0
  18. package/lib/cjs/actions/blue/withdraw.d.ts +1 -0
  19. package/lib/cjs/actions/blue/withdraw.js +2 -0
  20. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +1 -0
  21. package/lib/cjs/actions/blue/withdrawCollateral.js +1 -0
  22. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  23. package/lib/cjs/actions/midnight/takeLend.js +1 -0
  24. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  25. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  26. package/lib/cjs/blue/abis.d.ts +1 -1
  27. package/lib/cjs/blue/abis.js +1 -5
  28. package/lib/cjs/blue/constants.d.ts +1 -1
  29. package/lib/cjs/blue/constants.js +2 -1
  30. package/lib/cjs/blue/entities.d.ts +4 -4
  31. package/lib/cjs/blue/entities.js +1 -3
  32. package/lib/cjs/blue/errors.d.ts +2 -2
  33. package/lib/cjs/blue/errors.js +2 -5
  34. package/lib/cjs/blue/fetch.d.ts +2 -2
  35. package/lib/cjs/blue/fetch.js +1 -3
  36. package/lib/cjs/blue/utils.d.ts +1 -1
  37. package/lib/cjs/blue/utils.js +1 -2
  38. package/lib/cjs/client/morphoViemExtension.d.ts +1 -1
  39. package/lib/cjs/client/morphoViemExtension.js +1 -7
  40. package/lib/cjs/constants.d.ts +2 -2
  41. package/lib/cjs/constants.js +4 -1
  42. package/lib/cjs/entities/blue/blue.d.ts +112 -21
  43. package/lib/cjs/entities/blue/blue.js +58 -6
  44. package/lib/cjs/entities/index.d.ts +4 -4
  45. package/lib/cjs/entities/index.js +1 -3
  46. package/lib/cjs/entities/midnight/midnight.d.ts +9 -6
  47. package/lib/cjs/entities/midnight/midnight.js +12 -9
  48. package/lib/cjs/entities/midnight/types.d.ts +8 -1
  49. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +8 -0
  50. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -0
  51. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +16 -34
  52. package/lib/cjs/entities/vaultV2/vaultV2.js +12 -38
  53. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +77 -19
  54. package/lib/cjs/entities/vaultV2BlueReallocationData.js +376 -80
  55. package/lib/cjs/errors.d.ts +4 -4
  56. package/lib/cjs/errors.js +6 -10
  57. package/lib/cjs/fetch.d.ts +2 -2
  58. package/lib/cjs/fetch.js +1 -3
  59. package/lib/cjs/helpers/constant.d.ts +7 -0
  60. package/lib/cjs/helpers/constant.js +8 -1
  61. package/lib/cjs/helpers/deadShares.d.ts +82 -0
  62. package/lib/cjs/helpers/deadShares.js +200 -0
  63. package/lib/cjs/helpers/index.d.ts +2 -1
  64. package/lib/cjs/helpers/index.js +7 -1
  65. package/lib/cjs/helpers/validate.d.ts +11 -1
  66. package/lib/cjs/helpers/validate.js +17 -1
  67. package/lib/cjs/helpers/validateTakeableOffers.d.ts +4 -2
  68. package/lib/cjs/helpers/validateTakeableOffers.js +12 -1
  69. package/lib/cjs/midnight/abis.d.ts +1 -1
  70. package/lib/cjs/midnight/abis.js +3 -1
  71. package/lib/cjs/midnight/errors.d.ts +1 -2
  72. package/lib/cjs/midnight/errors.js +4 -5
  73. package/lib/cjs/types/error.d.ts +60 -5
  74. package/lib/cjs/types/error.js +68 -6
  75. package/lib/cjs/types/sharedLiquidity.d.ts +31 -11
  76. package/lib/cjs/utils.d.ts +2 -2
  77. package/lib/cjs/utils.js +2 -4
  78. package/lib/esm/abis.d.ts +2 -2
  79. package/lib/esm/abis.js +2 -2
  80. package/lib/esm/actions/blue/borrow.d.ts +1 -0
  81. package/lib/esm/actions/blue/borrow.js +1 -0
  82. package/lib/esm/actions/blue/refinance.d.ts +1 -0
  83. package/lib/esm/actions/blue/refinance.js +4 -1
  84. package/lib/esm/actions/blue/repay.d.ts +1 -0
  85. package/lib/esm/actions/blue/repay.js +1 -0
  86. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +1 -0
  87. package/lib/esm/actions/blue/repayWithdrawCollateral.js +3 -1
  88. package/lib/esm/actions/blue/supply.d.ts +1 -0
  89. package/lib/esm/actions/blue/supply.js +3 -1
  90. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -0
  91. package/lib/esm/actions/blue/supplyCollateral.js +1 -0
  92. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +1 -0
  93. package/lib/esm/actions/blue/supplyCollateralBorrow.js +3 -1
  94. package/lib/esm/actions/blue/withdraw.d.ts +1 -0
  95. package/lib/esm/actions/blue/withdraw.js +3 -1
  96. package/lib/esm/actions/blue/withdrawCollateral.d.ts +1 -0
  97. package/lib/esm/actions/blue/withdrawCollateral.js +1 -0
  98. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  99. package/lib/esm/actions/midnight/takeLend.js +1 -0
  100. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  101. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +1 -0
  102. package/lib/esm/blue/abis.d.ts +1 -1
  103. package/lib/esm/blue/abis.js +1 -1
  104. package/lib/esm/blue/constants.d.ts +1 -1
  105. package/lib/esm/blue/constants.js +1 -1
  106. package/lib/esm/blue/entities.d.ts +4 -4
  107. package/lib/esm/blue/entities.js +2 -2
  108. package/lib/esm/blue/errors.d.ts +2 -2
  109. package/lib/esm/blue/errors.js +2 -2
  110. package/lib/esm/blue/fetch.d.ts +2 -2
  111. package/lib/esm/blue/fetch.js +2 -2
  112. package/lib/esm/blue/utils.d.ts +1 -1
  113. package/lib/esm/blue/utils.js +1 -1
  114. package/lib/esm/client/morphoViemExtension.d.ts +1 -1
  115. package/lib/esm/client/morphoViemExtension.js +1 -7
  116. package/lib/esm/constants.d.ts +2 -2
  117. package/lib/esm/constants.js +2 -2
  118. package/lib/esm/entities/blue/blue.d.ts +112 -21
  119. package/lib/esm/entities/blue/blue.js +60 -8
  120. package/lib/esm/entities/index.d.ts +4 -4
  121. package/lib/esm/entities/index.js +2 -2
  122. package/lib/esm/entities/midnight/midnight.d.ts +9 -6
  123. package/lib/esm/entities/midnight/midnight.js +13 -10
  124. package/lib/esm/entities/midnight/types.d.ts +8 -1
  125. package/lib/esm/entities/vaultV1/vaultV1.d.ts +8 -0
  126. package/lib/esm/entities/vaultV1/vaultV1.js +5 -0
  127. package/lib/esm/entities/vaultV2/vaultV2.d.ts +16 -34
  128. package/lib/esm/entities/vaultV2/vaultV2.js +13 -39
  129. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +77 -19
  130. package/lib/esm/entities/vaultV2BlueReallocationData.js +377 -81
  131. package/lib/esm/errors.d.ts +4 -4
  132. package/lib/esm/errors.js +4 -4
  133. package/lib/esm/fetch.d.ts +2 -2
  134. package/lib/esm/fetch.js +2 -2
  135. package/lib/esm/helpers/constant.d.ts +7 -0
  136. package/lib/esm/helpers/constant.js +7 -0
  137. package/lib/esm/helpers/deadShares.d.ts +82 -0
  138. package/lib/esm/helpers/deadShares.js +195 -0
  139. package/lib/esm/helpers/index.d.ts +2 -1
  140. package/lib/esm/helpers/index.js +2 -1
  141. package/lib/esm/helpers/validate.d.ts +11 -1
  142. package/lib/esm/helpers/validate.js +15 -0
  143. package/lib/esm/helpers/validateTakeableOffers.d.ts +4 -2
  144. package/lib/esm/helpers/validateTakeableOffers.js +13 -2
  145. package/lib/esm/midnight/abis.d.ts +1 -1
  146. package/lib/esm/midnight/abis.js +1 -1
  147. package/lib/esm/midnight/errors.d.ts +1 -2
  148. package/lib/esm/midnight/errors.js +1 -2
  149. package/lib/esm/types/error.d.ts +60 -5
  150. package/lib/esm/types/error.js +64 -5
  151. package/lib/esm/types/sharedLiquidity.d.ts +31 -11
  152. package/lib/esm/utils.d.ts +2 -2
  153. package/lib/esm/utils.js +2 -2
  154. package/package.json +9 -8
@@ -4,6 +4,7 @@ exports.VaultV2BlueReallocationData = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
+ const common_js_1 = require("../actions/blue/common.js");
7
8
  const constant_js_1 = require("../helpers/constant.js");
8
9
  const utilization_js_1 = require("../helpers/utilization.js");
9
10
  const index_js_1 = require("../types/index.js");
@@ -14,6 +15,17 @@ const createCapReserveState = (markets) => ({
14
15
  touchedPairs: new Map(),
15
16
  reserveByPairKey: new Map(),
16
17
  });
18
+ const cloneCapReserveState = (state) => {
19
+ const touchedPairs = new Map();
20
+ for (const [vault, pairs] of state.touchedPairs)
21
+ touchedPairs.set(vault, new Map(pairs));
22
+ return {
23
+ initialMarkets: { ...state.initialMarkets },
24
+ marketAccruals: new Map(state.marketAccruals),
25
+ touchedPairs,
26
+ reserveByPairKey: new Map(state.reserveByPairKey),
27
+ };
28
+ };
17
29
  /** Creates isolated transaction-scoped state for one simulation. @internal */
18
30
  const createSimulationContext = () => ({
19
31
  donatedPenaltyAssets: {},
@@ -78,10 +90,6 @@ const cloneAccrualVault = (vault, markets) => new blue_sdk_1.AccrualVault({
78
90
  position: clonePosition(position, markets),
79
91
  })));
80
92
  const cloneAdapter = (adapter, markets) => {
81
- // BluePublicAllocator never moves Midnight liquidity, and reallocation never mutates a Midnight
82
- // adapter, so its read-only snapshot is shared as-is.
83
- if (adapter.type === "VaultV2MidnightAdapter")
84
- return adapter;
85
93
  const base = {
86
94
  address: adapter.address,
87
95
  parentVault: adapter.parentVault,
@@ -129,9 +137,8 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
129
137
  /**
130
138
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
131
139
  *
132
- * Constructor inputs are cloned, except Midnight adapter snapshots: those are
133
- * shared by reference and must be treated as read-only. Every simulated
134
- * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
140
+ * Constructor inputs are cloned. Every simulated reallocation returns a new
141
+ * instance. Planning keeps the transaction-scoped `firstTotalAssets`
135
142
  * denominator outside the durable snapshot while applying reallocations in
136
143
  * contract order. Penalty donations update simulated vault accounting but are
137
144
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -167,8 +174,22 @@ class VaultV2BlueReallocationData {
167
174
  mutableVaults;
168
175
  /** Mutable allocation state used only by cloned simulation transitions. */
169
176
  mutableAllocations;
177
+ /** Mutable Blue token balances used only by cloned simulation transitions. */
178
+ mutableBlueBalances;
170
179
  /** Chain id associated with this snapshot. */
171
180
  chainId;
181
+ /** Timestamp of the block the state was fetched at. */
182
+ timestamp;
183
+ /**
184
+ * Morpho Blue's ERC-20 balances at the snapshot block, indexed by token address.
185
+ * Explicit balances increase with idle-sourced reallocations in returned
186
+ * post-states. Sizing has zero margin over the snapshot balance, so activity
187
+ * on other Blue markets with the same loan token can make a plan revert;
188
+ * refetch close to submission. A missing token uses summed non-negative
189
+ * snapshot-market supply-minus-borrow only to size plans; balance-based
190
+ * rejection requires an explicit balance.
191
+ */
192
+ blueBalances;
172
193
  /** Markets indexed by market id. */
173
194
  markets;
174
195
  /** Vault V2 entities indexed by address. */
@@ -190,12 +211,16 @@ class VaultV2BlueReallocationData {
190
211
  constructor(input) {
191
212
  const isClone = input instanceof VaultV2BlueReallocationData;
192
213
  this.chainId = input.chainId;
214
+ this.timestamp =
215
+ input.timestamp == null ? undefined : BigInt(input.timestamp);
193
216
  this.mutableMarkets = {};
194
217
  this.mutableVaults = {};
195
218
  this.mutableAllocations = {};
219
+ this.mutableBlueBalances = {};
196
220
  this.markets = this.mutableMarkets;
197
221
  this.vaults = this.mutableVaults;
198
222
  this.allocations = this.mutableAllocations;
223
+ this.blueBalances = this.mutableBlueBalances;
199
224
  if (isClone) {
200
225
  this.publicAllocatorConfigs = input.publicAllocatorConfigs;
201
226
  this.activeAdapters = input.activeAdapters;
@@ -232,6 +257,10 @@ class VaultV2BlueReallocationData {
232
257
  this.mutableMarkets[marketId] =
233
258
  market == null ? undefined : new blue_sdk_1.Market({ ...market });
234
259
  }
260
+ for (const [token, balance] of Object.entries(input.blueBalances ?? {})) {
261
+ this.mutableBlueBalances[token] =
262
+ balance == null ? undefined : BigInt(balance);
263
+ }
235
264
  for (const [address, vault] of Object.entries(input.vaults ?? {})) {
236
265
  const clonedVault = vault == null
237
266
  ? undefined
@@ -253,8 +282,7 @@ class VaultV2BlueReallocationData {
253
282
  /**
254
283
  * Clones the complete simulation snapshot.
255
284
  *
256
- * @returns A deep clone of this simulation state. Midnight adapter snapshots are
257
- * shared by reference and must be treated as read-only.
285
+ * @returns A deep clone of this simulation state.
258
286
  * @example
259
287
  * ```ts
260
288
  * import { markets } from "@morpho-org/morpho-test";
@@ -563,16 +591,40 @@ class VaultV2BlueReallocationData {
563
591
  * Computes Vault V2 BluePublicAllocator calls available for a target market.
564
592
  *
565
593
  * Without `options.operation`, discovers every friendly call. With an
566
- * operation, targets the amount required by that borrow or loan-asset
567
- * withdrawal and falls back to 100% source utilization only when friendly
568
- * liquidity cannot cover the absolute shortfall. A shared relative-cap lower
569
- * bound may require one call to exceed the targeted amount. Friendly source
570
- * utilization defaults to 90% and is configurable through
571
- * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
572
- * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
573
- * considered. Market/vault state and the returned post-state stay at
574
- * `timestamp`; only target-market cap checks reserve interest the vault's
575
- * existing allocation would accrue through `timestamp + capAccrualBuffer`
594
+ * operation, penalty tiers are considered ascending, starting with free
595
+ * vaults. The free tier aims to bring the target market back to 90%
596
+ * utilization; positive tiers cover the remaining absolute shortfall or,
597
+ * when larger, Blue's loan-token balance deficit while the penalty is
598
+ * flash-loaned. Within each tier, source markets go to the
599
+ * friendly source utilization (90% by default) before 100%. Free capacity
600
+ * inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
601
+ * it instead. Discovery and liquidity getters still count every vault up to
602
+ * `options.maxPenalty`. A shared relative-cap lower bound may require one call
603
+ * to exceed the targeted amount. For `refinance`, compute the plan on the
604
+ * destination-market handle (for example,
605
+ * `client.morpho.blue(destination.marketParams, chainId)`), not the source
606
+ * handle. Pass the source position's `borrowAssets` accrued to
607
+ * `max(now, source.lastUpdate, destination.lastUpdate) + 2h` as
608
+ * `operation.amount`; the optional `operation.referralFeePct` is WAD-scaled.
609
+ * The planner includes the referral fee and its allocator-leg penalties in
610
+ * destination debt, so penalized legs also cover their own penalty.
611
+ * Refinance never uses vaults with a 100% penalty.
612
+ * BlueBundlesV1 flash-loans the plan's penalty from Blue before executing
613
+ * reallocation legs. When an explicit `blueBalances` value is supplied, plans
614
+ * throw `InsufficientSharedLiquidityError` if Blue cannot fund that flash
615
+ * loan or a market-sourced leg's withdrawal before later idle legs arrive.
616
+ * Legs are not reordered. A missing balance falls back to summed snapshot-
617
+ * market liquidity only to size plans and may make them larger; it cannot
618
+ * cause rejection for Blue-balance constraints.
619
+ * Sizing has zero margin over the snapshot balance; activity on other Blue
620
+ * markets with the same loan token can make a plan revert. Refetch close to
621
+ * submission; there is no balance-buffer option.
622
+ * Friendly source utilization defaults to 90% and is configurable through
623
+ * `options.maxWithdrawalUtilization`. Market/vault state and the returned
624
+ * post-state stay at `timestamp`. An enabled operation that needs no
625
+ * reallocation still returns a clone accrued to `timestamp`. Only
626
+ * target-market cap checks reserve interest the vault's existing allocation
627
+ * would accrue through `timestamp + capAccrualBuffer`
576
628
  * (two hours by default; `0n` disables it). When an operation's plan would
577
629
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
578
630
  * BluePublicAllocator cap, the plan is reduced to the larger of the
@@ -613,8 +665,9 @@ class VaultV2BlueReallocationData {
613
665
  * every leg of a plan.
614
666
  * @returns Flat action-ready reallocations and their post-simulation state.
615
667
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
616
- * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
617
- * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
668
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
669
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD, or an enabled borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
670
+ * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
618
671
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
619
672
  * @throws {UnknownReallocationMarketError} when a required market is absent.
620
673
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -622,7 +675,7 @@ class VaultV2BlueReallocationData {
622
675
  * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
623
676
  * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
624
677
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
625
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall.
678
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund the penalty flash loan, an earlier market-sourced withdrawal, or the final operation transfer.
626
679
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
627
680
  * @example
628
681
  * ```ts
@@ -676,6 +729,14 @@ class VaultV2BlueReallocationData {
676
729
  const { amount, type } = operation;
677
730
  if (amount <= 0n)
678
731
  throw new index_js_1.NonPositiveInputError("amount", amount);
732
+ const referralFeePct = type === "refinance" ? (operation.referralFeePct ?? 0n) : 0n;
733
+ if (referralFeePct < 0n)
734
+ throw new index_js_1.NegativeInputError("referralFeePct", referralFeePct);
735
+ if (referralFeePct >= blue_sdk_1.MathLib.WAD)
736
+ throw new index_js_1.ReferralFeePctExceededError(referralFeePct);
737
+ const feeAssets = type === "refinance"
738
+ ? (0, common_js_1.getBlueBundlesV1ReferralFeeAssets)(amount, referralFeePct)
739
+ : 0n;
679
740
  const timestamp = options.timestamp == null
680
741
  ? this.getLatestSnapshotTimestamp()
681
742
  : BigInt(options.timestamp);
@@ -687,6 +748,31 @@ class VaultV2BlueReallocationData {
687
748
  : [...options.reallocatableVaults],
688
749
  };
689
750
  const market = this.getMarket(marketId).accrueInterest(timestamp);
751
+ const blueBalanceKey = findAddressKey(this.mutableBlueBalances, market.params.loanToken);
752
+ const explicitBlueBalance = blueBalanceKey == null
753
+ ? undefined
754
+ : this.mutableBlueBalances[blueBalanceKey];
755
+ const hasExplicitBlueBalance = explicitBlueBalance !== undefined;
756
+ const blueBalance = explicitBlueBalance ??
757
+ Object.values(this.mutableMarkets).reduce((total, snapshotMarket) => snapshotMarket != null &&
758
+ (0, viem_1.isAddressEqual)(snapshotMarket.params.loanToken, market.params.loanToken)
759
+ ? total +
760
+ blue_sdk_1.MathLib.zeroFloorSub(snapshotMarket.totalSupplyAssets, snapshotMarket.totalBorrowAssets)
761
+ : total, 0n);
762
+ const getTransferShortfall = (reallocations) => {
763
+ const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
764
+ if (penaltyAssets === 0n)
765
+ return 0n;
766
+ let shortfall = blue_sdk_1.MathLib.zeroFloorSub(penaltyAssets, blueBalance);
767
+ let balance = blue_sdk_1.MathLib.zeroFloorSub(blueBalance, penaltyAssets);
768
+ for (const { from, assets } of reallocations) {
769
+ if (from.type === "idle")
770
+ balance += assets;
771
+ else
772
+ shortfall = blue_sdk_1.MathLib.max(shortfall, blue_sdk_1.MathLib.zeroFloorSub(assets, balance));
773
+ }
774
+ return shortfall;
775
+ };
690
776
  if (type === "withdraw" && amount > market.totalSupplyAssets) {
691
777
  throw new index_js_1.ReallocationWithdrawExceedsMarketSupplyError({
692
778
  marketId,
@@ -696,60 +782,225 @@ class VaultV2BlueReallocationData {
696
782
  }
697
783
  const newTotalBorrowAssets = type === "borrow"
698
784
  ? market.totalBorrowAssets + amount
699
- : market.totalBorrowAssets;
785
+ : type === "refinance"
786
+ ? market.totalBorrowAssets + amount + feeAssets
787
+ : market.totalBorrowAssets;
700
788
  const newTotalSupplyAssets = type === "withdraw"
701
789
  ? market.totalSupplyAssets - amount
702
790
  : market.totalSupplyAssets;
791
+ const requiredAssets = blue_sdk_1.MathLib.wDivUp(newTotalBorrowAssets, constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION) -
792
+ newTotalSupplyAssets;
703
793
  if (blue_sdk_1.MarketUtils.getUtilization({
704
794
  totalSupplyAssets: newTotalSupplyAssets,
705
795
  totalBorrowAssets: newTotalBorrowAssets,
706
- }) <= constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION)
707
- return { reallocations: [], data: this };
708
- const requiredAssets = blue_sdk_1.MathLib.wDivUp(newTotalBorrowAssets, constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION) -
709
- newTotalSupplyAssets;
710
- if (requiredAssets <= 0n)
711
- return { reallocations: [], data: this };
796
+ }) <= constant_js_1.DEFAULT_SUPPLY_TARGET_UTILIZATION ||
797
+ requiredAssets <= 0n) {
798
+ const data = this.clone();
799
+ data.setMarkets([market]);
800
+ return { reallocations: [], data };
801
+ }
712
802
  const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
713
803
  ? newTotalBorrowAssets - newTotalSupplyAssets
714
804
  : 0n;
805
+ const penaltyTiers = [
806
+ 0n,
807
+ ...new Set(Object.values(this.publicAllocatorConfigs).flatMap((config) => config != null && config.penalty > 0n && config.penalty <= maxPenalty
808
+ ? [config.penalty]
809
+ : [])),
810
+ ].sort((0, morpho_ts_1.bigIntComparator)((tier) => tier));
715
811
  const plan = (maxAssets, headroom) => {
716
- const reserves = createCapReserveState(this.mutableMarkets);
717
- const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
718
- context: createSimulationContext(),
719
- reserves,
720
- marketId,
721
- maxWithdrawalUtilization,
722
- maxAssets,
723
- capAccrualBuffer,
724
- allocatorCapHeadroom: headroom,
725
- options: normalizedOptions,
726
- });
727
- const reallocations = [...friendly.reallocations];
728
- const data = friendly.data;
729
- const friendlyMarket = data.getMarket(marketId);
730
- const friendlyBorrow = type === "borrow"
731
- ? friendlyMarket.totalBorrowAssets + amount
732
- : friendlyMarket.totalBorrowAssets;
733
- const friendlySupply = type === "withdraw"
734
- ? friendlyMarket.totalSupplyAssets - amount
735
- : friendlyMarket.totalSupplyAssets;
736
- if (friendlyBorrow > friendlySupply) {
737
- const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
738
- context: friendly.context,
739
- reserves,
740
- marketId,
741
- maxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
742
- maxAssets: friendlyBorrow - friendlySupply,
743
- capAccrualBuffer,
744
- allocatorCapHeadroom: headroom,
745
- options: normalizedOptions,
746
- });
747
- reallocations.push(...fallback.reallocations);
812
+ let reserves = createCapReserveState(this.mutableMarkets);
813
+ const reallocations = [];
814
+ let data = this.clone();
815
+ let context = createSimulationContext();
816
+ let remainingShortfall = absoluteShortfall;
817
+ let accountingShortfall = absoluteShortfall;
818
+ let allocatorCapBoundTargets = new Set();
819
+ let idleBoundVaults = new Set();
820
+ for (const penalty of penaltyTiers) {
821
+ if (type === "refinance" && penalty === blue_sdk_1.MathLib.WAD)
822
+ continue;
823
+ let isFriendlyPass = true;
824
+ let triedFullCapacityAttempt = false;
825
+ for (const utilization of [maxWithdrawalUtilization, blue_sdk_1.MathLib.WAD]) {
826
+ const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
827
+ isFriendlyPass = false;
828
+ if (remainingShortfall === 0n && !isFreeFriendlyPass)
829
+ continue;
830
+ let passMaxAssets = type === "refinance" && penalty > 0n
831
+ ? blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty)
832
+ : isFreeFriendlyPass
833
+ ? maxAssets
834
+ : remainingShortfall;
835
+ const retryPaidPass = penalty > 0n;
836
+ let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
837
+ let tryFullCapacityAttempt = false;
838
+ let isFullCapacityRetryPath = false;
839
+ const beforePassRemainingShortfall = remainingShortfall;
840
+ const beforePassAccountingShortfall = accountingShortfall;
841
+ // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
842
+ const passStart = retryPaidPass
843
+ ? {
844
+ data: data.clone(),
845
+ context,
846
+ reserves: cloneCapReserveState(reserves),
847
+ reallocationCount: reallocations.length,
848
+ }
849
+ : undefined;
850
+ let previousPassReallocatedAssets = 0n;
851
+ let previousPhysicalShortfall;
852
+ let hi;
853
+ let bestAttempt;
854
+ while (true) {
855
+ const isFullCapacityAttempt = tryFullCapacityAttempt;
856
+ tryFullCapacityAttempt = false;
857
+ if (passStart != null) {
858
+ data = passStart.data.clone();
859
+ context = passStart.context;
860
+ reserves = cloneCapReserveState(passStart.reserves);
861
+ reallocations.length = passStart.reallocationCount;
862
+ }
863
+ const pass = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
864
+ context,
865
+ reserves,
866
+ marketId,
867
+ maxWithdrawalUtilization: utilization,
868
+ maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
869
+ capAccrualBuffer,
870
+ allocatorCapHeadroom: headroom,
871
+ penalty,
872
+ options: normalizedOptions,
873
+ });
874
+ reallocations.push(...pass.reallocations);
875
+ data = pass.data;
876
+ context = pass.context;
877
+ if (isFreeFriendlyPass) {
878
+ allocatorCapBoundTargets = pass.allocatorCapBoundTargets;
879
+ idleBoundVaults = pass.idleBoundVaults;
880
+ }
881
+ const currentMarket = data.getMarket(marketId);
882
+ const penaltyAssets = type === "refinance"
883
+ ? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations)
884
+ : 0n;
885
+ const borrow = type === "borrow"
886
+ ? currentMarket.totalBorrowAssets + amount
887
+ : type === "refinance"
888
+ ? currentMarket.totalBorrowAssets +
889
+ amount +
890
+ feeAssets +
891
+ penaltyAssets
892
+ : currentMarket.totalBorrowAssets;
893
+ const supply = type === "withdraw"
894
+ ? currentMarket.totalSupplyAssets - amount
895
+ : currentMarket.totalSupplyAssets;
896
+ accountingShortfall = borrow > supply ? borrow - supply : 0n;
897
+ const penaltyForPhysicalShortfall = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
898
+ const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
899
+ const physicalShortfall = penaltyForPhysicalShortfall === 0n
900
+ ? 0n
901
+ : blue_sdk_1.MathLib.zeroFloorSub((type === "refinance"
902
+ ? amount + feeAssets + penaltyForPhysicalShortfall
903
+ : amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
904
+ remainingShortfall = blue_sdk_1.MathLib.max(accountingShortfall, physicalShortfall);
905
+ const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
906
+ ? getTransferShortfall(reallocations)
907
+ : 0n;
908
+ const attemptCoversShortfall = remainingShortfall === 0n;
909
+ const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
910
+ if (passStart == null)
911
+ break;
912
+ if (isFullCapacityAttempt)
913
+ passMaxAssets = passReallocatedAssets;
914
+ const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
915
+ const attemptPriority = hasExplicitBlueBalance
916
+ ? [0n, remainingShortfall, 0n, passReallocatedAssets]
917
+ : [
918
+ improvesAccounting ? 0n : 1n,
919
+ improvesAccounting ? accountingShortfall : 0n,
920
+ remainingShortfall,
921
+ passReallocatedAssets,
922
+ ];
923
+ const previousBestAttempt = bestAttempt;
924
+ let isBetterAttempt = previousBestAttempt == null;
925
+ if (previousBestAttempt != null) {
926
+ const firstDifference = attemptPriority.findIndex((priority, index) => priority !== previousBestAttempt.priority[index]);
927
+ isBetterAttempt =
928
+ firstDifference !== -1 &&
929
+ attemptPriority[firstDifference] <
930
+ previousBestAttempt.priority[firstDifference];
931
+ }
932
+ if (isBetterAttempt &&
933
+ (!isFullCapacityRetryPath ||
934
+ (attemptCoversShortfall && attemptTransferShortfall === 0n)))
935
+ bestAttempt = {
936
+ data,
937
+ context,
938
+ reserves: cloneCapReserveState(reserves),
939
+ reallocations: pass.reallocations,
940
+ remainingShortfall,
941
+ accountingShortfall,
942
+ passReallocatedAssets,
943
+ priority: attemptPriority,
944
+ };
945
+ if (attemptCoversShortfall)
946
+ hi = hi == null ? passMaxAssets : blue_sdk_1.MathLib.min(hi, passMaxAssets);
947
+ else
948
+ lo = blue_sdk_1.MathLib.max(lo, passMaxAssets);
949
+ if (hi != null) {
950
+ if (hi - lo <= 1n)
951
+ break;
952
+ passMaxAssets = (lo + hi) / 2n;
953
+ continue;
954
+ }
955
+ if (isFullCapacityAttempt && !attemptCoversShortfall)
956
+ break;
957
+ if (accountingShortfall === 0n &&
958
+ previousPhysicalShortfall != null &&
959
+ physicalShortfall >= previousPhysicalShortfall) {
960
+ if (!triedFullCapacityAttempt &&
961
+ passReallocatedAssets === passMaxAssets) {
962
+ triedFullCapacityAttempt = true;
963
+ tryFullCapacityAttempt = true;
964
+ isFullCapacityRetryPath = true;
965
+ continue;
966
+ }
967
+ break;
968
+ }
969
+ previousPhysicalShortfall = physicalShortfall;
970
+ if (passReallocatedAssets <= previousPassReallocatedAssets ||
971
+ penalty === blue_sdk_1.MathLib.WAD)
972
+ break;
973
+ previousPassReallocatedAssets = passReallocatedAssets;
974
+ passMaxAssets += blue_sdk_1.MathLib.mulDivUp(remainingShortfall, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD - penalty);
975
+ }
976
+ if (passStart != null) {
977
+ const improved = bestAttempt != null &&
978
+ (hasExplicitBlueBalance
979
+ ? bestAttempt.remainingShortfall < beforePassRemainingShortfall
980
+ : bestAttempt.accountingShortfall <
981
+ beforePassAccountingShortfall ||
982
+ bestAttempt.remainingShortfall <
983
+ beforePassRemainingShortfall);
984
+ if (improved && bestAttempt != null) {
985
+ data = bestAttempt.data;
986
+ context = bestAttempt.context;
987
+ reserves = cloneCapReserveState(bestAttempt.reserves);
988
+ reallocations.length = passStart.reallocationCount;
989
+ reallocations.push(...bestAttempt.reallocations);
990
+ remainingShortfall = bestAttempt.remainingShortfall;
991
+ accountingShortfall = bestAttempt.accountingShortfall;
992
+ }
993
+ else {
994
+ data = passStart.data;
995
+ context = passStart.context;
996
+ reserves = cloneCapReserveState(passStart.reserves);
997
+ reallocations.length = passStart.reallocationCount;
998
+ remainingShortfall = beforePassRemainingShortfall;
999
+ accountingShortfall = beforePassAccountingShortfall;
1000
+ }
1001
+ }
1002
+ }
748
1003
  }
749
- // The fallback pass only runs when the plan moves exactly the absolute
750
- // shortfall, which a reduced plan would move anyway.
751
- const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
752
- const idleBoundVaults = friendly.idleBoundVaults;
753
1004
  let reallocatedAssets = 0n;
754
1005
  let unboundAssets = 0n;
755
1006
  for (const { vault, from, to, assets } of reallocations) {
@@ -759,12 +1010,28 @@ class VaultV2BlueReallocationData {
759
1010
  !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
760
1011
  unboundAssets += assets;
761
1012
  }
1013
+ const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(reallocations);
1014
+ const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
1015
+ const physicalShortfall = penaltyAssets === 0n
1016
+ ? 0n
1017
+ : blue_sdk_1.MathLib.zeroFloorSub((type === "refinance"
1018
+ ? amount + feeAssets + penaltyAssets
1019
+ : amount) + penaltyAssets, blueBalance + idleAssets);
1020
+ const transferShortfall = getTransferShortfall(reallocations);
1021
+ const coversAccountingShortfall = type === "refinance"
1022
+ ? reallocatedAssets >= absoluteShortfall + penaltyAssets
1023
+ : reallocatedAssets >= absoluteShortfall;
762
1024
  return {
763
1025
  reallocations,
764
1026
  data,
765
1027
  liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
766
1028
  reallocatedAssets,
767
1029
  unboundAssets,
1030
+ physicalShortfall,
1031
+ coversShortfall: coversAccountingShortfall &&
1032
+ (type === "refinance" || penaltyAssets <= amount) &&
1033
+ (!hasExplicitBlueBalance ||
1034
+ (physicalShortfall === 0n && transferShortfall === 0n)),
768
1035
  };
769
1036
  };
770
1037
  // A leg that fills an allocator cap, or idle legs that together take
@@ -778,30 +1045,50 @@ class VaultV2BlueReallocationData {
778
1045
  ? absoluteShortfall
779
1046
  : target.unboundAssets, allocatorCapHeadroom);
780
1047
  // Shared-cap fitting is not monotonic in the budget.
781
- if (selected.reallocatedAssets < absoluteShortfall &&
782
- target.reallocatedAssets >= absoluteShortfall)
1048
+ if (!selected.coversShortfall && target.coversShortfall)
783
1049
  selected = target;
784
1050
  }
785
1051
  let available = blue_sdk_1.MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
786
1052
  // Without headroom, `target` already is the full-cap plan toward the target.
787
1053
  const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
788
1054
  for (const maxAssets of fullCapBudgets) {
789
- if (selected.reallocatedAssets >= absoluteShortfall)
1055
+ if (selected.coversShortfall)
790
1056
  break;
791
1057
  selected = plan(maxAssets, 0n);
792
1058
  if (selected.reallocatedAssets > available)
793
1059
  available = selected.reallocatedAssets;
794
1060
  }
795
- if (selected.reallocatedAssets < absoluteShortfall) {
1061
+ if (!selected.coversShortfall) {
1062
+ const selectedTransferShortfall = hasExplicitBlueBalance
1063
+ ? getTransferShortfall(selected.reallocations)
1064
+ : 0n;
1065
+ const selectedPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations);
1066
+ if (type !== "refinance" &&
1067
+ selectedPenaltyAssets > amount &&
1068
+ selected.reallocatedAssets >= absoluteShortfall &&
1069
+ (!hasExplicitBlueBalance ||
1070
+ (selected.physicalShortfall === 0n &&
1071
+ selectedTransferShortfall === 0n)))
1072
+ throw new index_js_1.InputExceedsMaxError({
1073
+ field: "reallocationPenaltyAssets",
1074
+ value: selectedPenaltyAssets,
1075
+ max: amount,
1076
+ });
796
1077
  throw new index_js_1.InsufficientSharedLiquidityError({
797
1078
  marketId,
798
- shortfall: absoluteShortfall,
1079
+ shortfall: blue_sdk_1.MathLib.max(absoluteShortfall +
1080
+ (type === "refinance"
1081
+ ? (0, common_js_1.getBlueBundlesV1PenaltyAssets)(selected.reallocations)
1082
+ : 0n), selected.reallocatedAssets +
1083
+ (hasExplicitBlueBalance
1084
+ ? blue_sdk_1.MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
1085
+ : 0n)),
799
1086
  available,
800
1087
  });
801
1088
  }
802
1089
  return { reallocations: selected.reallocations, data: selected.data };
803
1090
  }
804
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
1091
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, penalty, options = {}, }) {
805
1092
  if (options.enabled === false)
806
1093
  return {
807
1094
  reallocations: [],
@@ -844,23 +1131,23 @@ class VaultV2BlueReallocationData {
844
1131
  return {
845
1132
  key,
846
1133
  ids: getAdapterIds(adapterIdsCache, adapter, market),
847
- reserve: () => {
848
- let reserve = reserves.reserveByPairKey.get(key);
1134
+ reserve: (reserveState) => {
1135
+ let reserve = reserveState.reserveByPairKey.get(key);
849
1136
  if (reserve == null) {
850
- let accruals = reserves.marketAccruals.get(market.id);
1137
+ let accruals = reserveState.marketAccruals.get(market.id);
851
1138
  if (accruals == null) {
852
- const initialMarket = reserves.initialMarkets[market.id];
1139
+ const initialMarket = reserveState.initialMarkets[market.id];
853
1140
  if (initialMarket == null)
854
1141
  throw new index_js_1.UnknownReallocationMarketError(market.id);
855
1142
  accruals = [
856
1143
  initialMarket.accrueInterest(timestamp),
857
1144
  initialMarket.accrueInterest(timestamp + capAccrualBuffer),
858
1145
  ];
859
- reserves.marketAccruals.set(market.id, accruals);
1146
+ reserveState.marketAccruals.set(market.id, accruals);
860
1147
  }
861
1148
  const [atTimestamp, projected] = accruals;
862
1149
  reserve = blue_sdk_1.MathLib.zeroFloorSub(projected.toSupplyAssets(shares), atTimestamp.toSupplyAssets(shares));
863
- reserves.reserveByPairKey.set(key, reserve);
1150
+ reserveState.reserveByPairKey.set(key, reserve);
864
1151
  }
865
1152
  return reserve;
866
1153
  },
@@ -877,7 +1164,7 @@ class VaultV2BlueReallocationData {
877
1164
  if (seen.has(pair.key) || !pair.ids.includes(id))
878
1165
  continue;
879
1166
  seen.add(pair.key);
880
- reserve += pair.reserve();
1167
+ reserve += pair.reserve(reserves);
881
1168
  }
882
1169
  return reserve;
883
1170
  };
@@ -893,6 +1180,8 @@ class VaultV2BlueReallocationData {
893
1180
  publicAllocatorConfig.penalty >
894
1181
  (options.maxPenalty ?? constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY))
895
1182
  return;
1183
+ if (penalty != null && publicAllocatorConfig.penalty !== penalty)
1184
+ return;
896
1185
  const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
897
1186
  // Exclude rounded penalty dust from idle candidates so one donation
898
1187
  // cannot replenish liquidity for another same-plan reallocation.
@@ -943,7 +1232,7 @@ class VaultV2BlueReallocationData {
943
1232
  const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
944
1233
  const allocatorHeadroom = blue_sdk_1.MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
945
1234
  untracked +
946
- targetPair.reserve()), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
1235
+ targetPair.reserve(reserves)), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
947
1236
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
948
1237
  const minimumAllocationChange = blue_sdk_1.MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
949
1238
  const blockedTargetIds = targetAllocations
@@ -1312,7 +1601,7 @@ class VaultV2BlueReallocationData {
1312
1601
  }, utilization);
1313
1602
  }
1314
1603
  getLatestSnapshotTimestamp() {
1315
- let timestamp = 0n;
1604
+ let timestamp = this.timestamp ?? 0n;
1316
1605
  for (const market of Object.values(this.markets)) {
1317
1606
  if (market != null)
1318
1607
  timestamp = blue_sdk_1.MathLib.max(timestamp, market.lastUpdate);
@@ -1357,6 +1646,7 @@ class VaultV2BlueReallocationData {
1357
1646
  }
1358
1647
  data = new VaultV2BlueReallocationData({
1359
1648
  chainId: this.chainId,
1649
+ timestamp: this.timestamp,
1360
1650
  markets: probeMarkets,
1361
1651
  });
1362
1652
  if (sourceVaultKey != null) {
@@ -1441,6 +1731,12 @@ class VaultV2BlueReallocationData {
1441
1731
  }
1442
1732
  vault.assetBalance += reallocation.assets;
1443
1733
  }
1734
+ if (reallocation.from.type === "idle") {
1735
+ const blueBalanceKey = findAddressKey(data.mutableBlueBalances, targetMarket.params.loanToken);
1736
+ if (blueBalanceKey != null &&
1737
+ data.mutableBlueBalances[blueBalanceKey] != null)
1738
+ data.mutableBlueBalances[blueBalanceKey] += reallocation.assets;
1739
+ }
1444
1740
  if (firstTotalAssets == null) {
1445
1741
  // Vault V2's transient firstTotalAssets tracks the first allocation in a
1446
1742
  // transaction independently from elapsed time. Later allocations must not