Skip to content
Verified contractPartialLGPL-3.0-only

CompoundCarryTradeEngine

Address0x01385dd1091af38420f8dbb0b3cade09a3512da7
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.35

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.35+commit.47b9dedd
Language
solidity
Optimization
Yes, 200 runs
EVM version
osaka
Via IR
yes
License
LGPL-3.0-only
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,377,092
Creation transaction
0x8d809df76f…390e66cb5a

src/engines/lending/CompoundCarryTradeEngine.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {ReferencePrice} from "../../libraries/ReferencePrice.sol";

import {StrategyModule} from "../../core/StrategyModule.sol";
import {ForwardingGuard} from "../base/ForwardingGuard.sol";
import {CarryVaultCapability} from "../base/CarryVaultCapability.sol";
import {IComet} from "../../interfaces/protocols/compound/IComet.sol";
import {IERC20Minimal} from "../../interfaces/tokens/IERC20Minimal.sol";
import {IERC20Metadata} from "../../interfaces/tokens/IERC20Metadata.sol";
import {IReferenceOracle} from "../../interfaces/oracles/IReferenceOracle.sol";
import {ICarryRateOracle} from "../../interfaces/oracles/ICarryRateOracle.sol";
import {CometCarryMath} from "../../libraries/CometCarryMath.sol";
import {CarryTradeRisk} from "../../libraries/CarryTradeRisk.sol";
import {FullMath} from "../../libraries/uniswap/FullMath.sol";

/// @title CompoundCarryTradeEngine
/// @notice Asset-agnostic Comet carry automation using pinned, typed vault operations.
/// @dev Collateral stays signer-managed; borrowing and repayment always originate from the Safe.
///      Policies share the Safe's Comet debt and vault inventory, not policy-specific escrows.
///      Synchronous protection requires vault liquidity and Comet prices; ready Syrup claims
///      omit price/rate observations but require protocol identity and, while debt remains, repayment availability.
contract CompoundCarryTradeEngine is CarryVaultCapability {
    error CompoundCarryTradeEngine_InvalidPolicy();
    error CompoundCarryTradeEngine_IdentityChange();
    error CompoundCarryTradeEngine_IdentityMismatch();
    error CompoundCarryTradeEngine_WrongSafe();
    error CompoundCarryTradeEngine_InvalidAction();
    error CompoundCarryTradeEngine_InvalidPlanFields();
    error CompoundCarryTradeEngine_InvalidReference();
    error CompoundCarryTradeEngine_ReferenceDeviation();
    error CompoundCarryTradeEngine_InvalidRate();
    error CompoundCarryTradeEngine_AmountOutOfBounds();
    error CompoundCarryTradeEngine_DebtCapExceeded();
    error CompoundCarryTradeEngine_VaultAllocationCapExceeded();
    error CompoundCarryTradeEngine_PolicyLimitExceeded();
    error CompoundCarryTradeEngine_BorrowBudgetExceeded();
    error CompoundCarryTradeEngine_InsufficientLiquidity();
    error CompoundCarryTradeEngine_VaultCapacityExceeded();
    error CompoundCarryTradeEngine_ShareSlippage();
    error CompoundCarryTradeEngine_BorrowRateTooHigh();
    error CompoundCarryTradeEngine_HealthFactorTooLow();
    error CompoundCarryTradeEngine_CarrySpreadTooLow();
    error CompoundCarryTradeEngine_DeleverageNotTriggered();
    error CompoundCarryTradeEngine_PrincipalMismatch();
    error CompoundCarryTradeEngine_DebtDirection();
    error CompoundCarryTradeEngine_PositionChanged();
    error CompoundCarryTradeEngine_HealthDidNotImprove();
    error CompoundCarryTradeEngine_CarryWorsened();
    error CompoundCarryTradeEngine_MarketPaused();
    error CompoundCarryTradeEngine_CollateralDeactivated();
    error CompoundCarryTradeEngine_UtilizationTooHigh();
    error CompoundCarryTradeEngine_UnexpectedPosition();
    error CompoundCarryTradeEngine_EconomicCooldownNotElapsed();
    error CompoundCarryTradeEngine_OptimizationDisabled();
    error CompoundCarryTradeEngine_AnnualIncomeOutOfBounds();
    error CompoundCarryTradeEngine_AnnualIncomeDidNotImprove();
    error CompoundCarryTradeEngine_ExecutionQuote(
        uint8 action,
        uint256 debtAfter,
        uint256 vaultAssetsAfter,
        uint256 vaultRateBps,
        uint256 borrowRateBps,
        uint256 healthAfter
    );

    /// @notice Explicit Comet API variant; extra institutional guards are never silently ignored.
    enum CometKind {
        Standard,
        Institutional
    }

    /// @notice Fixed execution and reverting quote paths, including Syrup's asynchronous exits.
    enum Action {
        Leverage,
        Deleverage,
        DeleverageAll,
        RequestDeleverage,
        ClaimAndRepay,
        OptimizeDeleverage,
        QuoteLeverage,
        QuoteDeleverage,
        QuoteOptimizeDeleverage
    }

    /// @notice Pinned market/vault identities and Safe-owned risk limits.
    /// @dev Debt, maxVaultAssets, action amounts and epochBorrowBudget use raw base-asset units; health factors
    ///      use 1e18. Reference price is whole base tokens per collateral token at 1e18.
    ///      Rates are nominal annual bps; deviations and share slippage use 10,000 bps.
    ///      Economic synchronous exits are capped by the greater of a fraction of current debt
    ///      and economicDeleverageMinAmount, never above debt; persistence is keeper-enforced.
    ///      minAnnualIncomeImprovement uses raw base-asset units per year. Zero disables optimized
    ///      repayment; a positive value requires conservative estimated-income improvement for it and borrowing.
    ///      maxTotalDebt covers the whole Safe/Comet debt; maxVaultAssets covers all Safe-owned
    ///      configured-vault shares at conversion value. Only new leverage enforces these caps.
    ///      Staleness, intervals and epochs use seconds. All fields hashed by identityHash,
    ///      including venue/route/oracle/decimal identities and epochLength, remain fixed on update.
    struct Policy {
        IComet comet;
        CometKind cometKind;
        address collateralAsset;
        address baseAsset;
        address collateralPriceFeed;
        address basePriceFeed;
        uint8 collateralDecimals;
        uint8 baseDecimals;
        uint8 collateralOffset;
        VaultConfig vaultConfig;
        IReferenceOracle referenceOracle;
        ICarryRateOracle rateOracle;
        uint256 maxReferenceStaleness;
        uint256 maxCometReferenceDeviationBps;
        uint256 maxRateStaleness;
        uint256 safeHealthFactor;
        uint256 riskHealthFactor;
        int256 safeCarrySpreadBps;
        int256 riskCarrySpreadBps;
        uint256 maxBorrowRateBps;
        uint256 maxTotalDebt;
        uint256 maxVaultAssets;
        uint256 maxLeverageAmount;
        uint256 minLeverageAmount;
        uint256 maxShareSlippageBps;
        uint256 leverageMinInterval;
        uint256 epochLength;
        uint256 epochBorrowBudget;
        uint256 maxEconomicDeleverageBps;
        uint256 economicDeleverageMinInterval;
        uint256 economicDeleverageMinAmount;
        uint256 minAnnualIncomeImprovement;
    }

    /// @notice Typed keeper plan; queue paths use vaultShares, and claims also specify minAssetsOut.
    /// @dev loanAmount and minAssetsOut use raw base-asset units; share limits and vaultShares
    ///      use raw vault shares. DeleverageAll supplies zero numeric fields and infers debt-limited
    ///      capacity, additionally capped and paced for economic exits. Syrup request and ready
    ///      claim actions retain separate, unpaced settlement semantics; requests do not repay debt.
    ///      Optimization uses the exact deleverage fields. Quote variants use the corresponding
    ///      action's fields, bypass scheduling only, and always revert after the execution proof.
    struct Plan {
        bytes32 policyId;
        uint8 action;
        uint256 loanAmount;
        uint256 minSharesOut;
        uint256 maxSharesBurned;
        uint256 vaultShares;
        uint256 minAssetsOut;
    }

    mapping(bytes32 policyId => Policy policy) internal policies;

    /// @notice Maximum retained Compound policy IDs, bounding complete current-state review.
    uint256 public constant MAX_POLICIES = 32;

    bytes32[] private policyIds;

    /// @notice Last successful economic synchronous exit per policy, in Unix seconds.
    /// @dev Risk exits and asynchronous request/claim settlement do not use this clock.
    mapping(bytes32 policyId => uint256 timestamp) public lastEconomicDeleverage;

    /// @notice Immutable stateless reader used for Comet risk checks via static calls.
    CompoundCarryRisk public immutable RISK;

    /// @notice Bind the engine to one StrategyModule and deploy its stateless risk reader.
    /// @param module StrategyModule serving this engine's Safe.
    constructor(StrategyModule module) ForwardingGuard(module) {
        RISK = new CompoundCarryRisk();
    }

    struct Snapshot {
        IComet.UserBasic user;
        IComet.TotalsBasic totals;
        IComet.AssetInfo collateralInfo;
        uint256 collateral;
        uint256 debt;
        uint256 health;
        uint256 collateralPrice;
        uint256 basePrice;
        uint256 vaultShares;
        uint256 looseBase;
        uint256 looseCollateral;
        bool deactivated;
    }

    struct ExecutionContext {
        uint256 amount;
        uint256 maximumSharesBurned;
        uint256 proceeds;
        int256 carryBefore;
        bool healthTriggered;
        bool carryTriggered;
        bool optimizeIncome;
        // Before-state upper bound prevents bps quantization from proving a false improvement.
        int256 annualIncomeBefore;
    }

    event CarryPolicyAdded(bytes32 indexed policyId);
    event CarryPolicyUpdated(bytes32 indexed policyId);
    event EconomicDeleverageRecorded(bytes32 indexed policyId, uint256 timestamp);
    event CarryTradeExecuted(
        bytes32 indexed policyId,
        address indexed safe,
        Action action,
        uint256 assets,
        uint256 vaultShares,
        uint256 debtAfter
    );

    /// @notice Add a validated policy in the disabled state.
    /// @dev Callable only by the Safe; enablePolicy is separate. All IDs remain enumerable,
    ///      including disabled policies, and at most MAX_POLICIES may ever be added.
    /// @param policyId Safe-selected identifier.
    /// @param policy Pinned market/vault route and risk limits.
    function addPolicy(bytes32 policyId, Policy calldata policy) external {
        _onlySafe();
        _validatePolicy(policy);
        _addPolicy(policyId, keccak256(abi.encode(policy)));
        if (policyIds.length >= MAX_POLICIES) revert CompoundCarryTradeEngine_PolicyLimitExceeded();
        policyIds.push(policyId);
        policies[policyId] = policy;
        emit CarryPolicyAdded(policyId);
    }

    /// @notice Update risk limits while retaining identity, pending exits, cooldowns, and budget history.
    /// @dev Callable only by the Safe; disables all actions until explicitly re-enabled.
    /// @param policyId Existing identifier.
    /// @param policy Replacement policy with unchanged identities and epoch length.
    function updatePolicy(bytes32 policyId, Policy calldata policy) external {
        _onlySafe();
        _updatePolicy(policyId, keccak256(abi.encode(policy)));
        if (RISK.identityHash(policies[policyId]) != RISK.identityHash(policy)) {
            revert CompoundCarryTradeEngine_IdentityChange();
        }
        _validatePolicy(policy);
        policies[policyId] = policy;
        emit CarryPolicyUpdated(policyId);
    }

    /// @notice Disable all policy actions without deleting configuration or pending exits.
    /// @dev Callable only by the Safe; claims require re-enabling and external Maple queues continue independently.
    /// @param policyId Existing identifier.
    function disablePolicy(bytes32 policyId) external {
        _onlySafe();
        _disablePolicy(policyId);
    }

    /// @notice Read a Safe-owned carry policy.
    /// @dev Unrestricted read; an unconfigured identifier returns the zero-initialized record.
    /// @param policyId Policy identifier.
    /// @return policy Stored configuration.
    function getPolicy(bytes32 policyId) external view returns (Policy memory policy) {
        return policies[policyId];
    }

    /// @notice Count every configured policy, including disabled policies retained for audit.
    /// @return count Number of IDs, never above MAX_POLICIES.
    function policyCount() external view returns (uint256 count) {
        return policyIds.length;
    }

    /// @notice Read a retained policy ID in insertion order.
    /// @param index Zero-based index strictly below policyCount; other indices revert.
    /// @return policyId Configured policy identifier.
    function policyIdAt(uint256 index) external view returns (bytes32 policyId) {
        return policyIds[index];
    }

    /// @notice Check a typed plan using projected interest and current vault observations.
    /// @dev Unrestricted advisory view; decoding and external reads may revert. Prospective borrow
    ///      rates include the proposed amount but do not guarantee observed rates, liquidity or postconditions.
    ///      Quote plans bypass scheduling cooldowns and always revert after full execution; their
    ///      advisory admission does not establish that the corresponding real action is ready.
    /// @param safe Position owner served by the module.
    /// @param data ABI-encoded Plan.
    /// @return executable Whether all current-state conditions pass.
    /// @return reason First failed contextual check, or zero.
    function canExecute(address safe, bytes calldata data)
        external
        view
        override
        returns (bool executable, bytes4 reason)
    {
        if (safe != MODULE.SAFE()) return (false, CompoundCarryTradeEngine_WrongSafe.selector);
        Plan memory plan = abi.decode(data, (Plan));
        bool quote = _normalizePlan(plan);
        Policy memory policy = policies[plan.policyId];
        reason = _canUsePolicy(
            plan.policyId, !quote && plan.action == uint8(Action.Leverage) ? policy.leverageMinInterval : 0
        );
        if (reason != 0) return (false, reason);
        reason = RISK.shapeReason(plan);
        if (reason != 0) return (false, reason);
        reason = _identityReason(policy, safe);
        if (reason != 0) return (false, reason);
        Snapshot memory before = RISK.readPosition(policy, safe, true, plan.action != uint8(Action.ClaimAndRepay));
        reason = RISK.positionReason(policy, before);
        if (reason != 0) return (false, reason);
        (reason,) = _preconditions(policy, plan, before, safe, quote);
        // Zero is the typed validation-success sentinel.
        // slither-disable-next-line incorrect-equality
        return (reason == 0, reason);
    }

    /// @notice Execute one fixed carry action, reconciling actual accrued principal and Safe custody.
    /// @dev Callable only by the module, which supplies its Safe. Observed post-borrow rates and
    ///      principal/custody changes are checked. Claims repay only proceeds received in this call;
    ///      preexisting Safe base assets and collateral remain untouched by every action.
    ///      Quotes bypass scheduling only, run all other checks, then return observations by reverting
    ///      the complete transaction, including custody, cooldown and borrow-budget changes.
    /// @param safe Position owner served by the module.
    /// @param data ABI-encoded Plan.
    // StrategyModule's active-strategy mutex covers every protocol forward; direct
    // execute calls fail _onlyModule. Accrued debt and exact asset deltas are postconditions.
    // slither-disable-next-line reentrancy-balance,reentrancy-no-eth
    function execute(address safe, bytes calldata data) external override {
        _onlyModule();
        if (safe != MODULE.SAFE()) revert CompoundCarryTradeEngine_WrongSafe();
        Plan memory plan = abi.decode(data, (Plan));
        bool quote = _normalizePlan(plan);
        _requirePolicyEnabled(plan.policyId);
        _check(RISK.shapeReason(plan));
        Policy memory policy = policies[plan.policyId];
        _check(_identityReason(policy, safe));
        _forwardChecked(address(policy.comet), abi.encodeCall(IComet.accrueAccount, (safe)), true);
        Snapshot memory before = RISK.readPosition(policy, safe, false, plan.action != uint8(Action.ClaimAndRepay));
        _check(RISK.positionReason(policy, before));
        (bytes4 reason, ExecutionContext memory context) = _preconditions(policy, plan, before, safe, quote);
        _check(reason);
        if (plan.action == uint8(Action.Leverage)) {
            _touchCooldown(plan.policyId, quote ? 0 : policy.leverageMinInterval);
            _forwardChecked(
                address(policy.comet), abi.encodeCall(IComet.withdraw, (policy.baseAsset, context.amount)), true
            );
            _carryVaultDeposit(policy.vaultConfig, policy.baseAsset, context.amount, safe);
        } else if (plan.action == uint8(Action.RequestDeleverage)) {
            _carryVaultRequest(plan.policyId, policy.vaultConfig, plan.vaultShares, safe);
        } else {
            if (plan.action == uint8(Action.ClaimAndRepay)) {
                context.proceeds =
                    _carryVaultClaim(plan.policyId, policy.vaultConfig, policy.baseAsset, plan.vaultShares, safe);
                if (context.proceeds < plan.minAssetsOut) revert CompoundCarryTradeEngine_ShareSlippage();
                if (
                    before.debt != 0
                        && context.proceeds
                            > before.debt + FullMath.mulDiv(before.debt, policy.maxShareSlippageBps, 10_000) + 1
                ) {
                    revert CompoundCarryTradeEngine_AmountOutOfBounds();
                }
                context.amount = context.proceeds < before.debt ? context.proceeds : before.debt;
            } else {
                _carryVaultWithdraw(policy.vaultConfig, context.amount, safe);
            }
            if (context.amount != 0) _repay(policy, safe, context.amount);
        }
        Snapshot memory after_ = RISK.readPosition(policy, safe, false, plan.action != uint8(Action.ClaimAndRepay));
        _check(_identityReason(policy, safe));
        _postconditions(policy, plan, context, before, after_, safe);
        emit CarryTradeExecuted(plan.policyId, safe, Action(plan.action), context.amount, plan.vaultShares, after_.debt);
        if (quote) RISK.executionQuote(policy, plan.action, after_);
    }

    function _normalizePlan(Plan memory plan) internal pure returns (bool quote) {
        if (plan.action < uint8(Action.QuoteLeverage) || plan.action > uint8(Action.QuoteOptimizeDeleverage)) {
            return false;
        }
        plan.action = plan.action == uint8(Action.QuoteLeverage)
            ? uint8(Action.Leverage)
            : plan.action == uint8(Action.QuoteDeleverage) ? uint8(Action.Deleverage) : uint8(Action.OptimizeDeleverage);
        return true;
    }

    function _preconditions(Policy memory policy, Plan memory plan, Snapshot memory before, address safe, bool quote)
        internal
        view
        returns (bytes4 reason, ExecutionContext memory context)
    {
        context.amount = plan.loanAmount;
        if (plan.action == uint8(Action.Leverage)) {
            reason = _leverageReason(policy, plan, before, safe);
            if (reason == 0 && policy.minAnnualIncomeImprovement != 0) {
                context.annualIncomeBefore = RISK.annualIncomeUpperBound(policy, before);
            }
            return (reason, context);
        }
        if (plan.action == uint8(Action.ClaimAndRepay)) return (_claimReason(policy, plan, before, safe), context);
        (reason, context) = RISK.deleverageContext(
            policy,
            plan,
            before,
            _carryVaultWithdrawCapacity(policy.vaultConfig, safe),
            lastEconomicDeleverage[plan.policyId],
            quote
        );
        if (reason != 0) return (reason, context);
        if (plan.action == uint8(Action.RequestDeleverage)) {
            reason = _carryVaultRequestReason(policy.vaultConfig, safe);
            if (reason != 0) return (reason, context);
            if (plan.vaultShares > before.vaultShares) {
                return (CompoundCarryTradeEngine_VaultCapacityExceeded.selector, context);
            }
            uint256 quotedAssets = _carryVaultRequestAssets(policy.vaultConfig, plan.vaultShares);
            return (
                _exitSizeReason(
                    policy, plan.vaultShares, quotedAssets, before.debt, plan.action == uint8(Action.ClaimAndRepay)
                ),
                context
            );
        }
    }

    function _claimReason(Policy memory policy, Plan memory plan, Snapshot memory before, address safe)
        internal
        view
        returns (bytes4 reason)
    {
        if (policy.vaultConfig.kind != VaultKind.Syrup) return CarryVaultCapability_NotSyrup.selector;
        if (plan.vaultShares > _carryVaultClaimableShares(policy.vaultConfig, safe)) {
            return CompoundCarryTradeEngine_VaultCapacityExceeded.selector;
        }
        uint256 quote = _carryVaultPreviewClaim(policy.vaultConfig, plan.vaultShares, safe);
        if (before.debt == 0) {
            if (plan.vaultShares > _carryVaultPendingExitShares(plan.policyId, policy.vaultConfig, safe)) {
                return CompoundCarryTradeEngine_AmountOutOfBounds.selector;
            }
        } else {
            reason = RISK.repayPauseReason(policy);
            if (reason != 0) return reason;
            reason = _exitSizeReason(
                policy, plan.vaultShares, quote, before.debt, plan.action == uint8(Action.ClaimAndRepay)
            );
            if (reason != 0) return reason;
        }
        if (plan.minAssetsOut < CarryTradeRisk.minSharesOut(quote, policy.maxShareSlippageBps)) {
            return CompoundCarryTradeEngine_ShareSlippage.selector;
        }
    }

    function _exitSizeReason(Policy memory policy, uint256 shares, uint256 quote, uint256 debt, bool claim)
        internal
        view
        returns (bytes4)
    {
        uint256 maximumAssets = debt + FullMath.mulDiv(debt, policy.maxShareSlippageBps, 10_000) + 1;
        if (
            debt == 0 || shares > _carryVaultRequestShares(policy.vaultConfig, claim ? maximumAssets : debt)
                || quote == 0 || quote > maximumAssets
        ) {
            return CompoundCarryTradeEngine_AmountOutOfBounds.selector;
        }
        return bytes4(0);
    }

    function _postconditions(
        Policy memory policy,
        Plan memory plan,
        ExecutionContext memory context,
        Snapshot memory before,
        Snapshot memory after_,
        address safe
    ) internal {
        RISK.executionPostconditions(policy, plan, context, before, after_, safe);
        if (plan.action == uint8(Action.Leverage)) {
            uint256 increase = after_.debt - before.debt;
            _bookEpochNotional(
                plan.policyId,
                increase > context.amount ? increase : context.amount,
                policy.epochLength,
                policy.epochBorrowBudget
            );
        } else if (
            plan.action != uint8(Action.RequestDeleverage) && plan.action != uint8(Action.ClaimAndRepay)
                && (context.carryTriggered || context.optimizeIncome)
        ) {
            lastEconomicDeleverage[plan.policyId] = block.timestamp;
            emit EconomicDeleverageRecorded(plan.policyId, block.timestamp);
        }
        _assertNoResidualApproval(policy.baseAsset, address(policy.comet), safe);
    }

    function _repay(Policy memory policy, address safe, uint256 amount) internal {
        _forwardChecked(policy.baseAsset, abi.encodeCall(IERC20Minimal.approve, (address(policy.comet), amount)), true);
        _forwardChecked(address(policy.comet), abi.encodeCall(IComet.supply, (policy.baseAsset, amount)), true);
        _forwardChecked(policy.baseAsset, abi.encodeCall(IERC20Minimal.approve, (address(policy.comet), 0)), true);
        _assertNoResidualApproval(policy.baseAsset, address(policy.comet), safe);
    }

    function _identityReason(Policy memory policy, address safe) internal view returns (bytes4 reason) {
        reason = RISK.identityReason(policy);
        return reason != 0 ? reason : _carryVaultIdentityReason(policy.vaultConfig, policy.baseAsset, safe);
    }

    function _validatePolicy(Policy calldata policy) internal view {
        RISK.validatePolicy(policy);
        _check(_carryVaultIdentityReason(policy.vaultConfig, policy.baseAsset, MODULE.SAFE()));
    }

    function _leverageReason(Policy memory policy, Plan memory plan, Snapshot memory before, address safe)
        internal
        view
        returns (bytes4 reason)
    {
        reason = _carryVaultLeverageReason(policy.vaultConfig, safe);
        if (reason != 0) return reason;
        reason = RISK.leverageReason(policy, plan, before);
        if (reason != 0) return reason;
        (, uint256 resultingDebt) =
            RISK.principalAfter(before.user.principal, plan.loanAmount, before.totals.baseBorrowIndex, true);
        uint256 increase = resultingDebt - before.debt;
        (bool budget,) = _epochHasNotionalCapacity(
            plan.policyId,
            increase > plan.loanAmount ? increase : plan.loanAmount,
            policy.epochLength,
            policy.epochBorrowBudget
        );
        if (!budget) return CompoundCarryTradeEngine_BorrowBudgetExceeded.selector;
        if (plan.loanAmount > _carryVaultDepositCapacity(policy.vaultConfig, safe)) {
            return CompoundCarryTradeEngine_VaultCapacityExceeded.selector;
        }
        uint256 preview = policy.vaultConfig.vault.previewDeposit(plan.loanAmount);
        if (preview == 0 || plan.minSharesOut < CarryTradeRisk.minSharesOut(preview, policy.maxShareSlippageBps)) {
            return CompoundCarryTradeEngine_ShareSlippage.selector;
        }
    }

    function _check(bytes4 reason) internal pure {
        if (reason != 0) {
            assembly ("memory-safe") {
                mstore(0, reason)
                revert(0, 4)
            }
        }
    }

    function _isAllowedTarget(address) internal pure override returns (bool) {
        return false;
    }
}

/// @title CompoundCarryRisk
/// @notice Stateless Comet observations and risk checks shared by preflight and execution.
/// @dev The engine deploys and pins this reader. All entrypoints are unrestricted views or pure
///      calculations; caller-supplied inputs grant no authority. It never forwards calls or changes custody/state.
contract CompoundCarryRisk {
    /// @notice Read the Safe's Comet position, balances and optional price observations.
    /// @dev Unrestricted view; projection uses current rates and external calls may revert.
    /// @param policy Pinned Comet, collateral, and vault configuration.
    /// @param safe Position and asset owner.
    /// @param project Whether to project pending interest before reading debt.
    /// @param readPrices Whether health checks require price observations; false for claim settlement.
    /// @return snapshot Observed custody, principal, debt, and optional health data.
    function readPosition(CompoundCarryTradeEngine.Policy memory policy, address safe, bool project, bool readPrices)
        external
        view
        returns (CompoundCarryTradeEngine.Snapshot memory snapshot)
    {
        snapshot.user = policy.comet.userBasic(safe);
        snapshot.totals = policy.comet.totalsBasic();
        // Comet accrues interest through the current block timestamp.
        // forge-lint: disable-next-line(block-timestamp)
        if (project && block.timestamp != snapshot.totals.lastAccrualTime) {
            uint256 utilization = policy.comet.getUtilization();
            (snapshot.totals.baseSupplyIndex, snapshot.totals.baseBorrowIndex) = CometCarryMath.accruedIndices(
                snapshot.totals.baseSupplyIndex,
                snapshot.totals.baseBorrowIndex,
                policy.comet.getSupplyRate(utilization),
                policy.comet.getBorrowRate(utilization),
                block.timestamp - snapshot.totals.lastAccrualTime
            );
        }
        if (snapshot.user.principal <= 0) {
            snapshot.debt = CometCarryMath.debtAssets(snapshot.user.principal, snapshot.totals.baseBorrowIndex);
        }
        snapshot.collateralInfo = policy.comet.getAssetInfoByAddress(policy.collateralAsset);
        snapshot.collateral = policy.comet.collateralBalanceOf(safe, policy.collateralAsset);
        if (readPrices) {
            snapshot.collateralPrice = policy.comet.getPrice(policy.collateralPriceFeed);
            snapshot.basePrice = policy.comet.getPrice(policy.basePriceFeed);
            if (snapshot.collateralPrice == 0 || snapshot.basePrice == 0) {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_UnexpectedPosition();
            }
            snapshot.health = _health(policy, snapshot, snapshot.debt);
        }
        snapshot.vaultShares = policy.vaultConfig.vault.balanceOf(safe);
        snapshot.looseBase = IERC20Minimal(policy.baseAsset).balanceOf(safe);
        snapshot.looseCollateral = IERC20Minimal(policy.collateralAsset).balanceOf(safe);
        snapshot.deactivated = policy.cometKind == CompoundCarryTradeEngine.CometKind.Institutional
            && policy.comet.isCollateralDeactivated(policy.collateralOffset);
    }

    function _health(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory snapshot,
        uint256 debt
    ) internal pure returns (uint256) {
        return CometCarryMath.healthFactor(
            snapshot.collateral,
            snapshot.collateralPrice,
            snapshot.collateralInfo.scale,
            snapshot.collateralInfo.liquidateCollateralFactor,
            debt,
            snapshot.basePrice,
            10 ** policy.baseDecimals
        );
    }

    /// @notice Check that the supplied snapshot contains only the admitted borrowing position.
    /// @dev Unrestricted pure check of caller-supplied observations; it does not attest to live state.
    /// @param policy Pinned collateral identity and bitmap offset.
    /// @param snapshot Position to validate.
    /// @return Zero for an isolated borrowing position, otherwise a contextual selector.
    function positionReason(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory snapshot
    ) public pure returns (bytes4) {
        uint256 bitmap = uint256(snapshot.user.assetsIn) | (uint256(snapshot.user._reserved) << 16);
        uint256 expected = snapshot.collateral == 0 ? 0 : uint256(1) << policy.collateralOffset;
        if (snapshot.user.principal > 0 || bitmap != expected) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_UnexpectedPosition.selector;
        }
        return bytes4(0);
    }

    /// @notice Enforce exact custody, principal, shares and action-specific execution risk.
    /// @dev Unrestricted checks of supplied observations; the engine retains all policy state,
    ///      and any failed validation reverts forwarding and bookkeeping together.
    /// @param policy Safe-selected identities and risk limits.
    /// @param plan Normalized fixed action and exact share limits.
    /// @param context Frozen admission observations and actual settlement proceeds.
    /// @param before Accrued position before forwarding.
    /// @param after_ Position after forwarding.
    /// @param safe Safe whose native borrow collateralization is checked.
    function executionPostconditions(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Plan memory plan,
        CompoundCarryTradeEngine.ExecutionContext memory context,
        CompoundCarryTradeEngine.Snapshot memory before,
        CompoundCarryTradeEngine.Snapshot memory after_,
        address safe
    ) external view {
        _check(positionReason(policy, after_));
        if (
            before.collateral != after_.collateral || before.looseCollateral != after_.looseCollateral
                || before.user.assetsIn != after_.user.assetsIn || before.user._reserved != after_.user._reserved
                || before.totals.baseBorrowIndex != after_.totals.baseBorrowIndex
        ) revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_PositionChanged();
        if (plan.action == uint8(CompoundCarryTradeEngine.Action.Leverage)) {
            int104 expected = CometCarryMath.principalAfterBorrow(
                before.user.principal, context.amount, before.totals.baseBorrowIndex
            );
            if (after_.user.principal != expected) {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_PrincipalMismatch();
            }
            if (after_.debt <= before.debt) revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_DebtDirection();
            if (after_.debt > policy.maxTotalDebt) {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_DebtCapExceeded();
            }
            if (policy.vaultConfig.vault.convertToAssets(after_.vaultShares) > policy.maxVaultAssets) {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_VaultAllocationCapExceeded();
            }
            leveragePostconditions(policy, after_, safe, context.annualIncomeBefore);
            if (after_.vaultShares < before.vaultShares || after_.vaultShares - before.vaultShares < plan.minSharesOut)
            {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_ShareSlippage();
            }
        } else if (plan.action == uint8(CompoundCarryTradeEngine.Action.RequestDeleverage)) {
            if (after_.user.principal != before.user.principal) {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_PrincipalMismatch();
            }
            if (after_.vaultShares > before.vaultShares || before.vaultShares - after_.vaultShares != plan.vaultShares)
            {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_ShareSlippage();
            }
        } else {
            int104 expected = CometCarryMath.principalAfterRepay(
                before.user.principal, context.amount, before.totals.baseBorrowIndex
            );
            if (after_.user.principal != expected) {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_PrincipalMismatch();
            }
            if (before.debt != 0 && after_.debt >= before.debt) {
                revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_DebtDirection();
            }
            if (plan.action == uint8(CompoundCarryTradeEngine.Action.ClaimAndRepay)) {
                if (after_.vaultShares != before.vaultShares) {
                    revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_ShareSlippage();
                }
            } else {
                if (
                    after_.vaultShares > before.vaultShares
                        || before.vaultShares - after_.vaultShares > context.maximumSharesBurned
                ) {
                    revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_ShareSlippage();
                }
                protectivePostconditions(policy, context, before, after_);
            }
        }
        uint256 expectedLoose = before.looseBase + context.proceeds;
        if (plan.action == uint8(CompoundCarryTradeEngine.Action.ClaimAndRepay)) expectedLoose -= context.amount;
        if (after_.looseBase != expectedLoose) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_PositionChanged();
        }
    }

    function _utilization(IComet.TotalsBasic memory totals, uint256 borrowPrincipal) internal pure returns (uint256) {
        uint256 supply = FullMath.mulDiv(totals.totalSupplyBase, totals.baseSupplyIndex, 1e15);
        if (supply == 0) return 0;
        return FullMath.mulDiv(FullMath.mulDiv(borrowPrincipal, totals.baseBorrowIndex, 1e15), 1e18, supply);
    }

    function _currentBorrowRate(CompoundCarryTradeEngine.Policy memory policy, IComet.TotalsBasic memory totals)
        internal
        view
        returns (uint256)
    {
        return policy.comet.getBorrowRate(_utilization(totals, totals.totalBorrowBase));
    }

    function _carry(CompoundCarryTradeEngine.Policy memory policy, uint256 perSecondRate)
        internal
        view
        returns (bytes4 reason, int256 spread, uint256 borrowBps)
    {
        (uint256 yieldBps, uint256 updatedAt) = policy.rateOracle.vaultRateBps(address(policy.vaultConfig.vault));
        // Source freshness uses the chain clock and rejects future observations.
        // forge-lint: disable-start(block-timestamp)
        if (
            updatedAt == 0 || updatedAt > block.timestamp || block.timestamp - updatedAt > policy.maxRateStaleness
                || yieldBps > uint256(type(int256).max)
        ) return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_InvalidRate.selector, 0, 0);
        // forge-lint: disable-end(block-timestamp)
        borrowBps = CometCarryMath.borrowRateBpsUp(perSecondRate);
        if (borrowBps > uint256(type(int256).max)) {
            return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_InvalidRate.selector, 0, 0);
        }
        // Both rates are bounded by int256.max above; their difference fits int256.
        // forge-lint: disable-next-line(unsafe-typecast)
        spread = int256(yieldBps) - int256(borrowBps);
    }

    function _referenceReason(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory snapshot
    ) internal view returns (bytes4) {
        ReferencePrice.Data memory observation = ReferencePrice.read(
            policy.referenceOracle,
            policy.collateralAsset,
            policy.baseAsset,
            policy.collateralDecimals,
            policy.baseDecimals
        );
        uint256 price = observation.priceX18;
        uint256 updatedAt = observation.updatedAt;
        // Timestamp comparisons enforce the Safe's reference-feed freshness policy.
        // forge-lint: disable-start(block-timestamp)
        if (
            price == 0 || updatedAt == 0 || updatedAt > block.timestamp
                || block.timestamp - updatedAt > policy.maxReferenceStaleness
        ) return CompoundCarryTradeEngine.CompoundCarryTradeEngine_InvalidReference.selector;
        // forge-lint: disable-end(block-timestamp)
        uint256 crossPrice = FullMath.mulDiv(snapshot.collateralPrice, 1e18, snapshot.basePrice);
        if (CarryTradeRisk.deviationBps(crossPrice, price) > policy.maxCometReferenceDeviationBps) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_ReferenceDeviation.selector;
        }
        return bytes4(0);
    }

    /// @notice Check the configured Comet variant's base-repayment pause flags.
    /// @dev Unrestricted view; external protocol failures may revert.
    /// @param policy Comet address and explicit API variant.
    /// @return Zero when repayment is enabled, otherwise the pause selector.
    function repayPauseReason(CompoundCarryTradeEngine.Policy memory policy) external view returns (bytes4) {
        return _repayPauseReason(policy);
    }

    function _repayPauseReason(CompoundCarryTradeEngine.Policy memory policy) internal view returns (bytes4) {
        return policy.comet.isSupplyPaused()
            || (policy.cometKind == CompoundCarryTradeEngine.CometKind.Institutional
                && policy.comet.isBaseSupplyPaused())
            ? CompoundCarryTradeEngine.CompoundCarryTradeEngine_MarketPaused.selector
            : bytes4(0);
    }

    function _identityReason(CompoundCarryTradeEngine.Policy memory policy) internal view returns (bytes4) {
        IComet.AssetInfo memory info = policy.comet.getAssetInfoByAddress(policy.collateralAsset);
        if (
            policy.comet.baseToken() != policy.baseAsset || policy.comet.baseTokenPriceFeed() != policy.basePriceFeed
                || policy.comet.baseScale() != 10 ** policy.baseDecimals
                || IERC20Metadata(policy.baseAsset).decimals() != policy.baseDecimals
                || IERC20Metadata(policy.collateralAsset).decimals() != policy.collateralDecimals
                || info.asset != policy.collateralAsset || info.priceFeed != policy.collateralPriceFeed
                || info.scale != 10 ** policy.collateralDecimals || info.offset != policy.collateralOffset
                || info.offset >= policy.comet.numAssets()
                || info.borrowCollateralFactor > info.liquidateCollateralFactor || info.liquidateCollateralFactor > 1e18
        ) return CompoundCarryTradeEngine.CompoundCarryTradeEngine_IdentityMismatch.selector;
        return bytes4(0);
    }

    /// @notice Validate the policy's Comet identities, units and risk bounds.
    /// @dev Unrestricted view; reverts on invalid configuration or failed external reads.
    /// @param policy Pinned identities and risk limits to validate.
    function validatePolicy(CompoundCarryTradeEngine.Policy calldata policy) external view {
        if (
            address(policy.comet).code.length == 0 || policy.collateralAsset.code.length == 0
                || policy.baseAsset.code.length == 0 || policy.collateralPriceFeed.code.length == 0
                || policy.basePriceFeed.code.length == 0 || address(policy.referenceOracle).code.length == 0
                || address(policy.rateOracle).code.length == 0 || policy.collateralAsset == policy.baseAsset
                || address(policy.vaultConfig.vault) == policy.baseAsset
                || address(policy.vaultConfig.vault) == policy.collateralAsset
                || address(policy.referenceOracle) == policy.collateralPriceFeed
                || address(policy.referenceOracle) == policy.basePriceFeed || policy.collateralDecimals > 18
                || policy.baseDecimals > 18 || policy.collateralOffset >= 24
                || policy.safeHealthFactor <= policy.riskHealthFactor || policy.riskHealthFactor <= 1e18
                || policy.safeCarrySpreadBps < 0 || policy.safeCarrySpreadBps <= policy.riskCarrySpreadBps
                || policy.maxReferenceStaleness == 0 || policy.maxRateStaleness == 0
                || policy.maxCometReferenceDeviationBps > 10_000 || policy.maxShareSlippageBps >= 10_000
                || policy.maxBorrowRateBps > uint256(type(int256).max) || policy.maxTotalDebt == 0
                || policy.maxVaultAssets == 0 || policy.maxTotalDebt > uint256(uint104(type(int104).max))
                || policy.minLeverageAmount == 0 || policy.minLeverageAmount > policy.maxLeverageAmount
                || policy.maxLeverageAmount > policy.maxTotalDebt || policy.epochLength == 0
                || policy.epochLength > type(uint128).max || policy.epochBorrowBudget == 0
                || policy.epochBorrowBudget > type(uint128).max || policy.maxEconomicDeleverageBps == 0
                || policy.maxEconomicDeleverageBps > 10_000 || policy.economicDeleverageMinInterval == 0
                || policy.economicDeleverageMinAmount == 0 || policy.economicDeleverageMinAmount > policy.maxTotalDebt
        ) revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_InvalidPolicy();
        _check(_identityReason(policy));
        ReferencePrice.requirePair(
            policy.referenceOracle,
            policy.collateralAsset,
            policy.baseAsset,
            policy.collateralDecimals,
            policy.baseDecimals
        );
    }

    /// @notice Classify protective exits and bound synchronous repayment size and pacing.
    /// @dev Risk repayment bypasses economic limits and yield observations; optimization is
    ///      always paced and requires fresh annual-income observations. Async
    ///      requests keep their existing debt bounds; ready claims are validated separately.
    /// @param policy Safe-selected risk limits, with amounts in raw base-asset units.
    /// @param plan Typed exit action.
    /// @param before Accrued position preceding the exit.
    /// @param capacity Synchronous vault capacity under the configured route's semantics.
    /// @param lastEconomic Timestamp of the policy's last economic synchronous repayment.
    /// @param quote Whether scheduling cooldowns are bypassed for a reverting execution quote.
    /// @return reason Zero when trigger, sizing and pacing checks pass.
    /// @return context Observed triggers and bounded execution amounts.
    function deleverageContext(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Plan memory plan,
        CompoundCarryTradeEngine.Snapshot memory before,
        uint256 capacity,
        uint256 lastEconomic,
        bool quote
    ) external view returns (bytes4 reason, CompoundCarryTradeEngine.ExecutionContext memory context) {
        context.amount = plan.loanAmount;
        context.optimizeIncome = plan.action == uint8(CompoundCarryTradeEngine.Action.OptimizeDeleverage);
        if (context.optimizeIncome) {
            if (policy.minAnnualIncomeImprovement == 0) {
                return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_OptimizationDisabled.selector, context);
            }
            context.annualIncomeBefore = _annualIncome(policy, before, true);
        } else {
            context.healthTriggered =
                before.debt != 0 && (before.deactivated || before.health < policy.riskHealthFactor);
        }
        if (!context.healthTriggered && !context.optimizeIncome) {
            (reason, context.carryBefore,) = _carry(policy, _currentBorrowRate(policy, before.totals));
            if (reason != 0) return (reason, context);
            context.carryTriggered = before.debt != 0 && context.carryBefore < policy.riskCarrySpreadBps;
        }
        if (!context.healthTriggered && !context.carryTriggered && !context.optimizeIncome) {
            return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_DeleverageNotTriggered.selector, context);
        }
        if (plan.action == uint8(CompoundCarryTradeEngine.Action.RequestDeleverage)) return (bytes4(0), context);
        reason = _repayPauseReason(policy);
        if (reason != 0) return (reason, context);
        uint256 maximumAmount = before.debt;
        if (context.carryTriggered || context.optimizeIncome) {
            // This clock is separate from borrowing and never delays hard-risk recovery.
            // forge-lint: disable-next-line(block-timestamp)
            if (
                !quote && lastEconomic != 0
                    && (block.timestamp < lastEconomic
                        || block.timestamp - lastEconomic < policy.economicDeleverageMinInterval)
            ) {
                return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_EconomicCooldownNotElapsed.selector, context);
            }
            uint256 cap = FullMath.mulDiv(before.debt, policy.maxEconomicDeleverageBps, 10_000);
            if (cap < policy.economicDeleverageMinAmount) cap = policy.economicDeleverageMinAmount;
            if (cap < maximumAmount) maximumAmount = cap;
        }
        if (plan.action == uint8(CompoundCarryTradeEngine.Action.DeleverageAll)) {
            context.amount = maximumAmount < capacity ? maximumAmount : capacity;
        }
        // Reject zero input and never supply more than the frozen accrued debt.
        // slither-disable-next-line incorrect-equality
        if (context.amount == 0 || context.amount > maximumAmount) {
            return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_AmountOutOfBounds.selector, context);
        }
        if (context.amount > capacity) {
            return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_VaultCapacityExceeded.selector, context);
        }
        int104 resulting =
            CometCarryMath.principalAfterRepay(before.user.principal, context.amount, before.totals.baseBorrowIndex);
        if (
            resulting <= before.user.principal
                || CometCarryMath.debtAssets(resulting, before.totals.baseBorrowIndex) >= before.debt
        ) return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_DebtDirection.selector, context);
        uint256 maximumShares = CarryTradeRisk.maxSharesBurned(
            policy.vaultConfig.vault.previewWithdraw(context.amount), policy.maxShareSlippageBps
        );
        context.maximumSharesBurned =
            plan.action == uint8(CompoundCarryTradeEngine.Action.DeleverageAll) ? maximumShares : plan.maxSharesBurned;
        if (context.maximumSharesBurned > maximumShares) {
            return (CompoundCarryTradeEngine.CompoundCarryTradeEngine_ShareSlippage.selector, context);
        }
    }

    /// @notice Evaluate projected Comet risk for the proposed borrow.
    /// @dev Unrestricted view; includes the proposed principal in utilization/rate calculations.
    ///      Supplied snapshots and prospective rates do not guarantee execution postconditions.
    /// @param policy Comet risk bounds and independent oracle sources.
    /// @param plan Requested borrowing amount.
    /// @param before Accrued position preceding the proposed borrow.
    /// @return reason Zero when the projected Comet risk checks pass.
    function leverageReason(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Plan memory plan,
        CompoundCarryTradeEngine.Snapshot memory before
    ) external view returns (bytes4 reason) {
        reason = _referenceReason(policy, before);
        if (reason != 0) return reason;
        if (
            policy.comet.isWithdrawPaused()
                || (policy.cometKind == CompoundCarryTradeEngine.CometKind.Institutional
                    && policy.comet.isBorrowersWithdrawPaused())
        ) return CompoundCarryTradeEngine.CompoundCarryTradeEngine_MarketPaused.selector;
        if (before.deactivated) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_CollateralDeactivated.selector;
        }
        uint256 amount = plan.loanAmount;
        if (
            amount < policy.minLeverageAmount || amount > policy.maxLeverageAmount
                || before.debt + amount < policy.comet.baseBorrowMin()
        ) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_AmountOutOfBounds.selector;
        }
        uint256 vaultAssets = policy.vaultConfig.vault.convertToAssets(before.vaultShares);
        if (vaultAssets > policy.maxVaultAssets || amount > policy.maxVaultAssets - vaultAssets) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_VaultAllocationCapExceeded.selector;
        }
        int104 resultingPrincipal =
            CometCarryMath.principalAfterBorrow(before.user.principal, amount, before.totals.baseBorrowIndex);
        uint256 resultingDebt = CometCarryMath.debtAssets(resultingPrincipal, before.totals.baseBorrowIndex);
        if (resultingDebt > policy.maxTotalDebt) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_DebtCapExceeded.selector;
        }
        if (resultingDebt <= before.debt) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_DebtDirection.selector;
        }
        if (
            _health(policy, before, resultingDebt) < policy.safeHealthFactor
                || FullMath.mulDivRoundingUp(resultingDebt, before.basePrice, 10 ** policy.baseDecimals)
                    > CometCarryMath.collateralCapacity(
                        before.collateral,
                        before.collateralPrice,
                        before.collateralInfo.scale,
                        before.collateralInfo.borrowCollateralFactor
                    )
        ) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_HealthFactorTooLow.selector;
        }
        if (amount > IERC20Minimal(policy.baseAsset).balanceOf(address(policy.comet))) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_InsufficientLiquidity.selector;
        }
        // Positive borrowing increases the magnitude of a nonpositive principal.
        // forge-lint: disable-start(unsafe-typecast)
        uint256 newTotalBorrowBase = uint256(before.totals.totalBorrowBase)
            + uint256(int256(before.user.principal) - int256(resultingPrincipal));
        // forge-lint: disable-end(unsafe-typecast)
        if (newTotalBorrowBase > type(uint104).max) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_AmountOutOfBounds.selector;
        }
        uint256 utilization = _utilization(before.totals, newTotalBorrowBase);
        if (
            policy.cometKind == CompoundCarryTradeEngine.CometKind.Institutional
                && utilization > policy.comet.MAX_SUPPORTED_UTILIZATION()
        ) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_UtilizationTooHigh.selector;
        }
        uint256 rate = policy.cometKind == CompoundCarryTradeEngine.CometKind.Institutional
            ? CometCarryMath.borrowRateAt(
                utilization,
                policy.comet.borrowKink(),
                policy.comet.borrowPerSecondInterestRateBase(),
                policy.comet.borrowPerSecondInterestRateSlopeLow(),
                policy.comet.borrowPerSecondInterestRateSlopeHigh()
            )
            : policy.comet.getBorrowRate(utilization);
        (bytes4 rateReason, int256 spread, uint256 borrowBps) = _carry(policy, rate);
        if (rateReason != 0) return rateReason;
        if (borrowBps > policy.maxBorrowRateBps) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_BorrowRateTooHigh.selector;
        }
        if (spread < policy.safeCarrySpreadBps) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_CarrySpreadTooLow.selector;
        }
    }

    /// @notice Enforce the triggered health and carry bounds after protective repayment.
    /// @dev Unrestricted check of supplied snapshots; partial repayment may remain below the
    ///      safe bands, but health and any observed economic carry spread must not worsen.
    /// @param policy Safe and risk thresholds.
    /// @param context Admission triggers and upper income estimate observed before execution.
    /// @param before Position preceding repayment.
    /// @param after_ Position following repayment.
    function protectivePostconditions(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.ExecutionContext memory context,
        CompoundCarryTradeEngine.Snapshot memory before,
        CompoundCarryTradeEngine.Snapshot memory after_
    ) public view {
        if (after_.health < before.health) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_HealthDidNotImprove();
        }
        if (context.optimizeIncome) _requireAnnualIncomeImprovement(policy, after_, context.annualIncomeBefore);
        if (context.carryTriggered && after_.debt != 0) {
            (bytes4 reason, int256 spread,) = _carry(policy, _currentBorrowRate(policy, after_.totals));
            _check(reason);
            if (spread < context.carryBefore) revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_CarryWorsened();
        }
    }

    function _check(bytes4 reason) internal pure {
        if (reason != 0) {
            assembly ("memory-safe") {
                mstore(0, reason)
                revert(0, 4)
            }
        }
    }

    /// @notice Estimate whole-position annual income at the observed current rates.
    /// @dev Unrestricted view of supplied snapshots; income is nominal base tokens per year,
    ///      with vault yield rounded down and borrowing cost up. Each component must fit int256.
    /// @param policy Vault and fresh rate-source configuration.
    /// @param snapshot Accrued debt and Safe-owned vault shares.
    /// @return income Signed raw base-asset units per year; excludes rewards and future changes.
    function annualIncome(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory snapshot
    ) external view returns (int256 income) {
        return _annualIncome(policy, snapshot, false);
    }

    /// @notice Bound estimated annual income above the reported rates' bps uncertainty.
    /// @dev Unrestricted view of supplied snapshots. Uses one additional vault bps with upward
    ///      yield rounding and one fewer borrow bps, floored at zero, with downward cost rounding.
    ///      Comparing a later lower estimate against this upper baseline avoids rounding-driven churn.
    /// @param policy Vault and fresh nominal rate-source configuration.
    /// @param snapshot Accrued debt and Safe-owned vault shares before execution.
    /// @return income Signed raw base-asset units per year; not a forecast or future-return guarantee.
    function annualIncomeUpperBound(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory snapshot
    ) external view returns (int256 income) {
        return _annualIncome(policy, snapshot, true);
    }

    /// @notice Revert with observations from an execution whose engine checks already passed.
    /// @dev Always reverts. Supplied snapshots grant no authority or independent live attestation;
    ///      the engine calls this last so all forwarded effects and bookkeeping roll back together.
    /// @param policy Pinned vault and annual rate source.
    /// @param action Normalized action number, excluding quote action numbers.
    /// @param snapshot Post-execution debt, shares and health.
    function executionQuote(
        CompoundCarryTradeEngine.Policy memory policy,
        uint8 action,
        CompoundCarryTradeEngine.Snapshot memory snapshot
    ) external view {
        (uint256 assets, uint256 vaultRate, uint256 borrowRate) = _incomeInputs(policy, snapshot);
        revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_ExecutionQuote(
            action, snapshot.debt, assets, vaultRate, borrowRate, snapshot.health
        );
    }

    function _incomeInputs(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory snapshot
    ) internal view returns (uint256 assets, uint256 vaultRate, uint256 borrowRate) {
        (bytes4 reason, int256 spread, uint256 borrowBps) = _carry(policy, _currentBorrowRate(policy, snapshot.totals));
        _check(reason);
        // _carry bounds both APRs by int256.max; adding the spread recovers nonnegative vault APR.
        vaultRate = uint256(spread + int256(borrowBps));
        borrowRate = borrowBps;
        assets = policy.vaultConfig.vault.convertToAssets(snapshot.vaultShares);
    }

    function _annualIncome(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory snapshot,
        bool upperBound
    ) internal view returns (int256 income) {
        (uint256 assets, uint256 vaultRate, uint256 borrowRate) = _incomeInputs(policy, snapshot);
        // _incomeInputs bounds each APR by int256.max, so the extra vault bps fits uint256.
        uint256 annualYield = upperBound
            ? FullMath.mulDivRoundingUp(assets, vaultRate + 1, 10_000)
            : FullMath.mulDiv(assets, vaultRate, 10_000);
        uint256 annualCost = upperBound
            ? FullMath.mulDiv(snapshot.debt, borrowRate == 0 ? 0 : borrowRate - 1, 10_000)
            : FullMath.mulDivRoundingUp(snapshot.debt, borrowRate, 10_000);
        if (annualYield > uint256(type(int256).max) || annualCost > uint256(type(int256).max)) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_AnnualIncomeOutOfBounds();
        }
        // Both bounded nonnegative components fit int256, as does their signed difference.
        income = int256(annualYield) - int256(annualCost);
    }

    function _requireAnnualIncomeImprovement(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory after_,
        int256 beforeIncome
    ) internal view {
        int256 afterIncome = _annualIncome(policy, after_, false);
        if (afterIncome <= beforeIncome) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_AnnualIncomeDidNotImprove();
        }
        // Opposite-sign income can improve by more than int256.max; its unsigned delta still fits.
        uint256 improvement = beforeIncome < 0 && afterIncome >= 0
            ? uint256(-beforeIncome) + uint256(afterIncome)
            : uint256(afterIncome - beforeIncome);
        if (improvement < policy.minAnnualIncomeImprovement) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_AnnualIncomeDidNotImprove();
        }
    }

    /// @notice Check pinned Comet market identities.
    /// @dev Unrestricted view; protocol and metadata reads may revert.
    /// @param policy Engine policy to inspect.
    /// @return reason Zero when the current configuration matches.
    function identityReason(CompoundCarryTradeEngine.Policy memory policy) external view returns (bytes4 reason) {
        return _identityReason(policy);
    }

    /// @notice Read the carry spread against the current accrued market rate.
    /// @dev Unrestricted view using the supplied totals; external rate-source failures may revert.
    /// @param policy Pinned vault rate source and market.
    /// @param totals Accrued market indices and principal totals.
    /// @return reason Zero if the yield observation is valid.
    /// @return spread Yield minus borrowing APR in basis points.
    /// @return borrowBps Borrow APR in basis points.
    function carry(CompoundCarryTradeEngine.Policy memory policy, IComet.TotalsBasic memory totals)
        external
        view
        returns (bytes4 reason, int256 spread, uint256 borrowBps)
    {
        return _carry(policy, _currentBorrowRate(policy, totals));
    }

    /// @notice Enforce actual post-borrow risk and fresh rates.
    /// @dev Unrestricted check of supplied observations and current protocol state; the engine
    ///      calls this after borrowing, so the rate includes the executed borrow's utilization.
    /// @param policy Configured risk bounds.
    /// @param after_ Actual accrued position after borrowing.
    /// @param safe Owner whose native borrow capacity is checked.
    /// @param annualIncomeBefore Upper estimate of whole-position annual income before borrowing.
    function leveragePostconditions(
        CompoundCarryTradeEngine.Policy memory policy,
        CompoundCarryTradeEngine.Snapshot memory after_,
        address safe,
        int256 annualIncomeBefore
    ) public view {
        if (after_.deactivated || after_.health < policy.safeHealthFactor || !policy.comet.isBorrowCollateralized(safe))
        {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_HealthFactorTooLow();
        }
        _check(_referenceReason(policy, after_));
        (bytes4 reason, int256 spread, uint256 rate) = _carry(policy, _currentBorrowRate(policy, after_.totals));
        _check(reason);
        if (rate > policy.maxBorrowRateBps) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_BorrowRateTooHigh();
        }
        if (spread < policy.safeCarrySpreadBps) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_CarrySpreadTooLow();
        }
        if (
            policy.cometKind == CompoundCarryTradeEngine.CometKind.Institutional
                && _utilization(after_.totals, after_.totals.totalBorrowBase) > policy.comet.MAX_SUPPORTED_UTILIZATION()
        ) {
            revert CompoundCarryTradeEngine.CompoundCarryTradeEngine_UtilizationTooHigh();
        }
        if (policy.minAnnualIncomeImprovement != 0) {
            _requireAnnualIncomeImprovement(policy, after_, annualIncomeBefore);
        }
    }

    /// @notice Compute exact Comet principal and asset debt after a proposed movement.
    /// @dev Unrestricted pure calculation using Comet's rounding and 1e15 borrow-index scale.
    /// @param principal Current zero or negative principal.
    /// @param amount Raw base-asset units borrowed or repaid.
    /// @param index Accrued borrow index scaled by 1e15.
    /// @param borrow Whether the movement increases debt.
    /// @return nextPrincipal Expected principal after protocol rounding.
    /// @return nextDebt Expected asset debt represented by that principal.
    function principalAfter(int104 principal, uint256 amount, uint64 index, bool borrow)
        external
        pure
        returns (int104 nextPrincipal, uint256 nextDebt)
    {
        nextPrincipal = borrow
            ? CometCarryMath.principalAfterBorrow(principal, amount, index)
            : CometCarryMath.principalAfterRepay(principal, amount, index);
        nextDebt = CometCarryMath.debtAssets(nextPrincipal, index);
    }

    /// @notice Validate the fixed plan field layout.
    /// @dev Unrestricted pure shape check; does not authorize or assess the requested action.
    /// @param plan Requested carry action and its typed fields.
    /// @return Zero when the shape is valid, otherwise a contextual selector.
    function shapeReason(CompoundCarryTradeEngine.Plan memory plan) external pure returns (bytes4) {
        if (plan.action > uint8(CompoundCarryTradeEngine.Action.OptimizeDeleverage)) {
            return CompoundCarryTradeEngine.CompoundCarryTradeEngine_InvalidAction.selector;
        }
        bool valid;
        if (plan.action == uint8(CompoundCarryTradeEngine.Action.Leverage)) {
            valid = plan.loanAmount != 0 && plan.minSharesOut != 0 && plan.maxSharesBurned == 0 && plan.vaultShares == 0
                && plan.minAssetsOut == 0;
        } else if (
            plan.action == uint8(CompoundCarryTradeEngine.Action.Deleverage)
                || plan.action == uint8(CompoundCarryTradeEngine.Action.OptimizeDeleverage)
        ) {
            valid = plan.loanAmount != 0 && plan.minSharesOut == 0 && plan.maxSharesBurned != 0 && plan.vaultShares == 0
                && plan.minAssetsOut == 0;
        } else if (plan.action == uint8(CompoundCarryTradeEngine.Action.DeleverageAll)) {
            valid = plan.loanAmount == 0 && plan.minSharesOut == 0 && plan.maxSharesBurned == 0 && plan.vaultShares == 0
                && plan.minAssetsOut == 0;
        } else {
            valid = plan.loanAmount == 0 && plan.minSharesOut == 0 && plan.maxSharesBurned == 0 && plan.vaultShares != 0
                && (plan.action == uint8(CompoundCarryTradeEngine.Action.ClaimAndRepay)
                        ? plan.minAssetsOut != 0
                        : plan.minAssetsOut == 0);
        }
        return valid ? bytes4(0) : CompoundCarryTradeEngine.CompoundCarryTradeEngine_InvalidPlanFields.selector;
    }

    /// @notice Hash identities that a policy update must preserve.
    /// @dev Unrestricted pure hash; includes the complete vault route and retained budget period.
    /// @param policy Market, vault route, reference sources, and budget period.
    /// @return Hash of the immutable policy fields.
    function identityHash(CompoundCarryTradeEngine.Policy memory policy) external pure returns (bytes32) {
        return keccak256(
            abi.encode(
                policy.comet,
                policy.cometKind,
                policy.collateralAsset,
                policy.baseAsset,
                policy.collateralPriceFeed,
                policy.basePriceFeed,
                policy.collateralDecimals,
                policy.baseDecimals,
                policy.collateralOffset,
                policy.vaultConfig,
                policy.referenceOracle,
                policy.rateOracle,
                policy.epochLength
            )
        );
    }
}

src/core/StrategyModule.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IPolicyEngine} from "../interfaces/core/IPolicyEngine.sol";
import {IStrategy} from "../interfaces/core/IStrategy.sol";
import {StrategyRegistry} from "./StrategyRegistry.sol";

/// @title Enum
/// @notice Safe operation values: Call = 0, DelegateCall = 1.
/// @dev    Inlined to avoid vendoring the entire Safe contracts repo for a
///         single two-value enum. Enums encode as `uint8`, so this is
///         ABI-identical to Safe's own `Enum.Operation` on the module call path.
abstract contract Enum {
    enum Operation {
        Call,
        DelegateCall
    }
}

/// @title ISafe
/// @notice ABI-compatible subset of Safe's module execution interface.
/// @dev Module calls bypass the owner-transaction guard. Safe 1.5 can invoke a
///      separately installed module guard around each forwarded transaction.
interface ISafe {
    /// @notice Execute a transaction from an enabled Safe module.
    /// @dev The Safe authenticates the calling module and applies its module guard.
    /// @param to Target address.
    /// @param value Native asset amount in wei.
    /// @param data Target calldata.
    /// @param operation Call or delegatecall; Bound forwarding always uses Call.
    /// @return success Whether the target execution succeeded.
    function execTransactionFromModule(address to, uint256 value, bytes memory data, Enum.Operation operation)
        external
        returns (bool success);

    /// @notice Execute a module transaction and return the target's response.
    /// @dev Applies the same module authorization and installed module guard.
    /// @param to Target address.
    /// @param value Native asset amount in wei.
    /// @param data Target calldata.
    /// @param operation Call or delegatecall; Bound forwarding always uses Call.
    /// @return success Whether the target execution succeeded.
    /// @return returnData Target return or revert data.
    function execTransactionFromModuleReturnData(address to, uint256 value, bytes memory data, Enum.Operation operation)
        external
        returns (bool success, bytes memory returnData);

    /// @notice Check whether an address is enabled as a Safe module.
    /// @param module Address to inspect.
    /// @return True when the address is enabled.
    function isModuleEnabled(address module) external view returns (bool);
}

/// @title  StrategyModule
/// @notice Core Bound Safe Module. This router directs execution
///         payloads to the correct registered strategy.
///
/// @dev    This contract is enabled as a Safe Module via `enableModule()`.
///         It is the only contract that calls `execTransactionFromModule` on the
///         Safe. Individual strategies call back into this router to forward
///         their validated transactions to the Safe.
///
///         SECURITY: The StrategyModule itself holds no funds and has no
///         fallback/receive. It authenticates execution and isolates forwarding;
///         engines enforce their typed policies and execution postconditions.
///
///         Safe module calls bypass ITransactionGuard. A separately installed
///         Safe 1.5 module guard does run. This router does not require a specific
///         installed guard; deployment and keeper checks enforce that prerequisite.
contract StrategyModule {
    // ─── Errors ──────────────────────────────────────────────────────────

    error StrategyModule_StrategyNotRegistered(address strategy);
    error StrategyModule_OnlySafe(address caller);
    error StrategyModule_ExecutorNotAuthorized(address caller, address strategy);
    error StrategyModule_OnlyActiveStrategy(address caller, address activeStrategy);
    error StrategyModule_ExecutionFailed(address to, bytes data);
    error StrategyModule_ForbiddenTarget(address to);
    error StrategyModule_RegistrySafeMismatch(address safe, address registrySafe);
    error StrategyModule_ReentrantExecution(address activeStrategy);
    error StrategyModule_ZeroAddress();
    error StrategyModule_PolicyIdentityMismatch();

    // ─── Events ──────────────────────────────────────────────────────────

    event StrategyExecuted(address indexed strategy, address indexed safe, bytes32 dataHash);
    event SafeForwarded(
        address indexed strategy, address indexed to, uint256 value, Enum.Operation operation, bytes32 dataHash
    );
    event ExecutorSet(address indexed executor, bool allowed);
    event StrategyPermissionlessSet(address indexed strategy, bool allowed);

    // ─── State ───────────────────────────────────────────────────────────

    /// @notice The Safe multisig vault this router serves.
    address public immutable SAFE;

    /// @notice The StrategyRegistry that whitelists authorized strategies.
    StrategyRegistry public immutable REGISTRY;

    /// @notice Executors authorized across all registered engines and enabled policies.
    mapping(address executor => bool allowed) public isExecutor;

    /// @dev Registered strategies that may be executed by any caller.
    mapping(address strategy => bool allowed) private _isPermissionlessStrategy;

    /// @notice Registry epoch at which permissionless execution was enabled.
    mapping(address strategy => uint256 epoch) public permissionlessStrategyEpoch;

    /// @dev The strategy currently executing through `execute()`.
    address private _activeStrategy;

    /// @dev An active engine may request cleanup, which runs after it returns.
    bool private _autoRemovalRequested;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Bind the router to one Safe and its matching registry.
    /// @param safe  The Safe multisig address.
    /// @param registry The StrategyRegistry address.
    constructor(address safe, address registry) {
        if (safe == address(0) || registry == address(0)) revert StrategyModule_ZeroAddress();
        address registrySafe = StrategyRegistry(registry).SAFE();
        if (registrySafe != safe) revert StrategyModule_RegistrySafeMismatch(safe, registrySafe);
        SAFE = safe;
        REGISTRY = StrategyRegistry(registry);
    }

    // ─── Modifiers ───────────────────────────────────────────────────────

    modifier onlySafe() {
        if (msg.sender != SAFE) revert StrategyModule_OnlySafe(msg.sender);
        _;
    }

    // ─── Admin ───────────────────────────────────────────────────────────

    /// @notice Add or remove an authorized executor.
    /// @dev Safe-caller only; approval is router-wide, with no per-engine scope or expiry.
    /// @param executor The keeper/executor address to configure.
    /// @param allowed  Whether `executor` may call `execute()`.
    function setExecutor(address executor, bool allowed) external onlySafe {
        if (executor == address(0)) revert StrategyModule_ZeroAddress();

        isExecutor[executor] = allowed;

        emit ExecutorSet(executor, allowed);
    }

    /// @notice Allow or disallow permissionless execution for a registered strategy.
    /// @dev Safe-caller only. Approval covers the engine's entire action surface,
    ///      including cancellation. Use it only when every allowed action/state
    ///      satisfies the project's permissionless execution criteria.
    /// @param strategy The registered strategy to configure.
    /// @param allowed  Whether any caller may execute `strategy`.
    function setStrategyPermissionless(address strategy, bool allowed) external onlySafe {
        if (strategy == address(0)) revert StrategyModule_ZeroAddress();
        if (allowed && !REGISTRY.isRegistered(strategy)) {
            revert StrategyModule_StrategyNotRegistered(strategy);
        }

        _isPermissionlessStrategy[strategy] = allowed;
        permissionlessStrategyEpoch[strategy] = allowed ? REGISTRY.strategyEpoch(strategy) : 0;

        emit StrategyPermissionlessSet(strategy, allowed);
    }

    /// @notice Whether `strategy` currently has valid permissionless execution.
    /// @dev Permissionless approval is bound to the registry lifecycle epoch, so
    ///      removing and re-registering a strategy invalidates the old approval.
    /// @param strategy The strategy to query.
    /// @return allowed True if anyone may currently execute `strategy`.
    function isPermissionlessStrategy(address strategy) public view returns (bool allowed) {
        return _isPermissionlessStrategy[strategy]
            && permissionlessStrategyEpoch[strategy] == REGISTRY.strategyEpoch(strategy);
    }

    // ─── External ────────────────────────────────────────────────────────

    /// @notice Advisory plan validation forwarded to a registered strategy.
    /// @dev Checks registration and delegates the engine's advisory subset. It
    ///      does not check executor authorization, Safe module enablement or the
    ///      installed guard. External reads and malformed plans may revert.
    /// @param strategy Address of the IStrategy to query.
    /// @param data ABI-encoded payload to pass to the strategy.
    /// @return executable True when registration and engine advisory checks pass.
    /// @return reason `bytes4(0)` when executable; otherwise an error selector.
    function canExecute(address strategy, bytes calldata data) external view returns (bool executable, bytes4 reason) {
        if (!REGISTRY.isRegistered(strategy)) {
            return (false, StrategyModule_StrategyNotRegistered.selector);
        }
        return IStrategy(strategy).canExecute(SAFE, data);
    }

    /// @notice Advisory validation bound to an exact policy identity and selected plan policy.
    /// @dev Malformed plans and failed engine reads may revert. Does not check executor authority.
    /// @param strategy Registered policy engine.
    /// @param policyId Policy selected by the plan.
    /// @param expectedRevision Reviewed monotonic revision.
    /// @param expectedHash Hash of the complete reviewed typed policy.
    /// @param data Original engine-specific typed plan.
    /// @return executable Whether identity and engine advisory checks pass.
    /// @return reason First failed check, or zero.
    function canExecutePolicy(
        address strategy,
        bytes32 policyId,
        uint256 expectedRevision,
        bytes32 expectedHash,
        bytes calldata data
    ) external view returns (bool executable, bytes4 reason) {
        if (!REGISTRY.isRegistered(strategy)) {
            return (false, StrategyModule_StrategyNotRegistered.selector);
        }
        if (!_policyIdentityMatches(strategy, policyId, expectedRevision, expectedHash, data)) {
            return (false, StrategyModule_PolicyIdentityMismatch.selector);
        }
        return IStrategy(strategy).canExecute(SAFE, data);
    }

    /// @notice Execute only the exact reviewed policy revision and complete policy hash.
    /// @dev Preserves the engine's typed plan ABI. Unlike execute, this binds configuration at inclusion time.
    /// @param strategy Registered policy engine.
    /// @param policyId Policy selected by the plan.
    /// @param expectedRevision Reviewed monotonic revision.
    /// @param expectedHash Hash of the complete reviewed typed policy.
    /// @param data Original engine-specific typed plan.
    function executePolicy(
        address strategy,
        bytes32 policyId,
        uint256 expectedRevision,
        bytes32 expectedHash,
        bytes calldata data
    ) external {
        _authorizeExecution(strategy);
        if (!_policyIdentityMatches(strategy, policyId, expectedRevision, expectedHash, data)) {
            revert StrategyModule_PolicyIdentityMismatch();
        }
        _execute(strategy, data);
    }

    function _policyIdentityMatches(
        address strategy,
        bytes32 policyId,
        uint256 expectedRevision,
        bytes32 expectedHash,
        bytes calldata data
    ) private view returns (bool) {
        IPolicyEngine engine = IPolicyEngine(strategy);
        return expectedRevision != 0 && engine.policyConfigured(policyId) && engine.executionPolicyId(data) == policyId
            && engine.policyRevision(policyId) == expectedRevision && engine.policyHash(policyId) == expectedHash;
    }

    /// @notice Execute a strategy against the vault. Called by a Safe-approved
    ///         executor, the Safe itself, or anyone for an explicitly
    ///         permissionless strategy. The strategy's onchain invariants
    ///         determine whether the transaction proceeds or reverts. This compatibility
    ///         path does not bind a policy revision; reviewed automation uses executePolicy.
    /// @dev Holds the active-engine mutex until execution completes. Simulate
    ///      from the intended caller to include module and Safe guard checks.
    /// @param  strategy  Address of the IStrategy to execute.
    /// @param  data      ABI-encoded payload to pass to the strategy.
    function execute(address strategy, bytes calldata data) external {
        _authorizeExecution(strategy);
        _execute(strategy, data);
    }

    function _authorizeExecution(address strategy) private view {
        if (!REGISTRY.isRegistered(strategy)) {
            revert StrategyModule_StrategyNotRegistered(strategy);
        }
        if (msg.sender != SAFE && !isExecutor[msg.sender] && !isPermissionlessStrategy(strategy)) {
            revert StrategyModule_ExecutorNotAuthorized(msg.sender, strategy);
        }
        if (_activeStrategy != address(0)) {
            revert StrategyModule_ReentrantExecution(_activeStrategy);
        }
    }

    function _execute(address strategy, bytes calldata data) private {
        _activeStrategy = strategy;
        // slither-disable-start reentrancy-no-eth
        // Mutex, not a bug: the write below RELEASES the lock acquired above; a
        // reentrant execute() reverts on the _activeStrategy check while the call runs.
        IStrategy(strategy).execute(SAFE, data);
        _activeStrategy = address(0);
        // slither-disable-end reentrancy-no-eth

        if (_autoRemovalRequested) {
            _autoRemovalRequested = false;
            REGISTRY.removeCompleted(strategy);
        }

        // Emitted after the guarded strategy call completes successfully.
        // slither-disable-next-line reentrancy-events
        emit StrategyExecuted(strategy, SAFE, keccak256(data));
    }

    /// @notice Request atomic removal after the active engine finishes execution.
    /// @dev Only the currently executing engine may request this. The registry
    ///      requires current Safe preauthorization and no unfinished policies.
    ///      Cleanup runs after forwarding is closed; any failure reverts the plan.
    function requestAutoRemoval() external {
        address strategy = _activeStrategy;
        if (msg.sender != strategy || strategy == address(0)) {
            revert StrategyModule_OnlyActiveStrategy(msg.sender, strategy);
        }
        _autoRemovalRequested = true;
    }

    /// @notice Forward a typed protocol call from the currently executing engine.
    /// @dev    Only the strategy currently executing through `execute()` may
    ///         forward. The operation is hardcoded to Call; delegatecall is never
    ///         exposed to strategies. Control-plane targets are blocked so a
    ///         strategy cannot make the Safe call itself, the registry, or this
    ///         module's Safe-admin functions, current or historical engines, or enabled modules.
    ///         The engine validates admission before forwarding and postconditions
    ///         after protocol execution; any revert rolls back the whole transaction.
    /// @param  to        Target contract to call (e.g. Uniswap Router).
    /// @param  value     ETH value to send.
    /// @param  data      Calldata for the target.
    function forwardToSafe(address to, uint256 value, bytes calldata data) external {
        address strategy = _validateForward(to);

        bool success = ISafe(SAFE).execTransactionFromModule(to, value, data, Enum.Operation.Call);
        if (!success) {
            revert StrategyModule_ExecutionFailed(to, data);
        }

        // Emitted only after the Safe confirms the forwarded call succeeded.
        // slither-disable-next-line reentrancy-events
        emit SafeForwarded(strategy, to, value, Enum.Operation.Call, keccak256(data));
    }

    /// @notice Forward a typed protocol call and return the target response.
    /// @dev Uses the native Safe return-data execution path with the same active
    ///      engine, Call-only, control-plane isolation and failure checks as
    ///      `forwardToSafe`. Engines must validate returned values and postconditions.
    /// @param to Target contract to call.
    /// @param value ETH value to send in wei.
    /// @param data Calldata for the target.
    /// @return returnData Target response bytes after a successful Safe execution.
    function forwardToSafeWithReturnData(address to, uint256 value, bytes calldata data)
        external
        returns (bytes memory returnData)
    {
        address strategy = _validateForward(to);
        bool success;
        (success, returnData) = ISafe(SAFE).execTransactionFromModuleReturnData(to, value, data, Enum.Operation.Call);
        if (!success) revert StrategyModule_ExecutionFailed(to, data);
        emit SafeForwarded(strategy, to, value, Enum.Operation.Call, keccak256(data));
    }

    function _validateForward(address to) private view returns (address strategy) {
        strategy = _activeStrategy;
        if (msg.sender != strategy || strategy == address(0)) {
            revert StrategyModule_OnlyActiveStrategy(msg.sender, strategy);
        }
        if (
            to == SAFE || to == address(REGISTRY) || to == address(this) || REGISTRY.strategyEpoch(to) != 0
                || ISafe(SAFE).isModuleEnabled(to)
        ) revert StrategyModule_ForbiddenTarget(to);
    }
}

src/core/StrategyRegistry.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title IAutoRemovalEngine
/// @notice Policy lifecycle surface used for Safe-preauthorized engine removal.
interface IAutoRemovalEngine {
    /// @notice Return the engine's immutable Bound module.
    /// @return module Engine execution chokepoint.
    function MODULE() external view returns (address module);

    /// @notice Count configured policies that have not permanently retired.
    /// @return count Unfinished policies, including disabled policies.
    function unfinishedPolicyCount() external view returns (uint256 count);
}

/// @title IAutoRemovalModule
/// @notice Module identity checks for narrow completion-removal authorization.
interface IAutoRemovalModule {
    /// @notice Return the Safe served by the module.
    /// @return safe Immutable Safe address.
    function SAFE() external view returns (address safe);

    /// @notice Return the module's strategy registry.
    /// @return registry Immutable registry address.
    function REGISTRY() external view returns (address registry);
}

/// @title  StrategyRegistry
/// @notice Strategy whitelist for Bound. Maintains which strategies
///         are authorized to execute against the vault. Only registered
///         strategies can be invoked by the StrategyModule.
///
/// @dev    The Safe adds and removes strategies and may preauthorize automatic
///         removal after every engine policy has retired. That narrow permission
///         is bound to the engine's module and current registration epoch.
///         The caller check authenticates the Safe address, not its signature
///         provenance. Owner-quorum control requires the reviewed module setup
///         and installed module guard. Registration is a bytecode authorization
///         decision; this registry does not verify the engine ABI or module binding.
contract StrategyRegistry {
    // ─── Errors ──────────────────────────────────────────────────────────

    error StrategyRegistry_OnlySafe(address caller);
    error StrategyRegistry_AlreadyRegistered(address strategy);
    error StrategyRegistry_NotRegistered(address strategy);
    error StrategyRegistry_NotContract(address strategy);
    error StrategyRegistry_ZeroAddress();
    error StrategyRegistry_InvalidAutoRemovalModule(address strategy, address module);
    error StrategyRegistry_AutoRemovalNotAuthorized(address caller, address strategy);
    error StrategyRegistry_StrategyUnfinished(address strategy, uint256 count);

    // ─── Events ──────────────────────────────────────────────────────────

    event StrategyRegistered(address indexed strategy);
    event StrategyRemoved(address indexed strategy);
    event StrategyAutoRemovalSet(address indexed strategy, address indexed module, bool allowed, uint256 epoch);
    event StrategyAutoRemoved(address indexed strategy, address indexed module, uint256 epoch);

    // ─── State ───────────────────────────────────────────────────────────

    /// @notice The Safe multisig that owns this registry.
    address public immutable SAFE;

    /// @notice Mapping of strategy address → registered status.
    mapping(address => bool) public isRegistered;

    /// @notice Array of all currently registered strategies.
    address[] public strategies;

    /// @notice Index of each strategy in the `strategies` array (1-indexed for
    ///         zero-check; actual index = value - 1).
    mapping(address => uint256) internal _strategyIndex;

    /// @notice Monotonic lifecycle version for each strategy address.
    mapping(address strategy => uint256 epoch) public strategyEpoch;

    /// @notice Module authorized by the Safe to remove a completed engine.
    mapping(address strategy => address module) public strategyAutoRemovalModule;

    /// @notice Registration epoch to which an automatic-removal approval belongs.
    mapping(address strategy => uint256 epoch) public strategyAutoRemovalEpoch;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Bind the registry to one immutable Safe.
    /// @param safe The Safe multisig address that governs this registry.
    constructor(address safe) {
        if (safe == address(0)) revert StrategyRegistry_ZeroAddress();
        SAFE = safe;
    }

    // ─── Modifiers ───────────────────────────────────────────────────────

    modifier onlySafe() {
        if (msg.sender != SAFE) revert StrategyRegistry_OnlySafe(msg.sender);
        _;
    }

    // ─── Admin ───────────────────────────────────────────────────────────

    /// @notice Register a new strategy with the registry.
    /// @dev Safe-caller only. Requires deployed code and advances the lifecycle epoch.
    /// @param strategy Address of the IStrategy contract to whitelist.
    function register(address strategy) external onlySafe {
        if (strategy == address(0)) revert StrategyRegistry_ZeroAddress();
        if (strategy.code.length == 0) revert StrategyRegistry_NotContract(strategy);
        if (isRegistered[strategy]) revert StrategyRegistry_AlreadyRegistered(strategy);

        strategyEpoch[strategy]++;
        isRegistered[strategy] = true;
        strategies.push(strategy);
        _strategyIndex[strategy] = strategies.length; // 1-indexed

        emit StrategyRegistered(strategy);
    }

    /// @notice Remove a strategy from the registry.
    /// @dev Safe-caller only. Invalidates permissionless approval and reorders
    ///      enumeration. Existing external orders must be retired before removal.
    /// @param strategy Address of the IStrategy contract to remove.
    function remove(address strategy) external onlySafe {
        if (!isRegistered[strategy]) revert StrategyRegistry_NotRegistered(strategy);

        _remove(strategy);
    }

    /// @notice Preauthorize or revoke removal after all engine policies retire.
    /// @dev Safe-only. Approval covers only the current registration epoch and
    ///      the engine's Bound module; it never authorizes registration or updates.
    /// @param strategy Registered policy engine whose completion is trusted.
    /// @param allowed Whether its module may remove it after completion.
    function setStrategyAutoRemoval(address strategy, bool allowed) external onlySafe {
        address module = address(0);
        uint256 epoch = 0;
        if (allowed) {
            if (!isRegistered[strategy]) revert StrategyRegistry_NotRegistered(strategy);
            module = IAutoRemovalEngine(strategy).MODULE();
            if (
                module.code.length == 0 || IAutoRemovalModule(module).SAFE() != SAFE
                    || IAutoRemovalModule(module).REGISTRY() != address(this)
            ) revert StrategyRegistry_InvalidAutoRemovalModule(strategy, module);
            epoch = strategyEpoch[strategy];
        }
        strategyAutoRemovalModule[strategy] = module;
        strategyAutoRemovalEpoch[strategy] = epoch;
        emit StrategyAutoRemovalSet(strategy, module, allowed, epoch);
    }

    /// @notice Whether automatic removal is approved for this registration.
    /// @param strategy Policy engine to inspect.
    /// @return allowed True when registered with a current module-bound approval.
    function isStrategyAutoRemovalEnabled(address strategy) public view returns (bool allowed) {
        return isRegistered[strategy] && strategyAutoRemovalModule[strategy] != address(0)
            && strategyAutoRemovalEpoch[strategy] == strategyEpoch[strategy];
    }

    /// @notice Remove a completed engine through its Safe-approved module.
    /// @dev The module invokes this only after a successful engine execution has
    ///      returned and forwarding is closed. A failed cleanup reverts execution.
    ///      Disabled but unretired policies still count as unfinished.
    /// @param strategy Engine whose policies have all retired.
    function removeCompleted(address strategy) external {
        if (!isStrategyAutoRemovalEnabled(strategy) || msg.sender != strategyAutoRemovalModule[strategy]) {
            revert StrategyRegistry_AutoRemovalNotAuthorized(msg.sender, strategy);
        }
        uint256 unfinished = IAutoRemovalEngine(strategy).unfinishedPolicyCount();
        if (unfinished != 0) revert StrategyRegistry_StrategyUnfinished(strategy, unfinished);
        _remove(strategy);
        emit StrategyAutoRemoved(strategy, msg.sender, strategyEpoch[strategy]);
    }

    function _remove(address strategy) private {
        isRegistered[strategy] = false;
        strategyEpoch[strategy]++;

        // Swap-and-pop from the strategies array
        uint256 idx = _strategyIndex[strategy] - 1;
        uint256 lastIdx = strategies.length - 1;

        if (idx != lastIdx) {
            address lastStrategy = strategies[lastIdx];
            strategies[idx] = lastStrategy;
            _strategyIndex[lastStrategy] = idx + 1;
        }

        strategies.pop();
        delete _strategyIndex[strategy];

        emit StrategyRemoved(strategy);
    }

    // ─── Views ───────────────────────────────────────────────────────────

    /// @notice Return all currently registered strategies.
    /// @return Registered strategy addresses; order can change on removal.
    function getStrategies() external view returns (address[] memory) {
        return strategies;
    }

    /// @notice Return the number of registered strategies.
    /// @return Number of currently registered addresses.
    function count() external view returns (uint256) {
        return strategies.length;
    }
}

src/engines/base/BaseStrategyEngine.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {StrategyModule} from "../../core/StrategyModule.sol";
import {IPolicyEngine} from "../../interfaces/core/IPolicyEngine.sol";
import {Invariants} from "../../guards/Invariants.sol";

/// @title  BaseStrategyEngine
/// @notice Shared policy lifecycle, module gate, and per-policy execution state
///         for policy-configured strategy engines.
/// @dev    Concrete engines own their typed `Policy` records. This base owns only
///         the state common to every policy family: configured/enabled flags,
///         cooldown timestamps, and rolling notional/loss budget counters.
///         Policy state is separate; Safe balances and protocol positions are shared.
abstract contract BaseStrategyEngine is IPolicyEngine {
    // ─── Errors ──────────────────────────────────────────────────────────

    error BaseStrategyEngine_ZeroAddress();
    error BaseStrategyEngine_OnlyModule(address caller);
    error BaseStrategyEngine_OnlySafe(address caller);
    error BaseStrategyEngine_PolicyAlreadyExists(bytes32 policyId);
    error BaseStrategyEngine_PolicyNotConfigured(bytes32 policyId);
    error BaseStrategyEngine_PolicyNotEnabled(bytes32 policyId);
    error BaseStrategyEngine_BadEpochConfig(uint256 epochLength, uint256 epochBudget);
    error BaseStrategyEngine_EpochBudgetExceeded(uint256 used, uint256 requested, uint256 budget);
    error BaseStrategyEngine_EpochLossBudgetExceeded(uint256 used, uint256 requested, uint256 budget);

    // ─── Events ──────────────────────────────────────────────────────────

    event PolicyAdded(bytes32 indexed policyId);
    event PolicyIdentityUpdated(bytes32 indexed policyId, uint256 revision, bytes32 policyHash);
    event PolicyUpdated(bytes32 indexed policyId);
    event PolicyEnabled(bytes32 indexed policyId);
    event PolicyDisabled(bytes32 indexed policyId);
    event PolicyCooldownTouched(bytes32 indexed policyId, uint256 timestamp);
    event PolicyEpochBooked(bytes32 indexed policyId, uint256 epochStart, uint256 epochNotionalUsed);
    event PolicyEpochLossBooked(bytes32 indexed policyId, uint256 epochStart, uint256 epochLossUsed);

    // ─── State ───────────────────────────────────────────────────────────

    /// @notice The StrategyModule chokepoint this engine forwards through.
    StrategyModule public immutable MODULE;

    /// @notice Default policy id retained for integrations that use one policy.
    bytes32 public constant DEFAULT_POLICY_ID = bytes32(0);

    /// @notice Mutable execution state isolated per Safe-managed policy.
    /// @dev Current and previous buckets remain fully charged after projecting
    ///      rollover. This can charge activity for up to one extra epoch. Public
    ///      getters expose stored buckets, not projected available capacity.
    struct PolicyState {
        uint256 lastExecution;
        uint256 epochStart;
        uint256 epochNotionalUsed;
        uint256 prevEpochNotionalUsed;
        uint256 epochLossUsed;
        uint256 prevEpochLossUsed;
    }

    /// @notice Execution state by policy id.
    mapping(bytes32 policyId => PolicyState state) public policyState;

    /// @notice Whether a policy id has ever been added.
    mapping(bytes32 policyId => bool configured) public policyConfigured;

    /// @notice Whether a configured policy id is currently executable.
    mapping(bytes32 policyId => bool enabled) public policyEnabled;

    /// @notice Monotonic identity revision, including identical-content updates.
    mapping(bytes32 policyId => uint256 revision) public policyRevision;

    /// @notice Keccak-256 of the complete ABI-encoded typed policy.
    mapping(bytes32 policyId => bytes32 digest) public policyHash;

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Bind the engine to one immutable module and its Safe.
    /// @param module StrategyModule chokepoint.
    constructor(StrategyModule module) {
        if (address(module) == address(0)) revert BaseStrategyEngine_ZeroAddress();
        MODULE = module;
    }

    // ─── Gates ───────────────────────────────────────────────────────────

    /// @notice Revert unless the caller is the StrategyModule.
    function _onlyModule() internal view {
        if (msg.sender != address(MODULE)) revert BaseStrategyEngine_OnlyModule(msg.sender);
    }

    /// @notice Revert unless the caller is the Safe served by the module.
    function _onlySafe() internal view {
        if (msg.sender != MODULE.SAFE()) revert BaseStrategyEngine_OnlySafe(msg.sender);
    }

    /// @notice Revert unless `policyId` is configured and enabled.
    /// @param policyId Policy id to validate.
    function _requirePolicyEnabled(bytes32 policyId) internal virtual {
        if (!policyConfigured[policyId]) revert BaseStrategyEngine_PolicyNotConfigured(policyId);
        if (!policyEnabled[policyId]) revert BaseStrategyEngine_PolicyNotEnabled(policyId);
    }

    /// @notice Advisory non-reverting policy/cooldown check.
    /// @param policyId Policy id to validate.
    /// @param minInterval Minimum seconds between executions.
    /// @return reason Zero when usable; otherwise a custom error selector.
    function _canUsePolicy(bytes32 policyId, uint256 minInterval) internal view virtual returns (bytes4 reason) {
        if (!policyConfigured[policyId]) return BaseStrategyEngine_PolicyNotConfigured.selector;
        if (!policyEnabled[policyId]) return BaseStrategyEngine_PolicyNotEnabled.selector;
        uint256 last = policyState[policyId].lastExecution;
        // Cooldown granularity is intentionally timestamp-based.
        // forge-lint: disable-next-line(block-timestamp)
        if (last != 0 && (block.timestamp < last || block.timestamp - last < minInterval)) {
            return Invariants.Invariants_CooldownNotElapsed.selector;
        }
        return bytes4(0);
    }

    // ─── Policy Lifecycle ────────────────────────────────────────────────

    /// @notice Register a new disabled policy id.
    /// @param policyId Policy id being added.
    /// @param digest Hash of the complete ABI-encoded typed policy.
    function _addPolicy(bytes32 policyId, bytes32 digest) internal virtual {
        if (policyConfigured[policyId]) revert BaseStrategyEngine_PolicyAlreadyExists(policyId);
        policyConfigured[policyId] = true;
        policyEnabled[policyId] = false;
        policyState[policyId].epochStart = block.timestamp;
        emit PolicyAdded(policyId);
        _recordPolicyIdentity(policyId, digest);
    }

    /// @notice Mark an existing policy as updated without resetting audit state.
    /// @param policyId Policy id being updated.
    /// @param digest Hash of the complete ABI-encoded typed policy.
    function _updatePolicy(bytes32 policyId, bytes32 digest) internal virtual {
        if (!policyConfigured[policyId]) revert BaseStrategyEngine_PolicyNotConfigured(policyId);
        policyEnabled[policyId] = false;
        emit PolicyUpdated(policyId);
        _recordPolicyIdentity(policyId, digest);
    }

    /// @notice Resolve the policy selected by a flat typed execution plan.
    /// @dev Action wrappers override this resolver; malformed plans may revert.
    /// @param data ABI-encoded typed plan.
    /// @return policyId Selected Safe-owned policy.
    function executionPolicyId(bytes calldata data) external view virtual returns (bytes32 policyId) {
        return abi.decode(data, (bytes32));
    }

    /// @dev Advance the identity even when the complete typed config is unchanged.
    function _recordPolicyIdentity(bytes32 policyId, bytes32 digest) internal {
        policyHash[policyId] = digest;
        uint256 revision = ++policyRevision[policyId];
        emit PolicyIdentityUpdated(policyId, revision, digest);
    }

    /// @notice Enable an existing policy id.
    /// @dev Safe-caller only. The installed module guard and reviewed module set
    ///      establish owner-quorum control; this function does not inspect signatures.
    /// @param policyId Policy id being enabled.
    function enablePolicy(bytes32 policyId) public virtual {
        _onlySafe();
        if (!policyConfigured[policyId]) revert BaseStrategyEngine_PolicyNotConfigured(policyId);
        policyEnabled[policyId] = true;
        emit PolicyEnabled(policyId);
    }

    /// @notice Disable a policy without deleting its historical state.
    /// @param policyId Policy id being disabled.
    function _disablePolicy(bytes32 policyId) internal {
        if (!policyConfigured[policyId]) revert BaseStrategyEngine_PolicyNotConfigured(policyId);
        policyEnabled[policyId] = false;
        emit PolicyDisabled(policyId);
    }

    // ─── State Mutators ──────────────────────────────────────────────────

    /// @notice Enforce and advance a policy cooldown.
    /// @param policyId Policy id whose cooldown is touched.
    /// @param minInterval Minimum seconds between executions.
    function _touchCooldown(bytes32 policyId, uint256 minInterval) internal {
        uint256 last = policyState[policyId].lastExecution;
        if (last != 0) Invariants.checkCooldown(last, minInterval);
        policyState[policyId].lastExecution = block.timestamp;
        emit PolicyCooldownTouched(policyId, block.timestamp);
    }

    /// @notice Roll a policy's epoch buckets forward to the current time.
    /// @dev Advancing one window demotes current -> previous; advancing two or
    ///      more clears both, because nothing inside the trailing window
    ///      survives that long.
    /// @param state Policy state to advance in place.
    /// @param epochLength Epoch length in seconds.
    function _advanceEpoch(PolicyState storage state, uint256 epochLength) private {
        PolicyState memory projected = _projectEpochState(state, epochLength);
        state.epochStart = projected.epochStart;
        state.epochNotionalUsed = projected.epochNotionalUsed;
        state.prevEpochNotionalUsed = projected.prevEpochNotionalUsed;
        state.epochLossUsed = projected.epochLossUsed;
        state.prevEpochLossUsed = projected.prevEpochLossUsed;
    }

    /// @notice Project a policy's epoch buckets to the current time without
    ///         writing storage.
    /// @dev This is deliberately the sole epoch-rollover definition used by
    ///      booking and keeper advisory paths, so both enforce the same
    ///      sliding-window state at boundaries.
    /// @param state Policy state to project.
    /// @param epochLength Epoch length in seconds.
    /// @return projected Policy state as it would appear after advancement.
    function _projectEpochState(PolicyState memory state, uint256 epochLength)
        internal
        view
        returns (PolicyState memory projected)
    {
        projected = state;
        uint256 start = projected.epochStart;
        // Rolling policy budgets are intentionally timestamp-based. Zero is the
        // explicit sentinel for an epoch that has not started.
        // forge-lint: disable-next-line(block-timestamp)
        // slither-disable-next-line incorrect-equality
        if (start == 0 || block.timestamp < start) {
            projected.epochStart = block.timestamp;
            projected.prevEpochNotionalUsed = 0;
            projected.epochNotionalUsed = 0;
            projected.prevEpochLossUsed = 0;
            projected.epochLossUsed = 0;
            return projected;
        }

        // forge-lint: disable-next-line(block-timestamp)
        uint256 elapsed = block.timestamp - start;
        if (elapsed < epochLength) return projected;

        if (elapsed - epochLength < epochLength) {
            projected.prevEpochNotionalUsed = projected.epochNotionalUsed;
            projected.epochNotionalUsed = 0;
            projected.prevEpochLossUsed = projected.epochLossUsed;
            projected.epochLossUsed = 0;
            projected.epochStart = start + epochLength;
        } else {
            projected.prevEpochNotionalUsed = 0;
            projected.epochNotionalUsed = 0;
            projected.prevEpochLossUsed = 0;
            projected.epochLossUsed = 0;
            // forge-lint: disable-next-line(block-timestamp)
            projected.epochStart = block.timestamp;
        }
    }

    /// @notice Conservative sliding-window usage: current and previous buckets
    ///         remain fully charged until the previous bucket expires.
    /// @dev Activity timestamps are not stored, so discounting a previous bucket
    ///      can undercount recent activity. Retaining it in full bounds every
    ///      trailing window on positive, monotonic chain timestamps, at the cost
    ///      of charging expired activity for up to one extra epoch. Successful
    ///      bookings bound this sum by the budget.
    /// @param state Policy state, already advanced.
    /// @param epochLength Epoch length in seconds.
    /// @param current Current-bucket total.
    /// @param previous Previous-bucket total.
    /// @return used Conservative upper bound on usage inside the trailing window.
    function _slidingUsed(PolicyState memory state, uint256 epochLength, uint256 current, uint256 previous)
        private
        view
        returns (uint256 used)
    {
        // forge-lint: disable-next-line(block-timestamp)
        uint256 elapsed = block.timestamp - state.epochStart;
        if (elapsed >= epochLength) return current;
        return current + previous;
    }

    /// @notice Return the notional currently consumed by a policy's sliding window.
    /// @param policyId Policy id whose notional usage is projected.
    /// @param epochLength Epoch length in seconds.
    /// @return used Effective notional usage inside the trailing window.
    function _projectedEpochNotionalUsed(bytes32 policyId, uint256 epochLength) internal view returns (uint256 used) {
        PolicyState memory projected = _projectEpochState(policyState[policyId], epochLength);
        return _slidingUsed(projected, epochLength, projected.epochNotionalUsed, projected.prevEpochNotionalUsed);
    }

    /// @notice Check whether a requested notional fits within a projected sliding budget.
    /// @param policyId Policy id whose budget is checked.
    /// @param requested Notional requested by the prospective action.
    /// @param epochLength Epoch length in seconds.
    /// @param budget Maximum notional per sliding window.
    /// @return hasCapacity True when `requested` fits within the budget.
    /// @return used Effective notional usage inside the trailing window.
    function _epochHasNotionalCapacity(bytes32 policyId, uint256 requested, uint256 epochLength, uint256 budget)
        internal
        view
        returns (bool hasCapacity, uint256 used)
    {
        used = _projectedEpochNotionalUsed(policyId, epochLength);
        hasCapacity = requested <= budget && used <= budget - requested;
    }

    /// @notice Book notional against a sliding epoch budget.
    /// @param policyId Policy id whose budget is used.
    /// @param notional Notional in the concrete engine's policy denomination.
    /// @param epochLength Epoch length in seconds.
    /// @param epochBudget Maximum notional per sliding window.
    function _bookEpochNotional(bytes32 policyId, uint256 notional, uint256 epochLength, uint256 epochBudget) internal {
        if (epochLength == 0 || epochBudget == 0) {
            revert BaseStrategyEngine_BadEpochConfig(epochLength, epochBudget);
        }

        PolicyState storage state = policyState[policyId];
        _advanceEpoch(state, epochLength);
        PolicyState memory projected = state;
        uint256 used =
            _slidingUsed(projected, epochLength, projected.epochNotionalUsed, projected.prevEpochNotionalUsed);

        if (notional > epochBudget || used > epochBudget - notional) {
            revert BaseStrategyEngine_EpochBudgetExceeded(used, notional, epochBudget);
        }

        state.epochNotionalUsed += notional;
        emit PolicyEpochBooked(policyId, state.epochStart, state.epochNotionalUsed);
    }

    /// @notice Book realized loss against a sliding epoch loss budget.
    /// @dev The notional budget caps how much VALUE MOVES per window; it does
    ///      not cap how much value is LOST. A small-notional action can sit far
    ///      inside the notional budget and still lose the full per-action
    ///      allowance, so an executor able to act every `minInterval` can bleed
    ///      `maxAbsoluteLoss * epochLength / minInterval` per window. This
    ///      budget bounds cumulative loss directly.
    /// @param policyId Policy id whose loss budget is used.
    /// @param loss Realized loss in the concrete engine's policy denomination. Zero is a no-op.
    /// @param epochLength Epoch length in seconds.
    /// @param epochLossBudget Maximum cumulative loss per sliding window.
    function _bookEpochLoss(bytes32 policyId, uint256 loss, uint256 epochLength, uint256 epochLossBudget) internal {
        if (epochLength == 0) revert BaseStrategyEngine_BadEpochConfig(epochLength, epochLossBudget);
        // Exact zero is the intended no-loss sentinel, not a manipulable balance check.
        // slither-disable-next-line incorrect-equality
        if (loss == 0) return;

        PolicyState storage state = policyState[policyId];
        _advanceEpoch(state, epochLength);
        PolicyState memory projected = state;
        uint256 used = _slidingUsed(projected, epochLength, projected.epochLossUsed, projected.prevEpochLossUsed);

        if (loss > epochLossBudget || used > epochLossBudget - loss) {
            revert BaseStrategyEngine_EpochLossBudgetExceeded(used, loss, epochLossBudget);
        }

        state.epochLossUsed += loss;
        emit PolicyEpochLossBooked(policyId, state.epochStart, state.epochLossUsed);
    }
}

src/engines/base/CarryVaultCapability.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {ERC4626VaultCapability} from "./ERC4626VaultCapability.sol";
import {IERC4626Vault} from "../../interfaces/tokens/IERC4626Vault.sol";
import {IERC20Minimal} from "../../interfaces/tokens/IERC20Minimal.sol";
import {ISyrupRouter} from "../../interfaces/protocols/syrup/ISyrupRouter.sol";
import {ISyrupPool} from "../../interfaces/protocols/syrup/ISyrupPool.sol";
import {ISyrupPoolManager} from "../../interfaces/protocols/syrup/ISyrupPoolManager.sol";
import {ISyrupPermissionManager} from "../../interfaces/protocols/syrup/ISyrupPermissionManager.sol";
import {ISyrupWithdrawalManager} from "../../interfaces/protocols/syrup/ISyrupWithdrawalManager.sol";

/// @title CarryVaultCapability
/// @notice Typed vault modules for synchronous vaults and Maple manual queued exits.
/// @dev The owning engine enforces module-only execution, policy authorization, debt caps and slippage.
///      All forwarded operations originate from the Safe; assets/shares use raw token units.
///      Morpho V2 capacity is advisory: its maximum getters always return zero, so direct
///      execution determines liquidity. No forced deallocation or arbitrary adapter calls exist.
///      Maple manual-ready shares are aggregate Safe inventory, not segregated per policy.
///      Queue processing and manual-withdrawal/deposit/request permission remain external Maple dependencies.
abstract contract CarryVaultCapability is ERC4626VaultCapability {
    error CarryVaultCapability_InvalidConfig();
    error CarryVaultCapability_IdentityMismatch();
    error CarryVaultCapability_ManualWithdrawalRequired();
    error CarryVaultCapability_NotPermissioned();
    error CarryVaultCapability_PendingWithdrawal();
    error CarryVaultCapability_NotSyrup();
    error CarryVaultCapability_AsyncWithdrawalRequired();
    error CarryVaultCapability_InvalidAmount();
    error CarryVaultCapability_RequestMismatch();
    error CarryVaultCapability_ClaimUnavailable();
    error CarryVaultCapability_ClaimMismatch();

    /// @notice Reviewed forwarding and capacity semantics selected by the Safe's policy.
    enum VaultKind {
        StandardERC4626,
        MorphoV2,
        Syrup
    }

    /// @notice Fixed vault route; routers and queues are used only by the Syrup module.
    /// @dev depositData is Safe-selected opaque Maple deposit metadata, not a permission grant or keeper input.
    struct VaultConfig {
        VaultKind kind;
        IERC4626Vault vault;
        address router;
        address withdrawalManager;
        bytes32 depositData;
    }

    /// @notice Cached identifier of the latest request created by each policy.
    /// @dev Refreshed by engine request/claim paths, not by external Maple activity; query the
    ///      live queue before treating this observation as an outstanding request.
    mapping(bytes32 policyId => uint256 requestId) public syrupRequestId;

    /// @notice Cached unclaimed raw-share budget from each policy's request.
    /// @dev Use the normalized internal query before authorizing debt-free settlement:
    ///      external cancellation or claiming may make this stored observation stale.
    mapping(bytes32 policyId => uint256 shares) public syrupRequestRemainingShares;

    event SyrupPendingExitUpdated(bytes32 indexed policyId, uint256 indexed requestId, uint256 remainingShares);
    event SyrupWithdrawalClaimed(bytes32 indexed policyId, address indexed safe, uint256 shares, uint256 assets);

    /// @notice Check the current identities and required Maple manual settlement mode.
    /// @param config Safe-selected route.
    /// @param asset Expected underlying loan token.
    /// @param safe Safe holding shares and claims.
    /// @return reason Zero if valid, otherwise a contextual error selector.
    function _carryVaultIdentityReason(VaultConfig memory config, address asset, address safe)
        internal
        view
        returns (bytes4 reason)
    {
        address vault = address(config.vault);
        if (vault.code.length == 0 || config.vault.asset() != asset) {
            return CarryVaultCapability_IdentityMismatch.selector;
        }
        if (config.kind != VaultKind.Syrup) {
            if (config.router != address(0) || config.withdrawalManager != address(0) || config.depositData != 0) {
                return CarryVaultCapability_InvalidConfig.selector;
            }
            return bytes4(0);
        }
        if (
            config.router.code.length == 0 || config.withdrawalManager.code.length == 0 || config.router == vault
                || config.withdrawalManager == vault || config.router == config.withdrawalManager
        ) return CarryVaultCapability_InvalidConfig.selector;

        address manager = ISyrupPool(vault).manager();
        if (manager.code.length == 0) return CarryVaultCapability_IdentityMismatch.selector;
        ISyrupRouter router = ISyrupRouter(config.router);
        ISyrupWithdrawalManager queue = ISyrupWithdrawalManager(config.withdrawalManager);
        address permissionManager = ISyrupPoolManager(manager).poolPermissionManager();
        if (
            router.pool() != vault || router.asset() != asset || router.poolManager() != manager
                || queue.pool() != vault || queue.poolManager() != manager
                || ISyrupPoolManager(manager).withdrawalManager() != config.withdrawalManager
                || permissionManager.code.length == 0 || router.poolPermissionManager() != permissionManager
        ) return CarryVaultCapability_IdentityMismatch.selector;
        if (!queue.isManualWithdrawal(safe)) return CarryVaultCapability_ManualWithdrawalRequired.selector;
        return bytes4(0);
    }

    /// @notice Check Maple deposit permission and require all pending exits to settle first.
    /// @param config Safe-selected route.
    /// @param safe Share owner.
    /// @return reason Zero when ready, otherwise a contextual error selector.
    function _carryVaultLeverageReason(VaultConfig memory config, address safe) internal view returns (bytes4 reason) {
        if (config.kind != VaultKind.Syrup) return bytes4(0);
        if (_carryVaultHasPending(config, safe)) return CarryVaultCapability_PendingWithdrawal.selector;
        if (!_syrupPermission(config, safe, "P:deposit")) return CarryVaultCapability_NotPermissioned.selector;
        return bytes4(0);
    }

    /// @notice Check whether a fresh Maple request can be submitted.
    /// @dev Requires Maple request permission and no queued or ready Safe/pool inventory;
    ///      protective requests do not require deposit permission.
    /// @param config Safe-selected route.
    /// @param safe Claim owner.
    /// @return reason Zero when ready, otherwise a contextual error selector.
    function _carryVaultRequestReason(VaultConfig memory config, address safe) internal view returns (bytes4 reason) {
        if (config.kind != VaultKind.Syrup) return CarryVaultCapability_NotSyrup.selector;
        if (_carryVaultHasPending(config, safe)) return CarryVaultCapability_PendingWithdrawal.selector;
        if (!_syrupPermission(config, safe, "P:requestRedeem")) return CarryVaultCapability_NotPermissioned.selector;
        return bytes4(0);
    }

    /// @notice Read deposit capacity under the selected module's semantics.
    /// @dev Morpho V2 has no informative maximum; engine debt limits and actual execution govern.
    /// @param config Safe-selected route.
    /// @param safe Share receiver.
    /// @return assets Current capacity, or uint256.max for Morpho V2's advisory path.
    function _carryVaultDepositCapacity(VaultConfig memory config, address safe)
        internal
        view
        returns (uint256 assets)
    {
        if (config.kind == VaultKind.MorphoV2) return type(uint256).max;
        return config.vault.maxDeposit(config.kind == VaultKind.Syrup ? config.router : safe);
    }

    /// @notice Read current synchronous withdrawal capacity.
    /// @dev Morpho V2 returns the owner's asset entitlement, which may exceed liquid assets.
    ///      Syrup requires request/claim actions and therefore has no synchronous capacity.
    /// @param config Safe-selected route.
    /// @param safe Share owner.
    /// @return assets Advisory capacity for a synchronous withdrawal.
    function _carryVaultWithdrawCapacity(VaultConfig memory config, address safe)
        internal
        view
        returns (uint256 assets)
    {
        if (config.kind == VaultKind.Syrup) return 0;
        if (config.kind == VaultKind.MorphoV2) return config.vault.convertToAssets(config.vault.balanceOf(safe));
        return config.vault.maxWithdraw(safe);
    }

    /// @notice Deposit an exact amount through a fixed route, leaving no Safe allowance.
    /// @param config Safe-selected route.
    /// @param asset Underlying loan token.
    /// @param assets Amount deposited.
    /// @param safe Share receiver and caller of the forwarded operation.
    function _carryVaultDeposit(VaultConfig memory config, address asset, uint256 assets, address safe) internal {
        _requireCarryVault(_carryVaultIdentityReason(config, asset, safe));
        _requireCarryVault(_carryVaultLeverageReason(config, safe));
        // Zero is invalid input, not a manipulable balance equality.
        // slither-disable-next-line incorrect-equality
        if (assets == 0) revert CarryVaultCapability_InvalidAmount();
        if (config.kind != VaultKind.Syrup) {
            _depositExactAssets(config.vault, asset, assets, safe, true);
            return;
        }
        _forwardChecked(asset, abi.encodeCall(IERC20Minimal.approve, (config.router, assets)), true);
        _forwardChecked(config.router, abi.encodeCall(ISyrupRouter.deposit, (assets, config.depositData)), true);
        _forwardChecked(asset, abi.encodeCall(IERC20Minimal.approve, (config.router, 0)), true);
        _assertNoResidualApproval(asset, config.router, safe);
        _requireCarryVault(_carryVaultIdentityReason(config, asset, safe));
    }

    /// @notice Withdraw exact assets from a synchronous vault.
    /// @param config Safe-selected route.
    /// @param assets Exact assets to withdraw.
    /// @param safe Share owner and asset receiver.
    function _carryVaultWithdraw(VaultConfig memory config, uint256 assets, address safe) internal {
        if (config.kind == VaultKind.Syrup) revert CarryVaultCapability_AsyncWithdrawalRequired();
        // Zero is invalid input, not a manipulable balance equality.
        // slither-disable-next-line incorrect-equality
        if (assets == 0) revert CarryVaultCapability_InvalidAmount();
        _withdrawExactAssets(config.vault, assets, safe, true);
    }

    /// @notice Read the shares required for a current Maple exit-asset quote.
    /// @param config Syrup route.
    /// @param assets Desired assets, usually the current debt bound.
    /// @return shares Current loss-adjusted exit shares.
    function _carryVaultRequestShares(VaultConfig memory config, uint256 assets)
        internal
        view
        returns (uint256 shares)
    {
        if (config.kind != VaultKind.Syrup) revert CarryVaultCapability_NotSyrup();
        return ISyrupPool(address(config.vault)).convertToExitShares(assets);
    }

    /// @notice Quote current loss-adjusted proceeds for proposed Maple exit shares.
    /// @dev The engine uses this independently of share sizing to bound the exit's value.
    /// @param config Syrup route.
    /// @param shares Proposed exit shares.
    /// @return assets Current quoted proceeds, not guaranteed future settlement proceeds.
    function _carryVaultRequestAssets(VaultConfig memory config, uint256 shares)
        internal
        view
        returns (uint256 assets)
    {
        if (config.kind != VaultKind.Syrup) revert CarryVaultCapability_NotSyrup();
        return ISyrupPool(address(config.vault)).convertToExitAssets(shares);
    }

    /// @notice Escrow bounded shares in a new Safe-owned Maple withdrawal request.
    /// @dev The engine bounds shares against live debt. Maple, not Bound, later processes the queue.
    /// @param policyId Policy recording this pending exit.
    /// @param config Syrup route.
    /// @param shares Exact shares to escrow.
    /// @param safe Share and request owner.
    /// @return id Newly validated request identifier.
    // Only Compound's module-gated execute calls this helper. The module mutex blocks
    // reentry; pre/post balances intentionally prove exact Safe escrow and ownership.
    // slither-disable-next-line reentrancy-balance,reentrancy-no-eth
    function _carryVaultRequest(bytes32 policyId, VaultConfig memory config, uint256 shares, address safe)
        internal
        returns (uint256 id)
    {
        address asset = config.vault.asset();
        _requireCarryVault(_carryVaultIdentityReason(config, asset, safe));
        _requireCarryVault(_carryVaultRequestReason(config, safe));
        if (shares == 0) revert CarryVaultCapability_InvalidAmount();
        _syncSyrupRequest(policyId, config, safe);
        uint256 beforeShares = config.vault.balanceOf(safe);
        _forwardChecked(address(config.vault), abi.encodeCall(ISyrupPool.requestRedeem, (shares, safe)), true);
        uint256 afterShares = config.vault.balanceOf(safe);
        ISyrupWithdrawalManager queue = ISyrupWithdrawalManager(config.withdrawalManager);
        id = queue.requestIds(safe);
        (address owner, uint256 queuedShares) = queue.requests(id);
        if (
            id == 0 || owner != safe || queuedShares != shares || afterShares > beforeShares
                || beforeShares - afterShares != shares
        ) {
            revert CarryVaultCapability_RequestMismatch();
        }
        syrupRequestId[policyId] = id;
        syrupRequestRemainingShares[policyId] = shares;
        _requireCarryVault(_carryVaultIdentityReason(config, asset, safe));
        emit SyrupPendingExitUpdated(policyId, id, shares);
    }

    /// @notice Read all currently manual-ready shares owned by the Safe.
    /// @dev This is aggregate Safe/pool inventory, including requests made outside this policy.
    /// @param config Syrup route.
    /// @param safe Claim owner.
    /// @return shares Aggregate manual-ready shares; not segregated per request.
    function _carryVaultClaimableShares(VaultConfig memory config, address safe)
        internal
        view
        returns (uint256 shares)
    {
        if (config.kind != VaultKind.Syrup) return 0;
        return ISyrupWithdrawalManager(config.withdrawalManager).manualSharesAvailable(safe);
    }

    /// @notice Quote a manual claim using the Safe's explicit owner address.
    /// @dev The pool's own preview is caller-sensitive and would inspect the engine instead.
    /// @param config Syrup route.
    /// @param shares Ready shares to claim.
    /// @param safe Claim owner.
    /// @return assets Current expected claim proceeds.
    function _carryVaultPreviewClaim(VaultConfig memory config, uint256 shares, address safe)
        internal
        view
        returns (uint256 assets)
    {
        if (config.kind != VaultKind.Syrup) revert CarryVaultCapability_NotSyrup();
        if (shares == 0 || shares > _carryVaultClaimableShares(config, safe)) {
            revert CarryVaultCapability_ClaimUnavailable();
        }
        uint256 redeemable;
        (redeemable, assets) = ISyrupWithdrawalManager(config.withdrawalManager).previewRedeem(safe, shares);
        if (redeemable != shares || assets == 0) revert CarryVaultCapability_ClaimUnavailable();
    }

    /// @notice Redeem manual-ready shares and return only this transaction's observed proceeds.
    /// @dev The engine caps shares by current debt, or by its remaining request budget when debt is zero.
    ///      It repays at most the observed delta; existing Safe loan tokens never fund this claim.
    /// @param policyId Policy tracking the pending exit.
    /// @param config Syrup route.
    /// @param asset Expected underlying loan token.
    /// @param shares Exact ready shares to claim.
    /// @param safe Claim owner and asset receiver.
    /// @return assets Actual increase in the Safe's underlying balance.
    // Only Compound's module-gated execute calls this helper. The module mutex blocks
    // reentry; snapshot deltas intentionally prove exact proceeds and share settlement.
    // slither-disable-next-line reentrancy-balance,reentrancy-no-eth
    function _carryVaultClaim(bytes32 policyId, VaultConfig memory config, address asset, uint256 shares, address safe)
        internal
        returns (uint256 assets)
    {
        _requireCarryVault(_carryVaultIdentityReason(config, asset, safe));
        _carryVaultPreviewClaim(config, shares, safe);
        _syncSyrupRequest(policyId, config, safe);
        uint256 beforeAssets = IERC20Minimal(asset).balanceOf(safe);
        uint256 beforeShares = config.vault.balanceOf(safe);
        uint256 beforeReady = _carryVaultClaimableShares(config, safe);
        _forwardChecked(address(config.vault), abi.encodeCall(ISyrupPool.redeem, (shares, safe, safe)), true);
        uint256 afterAssets = IERC20Minimal(asset).balanceOf(safe);
        uint256 afterReady = _carryVaultClaimableShares(config, safe);
        if (
            afterAssets <= beforeAssets || config.vault.balanceOf(safe) != beforeShares || afterReady > beforeReady
                || beforeReady - afterReady != shares
        ) revert CarryVaultCapability_ClaimMismatch();
        assets = afterAssets - beforeAssets;
        uint256 remaining = syrupRequestRemainingShares[policyId];
        if (remaining != 0) {
            syrupRequestRemainingShares[policyId] = shares >= remaining ? 0 : remaining - shares;
            emit SyrupPendingExitUpdated(policyId, syrupRequestId[policyId], syrupRequestRemainingShares[policyId]);
        }
        _syncSyrupRequest(policyId, config, safe);
        _requireCarryVault(_carryVaultIdentityReason(config, asset, safe));
        emit SyrupWithdrawalClaimed(policyId, safe, shares, assets);
    }

    /// @notice Normalize the policy's unclaimed share budget against current queue inventory.
    /// @dev External cancellations and claims cannot leave a stale unlimited settlement budget.
    ///      Manual-ready inventory is aggregate: it cannot prove individual request provenance.
    /// @param policyId Policy whose original request bounds debt-free settlement.
    /// @param config Syrup route.
    /// @param safe Claim owner.
    /// @return shares Maximum remaining share budget observed now.
    function _carryVaultPendingExitShares(bytes32 policyId, VaultConfig memory config, address safe)
        internal
        view
        returns (uint256 shares)
    {
        if (config.kind != VaultKind.Syrup) return 0;
        uint256 recorded = syrupRequestRemainingShares[policyId];
        if (recorded == 0) return 0;
        uint256 queued = _trackedSyrupShares(policyId, config, safe);
        uint256 ready = _carryVaultClaimableShares(config, safe);
        // Compare before adding so unrelated aggregate inventory cannot overflow the bound.
        if (queued >= recorded || ready >= recorded - queued) return recorded;
        return queued + ready;
    }

    function _trackedSyrupShares(bytes32 policyId, VaultConfig memory config, address safe)
        private
        view
        returns (uint256 shares)
    {
        uint256 id = syrupRequestId[policyId];
        if (id == 0) return 0;
        (address owner, uint256 queued) = ISyrupWithdrawalManager(config.withdrawalManager).requests(id);
        if (queued != 0 && owner != safe) revert CarryVaultCapability_RequestMismatch();
        return queued;
    }

    function _syncSyrupRequest(bytes32 policyId, VaultConfig memory config, address safe) private {
        uint256 remaining = _carryVaultPendingExitShares(policyId, config, safe);
        uint256 id = syrupRequestId[policyId];
        uint256 currentId = _trackedSyrupShares(policyId, config, safe) == 0 ? 0 : id;
        if (remaining != syrupRequestRemainingShares[policyId] || currentId != id) {
            syrupRequestRemainingShares[policyId] = remaining;
            syrupRequestId[policyId] = currentId;
            emit SyrupPendingExitUpdated(policyId, currentId, remaining);
        }
    }

    function _carryVaultHasPending(VaultConfig memory config, address safe) private view returns (bool) {
        ISyrupWithdrawalManager queue = ISyrupWithdrawalManager(config.withdrawalManager);
        if (queue.manualSharesAvailable(safe) != 0) return true;
        uint256 id = queue.requestIds(safe);
        if (id == 0) return false;
        (address owner, uint256 shares) = queue.requests(id);
        if (shares != 0 && owner != safe) revert CarryVaultCapability_RequestMismatch();
        return shares != 0;
    }

    function _syrupPermission(VaultConfig memory config, address safe, bytes32 functionId) private view returns (bool) {
        ISyrupRouter router = ISyrupRouter(config.router);
        return
            ISyrupPermissionManager(router.poolPermissionManager())
                .hasPermission(router.poolManager(), safe, functionId);
    }

    function _requireCarryVault(bytes4 reason) private pure {
        if (reason == 0) return;
        assembly ("memory-safe") {
            mstore(0, reason)
            revert(0, 4)
        }
    }
}

src/engines/base/ERC4626VaultCapability.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {ForwardingGuard} from "./ForwardingGuard.sol";
import {IERC4626Vault} from "../../interfaces/tokens/IERC4626Vault.sol";
import {IERC20Minimal} from "../../interfaces/tokens/IERC20Minimal.sol";

/// @title ERC4626VaultCapability
/// @notice Shared typed ERC-4626 mechanics for policy engines.
/// @dev Owns no policy storage and exposes no external execution entrypoint. Calls originate
///      from the Safe; the owning engine enforces authorization, vault identity and share/risk
///      postconditions. Asset amounts use raw underlying units; shares belong to the Safe, not a policy.
abstract contract ERC4626VaultCapability is ForwardingGuard {
    // ─── ERC-4626 Forwarding ─────────────────────────────────────────────

    /// @notice Deposit an exact asset amount and mint shares directly to the Safe.
    /// @dev Brackets the Safe's exact vault approval; the owning engine checks minted-share slippage.
    /// @param vault ERC-4626 vault receiving the deposit.
    /// @param asset Underlying ERC-20 token approved for the vault.
    /// @param assets Exact underlying asset amount to deposit.
    /// @param safe Safe receiving the minted vault shares.
    /// @param allowed Whether the typed policy permits both token and vault targets.
    function _depositExactAssets(IERC4626Vault vault, address asset, uint256 assets, address safe, bool allowed)
        internal
    {
        _forwardChecked(asset, abi.encodeCall(IERC20Minimal.approve, (address(vault), assets)), allowed);
        _forwardChecked(address(vault), abi.encodeCall(IERC4626Vault.deposit, (assets, safe)), allowed);
        _forwardChecked(asset, abi.encodeCall(IERC20Minimal.approve, (address(vault), 0)), allowed);
        _assertNoResidualApproval(asset, address(vault), safe);
    }

    /// @notice Withdraw an exact asset amount from the Safe's vault position.
    /// @dev The Safe is caller, share owner and recipient; actual vault liquidity may still cause a revert.
    /// @param vault ERC-4626 vault paying the withdrawal.
    /// @param assets Exact underlying asset amount to withdraw.
    /// @param safe Safe that owns shares and receives withdrawn assets.
    /// @param allowed Whether the typed policy permits the vault target.
    function _withdrawExactAssets(IERC4626Vault vault, uint256 assets, address safe, bool allowed) internal {
        _forwardChecked(address(vault), abi.encodeCall(IERC4626Vault.withdraw, (assets, safe, safe)), allowed);
    }
}

src/engines/base/ForwardingGuard.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {BaseStrategyEngine} from "./BaseStrategyEngine.sol";
import {StrategyModule} from "../../core/StrategyModule.sol";
import {IERC20Minimal} from "../../interfaces/tokens/IERC20Minimal.sol";

/// @title  ForwardingGuard
/// @notice Shared Safe forwarding wrapper and ERC20 approval bracket for engines.
/// @dev    Concrete engines define the allowed targets by overriding
///         `_isAllowedTarget`. Dynamic targets such as order contracts can use
///         `_forwardChecked` after validating the target from typed policy data.
abstract contract ForwardingGuard is BaseStrategyEngine {
    // ─── Errors ──────────────────────────────────────────────────────────

    error ForwardingGuard_TargetNotAllowed(address to);
    error ForwardingGuard_ResidualApproval(address token, address spender, uint256 allowance);

    // ─── Constructor ─────────────────────────────────────────────────────

    /// @notice Bind forwarding and approval checks to one immutable module.
    /// @param module StrategyModule chokepoint.
    constructor(StrategyModule module) BaseStrategyEngine(module) {}

    // ─── Target Hook ─────────────────────────────────────────────────────

    /// @notice Whether `to` is a permitted forward target for this engine.
    /// @param to Target contract.
    /// @return allowed True if statically allowed.
    function _isAllowedTarget(address to) internal view virtual returns (bool allowed);

    // ─── Forwarding ──────────────────────────────────────────────────────

    /// @notice Forward a zero-value Safe call to a statically allowed target.
    /// @param to Target contract.
    /// @param data Calldata to forward.
    function _forward(address to, bytes memory data) internal {
        _forwardChecked(to, data, _isAllowedTarget(to));
    }

    /// @notice Forward a zero-value Safe call after a caller-supplied target check.
    /// @dev    A failing forward bubbles the module's own revert reason (e.g.
    ///         `StrategyModule_ExecutionFailed`) — deliberately not caught and
    ///         wrapped, so a failed keeper tx keeps its real revert reason.
    /// @param to Target contract.
    /// @param data Calldata to forward.
    /// @param allowed Whether the caller's typed validation allows `to`.
    function _forwardChecked(address to, bytes memory data, bool allowed) internal {
        if (!allowed) revert ForwardingGuard_TargetNotAllowed(to);
        MODULE.forwardToSafe(to, 0, data);
    }

    /// @notice Forward a validated zero-value Safe call and return its response.
    /// @dev Uses the module's Call-only forwarding and control-plane target checks.
    /// @param to Target contract.
    /// @param data Calldata to forward.
    /// @param allowed Whether the caller's typed validation allows `to`.
    /// @return returnData Response to validate against the engine's postconditions.
    function _forwardCheckedWithReturnData(address to, bytes memory data, bool allowed)
        internal
        returns (bytes memory returnData)
    {
        if (!allowed) revert ForwardingGuard_TargetNotAllowed(to);
        return MODULE.forwardToSafeWithReturnData(to, 0, data);
    }

    /// @notice Revert if `spender` keeps residual Safe allowance.
    /// @param token ERC20 token to inspect.
    /// @param spender Allowance spender.
    /// @param safe Safe address that owns the allowance.
    function _assertNoResidualApproval(address token, address spender, address safe) internal view {
        uint256 remaining = IERC20Minimal(token).allowance(safe, spender);
        if (remaining != 0) revert ForwardingGuard_ResidualApproval(token, spender, remaining);
    }
}

src/guards/Invariants.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title  Invariants
/// @notice Shared invariant-checking library for Bound strategies.
///         Oracle deviation, slippage, and target-allowlist checks now live
///         in `OraclePriceGuard`, `NotionalGuard`, and each engine's own
///         `ForwardingGuard`/`_isAllowedTarget` respectively; this library
///         only owns the cross-cutting cooldown check.
///
/// @dev    All functions are `internal` and `view`/`pure` so they can be
///         inlined into strategy contracts at compile time. Functions revert
///         with descriptive custom errors on violation.
library Invariants {
    // ─── Errors ──────────────────────────────────────────────────────────

    error Invariants_CooldownNotElapsed(uint256 lastExecution, uint256 minInterval, uint256 currentTime);

    // ─── Time-Based Invariants ───────────────────────────────────────────

    /// @notice Enforce a minimum cooldown period between strategy executions.
    /// @param  lastExecution  Timestamp of the last successful execution.
    /// @param  minInterval    Minimum seconds that must elapse.
    function checkCooldown(uint256 lastExecution, uint256 minInterval) internal view {
        // Strategy cooldowns intentionally use chain timestamps.
        // forge-lint: disable-next-line(block-timestamp)
        if (block.timestamp < lastExecution || block.timestamp - lastExecution < minInterval) {
            revert Invariants_CooldownNotElapsed(lastExecution, minInterval, block.timestamp);
        }
    }
}

src/interfaces/core/IPolicyEngine.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IStrategy} from "./IStrategy.sol";

/// @title  IPolicyEngine
/// @notice Shared interface for Bound strategy engines with Safe-owned policies.
/// @dev    Concrete engines add typed policy records and typed execution plans.
///         This interface exposes only the common lifecycle and state surface
///         inherited from `BaseStrategyEngine`.
interface IPolicyEngine is IStrategy {
    /// @notice Resolve the policy selected by an engine-specific typed plan.
    /// @param data ABI-encoded typed plan; malformed input may revert.
    /// @return policyId Selected Safe-owned policy.
    function executionPolicyId(bytes calldata data) external view returns (bytes32 policyId);

    /// @notice Monotonic add/update and executable-configuration revision.
    /// @param policyId Safe-owned policy.
    /// @return revision Current revision, or zero for an unconfigured policy.
    function policyRevision(bytes32 policyId) external view returns (uint256 revision);

    /// @notice Hash of the complete ABI-encoded typed policy.
    /// @param policyId Safe-owned policy.
    /// @return digest Current hash, or zero for an unconfigured policy.
    function policyHash(bytes32 policyId) external view returns (bytes32 digest);

    /// @notice Read the stored execution and budget buckets for a policy id.
    /// @dev Execution projects epoch rollover and charges the current plus the
    ///      full previous bucket. This conservatively bounds a trailing window
    ///      and can charge activity for up to one extra epoch. This getter does
    ///      not project rollover. Amount units are defined by the concrete engine;
    ///      policy counters do not segregate the Safe's assets or protocol account.
    /// @param policyId Safe-owned policy id.
    /// @return lastExecution Last successful execution timestamp, or zero.
    /// @return epochStart Current budget epoch start timestamp.
    /// @return epochNotionalUsed Notional booked in the current stored bucket.
    /// @return prevEpochNotionalUsed Notional used in the previous bucket.
    /// @return epochLossUsed Realized loss booked in the current stored bucket, if supported.
    /// @return prevEpochLossUsed Realized loss booked in the previous bucket.
    function policyState(bytes32 policyId)
        external
        view
        returns (
            uint256 lastExecution,
            uint256 epochStart,
            uint256 epochNotionalUsed,
            uint256 prevEpochNotionalUsed,
            uint256 epochLossUsed,
            uint256 prevEpochLossUsed
        );

    /// @notice Whether a policy id has been added.
    /// @param policyId Safe-owned policy id.
    /// @return configured True when the engine has policy config for `policyId`.
    function policyConfigured(bytes32 policyId) external view returns (bool configured);

    /// @notice Whether the Safe has enabled a configured policy id.
    /// @dev Enabled status alone does not establish that a plan can execute.
    /// @param policyId Safe-owned policy id.
    /// @return enabled True when the Safe has enabled execution for `policyId`.
    function policyEnabled(bytes32 policyId) external view returns (bool enabled);

    /// @notice Enable an existing policy id.
    /// @dev Only the Safe served by the engine's immutable module may call this.
    /// @param policyId Safe-owned policy id to enable.
    function enablePolicy(bytes32 policyId) external;
}

src/interfaces/core/IStrategy.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title  IStrategy
/// @notice Interface that all Bound strategy contracts must implement.
///         Each strategy represents a single automated execution — a targeted,
///         invariant-guarded execution against a specific DeFi protocol.
///
/// @dev    Strategies are registered in the StrategyRegistry and invoked by the
///         StrategyModule. Keepers produce typed execution plans off-chain; strategy
///         contracts validate those plans onchain before forwarding any Safe call.
interface IStrategy {
    /// @notice Evaluate the engine's advisory checks for a keeper plan.
    /// @dev Checks vary by engine and exclude caller authorization, installed
    ///      Safe guards and final execution postconditions. Malformed calldata
    ///      or failing external reads may revert. Simulate the complete module
    ///      transaction from the intended executor before submitting it.
    /// @param safe The Safe multisig vault.
    /// @param plan ABI-encoded strategy-specific execution plan.
    /// @return executable True when the implemented advisory checks pass.
    /// @return reason `bytes4(0)` when executable; otherwise the selector for the
    ///         first validation error the strategy can identify off-chain.
    function canExecute(address safe, bytes calldata plan) external view returns (bool executable, bytes4 reason);

    /// @notice Execute a typed plan against the configured protocol.
    /// @dev Bound engines restrict this entry point to their immutable module.
    ///      Validate admission conditions before moving custody, then enforce
    ///      postconditions after the typed protocol calls. Any failed check
    ///      reverts the entire transaction, including preceding protocol accrual.
    /// @param safe The address of the Safe multisig vault.
    /// @param plan ABI-encoded strategy-specific execution plan.
    function execute(address safe, bytes calldata plan) external;
}

src/interfaces/oracles/ICarryRateOracle.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title ICarryRateOracle
/// @notice Timestamped nominal annual vault APR used to evaluate a carry trade.
/// @dev Rates are nominal APR (not compounded APY), net of vault fees, in basis points, excluding offchain rewards.
///      A reviewed external adapter must establish the methodology and vault binding;
///      Bound supplies this interface, not a production APR implementation.
interface ICarryRateOracle {
    /// @notice Read the estimated nominal annual APR of a pinned vault.
    /// @dev Consumers enforce observation freshness. A recent timestamp does not
    ///      establish rate methodology, liquidity or future yield.
    /// @param vault ERC-4626 vault whose underlying yield is measured.
    /// @return rateBps Nominal annual APR in basis points, net of fees and excluding offchain rewards.
    /// @return updatedAt Timestamp when the yield observation was last updated.
    function vaultRateBps(address vault) external view returns (uint256 rateBps, uint256 updatedAt);
}

src/interfaces/oracles/IReferenceOracle.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title  IReferenceOracle
/// @notice External TOKEN1-per-TOKEN0 reference used for Bound valuations.
/// @dev Prices use whole-token units scaled by 1e18, independent of token atom
///      decimals. The interface exposes no token identity or source methodology;
///      deployment review must establish orientation, units and independence
///      from the execution venue. Composed feeds report their oldest observation.
///      Live-state adapters may report the current block time, which does not
///      establish freshness of the underlying valuation.
interface IReferenceOracle {
    /// @notice Reference price of TOKEN0 in TOKEN1, scaled 1e18.
    /// @dev Consumers validate positivity, non-future timestamps and their own
    ///      maximum observation age. External failures may revert the read.
    /// @return priceX18   TOKEN1-per-TOKEN0, fixed point 1e18 (> 0 when healthy).
    /// @return updatedAt Source observation timestamp, or read time for a documented live-state adapter.
    function token0PriceInToken1() external view returns (uint256 priceX18, uint256 updatedAt);
}

src/interfaces/oracles/IReviewedReferenceOracle.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IReferenceOracle} from "./IReferenceOracle.sol";

/// @title IReviewedReferenceOracle
/// @notice Reviewed token orientation, units and direct source identity for a reference.
/// @dev Declared metadata does not prove source methodology or transitive proxy configuration.
interface IReviewedReferenceOracle is IReferenceOracle {
    /// @notice Read the immutable reviewed whole-token TOKEN1-per-TOKEN0 binding.
    /// @return token0 Base token of the normalized price.
    /// @return token1 Quote token of the normalized price.
    /// @return token0Decimals Reviewed TOKEN0 atom decimals.
    /// @return token1Decimals Reviewed TOKEN1 atom decimals.
    /// @return source Direct underlying reference source.
    /// @return sourceIdentity Keccak-256 of ABI-encoded source address and runtime code hash.
    function referenceMetadata()
        external
        view
        returns (
            address token0,
            address token1,
            uint8 token0Decimals,
            uint8 token1Decimals,
            address source,
            bytes32 sourceIdentity
        );
}

src/interfaces/protocols/compound/IComet.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title IComet
/// @notice Minimal Compound III surface for Safe-owned borrowing and repayment.
/// @dev Structs preserve Comet wire encoding. Institutional-only queries require the
///      explicitly selected institutional variant; they are not standard Comet methods.
///      Raw amounts use the relevant token decimals, factors/rates use 1e18, and base indices use 1e15.
interface IComet {
    /// @notice Stored signed base principal, reward tracking and collateral membership.
    /// @dev Positive principal is supplied base; negative principal is debt before applying its index.
    struct UserBasic {
        int104 principal;
        uint64 baseTrackingIndex;
        uint64 baseTrackingAccrued;
        uint16 assetsIn;
        uint8 _reserved;
    }

    /// @notice Stored global indices, principal totals, last accrual time and pause flags.
    /// @dev Principal totals exclude index growth; lastAccrualTime is a Unix timestamp.
    struct TotalsBasic {
        uint64 baseSupplyIndex;
        uint64 baseBorrowIndex;
        uint64 trackingSupplyIndex;
        uint64 trackingBorrowIndex;
        uint104 totalSupplyBase;
        uint104 totalBorrowBase;
        uint40 lastAccrualTime;
        uint8 pauseFlags;
    }

    /// @notice Collateral token identity, valuation scale, risk factors and supply cap.
    /// @dev scale is raw units per token; factors use 1e18 and supplyCap uses raw collateral units.
    struct AssetInfo {
        uint8 offset;
        address asset;
        address priceFeed;
        uint64 scale;
        uint64 borrowCollateralFactor;
        uint64 liquidateCollateralFactor;
        uint64 liquidationFactor;
        uint128 supplyCap;
    }

    /// @notice Returns the sole borrowable token.
    /// @dev Collateral tokens are separate from this base asset.
    /// @return value Base token address.
    function baseToken() external view returns (address value);

    /// @notice Returns the price feed configured for the base asset.
    /// @dev Use getPrice to apply the protocol's feed validation.
    /// @return value Base asset price-feed address.
    function baseTokenPriceFeed() external view returns (address value);

    /// @notice Returns the raw units representing one whole base token.
    /// @dev Equals 10 ** base token decimals.
    /// @return value Base token amount scale.
    function baseScale() external view returns (uint256 value);

    /// @notice Returns the minimum permitted outstanding base borrow after withdrawal.
    /// @dev Small remaining debts can make a new borrow or withdrawal revert.
    /// @return value Minimum debt in raw base-token units.
    function baseBorrowMin() external view returns (uint256 value);

    /// @notice Returns the number of configured collateral assets.
    /// @dev Asset-list offsets are interpreted by this Comet deployment.
    /// @return value Number of configured collateral entries.
    function numAssets() external view returns (uint8 value);

    /// @notice Reads stored global accounting.
    /// @dev Does not accrue interest; apply current indices before interpreting principal totals as assets.
    /// @return value Stored indices, principal totals, timestamp and pause bitmap.
    function totalsBasic() external view returns (TotalsBasic memory value);

    /// @notice Reads the borrowed-to-supplied base ratio.
    /// @dev Uses stored indices and returns zero when supplied base is zero; does not accrue storage.
    /// @return value Utilization scaled by 1e18.
    function getUtilization() external view returns (uint256 value);

    /// @notice Returns the borrow curve utilization breakpoint.
    /// @dev Separates the low- and high-utilization slopes.
    /// @return value Kink utilization scaled by 1e18.
    function borrowKink() external view returns (uint256 value);

    /// @notice Returns the borrow curve base rate.
    /// @dev Per-second rate component before utilization-dependent slopes.
    /// @return value Per-second base rate scaled by 1e18.
    function borrowPerSecondInterestRateBase() external view returns (uint256 value);

    /// @notice Returns the borrow curve slope below the kink.
    /// @dev Applied to utilization expressed as a 1e18-scaled ratio.
    /// @return value Per-second low-utilization slope scaled by 1e18.
    function borrowPerSecondInterestRateSlopeLow() external view returns (uint256 value);

    /// @notice Returns the borrow curve slope above the kink.
    /// @dev Applied to utilization above the kink expressed as a 1e18-scaled ratio.
    /// @return value Per-second high-utilization slope scaled by 1e18.
    function borrowPerSecondInterestRateSlopeHigh() external view returns (uint256 value);

    /// @notice Reports whether protocol supply actions are paused.
    /// @dev Supply includes base repayment; external protocol administration controls this flag.
    /// @return value True when supply actions are paused.
    function isSupplyPaused() external view returns (bool value);

    /// @notice Reports whether protocol withdrawal actions are paused.
    /// @dev Withdrawal includes base borrowing; external protocol administration controls this flag.
    /// @return value True when withdrawal actions are paused.
    function isWithdrawPaused() external view returns (bool value);

    /// @notice Reports the institutional borrower-withdrawal pause flag.
    /// @dev Institutional variant only; borrowing must also satisfy the general withdrawal flag.
    /// @return value True when institutional borrower withdrawals are paused.
    function isBorrowersWithdrawPaused() external view returns (bool value);

    /// @notice Reports the institutional base-supply pause flag.
    /// @dev Institutional variant only; covers base supply and repayment in addition to the general supply flag.
    /// @return value True when institutional base supply is paused.
    function isBaseSupplyPaused() external view returns (bool value);

    /// @notice Returns the institutional maximum supported utilization.
    /// @dev Institutional variant only; constrains utilization after borrower withdrawal.
    /// @return value Maximum utilization scaled by 1e18.
    function MAX_SUPPORTED_UTILIZATION() external view returns (uint256 value);

    /// @notice Reads collateral parameters at one asset-list offset.
    /// @dev Offset must identify a configured collateral asset.
    /// @param offset Collateral asset-list offset.
    /// @return value Token, feed, amount scale, risk factors and supply cap.
    function getAssetInfo(uint8 offset) external view returns (AssetInfo memory value);

    /// @notice Reads collateral parameters for a token.
    /// @dev Reverts when the token is not supported collateral.
    /// @param asset Collateral token address.
    /// @return value Token, feed, amount scale, risk factors and supply cap.
    function getAssetInfoByAddress(address asset) external view returns (AssetInfo memory value);

    /// @notice Reads stored base principal and collateral membership for an account.
    /// @dev Principal excludes index growth; base balances are supplied or borrowed according to its sign.
    /// @param account Position owner.
    /// @return value Stored account principal, reward tracking and collateral bitmap.
    function userBasic(address account) external view returns (UserBasic memory value);

    /// @notice Reads the account's current base debt.
    /// @dev Projects pending interest in memory without accruing storage; returns zero for a supply position.
    /// @param account Position owner.
    /// @return value Debt in raw base-token units.
    function borrowBalanceOf(address account) external view returns (uint256 value);

    /// @notice Reads the account's current supplied base balance.
    /// @dev Projects pending interest in memory without accruing storage; returns zero for a borrow position.
    /// @param account Position owner.
    /// @return value Supplied amount in raw base-token units.
    function balanceOf(address account) external view returns (uint256 value);

    /// @notice Quotes the borrow rate for a utilization ratio.
    /// @dev Evaluates the configured rate curve without accruing interest.
    /// @param utilization Borrowed-to-supplied ratio scaled by 1e18.
    /// @return value Per-second borrow rate scaled by 1e18.
    function getBorrowRate(uint256 utilization) external view returns (uint64 value);

    /// @notice Quotes the supply rate for a utilization ratio.
    /// @dev Evaluates the configured rate curve without accruing interest.
    /// @param utilization Borrowed-to-supplied ratio scaled by 1e18.
    /// @return value Per-second supply rate scaled by 1e18.
    function getSupplyRate(uint256 utilization) external view returns (uint64 value);

    /// @notice Reads a positive protocol oracle price.
    /// @dev Uses the configured feed answer; this method does not expose or enforce observation freshness.
    /// @param priceFeed Protocol-configured price feed.
    /// @return value Price in the protocol's common numeraire, scaled by 1e8.
    function getPrice(address priceFeed) external view returns (uint256 value);

    /// @notice Checks whether current collateral covers borrowing requirements.
    /// @dev Uses stored base indices and protocol prices; this view does not accrue pending interest.
    /// @param account Position owner.
    /// @return value True when debt satisfies protocol borrow collateral factors.
    function isBorrowCollateralized(address account) external view returns (bool value);

    /// @notice Reports institutional collateral deactivation.
    /// @dev Institutional variant only; deactivated collateral cannot back new borrowing.
    /// @param offset Collateral asset-list offset.
    /// @return value True when collateral is deactivated.
    function isCollateralDeactivated(uint24 offset) external view returns (bool value);

    /// @notice Reads collateral held for an account.
    /// @dev Collateral balances do not accrue base interest.
    /// @param account Position owner.
    /// @param asset Collateral token address.
    /// @return amount Balance in raw collateral-token units.
    function collateralBalanceOf(address account, address asset) external view returns (uint128 amount);

    /// @notice Accrues global interest and account reward tracking through the current timestamp.
    /// @dev Permissionless; does not change the account's signed base principal.
    /// @param account Position owner.
    function accrueAccount(address account) external;

    /// @notice Withdraws assets from the caller's position.
    /// @dev Caller receives the tokens. Base withdrawal can create debt; health, minimum debt, pauses and liquidity apply.
    /// @param asset Base or collateral token to withdraw.
    /// @param amount Amount in raw token units.
    function withdraw(address asset, uint256 amount) external;

    /// @notice Supplies assets to the caller's position.
    /// @dev Requires token approval. Base supply repays debt; overpayment creates a positive base supply position.
    /// @param asset Base or collateral token to supply.
    /// @param amount Raw token units; uint256.max requests full base debt repayment.
    function supply(address asset, uint256 amount) external;
}

src/interfaces/protocols/syrup/ISyrupPermissionManager.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title ISyrupPermissionManager
/// @notice Maple's authoritative lender permission query.
/// @dev Minimal subset; Maple administrators control permission rules and lender authorization.
interface ISyrupPermissionManager {
    /// @notice Check one lender's permission for one pool operation.
    /// @dev Prefer this authoritative query over duplicating bitmap logic.
    /// @param poolManager Manager of the pool.
    /// @param lender Account performing the operation.
    /// @param functionId Maple's zero-padded bytes32 operation name, such as bytes32("P:deposit").
    /// @return allowed Whether the lender has the required permission.
    function hasPermission(address poolManager, address lender, bytes32 functionId) external view returns (bool allowed);
}

src/interfaces/protocols/syrup/ISyrupPool.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IERC4626Vault} from "../../tokens/IERC4626Vault.sol";

/// @title ISyrupPool
/// @notice Maple pool operations for queued, share-based exits.
/// @dev Minimal Maple subset with the shared ERC-4626 call signatures. Maple's current
///      withdrawal route overrides standard synchronous assumptions; withdraw is not
///      supported by the reviewed queue route and maxWithdraw returns zero.
interface ISyrupPool is IERC4626Vault {
    /// @notice Read the pool's manager.
    /// @dev Resolves the active permission and withdrawal route.
    /// @return manager_ Current manager.
    function manager() external view returns (address manager_);

    /// @notice Quote exit shares including unrealized losses.
    /// @dev Rounds up using the loss-adjusted exchange rate; does not establish available liquidity.
    /// @param assets Desired exit amount in raw underlying asset units.
    /// @return shares Required amount in raw pool share units.
    function convertToExitShares(uint256 assets) external view returns (uint256 shares);

    /// @notice Quote exit assets including unrealized losses.
    /// @dev Rounds down using the loss-adjusted exchange rate; does not establish available liquidity.
    /// @param shares Exit amount in raw pool share units.
    /// @return assets Current raw asset quote, not guaranteed future proceeds.
    function convertToExitAssets(uint256 shares) external view returns (uint256 assets);

    /// @notice Escrow the owner's shares for queued redemption.
    /// @dev Requires Maple permission and ownership or share allowance. Processing is external;
    ///      manual mode retains processed shares for a later redeem instead of paying automatically.
    /// @param shares Request amount in raw pool share units.
    /// @param owner Owner of the requested shares and eventual claim.
    /// @return escrowedShares Raw shares escrowed, not a queue request identifier.
    function requestRedeem(uint256 shares, address owner) external returns (uint256 escrowedShares);

    /// @notice Redeem shares made available by the manual withdrawal queue.
    /// @dev Requires Maple permission and ownership or share allowance; insufficient liquidity
    ///      can cause a partial redemption. Bound uses the Safe as caller, owner and receiver.
    /// @param shares Requested ready amount in raw pool share units.
    /// @param receiver Recipient of assets.
    /// @param owner Owner of the manual claim.
    /// @return assets Amount received in raw underlying asset units.
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

src/interfaces/protocols/syrup/ISyrupPoolManager.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title ISyrupPoolManager
/// @notice Identity queries required to validate a Maple pool's exit route.
/// @dev Minimal subset; external Maple administration can change these routes.
interface ISyrupPoolManager {
    /// @notice Read the active withdrawal manager.
    /// @dev Must match the queue pinned by the Safe policy.
    /// @return manager Withdrawal manager.
    function withdrawalManager() external view returns (address manager);

    /// @notice Read the active permission manager.
    /// @dev Must match the permission manager pinned by the Syrup router.
    /// @return manager Permission manager.
    function poolPermissionManager() external view returns (address manager);
}

src/interfaces/protocols/syrup/ISyrupRouter.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title ISyrupRouter
/// @notice Typed deposit route for an already authorized Maple lender.
/// @dev Minimal subset for previously authorized lenders. Router identities are immutable;
///      Bound rechecks them against active Maple routes and forwards deposits from the Safe.
interface ISyrupRouter {
    /// @notice Read the deposit asset.
    /// @dev Immutable router identity used to match the loan token.
    /// @return asset_ Underlying token.
    function asset() external view returns (address asset_);

    /// @notice Read the pool receiving deposits.
    /// @dev Identifies the share token returned to the calling Safe.
    /// @return pool_ Pool share token.
    function pool() external view returns (address pool_);

    /// @notice Read the pool manager pinned by the router.
    /// @dev Must match the pool and withdrawal manager identities.
    /// @return manager Pool manager.
    function poolManager() external view returns (address manager);

    /// @notice Read the permission manager pinned by the router.
    /// @dev Must match the active pool manager permission configuration.
    /// @return manager Permission manager.
    function poolPermissionManager() external view returns (address manager);

    /// @notice Deposit assets and return shares to the calling lender.
    /// @dev Caller must already have Maple's P:deposit permission and approve the router.
    ///      This method does not grant authorization or accept a permission signature.
    /// @param assets Amount pulled from the caller in raw underlying asset units.
    /// @param depositData Opaque integration metadata emitted by Maple.
    /// @return shares Raw pool share units received by the caller.
    function deposit(uint256 assets, bytes32 depositData) external returns (uint256 shares);
}

src/interfaces/protocols/syrup/ISyrupWithdrawalManager.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title ISyrupWithdrawalManager
/// @notice Maple queue v200 queries for Safe-owned pending and manual-ready shares.
/// @dev Minimal v200 query subset. Manual mode is controlled by Maple's pool delegate
///      or operational administrator. Neither Bound nor the Safe can guarantee queue processing.
interface ISyrupWithdrawalManager {
    /// @notice Read the queue's pool.
    /// @dev Must match the configured share token.
    /// @return pool_ Pool share token.
    function pool() external view returns (address pool_);

    /// @notice Read the queue's pool manager.
    /// @dev Must match the pool and router manager identities.
    /// @return manager Pool manager.
    function poolManager() external view returns (address manager);

    /// @notice Check whether processing retains shares for a manual claim.
    /// @dev The pool delegate or operational administrator controls this setting.
    /// @param owner Claim owner.
    /// @return manual Whether manual withdrawal is enabled.
    function isManualWithdrawal(address owner) external view returns (bool manual);

    /// @notice Read aggregate processed shares available for manual redemption.
    /// @dev Processed claims are aggregated by owner, not segregated by request.
    /// @param owner Claim owner.
    /// @return shares Raw pool share units ready across the owner's requests.
    function manualSharesAvailable(address owner) external view returns (uint256 shares);

    /// @notice Read the owner's latest live request identifier.
    /// @dev Older requests may also exist; zero means the owner has no queued requests.
    /// @param owner Request owner.
    /// @return requestId Latest live identifier, or zero when no requests remain.
    function requestIds(address owner) external view returns (uint256 requestId);

    /// @notice Read a request's unprocessed shares.
    /// @dev Completed or canceled requests are removed from queue storage.
    /// @param requestId Queue identifier.
    /// @return owner Request owner, or zero for a removed request.
    /// @return shares Remaining raw pool share units.
    function requests(uint256 requestId) external view returns (address owner, uint256 shares);

    /// @notice Quote a manual redemption for the specified owner.
    /// @dev Reverts above the owner's ready shares; may quote fewer shares when pool liquidity is insufficient.
    /// @param owner Claim owner; unlike the pool preview, this is explicit.
    /// @param shares Requested ready amount in raw pool share units.
    /// @return redeemableShares Raw pool share units which can currently be redeemed.
    /// @return assets Raw underlying units expected at the current loss-adjusted exchange rate.
    function previewRedeem(address owner, uint256 shares)
        external
        view
        returns (uint256 redeemableShares, uint256 assets);
}

src/interfaces/tokens/IERC20Metadata.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title IERC20Metadata
/// @notice ERC-20 decimal metadata used by Bound's valuation and deployment checks.
/// @dev Minimal subset. ERC-20 metadata is optional; supported assets must implement this query.
interface IERC20Metadata {
    /// @notice Token decimals.
    /// @dev One whole token is represented by 10 ** decimals_ raw units.
    /// @return decimals_ Number of token decimals.
    function decimals() external view returns (uint8 decimals_);
}

src/interfaces/tokens/IERC20Minimal.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title IERC20Minimal
/// @notice ERC-20 balance and allowance methods used by Bound.
/// @dev Minimal subset, not a complete ERC-20 interface. Amounts use raw token units.
///      Safe forwarding checks call success rather than decoding approval return data;
///      Bound's forwarding helpers require zero residual allowance after approval cleanup.
interface IERC20Minimal {
    /// @notice Sets the caller's allowance for a spender.
    /// @dev Replaces the existing allowance; token-specific approval restrictions may apply.
    /// @param spender Account that receives allowance.
    /// @param amount Allowance in raw token units.
    /// @return success True when the token reports approval success.
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Read token allowance.
    /// @dev Reports authorization, not the owner's available balance.
    /// @param owner Token owner.
    /// @param spender Allowance spender.
    /// @return amount Current allowance in raw token units.
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Read token balance.
    /// @dev The value follows the token's own accounting, including any rebasing behavior.
    /// @param account Token holder.
    /// @return amount Current balance in raw token units.
    function balanceOf(address account) external view returns (uint256);
}

src/interfaces/tokens/IERC4626Vault.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title IERC4626Vault
/// @notice Minimal ERC-4626 interface for synchronous vault deposits and withdrawals.
/// @dev Standard semantics below apply to compatible synchronous vaults. An inherited
///      protocol interface may explicitly document deviations, including queued exits.
///      Asset amounts use raw underlying units; share amounts use raw vault share units.
interface IERC4626Vault {
    /// @notice Returns the address of the vault's underlying asset.
    /// @dev Identifies the token supplied on deposit and received on withdrawal.
    /// @return The underlying asset address.
    function asset() external view returns (address);

    /// @notice Returns the share balance held by an owner.
    /// @dev Share ownership alone does not establish immediate withdrawal capacity.
    /// @param owner Account whose share balance is queried.
    /// @return The owner's balance in raw share units.
    function balanceOf(address owner) external view returns (uint256);

    /// @notice Converts shares to the equivalent underlying asset amount.
    /// @dev Rounds down; excludes fees and owner-specific execution limits.
    /// @param shares Amount in raw share units.
    /// @return Equivalent amount in raw underlying asset units.
    function convertToAssets(uint256 shares) external view returns (uint256);

    /// @notice Simulates a deposit of assets into the vault.
    /// @dev Includes deposit fees and rounds down; does not establish deposit capacity.
    /// @param assets Deposit amount in raw underlying asset units.
    /// @return Estimated amount minted in raw share units.
    function previewDeposit(uint256 assets) external view returns (uint256);

    /// @notice Simulates withdrawing assets from the vault.
    /// @dev Includes withdrawal fees and rounds up; does not establish withdrawal capacity.
    /// @param assets Withdrawal amount in raw underlying asset units.
    /// @return Estimated amount burned in raw share units.
    function previewWithdraw(uint256 assets) external view returns (uint256);

    /// @notice Returns the maximum assets a receiver may deposit.
    /// @dev Includes receiver-specific limits; zero means deposits are unavailable.
    /// @param receiver Receiver of minted shares.
    /// @return Maximum deposit in raw underlying asset units.
    function maxDeposit(address receiver) external view returns (uint256);

    /// @notice Returns the maximum assets an owner may withdraw.
    /// @dev Includes ownership and execution limits; zero means withdrawals are unavailable.
    /// @param owner Owner whose shares fund the withdrawal.
    /// @return Maximum withdrawal in raw underlying asset units.
    function maxWithdraw(address owner) external view returns (uint256);

    /// @notice Deposits assets and mints shares to a receiver.
    /// @dev Pulls assets from the caller, who must approve the vault; reverts if limits prevent deposit.
    /// @param assets Deposit amount in raw underlying asset units.
    /// @param receiver Receiver of minted shares.
    /// @return shares Amount minted in raw share units.
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /// @notice Withdraws assets by burning an owner's shares.
    /// @dev Requires the caller to be the owner or have share allowance; transfers exact assets or reverts.
    /// @param assets Withdrawal amount in raw underlying asset units.
    /// @param receiver Receiver of withdrawn assets.
    /// @param owner Owner whose shares are burned.
    /// @return shares Amount burned in raw share units.
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
}

src/libraries/CarryTradeRisk.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {FullMath} from "./uniswap/FullMath.sol";

/// @title CarryTradeRisk
/// @notice Full-precision arithmetic for wstETH-GHO carry-trade risk checks.
library CarryTradeRisk {
    /// @notice Aave ray units representing one basis point.
    uint256 internal constant RAY_PER_BPS = 1e23;

    /// @notice Number of basis points in one whole unit.
    uint256 internal constant BPS = 10_000;

    /// @notice Converts an Aave ray rate to basis points, rounding upward.
    /// @dev Upward rounding prevents overstating the carry spread.
    /// @param rateRay Annualized Aave rate in ray units.
    /// @return The rate in basis points, rounded up.
    function rayRateToBpsUp(uint256 rateRay) internal pure returns (uint256) {
        return FullMath.mulDivRoundingUp(rateRay, 1, RAY_PER_BPS);
    }

    /// @notice Computes the signed savings-minus-borrow carry spread.
    /// @dev The borrow rate is first converted with upward rounding.
    /// @param savingsRateBps Annual sGHO savings rate in basis points.
    /// @param borrowRateRay Annual Aave borrow rate in ray units.
    /// @return The signed carry spread in basis points.
    function carrySpreadBps(uint256 savingsRateBps, uint256 borrowRateRay) internal pure returns (int256) {
        // Safe: savingsRateBps is uint16 and the ray conversion is bounded far below int256.max.
        // forge-lint: disable-next-line(unsafe-typecast)
        return int256(savingsRateBps) - int256(rayRateToBpsUp(borrowRateRay));
    }

    /// @notice Computes the largest debt consistent with a target health factor.
    /// @dev Rounds down to ensure the resulting debt does not exceed the health target.
    /// @param collateralBase Collateral value in Aave base currency.
    /// @param liquidationThresholdBps Aave liquidation threshold in basis points.
    /// @param targetHealthFactor Desired health factor scaled by 1e18.
    /// @return The target debt in Aave base currency.
    function targetDebtBase(uint256 collateralBase, uint256 liquidationThresholdBps, uint256 targetHealthFactor)
        internal
        pure
        returns (uint256)
    {
        return FullMath.mulDiv(collateralBase, liquidationThresholdBps * 1e18, BPS * targetHealthFactor);
    }

    /// @notice Converts a raw token amount to Aave base-currency value.
    /// @dev Rounds down.
    /// @param amount Raw token amount.
    /// @param price Token price in Aave base currency per whole token.
    /// @param decimals Number of decimals used by the token.
    /// @return The base-currency value of the amount.
    function tokenAmountToBase(uint256 amount, uint256 price, uint8 decimals) internal pure returns (uint256) {
        return FullMath.mulDiv(amount, price, _tokenUnit(decimals));
    }

    /// @notice Converts base-currency value to a raw token amount, rounding down.
    /// @dev Use for leverage sizing so the token amount cannot exceed the base amount.
    /// @param amountBase Amount in Aave base currency.
    /// @param price Token price in Aave base currency per whole token.
    /// @param decimals Number of decimals used by the token.
    /// @return The raw token amount, rounded down.
    function baseToTokenDown(uint256 amountBase, uint256 price, uint8 decimals) internal pure returns (uint256) {
        return FullMath.mulDiv(amountBase, _tokenUnit(decimals), price);
    }

    /// @notice Converts base-currency value to a raw token amount, rounding up.
    /// @dev Use for repayments so the token amount covers the base debt.
    /// @param amountBase Amount in Aave base currency.
    /// @param price Token price in Aave base currency per whole token.
    /// @param decimals Number of decimals used by the token.
    /// @return The raw token amount, rounded up.
    function baseToTokenUp(uint256 amountBase, uint256 price, uint8 decimals) internal pure returns (uint256) {
        return FullMath.mulDivRoundingUp(amountBase, _tokenUnit(decimals), price);
    }

    /// @notice Computes the absolute observed-price deviation from a reference price.
    /// @dev The deviation is measured relative to the reference price and rounds down.
    /// @param observed Observed price.
    /// @param referencePrice Trusted reference price.
    /// @return The absolute deviation in basis points.
    function deviationBps(uint256 observed, uint256 referencePrice) internal pure returns (uint256) {
        uint256 difference = observed >= referencePrice ? observed - referencePrice : referencePrice - observed;
        return FullMath.mulDiv(difference, BPS, referencePrice);
    }

    /// @notice Applies slippage to a deposit preview, rounding the minimum down.
    /// @dev A lower share limit is conservative for a deposit.
    /// @param previewShares Shares returned by `previewDeposit`.
    /// @param slippageBps Maximum permitted share slippage in basis points.
    /// @return The minimum acceptable shares received.
    function minSharesOut(uint256 previewShares, uint256 slippageBps) internal pure returns (uint256) {
        return FullMath.mulDiv(previewShares, BPS - slippageBps, BPS);
    }

    /// @notice Applies slippage to a withdrawal preview, rounding the maximum up.
    /// @dev A higher share limit is conservative for a withdrawal.
    /// @param previewShares Shares returned by `previewWithdraw`.
    /// @param slippageBps Maximum permitted share slippage in basis points.
    /// @return The maximum acceptable shares burned.
    function maxSharesBurned(uint256 previewShares, uint256 slippageBps) internal pure returns (uint256) {
        return FullMath.mulDivRoundingUp(previewShares, BPS + slippageBps, BPS);
    }

    /// @notice Returns one whole token in raw token units.
    /// @param decimals Number of decimals used by the token.
    /// @return The raw units in one whole token.
    function _tokenUnit(uint8 decimals) private pure returns (uint256) {
        return 10 ** uint256(decimals);
    }
}

src/libraries/CometCarryMath.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {FullMath} from "./uniswap/FullMath.sol";

/// @title CometCarryMath
/// @notice Compound III debt, interest, and collateral arithmetic for carry positions.
/// @dev Preserves Comet's debt-value floor and principal ceil; positive base supply is excluded.
library CometCarryMath {
    uint256 internal constant BASE_INDEX_SCALE = 1e15;
    uint256 internal constant FACTOR_SCALE = 1e18;

    error CometCarryMath_BaseSupplyNotSupported();
    error CometCarryMath_InvalidIndex();
    error CometCarryMath_PrincipalOverflow();
    error CometCarryMath_IndexOverflow();
    error CometCarryMath_RepaymentExceedsDebt();

    /// @notice Values a borrowing principal using Comet's downward rounding.
    /// @param principal Zero or negative base principal.
    /// @param borrowIndex Current or projected borrowing index scaled by 1e15.
    /// @return Raw base assets currently owed.
    function debtAssets(int104 principal, uint64 borrowIndex) internal pure returns (uint256) {
        if (principal > 0) revert CometCarryMath_BaseSupplyNotSupported();
        if (principal == type(int104).min) revert CometCarryMath_PrincipalOverflow();
        _requireIndex(borrowIndex);
        // A nonpositive principal is negated after widening to avoid signed overflow.
        // forge-lint: disable-next-line(unsafe-typecast)
        return FullMath.mulDiv(uint256(-int256(principal)), borrowIndex, BASE_INDEX_SCALE);
    }

    /// @notice Converts total debt assets to a negative principal, rounding magnitude up.
    /// @param assets Entire debt asset balance, not the transaction's incremental amount.
    /// @param borrowIndex Current borrowing index scaled by 1e15.
    /// @return Negative principal that Comet stores for the debt.
    function borrowPrincipal(uint256 assets, uint64 borrowIndex) internal pure returns (int104) {
        _requireIndex(borrowIndex);
        uint256 magnitude = FullMath.mulDivRoundingUp(assets, BASE_INDEX_SCALE, borrowIndex);
        if (magnitude > uint256(uint104(type(int104).max))) revert CometCarryMath_PrincipalOverflow();
        // Magnitude is bounded by int104.max above.
        // forge-lint: disable-next-line(unsafe-typecast)
        return -int104(int256(magnitude));
    }

    /// @notice Computes the whole-position principal after borrowing base assets.
    /// @param principal Current zero or negative principal.
    /// @param assets Raw base assets withdrawn for the carry trade.
    /// @param borrowIndex Current borrowing index.
    /// @return Principal after Comet's whole-balance conversion.
    function principalAfterBorrow(int104 principal, uint256 assets, uint64 borrowIndex) internal pure returns (int104) {
        return borrowPrincipal(debtAssets(principal, borrowIndex) + assets, borrowIndex);
    }

    /// @notice Computes principal after repayment without creating base supply.
    /// @dev Repayments below baseBorrowMin are valid; the minimum only gates borrowing.
    /// @param principal Current zero or negative principal.
    /// @param assets Raw base assets repaid.
    /// @param borrowIndex Current borrowing index.
    /// @return Remaining negative principal, or zero for exact full repayment.
    function principalAfterRepay(int104 principal, uint256 assets, uint64 borrowIndex) internal pure returns (int104) {
        uint256 debt = debtAssets(principal, borrowIndex);
        if (assets > debt) revert CometCarryMath_RepaymentExceedsDebt();
        return borrowPrincipal(debt - assets, borrowIndex);
    }

    /// @notice Projects the supply and borrow indices using Comet's interval accrual.
    /// @dev Rates must be quoted against stored utilization before accrual.
    /// @param supplyIndex Stored supply index scaled by 1e15.
    /// @param borrowIndex Stored borrowing index scaled by 1e15.
    /// @param supplyRate Per-second supply rate scaled by 1e18.
    /// @param borrowRate Per-second borrow rate scaled by 1e18.
    /// @param elapsed Seconds since the stored lastAccrualTime.
    /// @return accruedSupplyIndex The projected supply index.
    /// @return accruedBorrowIndex The projected borrowing index.
    function accruedIndices(
        uint64 supplyIndex,
        uint64 borrowIndex,
        uint256 supplyRate,
        uint256 borrowRate,
        uint256 elapsed
    ) internal pure returns (uint64 accruedSupplyIndex, uint64 accruedBorrowIndex) {
        _requireIndex(supplyIndex);
        _requireIndex(borrowIndex);
        accruedSupplyIndex =
            _index(uint256(supplyIndex) + FullMath.mulDiv(supplyIndex, supplyRate * elapsed, FACTOR_SCALE));
        accruedBorrowIndex =
            _index(uint256(borrowIndex) + FullMath.mulDiv(borrowIndex, borrowRate * elapsed, FACTOR_SCALE));
    }

    /// @notice Computes collateral capacity in the price feed's quote units.
    /// @dev Preserves the protocol's separate downward price and factor roundings.
    /// @param collateral Raw collateral amount.
    /// @param price Collateral price per whole token, normally USD scaled by 1e8.
    /// @param scale Raw units per whole collateral token.
    /// @param factor Borrow or liquidation collateral factor scaled by 1e18.
    /// @return Collateral capacity in quote units.
    function collateralCapacity(uint256 collateral, uint256 price, uint256 scale, uint256 factor)
        internal
        pure
        returns (uint256)
    {
        return FullMath.mulDiv(FullMath.mulDiv(collateral, price, scale), factor, FACTOR_SCALE);
    }

    /// @notice Computes liquidation capacity divided by conservative debt value.
    /// @dev Rounding debt quote value up makes this at least as strict as Comet's liquidity check.
    /// @param collateral Raw collateral balance.
    /// @param collateralPrice Collateral price in shared quote units.
    /// @param collateralScale Raw units per collateral token.
    /// @param factor Liquidation collateral factor scaled by 1e18.
    /// @param debt Raw debt assets.
    /// @param debtPrice Base asset price in shared quote units.
    /// @param baseScale Raw units per base token.
    /// @return Health factor scaled by 1e18, or uint256.max when debt is zero.
    function healthFactor(
        uint256 collateral,
        uint256 collateralPrice,
        uint256 collateralScale,
        uint256 factor,
        uint256 debt,
        uint256 debtPrice,
        uint256 baseScale
    ) internal pure returns (uint256) {
        if (debt == 0) return type(uint256).max;
        uint256 capacity = collateralCapacity(collateral, collateralPrice, collateralScale, factor);
        uint256 value = FullMath.mulDivRoundingUp(debt, debtPrice, baseScale);
        return FullMath.mulDiv(capacity, FACTOR_SCALE, value);
    }

    /// @notice Evaluates Comet's configured kink curve for a prospective borrow.
    /// @dev Quotes the configured cost even when an institutional getter returns zero for an empty market.
    /// @param utilization Borrowed assets divided by supplied assets, scaled by 1e18.
    /// @param kink Utilization separating the two slopes, scaled by 1e18.
    /// @param rateBase Per-second base rate scaled by 1e18.
    /// @param slopeLow Per-second slope below the kink, scaled by 1e18.
    /// @param slopeHigh Per-second slope above the kink, scaled by 1e18.
    /// @return Per-second prospective borrow rate scaled by 1e18.
    function borrowRateAt(uint256 utilization, uint256 kink, uint256 rateBase, uint256 slopeLow, uint256 slopeHigh)
        internal
        pure
        returns (uint256)
    {
        if (utilization <= kink) return rateBase + FullMath.mulDiv(slopeLow, utilization, FACTOR_SCALE);
        return rateBase + FullMath.mulDiv(slopeLow, kink, FACTOR_SCALE)
            + FullMath.mulDiv(slopeHigh, utilization - kink, FACTOR_SCALE);
    }

    /// @notice Converts the per-second borrow rate to nominal annual basis points.
    /// @dev Rounds upward to avoid understating the borrowing cost; this is APR, not APY.
    /// @param ratePerSecond Borrow rate scaled by 1e18.
    /// @return Annual nominal borrow cost in basis points.
    function borrowRateBpsUp(uint256 ratePerSecond) internal pure returns (uint256) {
        return FullMath.mulDivRoundingUp(ratePerSecond, 365 days * 10_000, FACTOR_SCALE);
    }

    function _requireIndex(uint64 index) private pure {
        if (index < BASE_INDEX_SCALE) revert CometCarryMath_InvalidIndex();
    }

    function _index(uint256 value) private pure returns (uint64) {
        if (value > type(uint64).max) revert CometCarryMath_IndexOverflow();
        // Explicitly bounded above before narrowing.
        // forge-lint: disable-next-line(unsafe-typecast)
        return uint64(value);
    }
}

src/libraries/ReferencePrice.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

import {IReferenceOracle} from "../interfaces/oracles/IReferenceOracle.sol";
import {IReviewedReferenceOracle} from "../interfaces/oracles/IReviewedReferenceOracle.sol";

/// @title ReferencePrice
/// @notice Typed normalized reference observations with checked pair and source bindings.
/// @dev Source identity binds direct runtime code; feed semantics and transitive dependencies require review.
library ReferencePrice {
    error ReferencePrice_UnreviewedOracle(address oracle);
    error ReferencePrice_PairMismatch(address oracle);
    error ReferencePrice_SourceIdentityMismatch(address source);

    struct Metadata {
        address token0;
        address token1;
        uint8 token0Decimals;
        uint8 token1Decimals;
        address source;
        bytes32 sourceIdentity;
    }

    /// @notice A whole-token TOKEN1-per-TOKEN0 price scaled 1e18 and its reviewed binding.
    struct Data {
        uint256 priceX18;
        uint256 updatedAt;
        Metadata metadata;
    }

    /// @notice Check declared orientation, atom decimals and direct source identity.
    /// @dev Expected pair and decimal bounds come from the engine's validated policy.
    /// @param oracle Reviewed adapter, not an unbound raw feed.
    /// @param token0 Expected base token.
    /// @param token1 Expected quote token.
    /// @param token0Decimals Expected base-token atom decimals.
    /// @param token1Decimals Expected quote-token atom decimals.
    /// @return metadata Validated binding.
    function requirePair(
        IReferenceOracle oracle,
        address token0,
        address token1,
        uint8 token0Decimals,
        uint8 token1Decimals
    ) internal view returns (Metadata memory metadata) {
        (bool success, bytes memory result) = address(oracle)
            .staticcall(abi.encodeCall(IReviewedReferenceOracle.referenceMetadata, ()));
        if (!success || result.length != 192) revert ReferencePrice_UnreviewedOracle(address(oracle));
        metadata = abi.decode(result, (Metadata));
        if (
            metadata.token0 != token0 || metadata.token1 != token1 || metadata.token0Decimals != token0Decimals
                || metadata.token1Decimals != token1Decimals
        ) {
            revert ReferencePrice_PairMismatch(address(oracle));
        }
        if (
            metadata.source.code.length == 0
                || metadata.sourceIdentity != keccak256(abi.encode(metadata.source, metadata.source.codehash))
        ) {
            revert ReferencePrice_SourceIdentityMismatch(metadata.source);
        }
    }

    /// @notice Read a normalized observation together with its checked binding.
    /// @dev Does not infer feed semantics or freshness; consumers apply their own maximum age.
    /// @param oracle Reviewed adapter.
    /// @param token0 Expected base token.
    /// @param token1 Expected quote token.
    /// @param token0Decimals Expected base-token atom decimals.
    /// @param token1Decimals Expected quote-token atom decimals.
    /// @return observation Checked metadata and source observation.
    function read(IReferenceOracle oracle, address token0, address token1, uint8 token0Decimals, uint8 token1Decimals)
        internal
        view
        returns (Data memory observation)
    {
        observation.metadata = requirePair(oracle, token0, token1, token0Decimals, token1Decimals);
        (observation.priceX18, observation.updatedAt) = oracle.token0PriceInToken1();
    }
}

src/libraries/uniswap/FullMath.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.28;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an
///         intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division
///      where an intermediate value overflows 256 bits
///
///      Ported from Uniswap v3-core `FullMath` (originally Solidity 0.7, where
///      arithmetic wrapped by default). Under 0.8.x the entire body is wrapped in
///      a single `unchecked` block so the deliberate modular-arithmetic
///      identities (the 512-bit long division) keep their original wrapping
///      semantics. Do NOT "simplify" the bit-twiddling — it is exact by design.
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if
    ///         result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

            // Make sure the result is less than 2**256.
            // Also prevents denominator == 0
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            prod0 |= prod1 * twos;

            // Invert denominator mod 2**256
            // Now that denominator is an odd number, it has an inverse
            // modulo 2**256 such that denominator * inv = 1 mod 2**256.
            // Compute the inverse by starting with a seed that is correct
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use Newton-Raphson iteration to improve the precision.
            // Thanks to Hensel's lifting lemma, this also works in modular
            // arithmetic, doubling the correct bits in each step.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // inverse mod 2**256

            // Because the division is now exact we can divide by multiplying
            // with the modular inverse of denominator. This will give us the
            // correct result modulo 2**256. Since the precoditions guarantee
            // that the outcome is less than 2**256, this is the final result.
            // We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inv;
            return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if
    ///         result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) > 0) {
                require(result < type(uint256).max);
                result++;
            }
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "osaka",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.