@morpho-org/morpho-sdk 6.5.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.
@@ -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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_REALLOCATION_PENALTY = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.DEFAULT_LLTV_BUFFER = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = exports.ZERO_ADDRESS = exports.REWARDS_BASE_URL = exports.MORPHO_DOMAIN = exports.DOCS_BASE_URL = exports.ChainUtils = exports.ChainId = exports.BLUE_API_GRAPHQL_URL = exports.BLUE_API_BASE_URL = exports.MIDNIGHT_TIME_TO_MAX_LIF = exports.MIDNIGHT_SETTLEMENT_FEE_BREAKPOINTS = exports.MIDNIGHT_RATE_RATIFIER_V1_OFFER_TYPEHASH = exports.MIDNIGHT_PRICE_ROUNDING_STEP = exports.MIDNIGHT_PRICE_RATIFIER_V1_OFFER_TYPEHASH = exports.MIDNIGHT_OFFER_TYPEHASH = exports.MIDNIGHT_MAX_TREE_HEIGHT = exports.MIDNIGHT_MAX_TICK = exports.MIDNIGHT_MAX_SETTLEMENT_FEES = exports.MIDNIGHT_MAX_OFFER_CAP = exports.MIDNIGHT_MAX_CONTINUOUS_FEE = exports.MIDNIGHT_MAX_COLLATERALS_PER_BORROWER = exports.MIDNIGHT_MAX_COLLATERALS = exports.MIDNIGHT_MARKET_TYPEHASH = exports.MIDNIGHT_EIP712_DOMAIN_TYPEHASH = exports.MIDNIGHT_DEFAULT_TICK_SPACING = exports.MIDNIGHT_COLLATERAL_PARAMS_TYPEHASH = exports.MIDNIGHT_CBP = exports.BlueTransactionType = exports.SECONDS_PER_YEAR = exports.ORACLE_PRICE_SCALE = exports.BLUE_MAX_LIQUIDATION_INCENTIVE_FACTOR = exports.BLUE_LIQUIDATION_CURSOR = exports.isBlueMarketId = exports.ERC20_ALLOWANCE_RECIPIENTS = exports.EIP_712_FIELDS = exports.DEFAULT_SLIPPAGE_TOLERANCE = void 0;
3
+ exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_REALLOCATION_PENALTY = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.DEFAULT_LLTV_BUFFER = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.DEFAULT_ALLOCATOR_CAP_HEADROOM = exports.APPROVE_ONLY_ONCE_TOKENS = exports.ZERO_ADDRESS = exports.REWARDS_BASE_URL = exports.MORPHO_DOMAIN = exports.DOCS_BASE_URL = exports.ChainUtils = exports.ChainId = exports.BLUE_API_GRAPHQL_URL = exports.BLUE_API_BASE_URL = exports.MIDNIGHT_TIME_TO_MAX_LIF = exports.MIDNIGHT_SETTLEMENT_FEE_BREAKPOINTS = exports.MIDNIGHT_RATE_RATIFIER_V1_OFFER_TYPEHASH = exports.MIDNIGHT_PRICE_ROUNDING_STEP = exports.MIDNIGHT_PRICE_RATIFIER_V1_OFFER_TYPEHASH = exports.MIDNIGHT_OFFER_TYPEHASH = exports.MIDNIGHT_MAX_TREE_HEIGHT = exports.MIDNIGHT_MAX_TICK = exports.MIDNIGHT_MAX_SETTLEMENT_FEES = exports.MIDNIGHT_MAX_OFFER_CAP = exports.MIDNIGHT_MAX_CONTINUOUS_FEE = exports.MIDNIGHT_MAX_COLLATERALS_PER_BORROWER = exports.MIDNIGHT_MAX_COLLATERALS = exports.MIDNIGHT_MARKET_TYPEHASH = exports.MIDNIGHT_EIP712_DOMAIN_TYPEHASH = exports.MIDNIGHT_DEFAULT_TICK_SPACING = exports.MIDNIGHT_COLLATERAL_PARAMS_TYPEHASH = exports.MIDNIGHT_CBP = exports.BlueTransactionType = exports.SECONDS_PER_YEAR = exports.ORACLE_PRICE_SCALE = exports.BLUE_MAX_LIQUIDATION_INCENTIVE_FACTOR = exports.BLUE_LIQUIDATION_CURSOR = exports.isBlueMarketId = exports.ERC20_ALLOWANCE_RECIPIENTS = exports.EIP_712_FIELDS = exports.DEFAULT_SLIPPAGE_TOLERANCE = void 0;
4
4
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  Object.defineProperty(exports, "DEFAULT_SLIPPAGE_TOLERANCE", { enumerable: true, get: function () { return blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE; } });
6
6
  Object.defineProperty(exports, "EIP_712_FIELDS", { enumerable: true, get: function () { return blue_sdk_1.EIP_712_FIELDS; } });
@@ -41,6 +41,7 @@ Object.defineProperty(exports, "REWARDS_BASE_URL", { enumerable: true, get: func
41
41
  Object.defineProperty(exports, "ZERO_ADDRESS", { enumerable: true, get: function () { return morpho_ts_1.ZERO_ADDRESS; } });
42
42
  var constant_js_1 = require("./helpers/constant.js");
43
43
  Object.defineProperty(exports, "APPROVE_ONLY_ONCE_TOKENS", { enumerable: true, get: function () { return constant_js_1.APPROVE_ONLY_ONCE_TOKENS; } });
44
+ Object.defineProperty(exports, "DEFAULT_ALLOCATOR_CAP_HEADROOM", { enumerable: true, get: function () { return constant_js_1.DEFAULT_ALLOCATOR_CAP_HEADROOM; } });
44
45
  Object.defineProperty(exports, "DEFAULT_CAP_ACCRUAL_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_CAP_ACCRUAL_BUFFER; } });
45
46
  Object.defineProperty(exports, "DEFAULT_LLTV_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_LLTV_BUFFER; } });
46
47
  Object.defineProperty(exports, "DEFAULT_MAX_REALLOCATION_PENALTY", { enumerable: true, get: function () { return constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY; } });
@@ -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.
@@ -738,15 +738,17 @@ class MorphoBlue {
738
738
  * allocation through `timestamp + capAccrualBuffer` (two hours by default;
739
739
  * `0n` disables it). For market-source reallocations the source position's
740
740
  * interest is also reserved on cap ids shared with the target, and reserves
741
- * persist across every leg of a plan.
741
+ * persist across every leg of a plan. Operation plans keep
742
+ * `allocatorCapHeadroom` (1% of the cap by default) free under each target
743
+ * BluePublicAllocator cap unless the operation shortfall needs it.
742
744
  *
743
745
  * @param params.reallocationData - State returned by {@link getVaultV2BlueReallocationData}.
744
746
  * @param params.options - Optional allocator discovery controls and operation to support.
745
747
  * @returns Action-ready reallocations and their post-simulation state.
746
748
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
747
749
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
748
- * @throws {NegativeInputError} when the cap-accrual buffer, utilization, or penalty limit is negative.
749
- * @throws {InputExceedsMaxError} when a utilization or penalty limit exceeds WAD.
750
+ * @throws {NegativeInputError} when the cap-accrual buffer, allocator cap headroom, utilization, or penalty limit is negative.
751
+ * @throws {InputExceedsMaxError} when the allocator cap headroom, a utilization, or a penalty limit exceeds WAD.
750
752
  * @throws {NonPositiveInputError} when an enabled operation amount is not positive.
751
753
  * @throws {UnknownReallocationMarketError} when a required market is absent.
752
754
  * @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.
@@ -567,7 +567,15 @@ class VaultV2BlueReallocationData {
567
567
  * considered. Market/vault state and the returned post-state stay at
568
568
  * `timestamp`; only target-market cap checks reserve interest the vault's
569
569
  * existing allocation would accrue through `timestamp + capAccrualBuffer`
570
- * (two hours by default; `0n` disables it). For market-source reallocations
570
+ * (two hours by default; `0n` disables it). When an operation's plan would
571
+ * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
572
+ * BluePublicAllocator cap, the plan is reduced to the larger of the
573
+ * operation's absolute shortfall and what vaults below their cap moved. The
574
+ * kept headroom absorbs other allocations up to that share of the cap landing
575
+ * before inclusion. The plan uses the full cap only when the shortfall needs
576
+ * it, and can then still revert if another allocation lands first. A plan of
577
+ * only the shortfall leaves the market fully utilized, so a competing borrow
578
+ * or withdraw landing first can also make it revert. For market-source reallocations
571
579
  * the source position's interest is also reserved on cap ids shared with the
572
580
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
573
581
  * or allocator capacity are skipped before projecting source interest. The
@@ -593,8 +601,8 @@ class VaultV2BlueReallocationData {
593
601
  * every leg of a plan.
594
602
  * @returns Flat action-ready reallocations and their post-simulation state.
595
603
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
596
- * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
597
- * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
604
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
605
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
598
606
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
599
607
  * @throws {UnknownReallocationMarketError} when a required market is absent.
600
608
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -639,6 +647,7 @@ class VaultV2BlueReallocationData {
639
647
  const maxWithdrawalUtilization = (0, utilization_js_1.resolveMaxWithdrawalUtilization)(options.maxWithdrawalUtilization);
640
648
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
641
649
  const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options.capAccrualBuffer);
650
+ const allocatorCapHeadroom = (0, utilization_js_1.resolveAllocatorCapHeadroom)(options.allocatorCapHeadroom);
642
651
  const resolvedOptions = { ...options, maxPenalty };
643
652
  const operation = options.operation;
644
653
  if (operation == null) {
@@ -688,53 +697,103 @@ class VaultV2BlueReallocationData {
688
697
  newTotalSupplyAssets;
689
698
  if (requiredAssets <= 0n)
690
699
  return { reallocations: [], data: this };
691
- const reserves = createCapReserveState(this.mutableMarkets);
692
- const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
693
- context: createSimulationContext(),
694
- reserves,
695
- marketId,
696
- maxWithdrawalUtilization,
697
- maxAssets: requiredAssets,
698
- capAccrualBuffer,
699
- options: normalizedOptions,
700
- });
701
- const reallocations = [...friendly.reallocations];
702
- const data = friendly.data;
703
- const friendlyMarket = friendly.data.getMarket(marketId);
704
- const friendlyBorrow = type === "borrow"
705
- ? friendlyMarket.totalBorrowAssets + amount
706
- : friendlyMarket.totalBorrowAssets;
707
- const friendlySupply = type === "withdraw"
708
- ? friendlyMarket.totalSupplyAssets - amount
709
- : friendlyMarket.totalSupplyAssets;
710
- if (friendlyBorrow > friendlySupply) {
711
- const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
712
- context: friendly.context,
700
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
701
+ ? newTotalBorrowAssets - newTotalSupplyAssets
702
+ : 0n;
703
+ const plan = (maxAssets, headroom) => {
704
+ const reserves = createCapReserveState(this.mutableMarkets);
705
+ const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
706
+ context: createSimulationContext(),
713
707
  reserves,
714
708
  marketId,
715
- maxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
716
- maxAssets: friendlyBorrow - friendlySupply,
709
+ maxWithdrawalUtilization,
710
+ maxAssets,
717
711
  capAccrualBuffer,
712
+ allocatorCapHeadroom: headroom,
718
713
  options: normalizedOptions,
719
714
  });
720
- reallocations.push(...fallback.reallocations);
715
+ const reallocations = [...friendly.reallocations];
716
+ const data = friendly.data;
717
+ const friendlyMarket = data.getMarket(marketId);
718
+ const friendlyBorrow = type === "borrow"
719
+ ? friendlyMarket.totalBorrowAssets + amount
720
+ : friendlyMarket.totalBorrowAssets;
721
+ const friendlySupply = type === "withdraw"
722
+ ? friendlyMarket.totalSupplyAssets - amount
723
+ : friendlyMarket.totalSupplyAssets;
724
+ if (friendlyBorrow > friendlySupply) {
725
+ const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
726
+ context: friendly.context,
727
+ reserves,
728
+ marketId,
729
+ maxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
730
+ maxAssets: friendlyBorrow - friendlySupply,
731
+ capAccrualBuffer,
732
+ allocatorCapHeadroom: headroom,
733
+ options: normalizedOptions,
734
+ });
735
+ reallocations.push(...fallback.reallocations);
736
+ }
737
+ // The fallback pass only runs when the plan moves exactly the absolute
738
+ // shortfall, which a reduced plan would move anyway.
739
+ const capBoundTargets = friendly.allocatorCapBoundTargets;
740
+ let reallocatedAssets = 0n;
741
+ let unboundAssets = 0n;
742
+ for (const { vault, to, assets } of reallocations) {
743
+ reallocatedAssets += assets;
744
+ const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
745
+ if (!capBoundTargets.has(key))
746
+ unboundAssets += assets;
747
+ }
748
+ return {
749
+ reallocations,
750
+ data,
751
+ capBound: capBoundTargets.size > 0,
752
+ reallocatedAssets,
753
+ unboundAssets,
754
+ };
755
+ };
756
+ // A leg that fills an allocator cap reverts once any other allocation to
757
+ // that market lands first. A cap-bound plan therefore moves only the
758
+ // operation's shortfall, or what vaults below their cap already moved.
759
+ const target = plan(requiredAssets, allocatorCapHeadroom);
760
+ let selected = target;
761
+ if (allocatorCapHeadroom > 0n && target.capBound) {
762
+ selected = plan(absoluteShortfall > target.unboundAssets
763
+ ? absoluteShortfall
764
+ : target.unboundAssets, allocatorCapHeadroom);
765
+ // Shared-cap fitting is not monotonic in the budget.
766
+ if (selected.reallocatedAssets < absoluteShortfall &&
767
+ target.reallocatedAssets >= absoluteShortfall)
768
+ selected = target;
721
769
  }
722
- const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
723
- ? newTotalBorrowAssets - newTotalSupplyAssets
724
- : 0n;
725
- const reallocatedAssets = reallocations.reduce((total, { assets }) => total + assets, 0n);
726
- if (reallocatedAssets < absoluteShortfall) {
770
+ let available = blue_sdk_1.MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
771
+ // Without headroom, `target` already is the full-cap plan toward the target.
772
+ const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
773
+ for (const maxAssets of fullCapBudgets) {
774
+ if (selected.reallocatedAssets >= absoluteShortfall)
775
+ break;
776
+ selected = plan(maxAssets, 0n);
777
+ if (selected.reallocatedAssets > available)
778
+ available = selected.reallocatedAssets;
779
+ }
780
+ if (selected.reallocatedAssets < absoluteShortfall) {
727
781
  throw new index_js_1.InsufficientSharedLiquidityError({
728
782
  marketId,
729
783
  shortfall: absoluteShortfall,
730
- available: reallocatedAssets,
784
+ available,
731
785
  });
732
786
  }
733
- return { reallocations, data };
787
+ return { reallocations: selected.reallocations, data: selected.data };
734
788
  }
735
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, options = {}, }) {
789
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
736
790
  if (options.enabled === false)
737
- return { reallocations: [], data: this, context };
791
+ return {
792
+ reallocations: [],
793
+ data: this,
794
+ context,
795
+ allocatorCapBoundTargets: new Set(),
796
+ };
738
797
  this.getMarket(marketId);
739
798
  const timestamp = options.timestamp == null
740
799
  ? this.getLatestSnapshotTimestamp()
@@ -752,6 +811,7 @@ class VaultV2BlueReallocationData {
752
811
  const adapterIdsCache = new Map();
753
812
  const activeAdaptersCache = new Map();
754
813
  let remainingAssets = maxAssets;
814
+ const allocatorCapBoundTargets = new Set();
755
815
  // Onchain, market interest is booked once at transaction start, on pre-plan
756
816
  // positions at pre-plan rates, and stays on touched positions' cap ids.
757
817
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -859,9 +919,9 @@ class VaultV2BlueReallocationData {
859
919
  const adapterShares = adapter.supplyShares[marketId] ?? 0n;
860
920
  const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
861
921
  const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
862
- const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
922
+ const allocatorHeadroom = blue_sdk_1.MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
863
923
  untracked +
864
- targetPair.reserve());
924
+ targetPair.reserve()), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
865
925
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
866
926
  const minimumAllocationChange = blue_sdk_1.MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
867
927
  const blockedTargetIds = targetAllocations
@@ -894,6 +954,7 @@ class VaultV2BlueReallocationData {
894
954
  penalty: publicAllocatorConfig.penalty,
895
955
  },
896
956
  targetPair,
957
+ allocatorHeadroom,
897
958
  });
898
959
  }
899
960
  }
@@ -948,12 +1009,13 @@ class VaultV2BlueReallocationData {
948
1009
  },
949
1010
  targetPair,
950
1011
  sourcePair,
1012
+ allocatorHeadroom,
951
1013
  });
952
1014
  }
953
1015
  }
954
1016
  }
955
1017
  const capCompatibleCandidates = [];
956
- for (const { reallocation, targetPair, sourcePair, } of rawCandidates) {
1018
+ for (const { reallocation, targetPair, sourcePair, allocatorHeadroom, } of rawCandidates) {
957
1019
  let lower = 0n;
958
1020
  let upper = reallocation.assets;
959
1021
  const targetIds = targetPair.ids;
@@ -1028,6 +1090,7 @@ class VaultV2BlueReallocationData {
1028
1090
  reallocation: { ...reallocation, assets: selectedAssets },
1029
1091
  targetPair,
1030
1092
  sourcePair,
1093
+ allocatorHeadroom,
1031
1094
  });
1032
1095
  }
1033
1096
  return capCompatibleCandidates.sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"))[0];
@@ -1036,8 +1099,16 @@ class VaultV2BlueReallocationData {
1036
1099
  .sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"));
1037
1100
  const largest = candidates[0];
1038
1101
  if (largest == null)
1039
- return { reallocations, data, context: simulationContext };
1040
- const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, } = largest;
1102
+ return {
1103
+ reallocations,
1104
+ data,
1105
+ context: simulationContext,
1106
+ allocatorCapBoundTargets,
1107
+ };
1108
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1109
+ if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1110
+ // BluePublicAllocator caps are per vault and target adapter.
1111
+ allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1041
1112
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1042
1113
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1043
1114
  if (touchedVaultPairs == null) {
@@ -1062,7 +1133,12 @@ class VaultV2BlueReallocationData {
1062
1133
  if (remainingAssets != null)
1063
1134
  remainingAssets -= acceptedReallocation.assets;
1064
1135
  }
1065
- return { reallocations, data, context: simulationContext };
1136
+ return {
1137
+ reallocations,
1138
+ data,
1139
+ context: simulationContext,
1140
+ allocatorCapBoundTargets,
1141
+ };
1066
1142
  }
1067
1143
  /**
1068
1144
  * Sums friendly Vault V2 shared liquidity available to a target market.
@@ -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
  /**
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_TOKEN_APPROVALS = exports.APPROVE_ONLY_ONCE_TOKENS = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.DEFAULT_LLTV_BUFFER = exports.MAX_REALLOCATION_PENALTY = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
3
+ exports.MAX_TOKEN_APPROVALS = exports.APPROVE_ONLY_ONCE_TOKENS = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_ALLOCATOR_CAP_HEADROOM = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.DEFAULT_LLTV_BUFFER = exports.MAX_REALLOCATION_PENALTY = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.MAX_SLIPPAGE_TOLERANCE = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
@@ -20,6 +20,14 @@ exports.DEFAULT_LLTV_BUFFER = blue_sdk_1.MathLib.WAD / 200n;
20
20
  * `VaultV2BluePublicAllocatorOptions.capAccrualBuffer`.
21
21
  */
22
22
  exports.DEFAULT_CAP_ACCRUAL_BUFFER = morpho_ts_1.Time.s.from.h(2n);
23
+ /**
24
+ * Default headroom, as a WAD-scaled share of a BluePublicAllocator target-market
25
+ * cap (1%), kept below that cap when an operation's reallocation would
26
+ * otherwise fill it. It absorbs other allocations to the same market between
27
+ * the quote and inclusion. Override with
28
+ * `VaultV2BluePublicAllocatorOptions.allocatorCapHeadroom`.
29
+ */
30
+ exports.DEFAULT_ALLOCATOR_CAP_HEADROOM = blue_sdk_1.MathLib.WAD / 100n;
23
31
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
24
32
  exports.MAX_ABSOLUTE_SHARE_PRICE = 100n * blue_sdk_1.MathLib.RAY;
25
33
  /**
@@ -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,8 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveVaultV2ForceWithdrawEligibility = exports.computeVaultV2ForceWithdrawSharesBurnt = exports.computeVaultV2ForceWithdrawPlan = exports.computeVaultV2ForceWithdrawMinSharesBurnt = exports.computeVaultV2ForceWithdrawFeeSharesMinted = exports.validateRequirementSpender = exports.validateOfferSides = exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateMidnightMarketChainId = exports.validateChainId = exports.validateAccrualPosition = exports.computeVaultMaxSharePrice = exports.computeVaultMaxShareAllowance = exports.computeMinForceWithdrawSharePrice = exports.signAndVerifyTypedData = exports.grossFromNetAssets = exports.previewVaultV2InKindRedeem = exports.previewVaultV2ForceWithdraw = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_REALLOCATION_PENALTY = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.DEFAULT_LLTV_BUFFER = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = void 0;
3
+ exports.resolveVaultV2ForceWithdrawEligibility = exports.computeVaultV2ForceWithdrawSharesBurnt = exports.computeVaultV2ForceWithdrawPlan = exports.computeVaultV2ForceWithdrawMinSharesBurnt = exports.computeVaultV2ForceWithdrawFeeSharesMinted = exports.validateRequirementSpender = exports.validateOfferSides = exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateMidnightMarketChainId = exports.validateChainId = exports.validateAccrualPosition = exports.computeVaultMaxSharePrice = exports.computeVaultMaxShareAllowance = exports.computeMinForceWithdrawSharePrice = exports.signAndVerifyTypedData = exports.grossFromNetAssets = exports.previewVaultV2InKindRedeem = exports.previewVaultV2ForceWithdraw = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_REALLOCATION_PENALTY = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_MAX_REALLOCATION_PENALTY = exports.DEFAULT_LLTV_BUFFER = exports.DEFAULT_CAP_ACCRUAL_BUFFER = exports.DEFAULT_ALLOCATOR_CAP_HEADROOM = exports.APPROVE_ONLY_ONCE_TOKENS = void 0;
4
4
  var constant_js_1 = require("./constant.js");
5
5
  Object.defineProperty(exports, "APPROVE_ONLY_ONCE_TOKENS", { enumerable: true, get: function () { return constant_js_1.APPROVE_ONLY_ONCE_TOKENS; } });
6
+ Object.defineProperty(exports, "DEFAULT_ALLOCATOR_CAP_HEADROOM", { enumerable: true, get: function () { return constant_js_1.DEFAULT_ALLOCATOR_CAP_HEADROOM; } });
6
7
  Object.defineProperty(exports, "DEFAULT_CAP_ACCRUAL_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_CAP_ACCRUAL_BUFFER; } });
7
8
  Object.defineProperty(exports, "DEFAULT_LLTV_BUFFER", { enumerable: true, get: function () { return constant_js_1.DEFAULT_LLTV_BUFFER; } });
8
9
  Object.defineProperty(exports, "DEFAULT_MAX_REALLOCATION_PENALTY", { enumerable: true, get: function () { return constant_js_1.DEFAULT_MAX_REALLOCATION_PENALTY; } });
@@ -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
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.resolveMaxWithdrawalUtilization = exports.resolveCapAccrualBuffer = void 0;
3
+ exports.resolveMaxWithdrawalUtilization = exports.resolveAllocatorCapHeadroom = exports.resolveCapAccrualBuffer = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const index_js_1 = require("../types/index.js");
6
6
  const constant_js_1 = require("./constant.js");
@@ -22,6 +22,31 @@ const resolveCapAccrualBuffer = (value) => {
22
22
  return buffer;
23
23
  };
24
24
  exports.resolveCapAccrualBuffer = resolveCapAccrualBuffer;
25
+ /**
26
+ * Resolves and validates the BluePublicAllocator cap headroom share.
27
+ * @internal
28
+ * @param value - Optional WAD-scaled share of the allocator cap.
29
+ * @returns A share between zero and WAD, defaulting to 1%.
30
+ * @throws {NegativeInputError} when the share is negative.
31
+ * @throws {InputExceedsMaxError} when the share exceeds WAD.
32
+ * @example
33
+ * ```ts
34
+ * const headroom = resolveAllocatorCapHeadroom(undefined);
35
+ * ```
36
+ */
37
+ const resolveAllocatorCapHeadroom = (value) => {
38
+ const headroom = value ?? constant_js_1.DEFAULT_ALLOCATOR_CAP_HEADROOM;
39
+ if (headroom < 0n)
40
+ throw new index_js_1.NegativeInputError("allocatorCapHeadroom", headroom);
41
+ if (headroom > blue_sdk_1.MathLib.WAD)
42
+ throw new index_js_1.InputExceedsMaxError({
43
+ field: "allocatorCapHeadroom",
44
+ value: headroom,
45
+ max: blue_sdk_1.MathLib.WAD,
46
+ });
47
+ return headroom;
48
+ };
49
+ exports.resolveAllocatorCapHeadroom = resolveAllocatorCapHeadroom;
25
50
  /**
26
51
  * Resolves and validates a source withdrawal utilization ceiling.
27
52
  * @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.
@@ -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.
@@ -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.5.0",
4
+ "version": "6.6.0",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "repository": {
7
7
  "type": "git",
@@ -153,13 +153,13 @@
153
153
  "@morpho-org/blue-sdk": "^7.2.0",
154
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",