@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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UnsupportedPermitDomainExtensionsError = exports.MarketParamsIdMismatchError = exports.isUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedVaultV2AdapterError = exports.UnsupportedPreLiquidationParamsError = exports.UnsupportedMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownVaultConfigError = exports.UnknownTokenPriceError = exports.UnknownTokenError = exports.UnknownOfFactory = exports.UnknownMarketParamsError = exports.UnknownMarketAllocationError = exports.UnknownFactory = exports.UnknownDataError = exports.UnknownAddressError = exports.RegistryValueAlreadyRegisteredError = exports.InvalidMarketParamsError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.IncompleteChainRegistryError = exports.DivisionByZeroError = exports.BlueErrors = void 0;
3
+ exports.UnsupportedPermitDomainExtensionsError = exports.UnnamedAbiOutputsError = exports.UnknownAbiFunctionError = exports.NonTupleReturnValueError = exports.MarketParamsIdMismatchError = exports.isUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedVaultV2AdapterError = exports.UnsupportedPreLiquidationParamsError = exports.UnsupportedMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownVaultConfigError = exports.UnknownTokenPriceError = exports.UnknownTokenError = exports.UnknownOfFactory = exports.UnknownMarketParamsError = exports.UnknownMarketAllocationError = exports.UnknownFactory = exports.UnknownDataError = exports.UnknownAddressError = exports.RegistryValueAlreadyRegisteredError = exports.InvalidMarketParamsError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.IncompleteChainRegistryError = exports.DivisionByZeroError = exports.BlueErrors = void 0;
4
4
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  Object.defineProperty(exports, "BlueErrors", { enumerable: true, get: function () { return blue_sdk_1.BlueErrors; } });
6
6
  Object.defineProperty(exports, "DivisionByZeroError", { enumerable: true, get: function () { return blue_sdk_1.DivisionByZeroError; } });
@@ -31,4 +31,7 @@ Object.defineProperty(exports, "InvalidPermitDomainChainIdError", { enumerable:
31
31
  Object.defineProperty(exports, "InvalidPermitDomainVerifyingContractError", { enumerable: true, get: function () { return blue_sdk_viem_1.InvalidPermitDomainVerifyingContractError; } });
32
32
  Object.defineProperty(exports, "isUnknownOfFactoryError", { enumerable: true, get: function () { return blue_sdk_viem_1.isUnknownOfFactoryError; } });
33
33
  Object.defineProperty(exports, "MarketParamsIdMismatchError", { enumerable: true, get: function () { return blue_sdk_viem_1.MarketParamsIdMismatchError; } });
34
+ Object.defineProperty(exports, "NonTupleReturnValueError", { enumerable: true, get: function () { return blue_sdk_viem_1.NonTupleReturnValueError; } });
35
+ Object.defineProperty(exports, "UnknownAbiFunctionError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnknownAbiFunctionError; } });
36
+ Object.defineProperty(exports, "UnnamedAbiOutputsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnnamedAbiOutputsError; } });
34
37
  Object.defineProperty(exports, "UnsupportedPermitDomainExtensionsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnsupportedPermitDomainExtensionsError; } });
@@ -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.
@@ -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/cjs/errors.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MidnightTickOutOfRangeError = exports.MidnightSettlementFeeExceedsPriceError = exports.MidnightRatifierV1TakerNotAllowedError = exports.MidnightRateRatifierV1BoundOverflowError = exports.MidnightPriceGreaterThanOneError = exports.MidnightPayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidMidnightTypedDataSignatureError = exports.InvalidMidnightTreeHeightError = exports.InvalidMidnightTreeError = exports.InvalidMidnightTickSpacingError = exports.InvalidMidnightRatifierV1AddressError = exports.InvalidMidnightRateRatifierV1TimeError = exports.InvalidMidnightRateRatifierV1TickError = exports.InvalidMidnightRateRatifierV1RateError = exports.InvalidMidnightPositionLossFactorError = exports.InvalidMidnightPositionAccrualTimestampError = exports.InvalidMidnightPositionAccrualStateError = exports.InvalidMidnightOfferParameterError = exports.InvalidMidnightOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMidnightMarketParameterError = exports.InvalidMidnightEcrecoverSignatureVError = exports.MidnightChainIdMismatchError = exports.UnsupportedPermitDomainExtensionsError = exports.BlueMarketParamsIdMismatchError = exports.isBlueUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getBlueUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedBlueVaultV2AdapterError = exports.UnsupportedBluePreLiquidationParamsError = exports.UnsupportedBlueMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownBlueVaultConfigError = exports.UnknownBlueTokenPriceError = exports.UnknownBlueTokenError = exports.UnknownBlueOfFactory = exports.UnknownBlueMarketParamsError = exports.UnknownBlueMarketAllocationError = exports.UnknownBlueFactory = exports.UnknownBlueDataError = exports.UnknownAddressError = exports.InvalidBlueMarketParamsError = exports.IncompleteChainRegistryError = exports.BlueErrors = void 0;
4
- exports.RegistryValueAlreadyRegisteredError = exports.NegativeValueError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.DivisionByZeroError = exports._try = exports.UnknownMidnightCollateralIndexError = void 0;
3
+ exports.MidnightRateRatifierV1BoundOverflowError = exports.MidnightPriceGreaterThanOneError = exports.MidnightPayloadDecodeError = exports.MidnightMempoolValidationError = exports.MidnightApiError = exports.InvalidMidnightTypedDataSignatureError = exports.InvalidMidnightTreeHeightError = exports.InvalidMidnightTreeError = exports.InvalidMidnightTickSpacingError = exports.InvalidMidnightRatifierV1AddressError = exports.InvalidMidnightRateRatifierV1TimeError = exports.InvalidMidnightRateRatifierV1TickError = exports.InvalidMidnightRateRatifierV1RateError = exports.InvalidMidnightPositionLossFactorError = exports.InvalidMidnightPositionAccrualTimestampError = exports.InvalidMidnightPositionAccrualStateError = exports.InvalidMidnightOfferParameterError = exports.InvalidMidnightOfferGroupError = exports.InvalidMidnightApiResponseError = exports.InvalidMidnightApiQuoteTargetError = exports.InvalidMidnightMarketParameterError = exports.InvalidMidnightEcrecoverSignatureVError = exports.MidnightChainIdMismatchError = exports.UnsupportedPermitDomainExtensionsError = exports.UnnamedAbiOutputsError = exports.UnknownAbiFunctionError = exports.NonTupleReturnValueError = exports.BlueMarketParamsIdMismatchError = exports.isBlueUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getBlueUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedBlueVaultV2AdapterError = exports.UnsupportedBluePreLiquidationParamsError = exports.UnsupportedBlueMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownBlueVaultConfigError = exports.UnknownBlueTokenPriceError = exports.UnknownBlueTokenError = exports.UnknownBlueOfFactory = exports.UnknownBlueMarketParamsError = exports.UnknownBlueMarketAllocationError = exports.UnknownBlueFactory = exports.UnknownBlueDataError = exports.UnknownAddressError = exports.InvalidBlueMarketParamsError = exports.IncompleteChainRegistryError = exports.BlueErrors = void 0;
4
+ exports.RegistryValueAlreadyRegisteredError = exports.NegativeValueError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.DivisionByZeroError = exports._try = exports.UnknownMidnightCollateralIndexError = exports.MidnightTickOutOfRangeError = exports.MidnightSettlementFeeExceedsPriceError = exports.MidnightRatifierV1TakerNotAllowedError = void 0;
5
5
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  Object.defineProperty(exports, "BlueErrors", { enumerable: true, get: function () { return blue_sdk_1.BlueErrors; } });
7
7
  Object.defineProperty(exports, "IncompleteChainRegistryError", { enumerable: true, get: function () { return blue_sdk_1.IncompleteChainRegistryError; } });
@@ -28,6 +28,9 @@ Object.defineProperty(exports, "InvalidPermitDomainChainIdError", { enumerable:
28
28
  Object.defineProperty(exports, "InvalidPermitDomainVerifyingContractError", { enumerable: true, get: function () { return blue_sdk_viem_1.InvalidPermitDomainVerifyingContractError; } });
29
29
  Object.defineProperty(exports, "isBlueUnknownOfFactoryError", { enumerable: true, get: function () { return blue_sdk_viem_1.isUnknownOfFactoryError; } });
30
30
  Object.defineProperty(exports, "BlueMarketParamsIdMismatchError", { enumerable: true, get: function () { return blue_sdk_viem_1.MarketParamsIdMismatchError; } });
31
+ Object.defineProperty(exports, "NonTupleReturnValueError", { enumerable: true, get: function () { return blue_sdk_viem_1.NonTupleReturnValueError; } });
32
+ Object.defineProperty(exports, "UnknownAbiFunctionError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnknownAbiFunctionError; } });
33
+ Object.defineProperty(exports, "UnnamedAbiOutputsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnnamedAbiOutputsError; } });
31
34
  Object.defineProperty(exports, "UnsupportedPermitDomainExtensionsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnsupportedPermitDomainExtensionsError; } });
32
35
  var midnight_sdk_1 = require("@morpho-org/midnight-sdk");
33
36
  Object.defineProperty(exports, "MidnightChainIdMismatchError", { enumerable: true, get: function () { return midnight_sdk_1.ChainIdMismatchError; } });
@@ -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 { 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";