@morpho-org/morpho-sdk 6.4.0 → 6.6.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 (35) hide show
  1. package/lib/cjs/blue/errors.d.ts +1 -1
  2. package/lib/cjs/blue/errors.js +4 -1
  3. package/lib/cjs/constants.d.ts +1 -1
  4. package/lib/cjs/constants.js +2 -1
  5. package/lib/cjs/entities/blue/blue.d.ts +10 -6
  6. package/lib/cjs/entities/blue/blue.js +5 -3
  7. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +11 -3
  8. package/lib/cjs/entities/vaultV2BlueReallocationData.js +119 -43
  9. package/lib/cjs/errors.d.ts +1 -1
  10. package/lib/cjs/errors.js +5 -2
  11. package/lib/cjs/helpers/constant.d.ts +8 -0
  12. package/lib/cjs/helpers/constant.js +9 -1
  13. package/lib/cjs/helpers/index.d.ts +1 -1
  14. package/lib/cjs/helpers/index.js +2 -1
  15. package/lib/cjs/helpers/utilization.d.ts +13 -0
  16. package/lib/cjs/helpers/utilization.js +26 -1
  17. package/lib/cjs/types/sharedLiquidity.d.ts +17 -0
  18. package/lib/esm/blue/errors.d.ts +1 -1
  19. package/lib/esm/blue/errors.js +1 -1
  20. package/lib/esm/constants.d.ts +1 -1
  21. package/lib/esm/constants.js +1 -1
  22. package/lib/esm/entities/blue/blue.d.ts +10 -6
  23. package/lib/esm/entities/blue/blue.js +5 -3
  24. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +11 -3
  25. package/lib/esm/entities/vaultV2BlueReallocationData.js +120 -44
  26. package/lib/esm/errors.d.ts +1 -1
  27. package/lib/esm/errors.js +1 -1
  28. package/lib/esm/helpers/constant.d.ts +8 -0
  29. package/lib/esm/helpers/constant.js +8 -0
  30. package/lib/esm/helpers/index.d.ts +1 -1
  31. package/lib/esm/helpers/index.js +1 -1
  32. package/lib/esm/helpers/utilization.d.ts +13 -0
  33. package/lib/esm/helpers/utilization.js +25 -1
  34. package/lib/esm/types/sharedLiquidity.d.ts +17 -0
  35. package/package.json +4 -4
@@ -1,4 +1,4 @@
1
1
  export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidAddressError, InvalidBitLengthError, InvalidMarketParamsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MarketParamsIdMismatchError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
4
+ export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MarketParamsIdMismatchError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
@@ -1,4 +1,4 @@
1
1
  export { DEFAULT_SLIPPAGE_TOLERANCE, EIP_712_FIELDS, ERC20_ALLOWANCE_RECIPIENTS, isMarketId as isBlueMarketId, LIQUIDATION_CURSOR as BLUE_LIQUIDATION_CURSOR, MAX_LIQUIDATION_INCENTIVE_FACTOR as BLUE_MAX_LIQUIDATION_INCENTIVE_FACTOR, ORACLE_PRICE_SCALE, SECONDS_PER_YEAR, TransactionType as BlueTransactionType, } from "@morpho-org/blue-sdk";
2
2
  export { CBP as MIDNIGHT_CBP, COLLATERAL_PARAMS_TYPEHASH as MIDNIGHT_COLLATERAL_PARAMS_TYPEHASH, DEFAULT_TICK_SPACING as MIDNIGHT_DEFAULT_TICK_SPACING, EIP712_DOMAIN_TYPEHASH as MIDNIGHT_EIP712_DOMAIN_TYPEHASH, MARKET_TYPEHASH as MIDNIGHT_MARKET_TYPEHASH, MAX_COLLATERALS as MIDNIGHT_MAX_COLLATERALS, MAX_COLLATERALS_PER_BORROWER as MIDNIGHT_MAX_COLLATERALS_PER_BORROWER, MAX_CONTINUOUS_FEE as MIDNIGHT_MAX_CONTINUOUS_FEE, MAX_OFFER_CAP as MIDNIGHT_MAX_OFFER_CAP, MAX_SETTLEMENT_FEES as MIDNIGHT_MAX_SETTLEMENT_FEES, MAX_TICK as MIDNIGHT_MAX_TICK, MAX_TREE_HEIGHT as MIDNIGHT_MAX_TREE_HEIGHT, OFFER_TYPEHASH as MIDNIGHT_OFFER_TYPEHASH, PRICE_RATIFIER_V1_OFFER_TYPEHASH as MIDNIGHT_PRICE_RATIFIER_V1_OFFER_TYPEHASH, PRICE_ROUNDING_STEP as MIDNIGHT_PRICE_ROUNDING_STEP, RATE_RATIFIER_V1_OFFER_TYPEHASH as MIDNIGHT_RATE_RATIFIER_V1_OFFER_TYPEHASH, SETTLEMENT_FEE_BREAKPOINTS as MIDNIGHT_SETTLEMENT_FEE_BREAKPOINTS, TIME_TO_MAX_LIF as MIDNIGHT_TIME_TO_MAX_LIF, } from "@morpho-org/midnight-sdk";
3
3
  export { BLUE_API_BASE_URL, BLUE_API_GRAPHQL_URL, ChainId, ChainUtils, DOCS_BASE_URL, MORPHO_DOMAIN, REWARDS_BASE_URL, ZERO_ADDRESS, } from "@morpho-org/morpho-ts";
4
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./helpers/constant.js";
4
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./helpers/constant.js";
@@ -1,4 +1,4 @@
1
1
  export { DEFAULT_SLIPPAGE_TOLERANCE, EIP_712_FIELDS, ERC20_ALLOWANCE_RECIPIENTS, isMarketId as isBlueMarketId, LIQUIDATION_CURSOR as BLUE_LIQUIDATION_CURSOR, MAX_LIQUIDATION_INCENTIVE_FACTOR as BLUE_MAX_LIQUIDATION_INCENTIVE_FACTOR, ORACLE_PRICE_SCALE, SECONDS_PER_YEAR, TransactionType as BlueTransactionType, } from "@morpho-org/blue-sdk";
2
2
  export { CBP as MIDNIGHT_CBP, COLLATERAL_PARAMS_TYPEHASH as MIDNIGHT_COLLATERAL_PARAMS_TYPEHASH, DEFAULT_TICK_SPACING as MIDNIGHT_DEFAULT_TICK_SPACING, EIP712_DOMAIN_TYPEHASH as MIDNIGHT_EIP712_DOMAIN_TYPEHASH, MARKET_TYPEHASH as MIDNIGHT_MARKET_TYPEHASH, MAX_COLLATERALS as MIDNIGHT_MAX_COLLATERALS, MAX_COLLATERALS_PER_BORROWER as MIDNIGHT_MAX_COLLATERALS_PER_BORROWER, MAX_CONTINUOUS_FEE as MIDNIGHT_MAX_CONTINUOUS_FEE, MAX_OFFER_CAP as MIDNIGHT_MAX_OFFER_CAP, MAX_SETTLEMENT_FEES as MIDNIGHT_MAX_SETTLEMENT_FEES, MAX_TICK as MIDNIGHT_MAX_TICK, MAX_TREE_HEIGHT as MIDNIGHT_MAX_TREE_HEIGHT, OFFER_TYPEHASH as MIDNIGHT_OFFER_TYPEHASH, PRICE_RATIFIER_V1_OFFER_TYPEHASH as MIDNIGHT_PRICE_RATIFIER_V1_OFFER_TYPEHASH, PRICE_ROUNDING_STEP as MIDNIGHT_PRICE_ROUNDING_STEP, RATE_RATIFIER_V1_OFFER_TYPEHASH as MIDNIGHT_RATE_RATIFIER_V1_OFFER_TYPEHASH, SETTLEMENT_FEE_BREAKPOINTS as MIDNIGHT_SETTLEMENT_FEE_BREAKPOINTS, TIME_TO_MAX_LIF as MIDNIGHT_TIME_TO_MAX_LIF, } from "@morpho-org/midnight-sdk";
3
3
  export { BLUE_API_BASE_URL, BLUE_API_GRAPHQL_URL, ChainId, ChainUtils, DOCS_BASE_URL, MORPHO_DOMAIN, REWARDS_BASE_URL, ZERO_ADDRESS, } from "@morpho-org/morpho-ts";
4
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./helpers/constant.js";
4
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./helpers/constant.js";
@@ -819,15 +819,17 @@ export interface BlueActions {
819
819
  * allocation through `timestamp + capAccrualBuffer` (two hours by default;
820
820
  * `0n` disables it). For market-source reallocations the source position's
821
821
  * interest is also reserved on cap ids shared with the target, and reserves
822
- * persist across every leg of a plan.
822
+ * persist across every leg of a plan. Operation plans keep
823
+ * `allocatorCapHeadroom` (1% of the cap by default) free under each target
824
+ * BluePublicAllocator cap unless the operation shortfall needs it.
823
825
  *
824
826
  * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}.
825
827
  * @param params.options - Optional allocator discovery controls and operation to support.
826
828
  * @returns Action-ready reallocations and their post-simulation state.
827
829
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
828
830
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
829
- * @throws {NegativeInputError} when the cap-accrual buffer, utilization, or penalty limit is negative.
830
- * @throws {InputExceedsMaxError} when a utilization or penalty limit exceeds WAD.
831
+ * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, or penalty limit is negative.
832
+ * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
831
833
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
832
834
  * @throws {UnknownReallocationMarketError} when a required market is absent.
833
835
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -1037,15 +1039,17 @@ export declare class MorphoBlue implements BlueActions {
1037
1039
  * allocation through `timestamp + capAccrualBuffer` (two hours by default;
1038
1040
  * `0n` disables it). For market-source reallocations the source position's
1039
1041
  * interest is also reserved on cap ids shared with the target, and reserves
1040
- * persist across every leg of a plan.
1042
+ * persist across every leg of a plan. Operation plans keep
1043
+ * `allocatorCapHeadroom` (1% of the cap by default) free under each target
1044
+ * BluePublicAllocator cap unless the operation shortfall needs it.
1041
1045
  *
1042
1046
  * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}.
1043
1047
  * @param params.options - Optional allocator discovery controls and operation to support.
1044
1048
  * @returns Action-ready reallocations and their post-simulation state.
1045
1049
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
1046
1050
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
1047
- * @throws {NegativeInputError} when the cap-accrual buffer, utilization, or penalty limit is negative.
1048
- * @throws {InputExceedsMaxError} when a utilization or penalty limit exceeds WAD.
1051
+ * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, or penalty limit is negative.
1052
+ * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
1049
1053
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
1050
1054
  * @throws {UnknownReallocationMarketError} when a required market is absent.
1051
1055
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -735,15 +735,17 @@ export class MorphoBlue {
735
735
  * allocation through `timestamp + capAccrualBuffer` (two hours by default;
736
736
  * `0n` disables it). For market-source reallocations the source position's
737
737
  * interest is also reserved on cap ids shared with the target, and reserves
738
- * persist across every leg of a plan.
738
+ * persist across every leg of a plan. Operation plans keep
739
+ * `allocatorCapHeadroom` (1% of the cap by default) free under each target
740
+ * BluePublicAllocator cap unless the operation shortfall needs it.
739
741
  *
740
742
  * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}.
741
743
  * @param params.options - Optional allocator discovery controls and operation to support.
742
744
  * @returns Action-ready reallocations and their post-simulation state.
743
745
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
744
746
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
745
- * @throws {NegativeInputError} when the cap-accrual buffer, utilization, or penalty limit is negative.
746
- * @throws {InputExceedsMaxError} when a utilization or penalty limit exceeds WAD.
747
+ * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, or penalty limit is negative.
748
+ * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
747
749
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
748
750
  * @throws {UnknownReallocationMarketError} when a required market is absent.
749
751
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -366,7 +366,15 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
366
366
  * considered. Market/vault state and the returned post-state stay at
367
367
  * `timestamp`; only target-market cap checks reserve interest the vault's
368
368
  * existing allocation would accrue through `timestamp + capAccrualBuffer`
369
- * (two hours by default; `0n` disables it). For market-source reallocations
369
+ * (two hours by default; `0n` disables it). When an operation's plan would
370
+ * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
371
+ * 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
370
378
  * the source position's interest is also reserved on cap ids shared with the
371
379
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
372
380
  * or allocator capacity are skipped before projecting source interest. The
@@ -392,8 +400,8 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
392
400
  * every leg of a plan.
393
401
  * @returns Flat action-ready reallocations and their post-simulation state.
394
402
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
395
- * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
396
- * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
403
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
404
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
397
405
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
398
406
  * @throws {UnknownReallocationMarketError} when a required market is absent.
399
407
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -2,7 +2,7 @@ import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMark
2
2
  import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
3
3
  import { isAddressEqual } from "viem";
4
4
  import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
5
- import { resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../helpers/utilization.js";
5
+ import { resolveAllocatorCapHeadroom, resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../helpers/utilization.js";
6
6
  import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
7
7
  const MAX_SHARED_CAP_SEARCH_STEPS = 1024n;
8
8
  const createCapReserveState = (markets) => ({
@@ -564,7 +564,15 @@ export class VaultV2BlueReallocationData {
564
564
  * considered. Market/vault state and the returned post-state stay at
565
565
  * `timestamp`; only target-market cap checks reserve interest the vault's
566
566
  * existing allocation would accrue through `timestamp + capAccrualBuffer`
567
- * (two hours by default; `0n` disables it). For market-source reallocations
567
+ * (two hours by default; `0n` disables it). When an operation's plan would
568
+ * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
569
+ * 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
568
576
  * the source position's interest is also reserved on cap ids shared with the
569
577
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
570
578
  * or allocator capacity are skipped before projecting source interest. The
@@ -590,8 +598,8 @@ export class VaultV2BlueReallocationData {
590
598
  * every leg of a plan.
591
599
  * @returns Flat action-ready reallocations and their post-simulation state.
592
600
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
593
- * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
594
- * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
601
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
602
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
595
603
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
596
604
  * @throws {UnknownReallocationMarketError} when a required market is absent.
597
605
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -636,6 +644,7 @@ export class VaultV2BlueReallocationData {
636
644
  const maxWithdrawalUtilization = resolveMaxWithdrawalUtilization(options.maxWithdrawalUtilization);
637
645
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
638
646
  const capAccrualBuffer = resolveCapAccrualBuffer(options.capAccrualBuffer);
647
+ const allocatorCapHeadroom = resolveAllocatorCapHeadroom(options.allocatorCapHeadroom);
639
648
  const resolvedOptions = { ...options, maxPenalty };
640
649
  const operation = options.operation;
641
650
  if (operation == null) {
@@ -685,53 +694,103 @@ export class VaultV2BlueReallocationData {
685
694
  newTotalSupplyAssets;
686
695
  if (requiredAssets <= 0n)
687
696
  return { reallocations: [], data: this };
688
- const reserves = createCapReserveState(this.mutableMarkets);
689
- const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
690
- context: createSimulationContext(),
691
- reserves,
692
- marketId,
693
- maxWithdrawalUtilization,
694
- maxAssets: requiredAssets,
695
- capAccrualBuffer,
696
- options: normalizedOptions,
697
- });
698
- const reallocations = [...friendly.reallocations];
699
- const data = friendly.data;
700
- const friendlyMarket = friendly.data.getMarket(marketId);
701
- const friendlyBorrow = type === "borrow"
702
- ? friendlyMarket.totalBorrowAssets + amount
703
- : friendlyMarket.totalBorrowAssets;
704
- const friendlySupply = type === "withdraw"
705
- ? friendlyMarket.totalSupplyAssets - amount
706
- : friendlyMarket.totalSupplyAssets;
707
- if (friendlyBorrow > friendlySupply) {
708
- const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
709
- context: friendly.context,
697
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
698
+ ? newTotalBorrowAssets - newTotalSupplyAssets
699
+ : 0n;
700
+ const plan = (maxAssets, headroom) => {
701
+ const reserves = createCapReserveState(this.mutableMarkets);
702
+ const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
703
+ context: createSimulationContext(),
710
704
  reserves,
711
705
  marketId,
712
- maxWithdrawalUtilization: MathLib.WAD,
713
- maxAssets: friendlyBorrow - friendlySupply,
706
+ maxWithdrawalUtilization,
707
+ maxAssets,
714
708
  capAccrualBuffer,
709
+ allocatorCapHeadroom: headroom,
715
710
  options: normalizedOptions,
716
711
  });
717
- reallocations.push(...fallback.reallocations);
712
+ const reallocations = [...friendly.reallocations];
713
+ const data = friendly.data;
714
+ const friendlyMarket = data.getMarket(marketId);
715
+ const friendlyBorrow = type === "borrow"
716
+ ? friendlyMarket.totalBorrowAssets + amount
717
+ : friendlyMarket.totalBorrowAssets;
718
+ const friendlySupply = type === "withdraw"
719
+ ? friendlyMarket.totalSupplyAssets - amount
720
+ : friendlyMarket.totalSupplyAssets;
721
+ if (friendlyBorrow > friendlySupply) {
722
+ const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
723
+ context: friendly.context,
724
+ reserves,
725
+ marketId,
726
+ maxWithdrawalUtilization: MathLib.WAD,
727
+ maxAssets: friendlyBorrow - friendlySupply,
728
+ capAccrualBuffer,
729
+ allocatorCapHeadroom: headroom,
730
+ options: normalizedOptions,
731
+ });
732
+ reallocations.push(...fallback.reallocations);
733
+ }
734
+ // The fallback pass only runs when the plan moves exactly the absolute
735
+ // shortfall, which a reduced plan would move anyway.
736
+ const capBoundTargets = friendly.allocatorCapBoundTargets;
737
+ let reallocatedAssets = 0n;
738
+ let unboundAssets = 0n;
739
+ for (const { vault, to, assets } of reallocations) {
740
+ reallocatedAssets += assets;
741
+ const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
742
+ if (!capBoundTargets.has(key))
743
+ unboundAssets += assets;
744
+ }
745
+ return {
746
+ reallocations,
747
+ data,
748
+ capBound: capBoundTargets.size > 0,
749
+ reallocatedAssets,
750
+ unboundAssets,
751
+ };
752
+ };
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.
756
+ const target = plan(requiredAssets, allocatorCapHeadroom);
757
+ let selected = target;
758
+ if (allocatorCapHeadroom > 0n && target.capBound) {
759
+ selected = plan(absoluteShortfall > target.unboundAssets
760
+ ? absoluteShortfall
761
+ : target.unboundAssets, allocatorCapHeadroom);
762
+ // Shared-cap fitting is not monotonic in the budget.
763
+ if (selected.reallocatedAssets < absoluteShortfall &&
764
+ target.reallocatedAssets >= absoluteShortfall)
765
+ selected = target;
718
766
  }
719
- const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
720
- ? newTotalBorrowAssets - newTotalSupplyAssets
721
- : 0n;
722
- const reallocatedAssets = reallocations.reduce((total, { assets }) => total + assets, 0n);
723
- if (reallocatedAssets < absoluteShortfall) {
767
+ let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
768
+ // Without headroom, `target` already is the full-cap plan toward the target.
769
+ const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
770
+ for (const maxAssets of fullCapBudgets) {
771
+ if (selected.reallocatedAssets >= absoluteShortfall)
772
+ break;
773
+ selected = plan(maxAssets, 0n);
774
+ if (selected.reallocatedAssets > available)
775
+ available = selected.reallocatedAssets;
776
+ }
777
+ if (selected.reallocatedAssets < absoluteShortfall) {
724
778
  throw new InsufficientSharedLiquidityError({
725
779
  marketId,
726
780
  shortfall: absoluteShortfall,
727
- available: reallocatedAssets,
781
+ available,
728
782
  });
729
783
  }
730
- return { reallocations, data };
784
+ return { reallocations: selected.reallocations, data: selected.data };
731
785
  }
732
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, options = {}, }) {
786
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
733
787
  if (options.enabled === false)
734
- return { reallocations: [], data: this, context };
788
+ return {
789
+ reallocations: [],
790
+ data: this,
791
+ context,
792
+ allocatorCapBoundTargets: new Set(),
793
+ };
735
794
  this.getMarket(marketId);
736
795
  const timestamp = options.timestamp == null
737
796
  ? this.getLatestSnapshotTimestamp()
@@ -749,6 +808,7 @@ export class VaultV2BlueReallocationData {
749
808
  const adapterIdsCache = new Map();
750
809
  const activeAdaptersCache = new Map();
751
810
  let remainingAssets = maxAssets;
811
+ const allocatorCapBoundTargets = new Set();
752
812
  // Onchain, market interest is booked once at transaction start, on pre-plan
753
813
  // positions at pre-plan rates, and stays on touched positions' cap ids.
754
814
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -856,9 +916,9 @@ export class VaultV2BlueReallocationData {
856
916
  const adapterShares = adapter.supplyShares[marketId] ?? 0n;
857
917
  const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
858
918
  const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
859
- const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
919
+ const allocatorHeadroom = MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
860
920
  untracked +
861
- targetPair.reserve());
921
+ targetPair.reserve()), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
862
922
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
863
923
  const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
864
924
  const blockedTargetIds = targetAllocations
@@ -891,6 +951,7 @@ export class VaultV2BlueReallocationData {
891
951
  penalty: publicAllocatorConfig.penalty,
892
952
  },
893
953
  targetPair,
954
+ allocatorHeadroom,
894
955
  });
895
956
  }
896
957
  }
@@ -945,12 +1006,13 @@ export class VaultV2BlueReallocationData {
945
1006
  },
946
1007
  targetPair,
947
1008
  sourcePair,
1009
+ allocatorHeadroom,
948
1010
  });
949
1011
  }
950
1012
  }
951
1013
  }
952
1014
  const capCompatibleCandidates = [];
953
- for (const { reallocation, targetPair, sourcePair, } of rawCandidates) {
1015
+ for (const { reallocation, targetPair, sourcePair, allocatorHeadroom, } of rawCandidates) {
954
1016
  let lower = 0n;
955
1017
  let upper = reallocation.assets;
956
1018
  const targetIds = targetPair.ids;
@@ -1025,6 +1087,7 @@ export class VaultV2BlueReallocationData {
1025
1087
  reallocation: { ...reallocation, assets: selectedAssets },
1026
1088
  targetPair,
1027
1089
  sourcePair,
1090
+ allocatorHeadroom,
1028
1091
  });
1029
1092
  }
1030
1093
  return capCompatibleCandidates.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"))[0];
@@ -1033,8 +1096,16 @@ export class VaultV2BlueReallocationData {
1033
1096
  .sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"));
1034
1097
  const largest = candidates[0];
1035
1098
  if (largest == null)
1036
- return { reallocations, data, context: simulationContext };
1037
- const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, } = largest;
1099
+ return {
1100
+ reallocations,
1101
+ data,
1102
+ context: simulationContext,
1103
+ allocatorCapBoundTargets,
1104
+ };
1105
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1106
+ if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1107
+ // BluePublicAllocator caps are per vault and target adapter.
1108
+ allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1038
1109
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1039
1110
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1040
1111
  if (touchedVaultPairs == null) {
@@ -1059,7 +1130,12 @@ export class VaultV2BlueReallocationData {
1059
1130
  if (remainingAssets != null)
1060
1131
  remainingAssets -= acceptedReallocation.assets;
1061
1132
  }
1062
- return { reallocations, data, context: simulationContext };
1133
+ return {
1134
+ reallocations,
1135
+ data,
1136
+ context: simulationContext,
1137
+ allocatorCapBoundTargets,
1138
+ };
1063
1139
  }
1064
1140
  /**
1065
1141
  * Sums friendly Vault V2 shared liquidity available to a target market.
@@ -1,7 +1,7 @@
1
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,
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, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
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
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
7
  export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -1,6 +1,6 @@
1
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,
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, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
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
6
  export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
@@ -15,6 +15,14 @@ export declare const DEFAULT_LLTV_BUFFER: bigint;
15
15
  * `VaultV2BluePublicAllocatorOptions.capAccrualBuffer`.
16
16
  */
17
17
  export declare const DEFAULT_CAP_ACCRUAL_BUFFER: bigint;
18
+ /**
19
+ * Default headroom, as a WAD-scaled share of a BluePublicAllocator target-market
20
+ * cap (1%), kept below that cap when an operation's reallocation would
21
+ * otherwise fill it. It absorbs other allocations to the same market between
22
+ * the quote and inclusion. Override with
23
+ * `VaultV2BluePublicAllocatorOptions.allocatorCapHeadroom`.
24
+ */
25
+ export declare const DEFAULT_ALLOCATOR_CAP_HEADROOM: bigint;
18
26
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
19
27
  export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
20
28
  /**
@@ -17,6 +17,14 @@ export const DEFAULT_LLTV_BUFFER = MathLib.WAD / 200n;
17
17
  * `VaultV2BluePublicAllocatorOptions.capAccrualBuffer`.
18
18
  */
19
19
  export const DEFAULT_CAP_ACCRUAL_BUFFER = Time.s.from.h(2n);
20
+ /**
21
+ * Default headroom, as a WAD-scaled share of a BluePublicAllocator target-market
22
+ * cap (1%), kept below that cap when an operation's reallocation would
23
+ * otherwise fill it. It absorbs other allocations to the same market between
24
+ * the quote and inclusion. Override with
25
+ * `VaultV2BluePublicAllocatorOptions.allocatorCapHeadroom`.
26
+ */
27
+ export const DEFAULT_ALLOCATOR_CAP_HEADROOM = MathLib.WAD / 100n;
20
28
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
21
29
  export const MAX_ABSOLUTE_SHARE_PRICE = 100n * MathLib.RAY;
22
30
  /**
@@ -1,4 +1,4 @@
1
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
1
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
2
2
  export { addTransactionMetadata } from "./metadata.js";
3
3
  export { type PreviewVaultV2ForceWithdrawParams, previewVaultV2ForceWithdraw, type VaultV2ForceWithdrawPreview, } from "./previewVaultV2ForceWithdraw.js";
4
4
  export { type PreviewVaultV2InKindRedeemParams, previewVaultV2InKindRedeem, type VaultV2InKindRedeemMarketPreview, } from "./previewVaultV2InKindRedeem.js";
@@ -1,4 +1,4 @@
1
- export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
1
+ export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_LLTV_BUFFER, DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
2
2
  export { addTransactionMetadata } from "./metadata.js";
3
3
  export { previewVaultV2ForceWithdraw, } from "./previewVaultV2ForceWithdraw.js";
4
4
  export { previewVaultV2InKindRedeem, } from "./previewVaultV2InKindRedeem.js";
@@ -11,6 +11,19 @@ import { type BigIntish } from "@morpho-org/blue-sdk";
11
11
  * ```
12
12
  */
13
13
  export declare const resolveCapAccrualBuffer: (value?: BigIntish) => bigint;
14
+ /**
15
+ * Resolves and validates the BluePublicAllocator cap headroom share.
16
+ * @internal
17
+ * @param value - Optional WAD-scaled share of the allocator cap.
18
+ * @returns A share between zero and WAD, defaulting to 1%.
19
+ * @throws {NegativeInputError} when the share is negative.
20
+ * @throws {InputExceedsMaxError} when the share exceeds WAD.
21
+ * @example
22
+ * ```ts
23
+ * const headroom = resolveAllocatorCapHeadroom(undefined);
24
+ * ```
25
+ */
26
+ export declare const resolveAllocatorCapHeadroom: (value?: bigint) => bigint;
14
27
  /**
15
28
  * Resolves and validates a source withdrawal utilization ceiling.
16
29
  * @internal
@@ -1,6 +1,6 @@
1
1
  import { MathLib } from "@morpho-org/blue-sdk";
2
2
  import { InputExceedsMaxError, NegativeInputError } from "../types/index.js";
3
- import { DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, } from "./constant.js";
3
+ import { DEFAULT_ALLOCATOR_CAP_HEADROOM, DEFAULT_CAP_ACCRUAL_BUFFER, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, } from "./constant.js";
4
4
  /**
5
5
  * Resolves and validates the target-market cap-accrual buffer.
6
6
  * @internal
@@ -18,6 +18,30 @@ export const resolveCapAccrualBuffer = (value) => {
18
18
  throw new NegativeInputError("capAccrualBuffer", buffer);
19
19
  return buffer;
20
20
  };
21
+ /**
22
+ * Resolves and validates the BluePublicAllocator cap headroom share.
23
+ * @internal
24
+ * @param value - Optional WAD-scaled share of the allocator cap.
25
+ * @returns A share between zero and WAD, defaulting to 1%.
26
+ * @throws {NegativeInputError} when the share is negative.
27
+ * @throws {InputExceedsMaxError} when the share exceeds WAD.
28
+ * @example
29
+ * ```ts
30
+ * const headroom = resolveAllocatorCapHeadroom(undefined);
31
+ * ```
32
+ */
33
+ export const resolveAllocatorCapHeadroom = (value) => {
34
+ const headroom = value ?? DEFAULT_ALLOCATOR_CAP_HEADROOM;
35
+ if (headroom < 0n)
36
+ throw new NegativeInputError("allocatorCapHeadroom", headroom);
37
+ if (headroom > MathLib.WAD)
38
+ throw new InputExceedsMaxError({
39
+ field: "allocatorCapHeadroom",
40
+ value: headroom,
41
+ max: MathLib.WAD,
42
+ });
43
+ return headroom;
44
+ };
21
45
  /**
22
46
  * Resolves and validates a source withdrawal utilization ceiling.
23
47
  * @internal
@@ -24,6 +24,23 @@ export interface VaultV2BluePublicAllocatorOptions {
24
24
  * @default DEFAULT_CAP_ACCRUAL_BUFFER (2h)
25
25
  */
26
26
  readonly capAccrualBuffer?: BigIntish;
27
+ /**
28
+ * Share of each target-market BluePublicAllocator cap, scaled by WAD, that
29
+ * operation planning keeps free. When a reallocation toward the utilization
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.
37
+ * Discovery plans, `getPublicReallocationLiquidity` and
38
+ * `getAvailableLiquidityToUtilization` ignore it and use the full cap.
39
+ * Must not exceed WAD (100%). Set to `0n` to disable.
40
+ *
41
+ * @default DEFAULT_ALLOCATOR_CAP_HEADROOM (1%)
42
+ */
43
+ readonly allocatorCapHeadroom?: bigint;
27
44
  /**
28
45
  * Vault V2 addresses to consider. Arrays, readonly arrays, sets, and other
29
46
  * iterables are accepted. Defaults to every vault in the reallocation data.
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": "6.4.0",
4
+ "version": "6.6.0",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "repository": {
7
7
  "type": "git",
@@ -151,15 +151,15 @@
151
151
  ],
152
152
  "dependencies": {
153
153
  "@morpho-org/blue-sdk": "^7.2.0",
154
- "@morpho-org/blue-sdk-viem": "^6.1.0",
154
+ "@morpho-org/blue-sdk-viem": "^6.2.0",
155
155
  "@morpho-org/midnight-sdk": "^1.8.0",
156
- "@morpho-org/morpho-ts": "^3.2.0"
156
+ "@morpho-org/morpho-ts": "^3.2.1"
157
157
  },
158
158
  "peerDependencies": {
159
159
  "viem": "^2.0.0"
160
160
  },
161
161
  "devDependencies": {
162
- "@morpho-org/test": "^2.10.0",
162
+ "@morpho-org/test": "^2.10.1",
163
163
  "dotenv": "^17.4.2",
164
164
  "fast-check": "^4.9.0",
165
165
  "typescript": "7.0.2",