@morpho-org/morpho-sdk 8.1.0 → 8.2.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 (55) hide show
  1. package/lib/cjs/abis.d.ts +1 -1
  2. package/lib/cjs/abis.js +5 -1
  3. package/lib/cjs/blue/abis.d.ts +1 -1
  4. package/lib/cjs/blue/abis.js +5 -1
  5. package/lib/cjs/blue/entities.d.ts +4 -4
  6. package/lib/cjs/blue/entities.js +3 -1
  7. package/lib/cjs/blue/errors.d.ts +2 -2
  8. package/lib/cjs/blue/errors.js +5 -1
  9. package/lib/cjs/blue/fetch.d.ts +2 -2
  10. package/lib/cjs/blue/fetch.js +3 -1
  11. package/lib/cjs/blue/utils.d.ts +1 -1
  12. package/lib/cjs/blue/utils.js +2 -1
  13. package/lib/cjs/entities/index.d.ts +4 -4
  14. package/lib/cjs/entities/index.js +3 -1
  15. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +33 -9
  16. package/lib/cjs/entities/vaultV2/vaultV2.js +33 -1
  17. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +17 -9
  18. package/lib/cjs/entities/vaultV2BlueReallocationData.js +51 -17
  19. package/lib/cjs/errors.d.ts +4 -4
  20. package/lib/cjs/errors.js +10 -5
  21. package/lib/cjs/fetch.d.ts +2 -2
  22. package/lib/cjs/fetch.js +3 -1
  23. package/lib/cjs/midnight/errors.d.ts +2 -1
  24. package/lib/cjs/midnight/errors.js +5 -4
  25. package/lib/cjs/types/sharedLiquidity.d.ts +12 -7
  26. package/lib/cjs/utils.d.ts +2 -2
  27. package/lib/cjs/utils.js +4 -2
  28. package/lib/esm/abis.d.ts +1 -1
  29. package/lib/esm/abis.js +1 -1
  30. package/lib/esm/blue/abis.d.ts +1 -1
  31. package/lib/esm/blue/abis.js +1 -1
  32. package/lib/esm/blue/entities.d.ts +4 -4
  33. package/lib/esm/blue/entities.js +2 -2
  34. package/lib/esm/blue/errors.d.ts +2 -2
  35. package/lib/esm/blue/errors.js +2 -2
  36. package/lib/esm/blue/fetch.d.ts +2 -2
  37. package/lib/esm/blue/fetch.js +2 -2
  38. package/lib/esm/blue/utils.d.ts +1 -1
  39. package/lib/esm/blue/utils.js +1 -1
  40. package/lib/esm/entities/index.d.ts +4 -4
  41. package/lib/esm/entities/index.js +2 -2
  42. package/lib/esm/entities/vaultV2/vaultV2.d.ts +33 -9
  43. package/lib/esm/entities/vaultV2/vaultV2.js +33 -1
  44. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +17 -9
  45. package/lib/esm/entities/vaultV2BlueReallocationData.js +51 -17
  46. package/lib/esm/errors.d.ts +4 -4
  47. package/lib/esm/errors.js +4 -4
  48. package/lib/esm/fetch.d.ts +2 -2
  49. package/lib/esm/fetch.js +2 -2
  50. package/lib/esm/midnight/errors.d.ts +2 -1
  51. package/lib/esm/midnight/errors.js +2 -1
  52. package/lib/esm/types/sharedLiquidity.d.ts +12 -7
  53. package/lib/esm/utils.d.ts +2 -2
  54. package/lib/esm/utils.js +2 -2
  55. package/package.json +6 -6
@@ -1,8 +1,8 @@
1
- export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
1
+ export { AccrualPosition as BlueAccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MidnightAdapter, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, AssetBalances, ConstantWrappedToken, Eip5267Domain, ExchangeRateWrappedToken, Holding, Market as BlueMarket, MarketParams as BlueMarketParams, Position as BluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  PreLiquidationParams as BluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
5
+ PreLiquidationPosition as BluePreLiquidationPosition, Token, User as BlueUser, Vault, VaultConfig, VaultMarketAllocation, VaultMarketConfig, VaultToken, VaultUser, VaultV2, VaultV2Adapter, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2MidnightAdapter, VaultV2MorphoMarketV1Adapter, VaultV2MorphoMarketV1AdapterV2, VaultV2MorphoVaultV1Adapter, WrappedToken, } from "@morpho-org/blue-sdk";
6
6
  export { AccrualPosition as MidnightAccrualPosition, Group as MidnightGroup, Market as MidnightMarket, MarketParams as MidnightMarketParams, Offer as MidnightOffer, Position as MidnightPosition, Tree as MidnightTree, } from "@morpho-org/midnight-sdk";
7
7
  export { MorphoBlue } from "./blue/index.js";
8
8
  export { MorphoMidnight, } from "./midnight/index.js";
@@ -69,8 +69,9 @@ export interface VaultV2Actions {
69
69
  * owner is consumed and none was passed explicitly.
70
70
  * @throws {Permit2SignatureTransferNonceAlreadyUsedError} from `getRequirements()` when the
71
71
  * explicit Permit2 nonce is consumed.
72
- * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, or from
73
- * `getRequirements()` when the Permit2 nonce exceeds uint256.
72
+ * @throws {InputExceedsMaxError} when funding or the deadline exceeds uint256, when the vault's
73
+ * liquidity adapter is a Midnight adapter (it cannot receive vault allocations, so no deposit
74
+ * fits and `max` is `0n`), or from `getRequirements()` when the Permit2 nonce exceeds uint256.
74
75
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple token signatures are supplied.
75
76
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
76
77
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
@@ -153,7 +154,9 @@ export interface VaultV2Actions {
153
154
  * @throws {NonPositiveInputError} when `amount` or the computed share cap is not positive.
154
155
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
155
156
  * at any `getRequirements()` call.
156
- * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
157
+ * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation,
158
+ * or when the vault's liquidity adapter is a Midnight adapter and `amount` exceeds the vault's
159
+ * idle assets.
157
160
  * @throws {NegativeInputError} when `referralFeePct` or `slippageTolerance` is negative.
158
161
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
159
162
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no nonzero recipient.
@@ -218,7 +221,24 @@ export interface VaultV2Actions {
218
221
  * @throws {NonPositiveInputError} when `shares` is not positive.
219
222
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
220
223
  * requirement resolution.
221
- * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256.
224
+ * @throws {InputExceedsMaxError} when `shares` or `deadline` exceeds uint256, or from
225
+ * `getRequirements()` when the vault's liquidity adapter is a Midnight adapter and `shares`
226
+ * are worth more than the vault's idle assets.
227
+ * @throws {UnknownBlueFactory} from `getRequirements()` when the configured chain has no VaultV2 factory.
228
+ * @throws {UnknownBlueOfFactory} from `getRequirements()` when the vault is not a VaultV2 from the
229
+ * configured factory.
230
+ * @throws {UnsupportedBlueVaultV2AdapterError} from `getRequirements()` when the vault or one of its
231
+ * adapters uses an unsupported adapter class.
232
+ * @throws {UnsupportedBlueMarketIrmError} from `getRequirements()` when the vault's liquidity adapter
233
+ * is a Midnight adapter and accrual projects an underlying market with positive debt that uses an
234
+ * unsupported IRM.
235
+ * @throws {UnknownBlueMarketAllocationError} from `getRequirements()` when the vault's liquidity
236
+ * adapter is a Midnight adapter and accrual meets a nested Vault V1 withdraw queue market without
237
+ * allocation data.
238
+ * @throws {InvalidMidnightPositionLossFactorError} from `getRequirements()` when the vault's liquidity
239
+ * adapter is a Midnight adapter and accrual meets a market loss factor below a position's.
240
+ * @throws {InvalidMidnightPositionAccrualStateError} from `getRequirements()` when the vault's
241
+ * liquidity adapter is a Midnight adapter and accrual meets invalid Midnight position inputs.
222
242
  * @throws {NegativeInputError} when `referralFeePct` is negative.
223
243
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
224
244
  * @throws {ReferralFeeRecipientMissingError} when a positive fee has no non-zero recipient.
@@ -226,7 +246,7 @@ export interface VaultV2Actions {
226
246
  * @throws {UnknownAddressError} when VaultBundlesV1 is not registered on the target chain.
227
247
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
228
248
  * contract has no code at its registered address.
229
- * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, `eth_chainId`, or
249
+ * @throws {viem.BaseError} from `getRequirements()` when a vault-state, allowance, nonce, `eth_chainId`, or
230
250
  * `eth_getCode` read fails.
231
251
  * @throws {UnknownTokenError} from `getRequirements()` when the share token fetched by
232
252
  * `getData()` has unusable decimals.
@@ -303,9 +323,11 @@ export interface VaultV2Actions {
303
323
  * @throws {InputExceedsMaxError} when `deadline` exceeds `uint256`.
304
324
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
305
325
  * requirement resolution.
306
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter.
326
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have one adapter, including
327
+ * a vault that mixes Blue and Midnight adapters.
307
328
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
308
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
329
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
330
+ * including a Midnight adapter.
309
331
  * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
310
332
  * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
311
333
  * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
@@ -429,9 +451,11 @@ export interface VaultV2Actions {
429
451
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
430
452
  * requirement resolution.
431
453
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
432
- * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter.
454
+ * @throws {VaultV2SingleAdapterRequiredError} when the vault does not have exactly one adapter,
455
+ * including a vault that mixes Blue and Midnight adapters.
433
456
  * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
434
- * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
457
+ * @throws {VaultV2UnsupportedExitAdapterError} when the adapter is not a MorphoMarketV1AdapterV2,
458
+ * including a Midnight adapter.
435
459
  * @throws {VaultV2UnsupportedLiquidityAdapterError} when the vault routes liquidity through
436
460
  * another adapter.
437
461
  * @throws {VaultV2UndecodableLiquidityDataError} when the vault's `liquidityData` does not decode
@@ -16,6 +16,11 @@ import { getBundlesTokenRequirements } from "../requirements/index.js";
16
16
  // Maximum accepted deadline horizon; the on-chain management fee is capped at 5%/yr so the
17
17
  // accrual model stays well-defined inside it.
18
18
  const VAULT_V2_FEE_PROJECTION_HORIZON = Time.s.from.y(1n);
19
+ /**
20
+ * Midnight adapters revert vault-initiated `allocate` and `deallocate` (`SelfAllocationOnly`), so a
21
+ * vault routing liquidity through one accepts no deposit and serves exits from idle assets only.
22
+ */
23
+ const isMidnightLiquidityAdapter = (vaultData) => vaultData.accrualLiquidityAdapter?.type === "VaultV2MidnightAdapter";
19
24
  /** Binds a viem client to a Vault V2 vault's action builders. */
20
25
  export class MorphoVaultV2 {
21
26
  client;
@@ -79,6 +84,13 @@ export class MorphoVaultV2 {
79
84
  // The native path must target the chain's registered wrapped-native asset.
80
85
  validateNativeVaultAsset(this.chainId, vaultAsset);
81
86
  }
87
+ if (isMidnightLiquidityAdapter(vaultData)) {
88
+ throw new InputExceedsMaxError({
89
+ field: funding.value > 0n ? "nativeAmount" : "amount",
90
+ value: funding.assets,
91
+ max: 0n,
92
+ });
93
+ }
82
94
  const referralFeeAssets = getBundlesReferralFeeAssets(funding.assets, common.referralFeePct);
83
95
  const maxSharePrice = computeVaultMaxSharePrice({
84
96
  vaultData,
@@ -162,6 +174,14 @@ export class MorphoVaultV2 {
162
174
  throw new NonPositiveInputError("amount", amount);
163
175
  // Reject values outside the ABI range before resolving any requirements.
164
176
  validateUint256Field("amount", amount);
177
+ if (isMidnightLiquidityAdapter(vaultData) &&
178
+ amount > vaultData.assetBalance) {
179
+ throw new InputExceedsMaxError({
180
+ field: "amount",
181
+ value: amount,
182
+ max: vaultData.assetBalance,
183
+ });
184
+ }
165
185
  const createdAt = Time.timestamp();
166
186
  const deadline = params.deadline ?? createdAt + Time.s.from.h(2n);
167
187
  if (deadline <= createdAt)
@@ -252,8 +272,20 @@ export class MorphoVaultV2 {
252
272
  if (deadline <= now)
253
273
  throw new ExpiredDeadlineError(deadline, now);
254
274
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
275
+ const vaultData = await this.getData();
276
+ if (isMidnightLiquidityAdapter(vaultData)) {
277
+ // Onchain redeem accrues interest before converting shares to assets.
278
+ const { vault: accrued } = vaultData.accrueInterest(now);
279
+ if (accrued.toAssets(shares) > accrued.assetBalance) {
280
+ throw new InputExceedsMaxError({
281
+ field: "shares",
282
+ value: shares,
283
+ max: accrued.toShares(accrued.assetBalance),
284
+ });
285
+ }
286
+ }
255
287
  return getVaultBundlesSharesRequirements(this.client.viemClient, {
256
- vaultData: await this.getData(),
288
+ vaultData,
257
289
  version: "vaultV2",
258
290
  owner: userAddress,
259
291
  chainId: this.chainId,
@@ -39,8 +39,9 @@ export interface InputVaultV2BlueReallocationData {
39
39
  /**
40
40
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
41
41
  *
42
- * Constructor inputs are cloned. Every simulated reallocation returns a new
43
- * instance. Planning keeps the transaction-scoped `firstTotalAssets`
42
+ * Constructor inputs are cloned, except Midnight adapter snapshots: those are
43
+ * shared by reference and must be treated as read-only. Every simulated
44
+ * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
44
45
  * denominator outside the durable snapshot while applying reallocations in
45
46
  * contract order. Penalty donations update simulated vault accounting but are
46
47
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -100,7 +101,8 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
100
101
  /**
101
102
  * Clones the complete simulation snapshot.
102
103
  *
103
- * @returns A deep clone of this simulation state.
104
+ * @returns A deep clone of this simulation state. Midnight adapter snapshots are
105
+ * shared by reference and must be treated as read-only.
104
106
  * @example
105
107
  * ```ts
106
108
  * import { markets } from "@morpho-org/morpho-test";
@@ -369,12 +371,18 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
369
371
  * (two hours by default; `0n` disables it). When an operation's plan would
370
372
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
371
373
  * BluePublicAllocator cap, the plan is reduced to the larger of the
372
- * operation's absolute shortfall and what vaults below their cap moved. The
373
- * kept headroom absorbs other allocations up to that share of the cap landing
374
- * before inclusion. The plan uses the full cap only when the shortfall needs
375
- * it, and can then still revert if another allocation lands first. A plan of
376
- * only the shortfall leaves the market fully utilized, so a competing borrow
377
- * or withdraw landing first can also make it revert. For market-source reallocations
374
+ * operation's absolute shortfall and what unbound legs moved (legs that
375
+ * neither come within the headroom of an allocator cap nor take nearly all
376
+ * of their source vault's idle). The kept headroom absorbs other allocations
377
+ * up to that share of the cap landing before inclusion. The plan uses the
378
+ * full cap only when the shortfall needs it, and can then still revert if
379
+ * another allocation lands first.
380
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
381
+ * vault's starting idle are bound the same way, so an operation without
382
+ * shortfall whose plan draws only on such idle plans no reallocation.
383
+ * A plan of only the shortfall leaves the market fully utilized, so a
384
+ * competing borrow or withdraw landing first can also make it revert. For
385
+ * market-source reallocations
378
386
  * the source position's interest is also reserved on cap ids shared with the
379
387
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
380
388
  * or allocator capacity are skipped before projecting source interest. The
@@ -75,6 +75,10 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
75
75
  position: clonePosition(position, markets),
76
76
  })));
77
77
  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;
78
82
  const base = {
79
83
  address: adapter.address,
80
84
  parentVault: adapter.parentVault,
@@ -122,8 +126,9 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
122
126
  /**
123
127
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
124
128
  *
125
- * Constructor inputs are cloned. Every simulated reallocation returns a new
126
- * instance. Planning keeps the transaction-scoped `firstTotalAssets`
129
+ * Constructor inputs are cloned, except Midnight adapter snapshots: those are
130
+ * shared by reference and must be treated as read-only. Every simulated
131
+ * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
127
132
  * denominator outside the durable snapshot while applying reallocations in
128
133
  * contract order. Penalty donations update simulated vault accounting but are
129
134
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -245,7 +250,8 @@ export class VaultV2BlueReallocationData {
245
250
  /**
246
251
  * Clones the complete simulation snapshot.
247
252
  *
248
- * @returns A deep clone of this simulation state.
253
+ * @returns A deep clone of this simulation state. Midnight adapter snapshots are
254
+ * shared by reference and must be treated as read-only.
249
255
  * @example
250
256
  * ```ts
251
257
  * import { markets } from "@morpho-org/morpho-test";
@@ -567,12 +573,18 @@ export class VaultV2BlueReallocationData {
567
573
  * (two hours by default; `0n` disables it). When an operation's plan would
568
574
  * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
569
575
  * BluePublicAllocator cap, the plan is reduced to the larger of the
570
- * operation's absolute shortfall and what vaults below their cap moved. The
571
- * kept headroom absorbs other allocations up to that share of the cap landing
572
- * before inclusion. The plan uses the full cap only when the shortfall needs
573
- * it, and can then still revert if another allocation lands first. A plan of
574
- * only the shortfall leaves the market fully utilized, so a competing borrow
575
- * or withdraw landing first can also make it revert. For market-source reallocations
576
+ * operation's absolute shortfall and what unbound legs moved (legs that
577
+ * neither come within the headroom of an allocator cap nor take nearly all
578
+ * of their source vault's idle). The kept headroom absorbs other allocations
579
+ * up to that share of the cap landing before inclusion. The plan uses the
580
+ * full cap only when the shortfall needs it, and can then still revert if
581
+ * another allocation lands first.
582
+ * Idle legs that together leave at most `allocatorCapHeadroom` of a source
583
+ * vault's starting idle are bound the same way, so an operation without
584
+ * shortfall whose plan draws only on such idle plans no reallocation.
585
+ * A plan of only the shortfall leaves the market fully utilized, so a
586
+ * competing borrow or withdraw landing first can also make it revert. For
587
+ * market-source reallocations
576
588
  * the source position's interest is also reserved on cap ids shared with the
577
589
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
578
590
  * or allocator capacity are skipped before projecting source interest. The
@@ -733,29 +745,32 @@ export class VaultV2BlueReallocationData {
733
745
  }
734
746
  // The fallback pass only runs when the plan moves exactly the absolute
735
747
  // shortfall, which a reduced plan would move anyway.
736
- const capBoundTargets = friendly.allocatorCapBoundTargets;
748
+ const allocatorCapBoundTargets = friendly.allocatorCapBoundTargets;
749
+ const idleBoundVaults = friendly.idleBoundVaults;
737
750
  let reallocatedAssets = 0n;
738
751
  let unboundAssets = 0n;
739
- for (const { vault, to, assets } of reallocations) {
752
+ for (const { vault, from, to, assets } of reallocations) {
740
753
  reallocatedAssets += assets;
741
754
  const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
742
- if (!capBoundTargets.has(key))
755
+ if (!allocatorCapBoundTargets.has(key) &&
756
+ !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
743
757
  unboundAssets += assets;
744
758
  }
745
759
  return {
746
760
  reallocations,
747
761
  data,
748
- capBound: capBoundTargets.size > 0,
762
+ liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
749
763
  reallocatedAssets,
750
764
  unboundAssets,
751
765
  };
752
766
  };
753
- // A leg that fills an allocator cap reverts once any other allocation to
754
- // that market lands first. A cap-bound plan therefore moves only the
755
- // operation's shortfall, or what vaults below their cap already moved.
767
+ // A leg that fills an allocator cap, or idle legs that together take
768
+ // (nearly) all of a source vault's starting idle, revert once another
769
+ // allocation lands first. A bound plan therefore moves only the operation's
770
+ // shortfall, or what unbound legs moved.
756
771
  const target = plan(requiredAssets, allocatorCapHeadroom);
757
772
  let selected = target;
758
- if (allocatorCapHeadroom > 0n && target.capBound) {
773
+ if (allocatorCapHeadroom > 0n && target.liquidityBound) {
759
774
  selected = plan(absoluteShortfall > target.unboundAssets
760
775
  ? absoluteShortfall
761
776
  : target.unboundAssets, allocatorCapHeadroom);
@@ -790,6 +805,7 @@ export class VaultV2BlueReallocationData {
790
805
  data: this,
791
806
  context,
792
807
  allocatorCapBoundTargets: new Set(),
808
+ idleBoundVaults: new Set(),
793
809
  };
794
810
  this.getMarket(marketId);
795
811
  const timestamp = options.timestamp == null
@@ -809,6 +825,9 @@ export class VaultV2BlueReallocationData {
809
825
  const activeAdaptersCache = new Map();
810
826
  let remainingAssets = maxAssets;
811
827
  const allocatorCapBoundTargets = new Set();
828
+ const idleBoundVaults = new Set();
829
+ const initialIdleAssets = new Map();
830
+ const idleTakenAssets = new Map();
812
831
  // Onchain, market interest is booked once at transaction start, on pre-plan
813
832
  // positions at pre-plan rates, and stays on touched positions' cap ids.
814
833
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -877,6 +896,9 @@ export class VaultV2BlueReallocationData {
877
896
  const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssetsKey == null
878
897
  ? 0n
879
898
  : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey]);
899
+ const vaultAddressKey = vaultAddress.toLowerCase();
900
+ if (!initialIdleAssets.has(vaultAddressKey))
901
+ initialIdleAssets.set(vaultAddressKey, availableIdleAssets);
880
902
  let activeAdapters = activeAdaptersCache.get(vaultAddress);
881
903
  if (activeAdapters == null) {
882
904
  activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
@@ -1101,11 +1123,22 @@ export class VaultV2BlueReallocationData {
1101
1123
  data,
1102
1124
  context: simulationContext,
1103
1125
  allocatorCapBoundTargets,
1126
+ idleBoundVaults,
1104
1127
  };
1105
1128
  const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1106
1129
  if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1107
1130
  // BluePublicAllocator caps are per vault and target adapter.
1108
1131
  allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1132
+ if (acceptedReallocation.from.type === "idle") {
1133
+ const vaultKey = acceptedReallocation.vault.toLowerCase();
1134
+ const taken = (idleTakenAssets.get(vaultKey) ?? 0n) + acceptedReallocation.assets;
1135
+ idleTakenAssets.set(vaultKey, taken);
1136
+ // Candidates always record this; a missing entry counts the vault as bound.
1137
+ const initial = initialIdleAssets.get(vaultKey) ?? 0n;
1138
+ if (taken >=
1139
+ MathLib.zeroFloorSub(initial, MathLib.wMulUp(initial, allocatorCapHeadroom)))
1140
+ idleBoundVaults.add(vaultKey);
1141
+ }
1109
1142
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1110
1143
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1111
1144
  if (touchedVaultPairs == null) {
@@ -1135,6 +1168,7 @@ export class VaultV2BlueReallocationData {
1135
1168
  data,
1136
1169
  context: simulationContext,
1137
1170
  allocatorCapBoundTargets,
1171
+ idleBoundVaults,
1138
1172
  };
1139
1173
  }
1140
1174
  /**
@@ -1,7 +1,7 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -1,6 +1,6 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
package/lib/esm/fetch.js CHANGED
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
@@ -1 +1,2 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
2
+ export { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
@@ -1 +1,2 @@
1
- export { ChainIdMismatchError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
1
+ export { ChainIdMismatchError, InvalidEcrecoverSignatureVError, InvalidMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError, InvalidOfferParameterError, InvalidRateRatifierV1RateError, InvalidRateRatifierV1TickError, InvalidRateRatifierV1TimeError, InvalidRatifierV1AddressError, InvalidTickSpacingError, InvalidTreeError, InvalidTreeHeightError, InvalidTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError, PriceGreaterThanOneError, RateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError, TickOutOfRangeError, UnknownCollateralIndexError, } from "@morpho-org/midnight-sdk";
2
+ export { InvalidPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionLossFactorError, } from "@morpho-org/morpho-ts";
@@ -28,15 +28,20 @@ export interface VaultV2BluePublicAllocatorOptions {
28
28
  * Share of each target-market BluePublicAllocator cap, scaled by WAD, that
29
29
  * operation planning keeps free. When a reallocation toward the utilization
30
30
  * target would come within this headroom of the cap, the plan is reduced to
31
- * the larger of the operation's absolute shortfall and what vaults below
32
- * their cap were already moving. A plan of only the shortfall leaves the
33
- * market fully utilized, so a competing borrow or withdraw landing first can
34
- * still make it revert. If the shortfall cannot be covered while keeping the
35
- * headroom, the plan uses the full cap, first for the shortfall only and
36
- * then toward the utilization target if that is still short.
31
+ * the larger of the operation's absolute shortfall and what unbound legs
32
+ * were already moving (legs that neither come within the headroom of an
33
+ * allocator cap nor take nearly all of their source vault's idle). A plan of
34
+ * only the shortfall leaves the market fully utilized, so a competing borrow
35
+ * or withdraw landing first can still make it revert. If the shortfall cannot
36
+ * be covered while keeping the headroom, the plan uses the full cap, first for
37
+ * the shortfall only and then toward the utilization target if that is still
38
+ * short.
39
+ * The same share marks idle legs as bound: idle legs that together leave at
40
+ * most this share of a source vault's starting idle reduce the plan the same
41
+ * way, since any idle withdrawal landing first would make it revert.
37
42
  * Discovery plans, `getPublicReallocationLiquidity` and
38
43
  * `getAvailableLiquidityToUtilization` ignore it and use the full cap.
39
- * Must not exceed WAD (100%). Set to `0n` to disable.
44
+ * Must not exceed WAD (100%). Set to `0n` to disable both rules.
40
45
  *
41
46
  * @default DEFAULT_ALLOCATOR_CAP_HEADROOM (1%)
42
47
  */
@@ -3,7 +3,7 @@ export { AdaptiveCurveIrmLib as BlueAdaptiveCurveIrmLib, CapacityLimitReason,
3
3
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
4
4
  defaultPreLiquidationParamsRegistry as blueDefaultPreLiquidationParamsRegistry,
5
5
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
6
- getDefaultPreLiquidationParams as getBlueDefaultPreLiquidationParams, MarketUtils as BlueMarketUtils, MathLib, SharesMath as BlueSharesMath, VaultUtils, VaultV2BlueMarketPublicAllocatorConfigUtils, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
6
+ getDefaultPreLiquidationParams as getBlueDefaultPreLiquidationParams, MarketUtils as BlueMarketUtils, MathLib, SharesMath as BlueSharesMath, VaultUtils, VaultV2BlueMarketPublicAllocatorConfigUtils, VaultV2BluePublicAllocatorConfigUtils, VaultV2MidnightAdapterUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
7
7
  export { catchRevertOnly, decodeBytes32String, getAuthorizationTypedData as getBlueAuthorizationTypedData, getPermit2PermitTypedData, getPermit2TransferFromTypedData, getPermitTypedData, isContractRevertError, isTransportError, isUndecodableResultError, MetaMorphoAction as BlueMetaMorphoAction, optionalBoolean, readContractRestructured, restructure, safeGetAddress, safeParseNumber, safeParseUnits, } from "@morpho-org/blue-sdk-viem";
8
8
  export { EcrecoverRatifier as MidnightEcrecoverRatifier,
9
9
  /** @deprecated Use MidnightEcrecoverRatifier with a tagged tree. */
@@ -17,7 +17,7 @@ RatifierUtils as MidnightRatifierUtils, SetterRatifier as MidnightSetterRatifier
17
17
  /** @deprecated Use MidnightSetterRatifier with a tagged tree. */
18
18
  SetterRatifierUtils as MidnightSetterRatifierUtils, TakeAmountsLib as MidnightTakeAmountsLib, TickLib as MidnightTickLib, TreeUtils as MidnightTreeUtils, } from "@morpho-org/midnight-sdk";
19
19
  export type { ArrayElementType, DeepPartial, DottedKeys, FieldType, PartialDottedKeys, } from "@morpho-org/morpho-ts";
20
- export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries, filterDefined, fromEntries, getLast, getLastDefined, getSubdomainBaseUrl, getValue, hasValue, isDefined, isNotNull, isNotUndefined, keys, mergeEntries, retryPromiseLinearBackoff, Time, transformValue, values, } from "@morpho-org/morpho-ts";
20
+ export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries, filterDefined, fromEntries, getLast, getLastDefined, getSubdomainBaseUrl, getValue, hasValue, isDefined, isNotNull, isNotUndefined, keys, MidnightPositionLib, mergeEntries, retryPromiseLinearBackoff, Time, transformValue, values, } from "@morpho-org/morpho-ts";
21
21
  export { validateClientChainId } from "./actions/requirements/validateClientChainId.js";
22
22
  export { addTransactionMetadata } from "./helpers/metadata.js";
23
23
  export { type PreviewVaultV2ForceWithdrawParams, previewVaultV2ForceWithdraw, type VaultV2ForceWithdrawPreview, } from "./helpers/previewVaultV2ForceWithdraw.js";
package/lib/esm/utils.js CHANGED
@@ -2,7 +2,7 @@ export { AdaptiveCurveIrmLib as BlueAdaptiveCurveIrmLib, CapacityLimitReason,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  defaultPreLiquidationParamsRegistry as blueDefaultPreLiquidationParamsRegistry,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- getDefaultPreLiquidationParams as getBlueDefaultPreLiquidationParams, MarketUtils as BlueMarketUtils, MathLib, SharesMath as BlueSharesMath, VaultUtils, VaultV2BlueMarketPublicAllocatorConfigUtils, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
5
+ getDefaultPreLiquidationParams as getBlueDefaultPreLiquidationParams, MarketUtils as BlueMarketUtils, MathLib, SharesMath as BlueSharesMath, VaultUtils, VaultV2BlueMarketPublicAllocatorConfigUtils, VaultV2BluePublicAllocatorConfigUtils, VaultV2MidnightAdapterUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
6
6
  export { catchRevertOnly, decodeBytes32String, getAuthorizationTypedData as getBlueAuthorizationTypedData, getPermit2PermitTypedData, getPermit2TransferFromTypedData, getPermitTypedData, isContractRevertError, isTransportError, isUndecodableResultError, MetaMorphoAction as BlueMetaMorphoAction, optionalBoolean, readContractRestructured, restructure, safeGetAddress, safeParseNumber, safeParseUnits, } from "@morpho-org/blue-sdk-viem";
7
7
  export { EcrecoverRatifier as MidnightEcrecoverRatifier,
8
8
  /** @deprecated Use MidnightEcrecoverRatifier with a tagged tree. */
@@ -15,7 +15,7 @@ RateRatifierV1Utils as MidnightRateRatifierV1Utils, Ratifier as MidnightRatifier
15
15
  RatifierUtils as MidnightRatifierUtils, SetterRatifier as MidnightSetterRatifier,
16
16
  /** @deprecated Use MidnightSetterRatifier with a tagged tree. */
17
17
  SetterRatifierUtils as MidnightSetterRatifierUtils, TakeAmountsLib as MidnightTakeAmountsLib, TickLib as MidnightTickLib, TreeUtils as MidnightTreeUtils, } from "@morpho-org/midnight-sdk";
18
- export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries, filterDefined, fromEntries, getLast, getLastDefined, getSubdomainBaseUrl, getValue, hasValue, isDefined, isNotNull, isNotUndefined, keys, mergeEntries, retryPromiseLinearBackoff, Time, transformValue, values, } from "@morpho-org/morpho-ts";
18
+ export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries, filterDefined, fromEntries, getLast, getLastDefined, getSubdomainBaseUrl, getValue, hasValue, isDefined, isNotNull, isNotUndefined, keys, MidnightPositionLib, mergeEntries, retryPromiseLinearBackoff, Time, transformValue, values, } from "@morpho-org/morpho-ts";
19
19
  export { validateClientChainId } from "./actions/requirements/validateClientChainId.js";
20
20
  export { addTransactionMetadata } from "./helpers/metadata.js";
21
21
  export { previewVaultV2ForceWithdraw, } from "./helpers/previewVaultV2ForceWithdraw.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@morpho-org/morpho-sdk",
3
3
  "description": "Abstraction layer for Morpho's complexity.",
4
- "version": "8.1.0",
4
+ "version": "8.2.0-next.0",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "repository": {
7
7
  "type": "git",
@@ -152,17 +152,17 @@
152
152
  "MIGRATION-v7-to-v8.md"
153
153
  ],
154
154
  "dependencies": {
155
- "@morpho-org/blue-sdk": "^8.0.1",
156
- "@morpho-org/blue-sdk-viem": "^7.0.0",
157
- "@morpho-org/midnight-sdk": "^2.1.0",
158
- "@morpho-org/morpho-ts": "^4.0.1"
155
+ "@morpho-org/blue-sdk": "^8.1.0-next.0",
156
+ "@morpho-org/blue-sdk-viem": "^7.1.0-next.0",
157
+ "@morpho-org/midnight-sdk": "^2.2.0-next.0",
158
+ "@morpho-org/morpho-ts": "^4.1.0-next.0"
159
159
  },
160
160
  "peerDependencies": {
161
161
  "viem": "^2.0.0"
162
162
  },
163
163
  "devDependencies": {
164
164
  "@morpho-org/morpho-test": "^4.1.0",
165
- "@morpho-org/test": "^2.11.0",
165
+ "@morpho-org/test": "^2.12.0-next.0",
166
166
  "fast-check": "^4.9.0",
167
167
  "typescript": "7.0.2",
168
168
  "viem": "^2.55.10",