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