Skip to content
Verified contractPartialMIT

ManifestHook

Address0xededbb6315705cd138b15f5638ce83601eaaefe0
Balance

0 ETH

 

Transactions

10

 

Compiler

solc 0.8.26

 

Same code

2 more contracts

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,348,228
Creation transaction
0x3bae514c57…a928ad119b
Libraries
contracts/hooks/ManifestHook.sol:ArbExec0x3fe6…e4df0dcontracts/hooks/ManifestHook.sol:HookMath0xcafd…cf1d36contracts/hooks/ManifestHook.sol:DynamicFeeLib0x8c9d…9b3bb7contracts/hooks/ManifestHook.sol:SwapEstimation0xf075…e5a769

56 files

The source code is large: one file is shown at a time. Choose a file in the list.

contracts/hooks/ManifestHook.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {BaseHook} from "@uniswap/v4-periphery/src/utils/BaseHook.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";
import {IAuthManager} from "../authmanager/interfaces/IAuthManager.sol";
import {IUSHTokenBase} from "../ush/interfaces/IUSHTokenBase.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import {IManifestHook} from "./interfaces/IManifestHook.sol";
import {IUSHPriceOracle} from "../oracle/interfaces/IUSHPriceOracle.sol";
import {SwapEstimation} from "./lib/SwapEstimation.sol";
import {DynamicFeeLib} from "./lib/DynamicFeeLib.sol";
import {PriceMath} from "./lib/PriceMath.sol";
import {HookMath} from "./lib/HookMath.sol";
import {ArbExec} from "./lib/ArbExec.sol";
/// @notice Interface for getting the original msg.sender from routers

interface IMsgSender {
    function msgSender() external view returns (address);
}

/**
 * @title ManifestHook
 * @author Manifest Protocol
 * @notice Uniswap V4 hook implementing the Manifest AMM for USH stablecoin peg maintenance
 *
 * @dev Core mechanisms:
 *      1. UPWARD ARBITRAGE (price > target): mint USH, sell for USDe, par value to treasury, profit to
 *         rewards. Executes atomically within the afterSwap callback (MEV-resistant).
 *      2. DOWNWARD ARBITRAGE (price < target): buy USH with treasury USDe, burn USH, profit to rewards.
 *         Requires treasury approval for USDe spending.
 *      3. FLEX MECHANISM: buffer for the price deviation arbitrage cannot fully correct. Walks tick
 *         boundaries for the exact requirement (flexNeeded = calculateFlexBurnedToTarget) and mints or
 *         burns the difference against the current flex balance.
 *      4. CIRCUIT BREAKER (OR of three causes, gates user swaps in _beforeSwap): USDe/USD depeg from the
 *         Chainlink/RedStone feed, USH NAV outside [ushNavFloor, ushNavCeiling] read from
 *         ushPriceOracle, and an emergency-paused NAV oracle (getConfiguration), a fail-safe halt. The
 *         owner can override all three with circuitBreakerOverride.
 *
 * @dev Security considerations: ReentrancyGuard on arbitrage execution, transient storage (EIP-1153)
 *      against recursive arbitrage loops, two-step ownership transfer, timelocked AuthManager updates,
 *      and a trusted-sender allowlist for Uniswap router validation.
 *
 * @dev Token decimals: USH 18, USDe 18. Price normalization: 1e18 = $1.00.
 *
 * @custom:security-contact [email protected]
 */
contract ManifestHook is BaseHook, ReentrancyGuard, IManifestHook {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using CurrencyLibrary for Currency;
    using SafeERC20 for IERC20;

    /* ========================================================================== */
    /*                                  CONSTANTS                                 */
    /* ========================================================================== */

    uint256 private constant TIMELOCK_PERIOD = 7 days;
    uint256 private constant TIMELOCK_EXPIRY = 14 days;
    /// @dev USDe/USD depeg-breaker tolerance. The default is the setUsdeUsdPeg band width (0.5%), so a
    ///      fresh hook halts once USDe leaves the range in which p can track it. The max is left above
    ///      the default so an owner can widen the halt band during a sustained, legitimate USDe basis
    ///      excursion instead of halting the only USH venue.
    uint256 private constant DEFAULT_USDE_USD_TOLERANCE = 0.005e18;
    uint256 private constant MAX_USDE_USD_TOLERANCE = 0.05e18;
    /// @dev Circuit-breaker band on the USH NAV oracle price; NAV outside [floor, ceiling] halts swaps.
    ///      Raising the band calls setUshNavCeiling before setUshNavFloor, since each setter requires
    ///      floor < ceiling.
    uint256 private constant DEFAULT_USH_NAV_FLOOR = 0.995e18;
    uint256 private constant DEFAULT_USH_NAV_CEILING = 1.005e18;
    uint256 private constant DEFAULT_ORACLE_STALENESS_THRESHOLD = 1 hours;
    /// @dev Upper bound governance may set for oracleStalenessThreshold. Both candidate USDe/USD feeds
    ///      publish on a daily heartbeat, not on deviation: measured gaps run at 23h (Chainlink
    ///      `usde-usd.data.eth`) and up to 24h00m24s (RedStone). isUsdeDepegged trips on `age > threshold`,
    ///      so a 24h bound leaves no margin and swaps revert CircuitBreakerActive until the late round
    ///      lands. 25h is the ceiling, not the operating value: deployment sets `oracleStalenessThreshold`
    ///      to 24h10m, clearing the measured heartbeat without widening the bound to the full 25h.
    uint256 private constant MAX_ORACLE_STALENESS_THRESHOLD = 25 hours;
    /// @dev Bounds for the configurable USDe/USD peg (p). USDe redeems 1:1 to USDC = $1, so p stays pinned
    ///      near $1; this band lets governance nudge p for minor USDe/USDC drift. usdeUsdTolerance defaults
    ///      to this same band width, so by default p at a band edge sits at the depeg-breaker threshold
    ///      rather than well inside it.
    uint256 private constant MIN_USDE_USD_PEG = 0.995e18;
    uint256 private constant MAX_USDE_USD_PEG = 1.005e18;
    uint256 private constant MIN_SWAP_PRICE_TOLERANCE = 0;
    uint256 private constant MAX_SWAP_PRICE_TOLERANCE = 0.01e18;
    /// @notice Transient storage slot for system swap flag (EIP-1153)
    /// @dev Marks protocol-initiated arbitrage swaps: _beforeSwap skips the user checks and _afterSwap skips
    ///      arb/flex, preventing recursion. Transient storage clears after the transaction; slot 0x01 avoids
    ///      collision with common storage patterns.
    uint256 private constant SYSTEM_SWAP_SLOT = 0x01;
    /// @notice Transient storage slot for the inventory-bound flag (EIP-1153)
    /// @dev Set only around the _afterSwap arbitrage, where ArbExec caps each take by the PoolManager's balance
    ///      while no delta is open in the unlock. The _beforeSwap catch-up leaves it clear and takes without a
    ///      cap. MUST match ArbExec.INVENTORY_BOUND_SLOT.
    uint256 private constant INVENTORY_BOUND_SLOT = 0x02;
    /// @dev Transient slots for the arb legs' gas budget. TX_SPENT: gas used by earlier user swaps in this
    ///      transaction, as the hook measured it. GAS_USED_BEFORE and GAS_LEFT_AT_BEFORE_EXIT: what
    ///      _beforeSwap used and had left when it returned, so _afterSwap can work out the swap's own gas.
    ///      LEG_CLOCK and LEG_FLAGS: set by each callback before its leg, so `clock - gasleft()` is the gas the
    ///      transaction has used so far. Every value is a difference within one frame or between the two
    ///      callbacks of one swap (same call depth), so the caller's gas limit never changes it.
    uint256 private constant TX_SPENT_SLOT = 0x03;
    uint256 private constant GAS_USED_BEFORE_SLOT = 0x04;
    uint256 private constant GAS_LEFT_AT_BEFORE_EXIT_SLOT = 0x05;
    uint256 private constant LEG_CLOCK_SLOT = 0x06;
    uint256 private constant LEG_FLAGS_SLOT = 0x07;

    // --- Gas budget of the arbitrage legs ---
    /// @dev EIP-7825 caps a transaction at 2^24 gas. Each arb leg sizes its route so the hook's work, the swap
    ///      and the external reserve stay under that cap. The caller's gas limit plays no part: a limit that is
    ///      too low makes the transaction fail; it never makes the arb smaller.
    uint256 private constant DEFAULT_EXTERNAL_GAS_RESERVE = 2_000_000;
    uint256 private constant MIN_EXTERNAL_GAS_RESERVE = 500_000;
    uint256 private constant MAX_EXTERNAL_GAS_RESERVE = 8_000_000;

    // --- Dynamic Fee Constants ---
    uint24 private constant DEFAULT_BASE_BUY_FEE = 100;
    uint24 private constant DEFAULT_BASE_SELL_FEE = 1000;
    uint24 private constant DEFAULT_MAX_SELL_FEE = 50000;
    uint256 private constant DEFAULT_SURCHARGE_MULTIPLIER = 0.5e18;
    uint256 private constant DEFAULT_PRESSURE_HALF_LIFE = 6 hours;
    uint24 private constant MAX_BASE_FEE = 100000;
    /// @dev Widest value _getProtocolFeeForDirection can return: it masks the raw slot0 protocol-fee field
    ///      without clamping, so the reachable domain is the FIELD WIDTH, not V4's 1000-pip
    ///      MAX_PROTOCOL_FEE policy cap. setDynamicFeeParams reserves this much headroom below MAX_LP_FEE
    ///      so the exact-output gross-up denominator stays positive without relying on V4's fee validation.
    uint24 private constant PROTOCOL_FEE_FIELD_MAX = 0xfff;
    uint256 private constant MAX_SURCHARGE_MULTIPLIER = 10e18;
    uint256 private constant MIN_PRESSURE_HALF_LIFE = 1 hours;
    uint256 private constant MAX_PRESSURE_HALF_LIFE = 7 days;

    /* ========================================================================== */
    /*                              STATE VARIABLES                               */
    /* ========================================================================== */

    // --- Auth & Ownership ---

    /// @notice The Auth Manager contract
    IAuthManager public authManager;

    /// @notice Pending Auth Manager address for timelock updates
    address private _pendingAuthManager;

    /// @notice Timestamp when Auth Manager update was requested
    uint256 private _setAuthManagerReqTimestamp;

    /// @notice Mapping of trusted sender addresses
    mapping(address => bool) public trustedSenders;

    /// @notice Array to track all trusted senders
    /// @dev Expected to stay under about ten router/periphery addresses: removeTrustedSender is O(n), so a
    ///      large list costs gas.
    address[] private _trustedSendersList;

    /// @notice Owner for administrative operations
    address public owner;

    /// @notice Pending owner for two-step ownership transfer
    address public pendingOwner;

    /// @notice Address authorized to pause/unpause (in addition to owner)
    address public pauser;

    // --- ManifestHook Specific ---

    /// @notice Target price in the canonical USH frame: USDe per USH, 18 decimals, derived as
    ///         NAV / usdeUsdPeg, so the USD leg divides out. 1e18 means one USDe per USH, which is
    ///         $1 only while USDe holds its peg.
    uint256 public targetPrice = 1e18;

    /// @notice Pause state
    bool public paused;

    /// @notice Flex Wallet - holds Flex USH tokens
    address public flexWallet;

    /// @notice Treasury - holds USDe for downward arbitrage
    address public treasury;

    /// @notice Rewards Wallet - receives arbitrage profits in USH
    address public rewardsWallet;

    /// @notice USDe/USD price oracle (Chainlink)
    AggregatorV3Interface public usdeUsdOracle;

    /// @notice Cached decimals of usdeUsdOracle. Feeds report fixed decimals, so caching avoids a
    ///         per-swap decimals() staticcall; refreshed whenever the feed is set.
    uint8 public usdeUsdOracleDecimals;

    /// @notice USH NAV price oracle. targetPrice tracks this live: targetPrice = NAV / p.
    IUSHPriceOracle public ushPriceOracle;

    /// @notice Circuit breaker override flag
    bool public circuitBreakerOverride;

    /// @notice Whether upward arbitrage (price > target) is enabled
    bool public upwardArbitrageEnabled = true;

    /// @notice Whether downward arbitrage (price < target) is enabled
    bool public downwardArbitrageEnabled = true;

    /// @notice Swap price tolerance for arbitrage (default 0 = exact target)
    /// @dev Allows swaps to cross tick boundaries near target price
    uint256 public swapPriceTolerance = 0;

    /// @notice USDe/USD depeg tolerance (configurable; default 0.5%)
    uint256 public usdeUsdTolerance = DEFAULT_USDE_USD_TOLERANCE;

    /// @notice USH NAV circuit-breaker band; if the NAV price is outside [ushNavFloor, ushNavCeiling]
    ///         the breaker halts swaps (configurable, default +/-0.5% around $1). Reads the oracle
    ///         directly, not the pool price, so pool drift cannot trip it, and it self-clears when NAV
    ///         returns inside the band.
    uint256 public ushNavFloor = DEFAULT_USH_NAV_FLOOR;
    uint256 public ushNavCeiling = DEFAULT_USH_NAV_CEILING;

    /// @notice USDe/USD peg (p) used in targetPrice = NAV / p. Default 1e18 ($1) under the Ethena
    ///         1:1 arrangement; owner-adjustable within [MIN_USDE_USD_PEG, MAX_USDE_USD_PEG].
    uint256 public usdeUsdPeg = 1e18;

    /// @notice Oracle staleness threshold (configurable, default 1 hour)
    uint256 public oracleStalenessThreshold = DEFAULT_ORACLE_STALENESS_THRESHOLD;

    /// @notice USH token
    IUSHTokenBase public ushToken;

    /// @notice USDe token
    IERC20 public usdeToken;

    /// @notice Whether a pool has been registered
    bool private _poolRegistered;

    /// @notice Whether the flexWallet balance is reverse flex, as set by the last swap that reconciled it. It stays
    ///         set when a target move leaves the pool below target before the next swap.
    bool public isReverseFlex;

    /// @notice Whether the hard breaker latch is tripped (sell fee hit ceiling)
    bool public hardBreakerTripped;

    /// @notice Target price for arbitrage (arb pushes toward this instead of targetPrice to conserve treasury)
    /// @dev When 0, arb uses targetPrice. Flex always uses targetPrice.
    uint256 public targetArbPrice;

    /// @notice Gas kept free in every swap transaction for work the hook cannot measure: the router's work
    ///         around the swap, the token transfers and the intrinsic cost.
    uint256 public externalGasReserve = DEFAULT_EXTERNAL_GAS_RESERVE;

    /// @notice Minimum USDe balance to maintain in treasury after downward arbitrage
    /// @dev A downward arb spends at most treasuryBalance - minTreasuryBalance; 0 means no floor. At or below
    ///      the floor nothing is spent, and the arb reports DownwardArbitrageExecuted(0, 0, 0, true).
    uint256 public minTreasuryBalance;

    // --- Dynamic Fee State ---

    /// @notice Base fee for buy swaps (V4 fee units, hundredths of bip)
    uint24 public baseBuyFee = DEFAULT_BASE_BUY_FEE;

    /// @notice Base fee for sell swaps (V4 fee units, hundredths of bip)
    uint24 public baseSellFee = DEFAULT_BASE_SELL_FEE;

    /// @notice Maximum sell fee including surcharge (V4 fee units)
    uint24 public maxSellFee = DEFAULT_MAX_SELL_FEE;

    /// @notice Surcharge multiplier (0.5e18 = 50%)
    uint256 public surchargeMultiplier = DEFAULT_SURCHARGE_MULTIPLIER;

    /// @notice USH principal deposited into the pool as liquidity, net of withdrawals.
    /// @dev Subtracted from totalSupply to give the surcharge denominator, so the fee prices pressure
    ///      against the float that can actually sell. Written ONLY by the two liquidity callbacks, from the
    ///      PRINCIPAL leg (callerDelta - feesAccrued): LP fees reach the pool through swaps, which this
    ///      counter does not watch, so debiting them on collect would walk it down for free. Swaps are
    ///      likewise not tracked, which is why this is net principal and not live pool inventory: it
    ///      understates the pool after selling pressure and overstates it after buying pressure.
    ///      `setPoolUshBaseline` is the correction path for that drift.
    uint256 public poolUshBaseline;

    /// @notice Half-life for pressure decay (seconds)
    uint256 public pressureHalfLife = DEFAULT_PRESSURE_HALF_LIFE;

    /// @notice Accumulated net sell pressure (USH-denominated, 18 decimals)
    uint256 public netSellPressure;

    /// @notice Timestamp of last pressure update
    uint256 public lastPressureUpdateTime;

    /// @notice Whether surcharge fee escalation is enabled
    bool public surchargeEnabled = true;

    /* ========================================================================== */
    /*                                 MODIFIERS                                  */
    /* ========================================================================== */

    modifier onlyOwner() {
        if (msg.sender != owner) revert OnlyOwner();
        _;
    }

    modifier onlyPauserOrOwner() {
        if (msg.sender != owner && msg.sender != pauser) revert OnlyPauserOrOwner();
        _;
    }

    modifier onlyPendingOwner() {
        if (msg.sender != pendingOwner) revert OnlyPendingOwner();
        _;
    }

    /* ========================================================================== */
    /*                                CONSTRUCTOR                                 */
    /* ========================================================================== */

    constructor(
        IPoolManager _poolManager,
        address _authManager,
        address _owner,
        address[] memory _initialTrustedSenders,
        address _ushToken,
        address _usdeToken,
        address _flexWallet,
        address _treasury,
        address _rewardsWallet,
        address _usdeUsdOracle,
        address _ushPriceOracle,
        address _pauser
    ) BaseHook(_poolManager) {
        // Auth validations
        if (_authManager == address(0)) revert InvalidAuthManager();
        if (_owner == address(0)) revert ZeroAddress();
        if (_initialTrustedSenders.length == 0) revert NoTrustedSendersProvided();

        // ManifestHook validations
        if (_ushToken == address(0)) revert ZeroUshToken();
        if (_usdeToken == address(0)) revert ZeroUsdeToken();
        if (_flexWallet == address(0)) revert ZeroFlexWallet();
        if (_treasury == address(0)) revert ZeroTreasury();
        if (_rewardsWallet == address(0)) revert ZeroRewardsWallet();
        if (_usdeUsdOracle == address(0)) revert ZeroOracle();
        if (_ushPriceOracle == address(0)) revert ZeroUshPriceOracle();
        if (_pauser == address(0)) revert ZeroPauser();

        // Set auth state
        authManager = IAuthManager(_authManager);
        owner = _owner;

        // Set ManifestHook state
        ushToken = IUSHTokenBase(_ushToken);
        usdeToken = IERC20(_usdeToken);
        flexWallet = _flexWallet;
        treasury = _treasury;
        rewardsWallet = _rewardsWallet;
        usdeUsdOracle = AggregatorV3Interface(_usdeUsdOracle);
        usdeUsdOracleDecimals = AggregatorV3Interface(_usdeUsdOracle).decimals();
        _probeUshPriceOracle(_ushPriceOracle);
        ushPriceOracle = IUSHPriceOracle(_ushPriceOracle);
        pauser = _pauser;

        // Initialize trusted senders
        for (uint256 i = 0; i < _initialTrustedSenders.length; i++) {
            if (trustedSenders[_initialTrustedSenders[i]]) revert SenderAlreadyTrusted();
            _addTrustedSender(_initialTrustedSenders[i]);
        }
    }

    /* ========================================================================== */
    /*                             OWNERSHIP MANAGEMENT                           */
    /* ========================================================================== */

    /// @notice Initiate ownership transfer (two-step pattern)
    function transferOwnership(address newOwner) external onlyOwner {
        if (newOwner == address(0)) revert ZeroAddress();
        pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner, newOwner);
    }

    /// @notice Accept ownership transfer
    function acceptOwnership() external onlyPendingOwner {
        address oldOwner = owner;
        owner = pendingOwner;
        pendingOwner = address(0);
        emit OwnershipTransferred(oldOwner, owner);
    }

    /// @notice Cancel pending ownership transfer
    function cancelOwnershipTransfer() external onlyOwner {
        if (pendingOwner == address(0)) revert NoPendingOwnership();
        address cancelledPending = pendingOwner;
        pendingOwner = address(0);
        emit OwnershipTransferCancelled(owner, cancelledPending);
    }

    /* ========================================================================== */
    /*                           AUTH MANAGER MANAGEMENT                          */
    /* ========================================================================== */

    /// @notice Set a new Auth Manager with timelock protection
    function setAuthManager(address _authManager) external onlyOwner {
        if (_authManager == address(0)) revert InvalidAuthManager();

        uint256 timelockReady;
        uint256 timelockExpiry;
        unchecked {
            timelockReady = _setAuthManagerReqTimestamp + TIMELOCK_PERIOD;
            timelockExpiry = timelockReady + TIMELOCK_EXPIRY;
        }

        if (
            block.timestamp >= timelockReady && block.timestamp <= timelockExpiry && _authManager == _pendingAuthManager
                && _pendingAuthManager != address(0)
        ) {
            // Timelock passed and not expired, execute update
            address oldManager = address(authManager);
            authManager = IAuthManager(_authManager);
            _pendingAuthManager = address(0);
            _setAuthManagerReqTimestamp = 0;
            emit AuthManagerUpdated(oldManager, _authManager);
        } else if (
            block.timestamp > timelockExpiry && _pendingAuthManager != address(0) && _authManager == _pendingAuthManager
        ) {
            revert TimelockExpired();
        } else if (_authManager != _pendingAuthManager) {
            _pendingAuthManager = _authManager;
            _setAuthManagerReqTimestamp = block.timestamp;
            emit AuthManagerUpdateRequested(_authManager, block.timestamp);
        } else {
            // Same address, still inside the delay: reject so a mined call cannot read as an executed rotation.
            // Restarting the delay for this address goes through cancelAuthManagerUpdate then a fresh request.
            revert TimelockNotReady();
        }
    }

    /// @notice Cancel pending Auth Manager update
    function cancelAuthManagerUpdate() external onlyOwner {
        if (_pendingAuthManager == address(0)) revert NoPendingUpdate();
        address cancelledManager = _pendingAuthManager;
        _pendingAuthManager = address(0);
        _setAuthManagerReqTimestamp = 0;
        emit AuthManagerUpdateCancelled(cancelledManager, block.timestamp);
    }

    /// @notice Get pending Auth Manager address and timelock info
    function getPendingAuthManager() external view returns (address pendingManager, uint256 unlockTime) {
        pendingManager = _pendingAuthManager;
        if (_pendingAuthManager != address(0)) {
            unchecked {
                unlockTime = _setAuthManagerReqTimestamp + TIMELOCK_PERIOD;
            }
        }
    }

    /* ========================================================================== */
    /*                          TRUSTED SENDER MANAGEMENT                         */
    /* ========================================================================== */

    /// @notice Add a trusted sender address
    function addTrustedSender(address sender) external onlyOwner {
        if (sender == address(0)) revert ZeroAddress();
        if (trustedSenders[sender]) revert SenderAlreadyTrusted();
        _addTrustedSender(sender);
    }

    /// @notice Remove a trusted sender address
    function removeTrustedSender(address sender) external onlyOwner {
        if (!trustedSenders[sender]) revert SenderNotTrusted();
        if (_trustedSendersList.length == 1) revert MinimumTrustedSenderRequired();

        trustedSenders[sender] = false;

        uint256 listLen = _trustedSendersList.length;
        for (uint256 i = 0; i < listLen;) {
            if (_trustedSendersList[i] == sender) {
                unchecked {
                    _trustedSendersList[i] = _trustedSendersList[listLen - 1];
                }
                _trustedSendersList.pop();
                break;
            }
            unchecked {
                ++i;
            }
        }

        emit TrustedSenderRemoved(sender);
    }

    /// @notice Get all trusted senders
    function getTrustedSenders() external view returns (address[] memory) {
        return _trustedSendersList;
    }

    /// @notice Internal function to add a trusted sender
    /// @param sender The address to add to the trusted senders list
    function _addTrustedSender(address sender) internal {
        trustedSenders[sender] = true;
        _trustedSendersList.push(sender);
        emit TrustedSenderAdded(sender);
    }

    /* ========================================================================== */
    /*                              PAUSE MECHANISM                               */
    /* ========================================================================== */

    /// @notice Pause the hook (disables swaps, allows liquidity operations)
    function pause() external onlyPauserOrOwner {
        paused = true;
        emit Paused(msg.sender);
    }

    /// @notice Unpause the hook
    function unpause() external onlyPauserOrOwner {
        paused = false;
        emit Unpaused(msg.sender);
    }

    /// @notice Set the pauser address (owner only)
    /// @param newPauser New pauser address
    function setPauser(address newPauser) external onlyOwner {
        if (newPauser == address(0)) revert ZeroPauser();
        address oldPauser = pauser;
        pauser = newPauser;
        emit PauserUpdated(oldPauser, newPauser);
    }

    /* ========================================================================== */
    /*                              CIRCUIT BREAKER                               */
    /* ========================================================================== */

    /// @notice Check if USDe is depegged from USD
    /// @dev The Chainlink read fails safe on a non-positive answer, a stale round (answeredInRound <
    ///      roundId), or an updatedAt older than oracleStalenessThreshold. The answer is normalized to 18
    ///      decimals from the cached usdeUsdOracleDecimals, so a feed that changes decimals in place (a
    ///      Chainlink proxy phase upgrade) must be re-registered via setUsdeUsdOracle to refresh the cache.
    function isUsdeDepeggedFromUsd() public view returns (bool) {
        return HookMath.isUsdeDepegged(usdeUsdOracle, usdeUsdOracleDecimals, usdeUsdTolerance, oracleStalenessThreshold);
    }

    /// @notice True if the USH NAV oracle price has fallen below ushNavFloor.
    /// @dev Reads the NAV oracle DIRECTLY, never the pool price, so pool drift cannot trip it: it
    ///      fires only on a genuine move of USH's booked value. While tripped _beforeSwap reverts, so
    ///      arb and flex do not run either. Clears once the oracle NAV returns inside the band.
    function isUshNavBelowFloor() public view returns (bool) {
        return ushPriceOracle.getCurrentPrice() < ushNavFloor;
    }

    /// @notice True if the USH NAV oracle price has risen above ushNavCeiling.
    /// @dev Same oracle-direct read as the floor.
    function isUshNavAboveCeiling() public view returns (bool) {
        return ushPriceOracle.getCurrentPrice() > ushNavCeiling;
    }

    /// @dev Band-membership test shared by isUshNavOutOfBand (fresh oracle read) and _beforeSwap
    ///      (cached nav), so the bound comparison lives in exactly one place.
    function _navOutOfBand(uint256 nav) internal view returns (bool) {
        return nav < ushNavFloor || nav > ushNavCeiling;
    }

    /// @notice True if the USH NAV oracle price is outside the [ushNavFloor, ushNavCeiling] band.
    function isUshNavOutOfBand() public view returns (bool) {
        return _navOutOfBand(ushPriceOracle.getCurrentPrice());
    }

    /// @notice True if the NAV oracle has been emergency-paused by its owner.
    /// @dev A paused NAV oracle means "do not trust this feed"; the pool halts with it (fail-safe),
    ///      unlike a merely stale oracle which we run against its last-known NAV.
    function isNavOraclePaused() public view returns (bool) {
        (,,,, bool navPaused) = ushPriceOracle.getConfiguration();
        return navPaused;
    }

    /// @notice True if any circuit breaker is active (user swaps halt).
    /// @dev ORs three breakers, each reading an oracle and never the pool price, so a pool drifting
    ///      from NAV is NOT a breaker condition and cannot trip its own halt: the USDe/USD depeg
    ///      guard (protects the p ~ 1
    ///      assumption in targetPrice = NAV / p), the USH NAV band, and the NAV-oracle pause.
    ///      Arb and flex run only inside the swap callbacks _beforeSwap gates, so an active breaker
    ///      halts them with the swap. _beforeSwap's revert carries which cause fired.
    function isCircuitBreakerActive() public view returns (bool) {
        if (circuitBreakerOverride) return false;
        return isUsdeDepeggedFromUsd() || isUshNavOutOfBand() || isNavOraclePaused();
    }

    /// @notice Set circuit breaker override
    function setCircuitBreakerOverride(bool enabled) external onlyOwner {
        circuitBreakerOverride = enabled;
        emit CircuitBreakerOverrideSet(enabled);
    }

    /// @notice Enable or disable upward arbitrage execution
    function setUpwardArbitrageEnabled(bool enabled) external onlyOwner {
        upwardArbitrageEnabled = enabled;
        emit UpwardArbitrageEnabledSet(enabled);
    }

    /// @notice Enable or disable downward arbitrage execution
    function setDownwardArbitrageEnabled(bool enabled) external onlyOwner {
        downwardArbitrageEnabled = enabled;
        emit DownwardArbitrageEnabledSet(enabled);
    }

    /// @notice Set the external gas reserve (500,000 to 8,000,000). Raise it for routers that do more work
    ///         around the swap; on dense books the arb legs shrink by the same amount.
    function setExternalGasReserve(uint256 reserve) external onlyOwner {
        if (reserve < MIN_EXTERNAL_GAS_RESERVE || reserve > MAX_EXTERNAL_GAS_RESERVE) revert InvalidGasReserve();
        emit ExternalGasReserveUpdated(externalGasReserve, reserve);
        externalGasReserve = reserve;
    }

    /// @notice Reset the hard breaker latch (owner only)
    function resetHardBreaker() external onlyOwner {
        hardBreakerTripped = false;
        emit HardBreakerReset();
    }

    /// @notice Set target arbitrage price (arb pushes toward this instead of targetPrice)
    /// @param _price New target arb price (18 decimals, 0 = use targetPrice)
    function setTargetArbPrice(uint256 _price) external onlyOwner {
        uint256 oldPrice = targetArbPrice;
        targetArbPrice = _price;
        emit TargetArbPriceUpdated(oldPrice, _price);
    }

    /// @notice Set minimum USDe balance to maintain in treasury after downward arbitrage
    /// @param _minBalance New minimum treasury balance (18 decimals, 0 = no floor)
    function setMinTreasuryBalance(uint256 _minBalance) external onlyOwner {
        uint256 oldValue = minTreasuryBalance;
        minTreasuryBalance = _minBalance;
        emit MinTreasuryBalanceUpdated(oldValue, _minBalance);
    }

    /// @notice Update swap price tolerance for arbitrage
    /// @param _tolerance New tolerance value (between MIN and MAX)
    function setSwapPriceTolerance(uint256 _tolerance) external onlyOwner {
        if (_tolerance < MIN_SWAP_PRICE_TOLERANCE) revert ToleranceTooLow();
        if (_tolerance > MAX_SWAP_PRICE_TOLERANCE) revert ToleranceTooHigh();
        uint256 oldTolerance = swapPriceTolerance;
        swapPriceTolerance = _tolerance;
        emit SwapPriceToleranceUpdated(oldTolerance, _tolerance);
    }

    /// @notice Set the lower bound of the NAV circuit-breaker band. Must be > 0 and < ushNavCeiling.
    /// @param _floor New floor (18 decimals); must be > 0 and < ushNavCeiling.
    /// @dev No fixed $1 cap. To move the band up, raise the ceiling first (setUshNavCeiling), then the
    ///      floor, since each setter requires floor < ceiling.
    function setUshNavFloor(uint256 _floor) external onlyOwner {
        if (_floor == 0 || _floor >= ushNavCeiling) revert InvalidNavFloor();
        uint256 oldFloor = ushNavFloor;
        ushNavFloor = _floor;
        emit UshNavFloorUpdated(oldFloor, _floor);
    }

    /// @notice Set the upper bound of the NAV circuit-breaker band. Must be > ushNavFloor.
    /// @dev No absolute cap.
    function setUshNavCeiling(uint256 _ceiling) external onlyOwner {
        if (_ceiling <= ushNavFloor) revert InvalidNavCeiling();
        uint256 oldCeiling = ushNavCeiling;
        ushNavCeiling = _ceiling;
        emit UshNavCeilingUpdated(oldCeiling, _ceiling);
    }

    /// @notice Update the USDe/USD peg (p) used in targetPrice = NAV / p.
    /// @param _peg New peg (18 decimals); must be within [MIN_USDE_USD_PEG, MAX_USDE_USD_PEG]
    ///        (the lower bound is > 0, so this also rules out a divide-by-zero in _refreshTargetPrice).
    function setUsdeUsdPeg(uint256 _peg) external onlyOwner {
        if (_peg < MIN_USDE_USD_PEG || _peg > MAX_USDE_USD_PEG) revert InvalidUsdeUsdPeg();
        uint256 oldPeg = usdeUsdPeg;
        usdeUsdPeg = _peg;
        // Recompute targetPrice with the new peg in the same tx, so public views (targetPrice,
        // calculateFlex*) never serve a target derived from the old configuration.
        _refreshTargetPrice();
        emit UsdeUsdPegUpdated(oldPeg, _peg);
    }

    /// @notice Update USDe/USD depeg tolerance
    /// @param _tolerance New tolerance value (must not exceed MAX_USDE_USD_TOLERANCE)
    function setUsdeUsdTolerance(uint256 _tolerance) external onlyOwner {
        if (_tolerance > MAX_USDE_USD_TOLERANCE) revert ToleranceTooHigh();
        uint256 oldTolerance = usdeUsdTolerance;
        usdeUsdTolerance = _tolerance;
        emit UsdeUsdToleranceUpdated(oldTolerance, _tolerance);
    }

    /// @notice Update oracle staleness threshold
    /// @param _threshold New threshold value (must not exceed MAX_ORACLE_STALENESS_THRESHOLD)
    function setOracleStalenessThreshold(uint256 _threshold) external onlyOwner {
        if (_threshold > MAX_ORACLE_STALENESS_THRESHOLD) revert ThresholdTooHigh();
        if (_threshold == 0) revert ThresholdTooLow();
        uint256 oldThreshold = oracleStalenessThreshold;
        oracleStalenessThreshold = _threshold;
        emit OracleStalenessThresholdUpdated(oldThreshold, _threshold);
    }

    /* ========================================================================== */
    /*                              VIEW FUNCTIONS                                */
    /* ========================================================================== */

    /// @notice Get current pool price (18 decimals, normalized where $1 = 1e18)
    function getCurrentPrice(PoolKey calldata key) public view returns (uint256) {
        (uint160 sqrtPriceX96,,,) = poolManager.getSlot0(key.toId());
        uint256 rawPrice = PriceMath.sqrtPriceX96ToPrice(sqrtPriceX96);
        // Canonical USH frame (USDe per USH): V4's raw price is token1/token0, so when USH sorts as
        // currency1 the raw price is USH-per-USDe and must be reciprocated. Every internal price
        // comparison uses this normalized value.
        if (_isUshCurrency0(key)) return rawPrice;
        return rawPrice == 0 ? type(uint256).max : FullMath.mulDiv(1e18, 1e18, rawPrice);
    }

    /// @notice Calculate flex burned to reach target using multi-tick estimation
    /// @dev Returns mUSH amount in 18 decimals. Iterates through tick boundaries
    ///      to correctly account for liquidity changes across concentrated positions.
    function calculateFlexBurnedToTarget(PoolKey calldata key) public view returns (uint256) {
        (uint160 sqrtStartX96,,,) = poolManager.getSlot0(key.toId());
        bool ushIs0 = _isUshCurrency0(key);
        uint160 sqrtTargetX96 = _ushFrameToPoolSqrt(key, targetPrice);
        // Below-target in USH terms means the raw price sits on the BUY side of the raw target:
        // below it when USH is currency0, above it when USH is currency1 (raw = USH-per-USDe).
        if (ushIs0 ? sqrtStartX96 >= sqrtTargetX96 : sqrtStartX96 <= sqrtTargetX96) return 0;

        // Buying USH with USDe to push the USH price up toward target: oneForZero when USH is
        // currency0, zeroForOne when USH is currency1. Map (amount0, amount1) to (USH, USDe).
        (uint256 amount0, uint256 amount1) =
            SwapEstimation.estimateSwapAmounts(poolManager, key, sqrtTargetX96, !ushIs0);
        (uint256 ushOut, uint256 usdeIn) = ushIs0 ? (amount0, amount1) : (amount1, amount0);
        if (ushOut == 0) return 0;

        // Convert mUSDe to mUSH equivalent (both 18 dec), rounded UP so the subtracted term is larger and
        // flex comes out smaller. The guarantee is bounded, not strictly non-over-minting: SwapEstimation
        // double-ceilings amount0 (per-tick ceil, then a second ceil on the division), and when USH is
        // currency0 ushOut IS amount0, so forward flex can EXCEED the true gap by ~1 wei from this division
        // plus ~2 wei per crossed tick. It does not accumulate, because flex is recomputed absolutely each
        // swap. When USH is currency1 the double-ceiling lands on the subtracted usdeIn side instead, so
        // the same bound runs deflationary, apart from the added leg's own single ceil.
        uint256 usdeInValue = FullMath.mulDivRoundingUp(usdeIn, 1e18, targetPrice);
        return ushOut > usdeInValue ? ushOut - usdeInValue : 0;
    }

    /// @notice Calculate flex minted to reach target from above (reverse flex)
    /// @dev Returns mUSH amount in 18 decimals. Symmetric counterpart of calculateFlexBurnedToTarget.
    ///      When price > target, selling USH yields MORE USDe value than the USH spent.
    ///      This surplus (usdeOutValue - ushIn) is the value gap above par.
    ///      Walks tick boundaries with SwapEstimation in the USH-selling direction: zeroForOne when USH
    ///      is currency0, oneForZero when it is currency1.
    function calculateFlexMintedToTarget(PoolKey calldata key) public view returns (uint256) {
        (uint160 sqrtStartX96,,,) = poolManager.getSlot0(key.toId());
        bool ushIs0 = _isUshCurrency0(key);
        uint160 sqrtTargetX96 = _ushFrameToPoolSqrt(key, targetPrice);
        // Above-target in USH terms means the raw price sits on the SELL side of the raw target:
        // above it when USH is currency0, below it when USH is currency1 (raw = USH-per-USDe).
        if (ushIs0 ? sqrtStartX96 <= sqrtTargetX96 : sqrtStartX96 >= sqrtTargetX96) return 0;

        // Selling USH to push the USH price down to target: zeroForOne when USH is currency0,
        // oneForZero when USH is currency1. Map (amount0, amount1) to (USH, USDe).
        // ROUNDING NOTE (USH as currency1): SwapEstimation ceilings amount0 more aggressively than
        // amount1, and in this orientation that amount0 lands on the ADDED usdeOut side, so reverse flex
        // can exceed the true gap by ~1-2 wei per crossed tick segment (bounded, non-accumulating:
        // recomputed absolutely each swap). The currency0 orientation puts that amount0 on the subtracted
        // ushIn side instead, so the same bound runs deflationary, apart from amount1's own single ceil.
        (uint256 amount0, uint256 amount1) = SwapEstimation.estimateSwapAmounts(poolManager, key, sqrtTargetX96, ushIs0);
        (uint256 ushIn, uint256 usdeOut) = ushIs0 ? (amount0, amount1) : (amount1, amount0);
        if (ushIn == 0) return 0;

        // Convert mUSDe to mUSH equivalent (both 18 dec), rounded DOWN (floor) so usdeOutValue is smaller
        // and reverse flex (usdeOutValue - ushIn) comes out smaller: the protocol never over-mints reverse
        // flex USH (inflationary), at the cost of under-minting by up to 1 wei per swap (deflationary,
        // conservative). Opposite to calculateFlexBurnedToTarget, which rounds UP, only because the USDe
        // term sits on the other side of the subtraction. Both directions produce less flex, by design.
        uint256 usdeOutValue = FullMath.mulDiv(usdeOut, 1e18, targetPrice);
        return usdeOutValue > ushIn ? usdeOutValue - ushIn : 0;
    }

    /* ========================================================================== */
    /*                              HOOK PERMISSIONS                              */
    /* ========================================================================== */

    /// @notice Hook permissions for ManifestHook
    function getHookPermissions() public pure override returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: true, // Auth check + pool registration
            afterInitialize: false,
            beforeAddLiquidity: true, // Auth + Flex constraint check
            afterAddLiquidity: true,
            beforeRemoveLiquidity: true, // Auth + Flex constraint check
            afterRemoveLiquidity: true, // Retained for the mined address; body is a no-op
            beforeSwap: true, // Auth check
            afterSwap: true, // Arbitrage/Flex
            beforeDonate: true, // Auth check
            afterDonate: false,
            beforeSwapReturnDelta: false,
            afterSwapReturnDelta: false,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

    /* ========================================================================== */
    /*                               HOOK CALLBACKS                               */
    /* ========================================================================== */

    /// @notice Hook callback before pool initialization
    /// @dev Performs auth checks and registers this hook to a single pool
    ///      Only one pool can be registered per hook deployment
    function _beforeInitialize(address sender, PoolKey calldata key, uint160) internal override returns (bytes4) {
        _checkAllowed(sender);
        authManager.checkManifestAccount(_getSender(sender));

        // The hook manages exactly the USH/USDe pair, either sort order. Any other pair would be silently
        // priced in a nonsense USH frame, so reject unknown pairs at registration.
        {
            address c0 = Currency.unwrap(key.currency0);
            address c1 = Currency.unwrap(key.currency1);
            bool isUshUsdePair = (c0 == address(ushToken) && c1 == address(usdeToken))
                || (c0 == address(usdeToken) && c1 == address(ushToken));
            if (!isUshUsdePair) revert InvalidPoolCurrencies();
        }

        // The whole fee schedule reaches the pool through one channel: the OVERRIDE_FEE_FLAG that
        // _beforeSwap returns. V4 parses that return only under `key.fee.isDynamicFee()` (Hooks.beforeSwap)
        // and otherwise discards it with no revert and no event, charging the static tier instead. A pool
        // registered on a static tier therefore runs with the base fees, the sell surcharge, the maxSellFee
        // clamp and the zero-fee arb path all inert. Having the guard is what prevents that; its position
        // ahead of the latch below only decides WHICH error a static-fee attempt reports, since a revert
        // anywhere in this body discards the latch's write with the rest of the frame.
        if (!LPFeeLibrary.isDynamicFee(key.fee)) revert NonDynamicPoolFee();

        // Ensure only one pool can be registered per hook instance
        if (_poolRegistered) revert PoolAlreadyRegistered();
        _poolRegistered = true;
        emit PoolRegistered(key.toId());

        return BaseHook.beforeInitialize.selector;
    }

    /// @notice Hook callback before adding liquidity
    /// @dev Validates auth and Flex constraints. All checks enforced regardless of pause state.
    function _beforeAddLiquidity(address sender, PoolKey calldata key, ModifyLiquidityParams calldata, bytes calldata)
        internal
        override
        returns (bytes4)
    {
        _checkAllowed(sender);
        authManager.checkManifestAccount(_getSender(sender));

        // Refresh targetPrice from the live NAV oracle before the flex pre-check: without it the pre-check
        // runs against a stale (higher) target and can false-revert an add the live target would permit.
        _refreshTargetPrice();

        _requireFlexForAdd(key);

        return BaseHook.beforeAddLiquidity.selector;
    }

    /// @notice Hook callback after adding liquidity
    /// @dev Validates the Flex invariant AFTER liquidity is added: an add raises flexNeeded (more
    ///      liquidity in the price path means more USH flows out on a buy to target). The before-check
    ///      alone is insufficient because it evaluates flexNeeded against the pre-addition profile.
    function _afterAddLiquidity(
        address,
        PoolKey calldata key,
        ModifyLiquidityParams calldata,
        BalanceDelta callerDelta,
        BalanceDelta feesAccrued,
        bytes calldata
    ) internal override returns (bytes4, BalanceDelta) {
        // Refresh targetPrice from the live NAV oracle before the flex constraint is evaluated.
        _refreshTargetPrice();

        _requireFlexForAdd(key);

        _trackPoolUsh(key, callerDelta, feesAccrued);

        return (BaseHook.afterAddLiquidity.selector, BalanceDeltaLibrary.ZERO_DELTA);
    }

    /// @notice Apply a liquidity operation's USH PRINCIPAL to `poolUshBaseline`.
    /// @dev `PoolManager` builds the caller's delta as `principalDelta + feesAccrued`, so subtracting the
    ///      fee leg recovers the principal. That subtraction is the whole point: V4 routes a bare fee
    ///      collect (`liquidityDelta == 0`) to the REMOVE callbacks with `callerDelta == feesAccrued`, so
    ///      crediting the whole delta would debit the counter by USH that never entered through this path.
    ///      Both signs are handled on both callbacks; a one-sided condition would silently drop the real
    ///      movements a single-sided position produces. The subtraction floors at zero rather than
    ///      reverting, because an LP exit must never be blocked by this counter.
    ///      The subtraction runs in the reverse order to the sentence above, because `fees - caller` IS
    ///      `-(caller - fees)` and the counter wants the pool-side sign. Folding the negation into the
    ///      operand order also drops a checked negation and the two int128 bounds checks the packed
    ///      subtraction runs, one of them on a leg this function never reads.
    function _trackPoolUsh(PoolKey calldata key, BalanceDelta callerDelta, BalanceDelta feesAccrued) internal {
        int256 ushDelta = _isUshCurrency0(key)
            ? int256(feesAccrued.amount0()) - int256(callerDelta.amount0())
            : int256(feesAccrued.amount1()) - int256(callerDelta.amount1());
        if (ushDelta == 0) return;
        uint256 baseline = poolUshBaseline;
        if (ushDelta > 0) {
            baseline += uint256(ushDelta);
        } else {
            uint256 out = uint256(-ushDelta);
            baseline = out < baseline ? baseline - out : 0;
        }
        poolUshBaseline = baseline;
        emit PoolUshBaselineAccrued(ushDelta, baseline);
    }

    function _beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata,
        bytes calldata
    ) internal override returns (bytes4) {
        _checkAllowed(sender);
        authManager.checkManifestAccount(_getSender(sender));

        // Best-effort refresh: a reverting NAV oracle must never block an LP exit, so a failed read
        // keeps the stored targetPrice (the advisory check below then runs against last-good).
        _tryRefreshTargetPrice();

        // Flex accounting on removal is advisory, NOT a gate: removing liquidity provably REDUCES the
        // required flex (calculateFlexBurnedToTarget scales with pool liquidity), so a shortfall must never
        // block an LP exit and trap funds. Adds, which raise it, keep the hard gate.
        (bool ok, bool staleDirection, uint256 flexBalance, uint256 flexNeeded) = _flexState(key);
        if (!ok) emit InsufficientFlexForLiquidityWarning(flexBalance, flexNeeded, staleDirection);

        return BaseHook.beforeRemoveLiquidity.selector;
    }

    /// @notice Hook callback after removing liquidity
    /// @dev Debits the withdrawn USH principal from `poolUshBaseline`. A bare fee collect also lands here
    ///      (V4 routes `liquidityDelta <= 0` to the remove callbacks), and `_trackPoolUsh` deliberately
    ///      leaves it a no-op.
    function _afterRemoveLiquidity(
        address,
        PoolKey calldata key,
        ModifyLiquidityParams calldata,
        BalanceDelta callerDelta,
        BalanceDelta feesAccrued,
        bytes calldata
    ) internal override returns (bytes4, BalanceDelta) {
        _trackPoolUsh(key, callerDelta, feesAccrued);
        return (BaseHook.afterRemoveLiquidity.selector, BalanceDeltaLibrary.ZERO_DELTA);
    }

    /// @notice Hook callback before swap execution
    /// @dev A protocol arb swap bypasses everything; a user swap runs, in order: pause, NAV refresh,
    ///      circuit breaker, auth, flex (warning only), catch-up arb, dynamic fee (a pure quote; pressure
    ///      moves in _afterSwap). The fee comes after the arb so its curve walk starts from the price
    ///      Pool.swap will execute from. The hard-breaker latch is deliberately NOT here: it lives in
    ///      _afterSwap, keyed off realized pressure.
    /// @dev nonReentrant protects the catch-up arb's external calls, matching _afterSwap, and the shared
    ///      guard is released between the two because they run as sequential top-level callbacks. The
    ///      nested system swap cannot re-enter this callback anyway: V4 skips the hook callbacks when the
    ///      swap's initiator is the hook itself (msg.sender == self), and SYSTEM_SWAP_SLOT is
    ///      belt-and-suspenders on top.
    function _beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata)
        internal
        override
        nonReentrant
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        uint256 gasStart = gasleft();
        // 1. Bypass all checks for protocol-initiated arbitrage swaps
        uint256 isSystemSwap;
        assembly {
            isSystemSwap := tload(SYSTEM_SWAP_SLOT)
        }
        if (isSystemSwap == 1) {
            // System swap - skip ManifestHook checks, zero fee for arb swaps
            return (BaseHook.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, LPFeeLibrary.OVERRIDE_FEE_FLAG);
        }

        // 2. Pause check (user swaps only)
        if (paused) revert HookPaused();

        // 3. Refresh targetPrice from the live NAV oracle so the flex constraint and dynamic
        //    fee below level-set against the current NAV.
        uint256 nav = _refreshTargetPrice();

        // 4. Circuit breaker check (user swaps only). Evaluate each cause once and carry the full
        //    cause set in the revert data (an emit would be discarded when the frame reverts). NAV
        //    is reused from the refresh above, not re-read: it cannot move within a single tx.
        if (!circuitBreakerOverride) {
            bool usdeDepegged = isUsdeDepeggedFromUsd();
            bool navOutOfBand = _navOutOfBand(nav);
            bool navPaused = isNavOraclePaused();
            if (usdeDepegged || navOutOfBand || navPaused) {
                revert CircuitBreakerActive(usdeDepegged, navOutOfBand, navPaused);
            }
        }

        // 5. Auth checks (user swaps only)
        _checkAllowed(sender);
        authManager.checkUser(_getSender(sender));

        // 6. Flex constraint check (user swaps only). Advisory: warn when the check fails and let the swap run.
        (bool flexOk, bool staleDirection, uint256 flexBalance, uint256 flexNeeded) = _flexState(key);
        if (!flexOk) emit InsufficientFlexForSwapWarning(flexBalance, flexNeeded, staleDirection);

        // 7. Catch-up arbitrage. Clears the residual a prior swap's capped afterSwap arb left, so the pool is
        //    back at target before the user swap runs. INVENTORY_BOUND_SLOT is clear here, so ArbExec takes
        //    without a cap: every earlier unlock has settled, so the PoolManager holds at least this pool's
        //    reserves unless tokens left it outside V4's accounting. A shortfall means a debt opened earlier in
        //    this unlock or a USH burn taken from the PoolManager, and the take reverts ArbInventoryShortfall,
        //    and with it the swap and the unlock, rather than filling the swap at the uncorrected price. The
        //    direction follows the residual, not the incoming swap, so the revert can hit a swap in either
        //    direction. Arb only: _afterSwap remains the sole flex reconciler. No auth of its own: it runs
        //    after the user gate above and its nested swap sets SYSTEM_SWAP_SLOT.
        //    Gas: the catch-up's share of the room left under the cap. Only an exact-output USH sell reserves
        //    the fee quote's walk, because only that quote walks the curve.
        bool exactOutputSell = params.amountSpecified > 0 && params.zeroForOne == _isUshCurrency0(key);
        uint256 flags = HookMath.FLAG_CATCH_UP | (exactOutputSell ? HookMath.FLAG_EXACT_OUTPUT : 0)
            | (params.zeroForOne ? HookMath.FLAG_USER_ZERO_FOR_ONE : 0);
        assembly ("memory-safe") {
            tstore(LEG_CLOCK_SLOT, add(tload(TX_SPENT_SLOT), gasStart))
            tstore(LEG_FLAGS_SLOT, flags)
        }
        _runArbitrage(key);

        // 8. Compute dynamic fee based on direction and sell pressure. Quoted AFTER the catch-up, because
        //    an exact-output sell has no USH leg in the request and _computeDynamicFee walks the curve for
        //    it. Pool.swap then executes from the POST-catch-up price, so a quote taken ahead of step 7
        //    sizes the walk from a price the swap never sees: it undercharges when the catch-up runs
        //    upward and overcharges when it runs downward. The arb reads no fee, so it does not care that
        //    it now runs first. Two accepted consequences: the walk's 256-iteration cap now bites from a
        //    different starting price (bounded by the dislocation, ~0.45% of the budget's reach at a 3%
        //    gap), and an int256.min sell pays for a rolled-back arb before InvalidSwapAmount fires.
        uint24 dynamicFee = _computeDynamicFee(key, params);

        // 9. Ledger for _afterSwap: the gas this callback used, and the gas left as it returns.
        assembly ("memory-safe") {
            tstore(GAS_USED_BEFORE_SLOT, sub(gasStart, gas()))
            tstore(GAS_LEFT_AT_BEFORE_EXIT_SLOT, gas())
        }

        return
            (
                BaseHook.beforeSwap.selector,
                BeforeSwapDeltaLibrary.ZERO_DELTA,
                LPFeeLibrary.OVERRIDE_FEE_FLAG | dynamicFee
            );
    }

    /// @notice afterSwap hook - executes arbitrage and Flex accounting
    /// @dev nonReentrant protects against reentrancy through external calls in arbitrage functions
    function _afterSwap(address, PoolKey calldata key, SwapParams calldata, BalanceDelta delta, bytes calldata)
        internal
        override
        nonReentrant
        returns (bytes4, int128)
    {
        uint256 gasStart = gasleft();
        // 1. Check system swap flag (arbitrage swaps from protocol)
        uint256 isSystemSwap;
        assembly {
            isSystemSwap := tload(SYSTEM_SWAP_SLOT)
        }
        if (isSystemSwap == 1) {
            // System swap - skip arbitrage/flex (prevents loop)
            return (BaseHook.afterSwap.selector, 0);
        }

        // targetPrice was already refreshed in _beforeSwap of this same swap tx (V4 fires afterSwap
        // only after beforeSwap for this permission set), and NAV cannot move mid-tx, so no refresh here.

        // 2. Accrue sell pressure from this swap's REALIZED USH leg, before any arb runs.
        //    `delta` is the user's fill: system swaps returned above, so the hook's own arb legs are
        //    never counted here. For an exact-input sell the USH leg is the fee-inclusive gross
        //    input, which is the number the surcharge should see. Widening int128 to int256 before
        //    the library negates it keeps int128.min unreachable, so the negation cannot overflow.
        {
            int256 ushDelta = int256(_isUshCurrency0(key) ? delta.amount0() : delta.amount1());
            if (ushDelta != 0) {
                (uint24 feeLevel, uint256 reconciled) = DynamicFeeLib.reconcilePressure(
                    DynamicFeeLib.ReconcileInput({
                        currentPressure: netSellPressure,
                        lastUpdateTime: lastPressureUpdateTime,
                        halfLife: pressureHalfLife,
                        ushDelta: ushDelta,
                        ushToken: address(ushToken),
                        poolUshBaseline: poolUshBaseline,
                        baseSellFee: baseSellFee,
                        maxSellFee: maxSellFee,
                        surchargeMultiplier: surchargeMultiplier,
                        surchargeEnabled: surchargeEnabled
                    })
                );
                netSellPressure = reconciled;
                lastPressureUpdateTime = block.timestamp;
                emit SellPressureAccrued(ushDelta < 0, reconciled);

                // Hard breaker, on realized pressure and never the requested amount, BEFORE _runArbitrage
                // so the latch gates this swap's own afterSwap downward arb (not the beforeSwap catch-up
                // of the same swap, which already ran).
                if (!hardBreakerTripped && ushDelta < 0 && feeLevel >= maxSellFee) {
                    hardBreakerTripped = true;
                    emit HardBreakerTripped();
                }
            }
        }

        // 3. Run the arb dispatch for this swap's own dislocation, then reconcile flex below from the
        //    resulting price. INVENTORY_BOUND_SLOT is set around it: this arb takes its output before the
        //    router settles the user's input, so ArbExec caps each take by the PoolManager's balance and leaves
        //    the gap to flex. A delta left open by an earlier action in the unlock lifts the cap instead.
        //    Gas: the room left under the cap after earlier swaps, this swap and both callbacks so far. Both
        //    callbacks get their gas through the same 63/64 forwarding, so
        //    (64 * left + usedBefore - 64 * gasStart) / 63 is the gas spent between them, whatever limit the
        //    caller set. That includes the PoolManager's work around Pool.swap, a few thousand gas more than
        //    the swap alone, which only makes the leg smaller. Comparing 64 * left + usedBefore with
        //    64 * gasStart keeps the subtraction from wrapping.
        uint256 clock;
        assembly ("memory-safe") {
            let usedBefore := tload(GAS_USED_BEFORE_SLOT)
            let beforeSide := add(mul(64, tload(GAS_LEFT_AT_BEFORE_EXIT_SLOT)), usedBefore)
            let afterSide := mul(64, gasStart)
            let swapGas := 0
            if gt(beforeSide, afterSide) { swapGas := div(sub(beforeSide, afterSide), 63) }
            clock := add(add(add(tload(TX_SPENT_SLOT), usedBefore), swapGas), gasStart)
            tstore(LEG_CLOCK_SLOT, clock)
            tstore(LEG_FLAGS_SLOT, 0)
            tstore(INVENTORY_BOUND_SLOT, 1)
        }
        uint256 currentPrice = _runArbitrage(key);
        assembly {
            tstore(INVENTORY_BOUND_SLOT, 0)
        }

        // Flex accounting: handles both forward flex (price < target) and
        // reverse flex (price still > target after the arb step).
        //
        // Forward flex: minted when price < target, burned as price rises toward target.
        // Reverse flex: minted while the price stays above target after the arb step, and used as fuel by
        // the next upward arb (_executeUpwardArbitrage).
        //
        // The isReverseFlex flag disambiguates flexWallet balance semantics.
        if (currentPrice < targetPrice) {
            // Price is below target, so forward flex is needed
            uint256 currentFlex = IERC20(address(ushToken)).balanceOf(flexWallet);

            // If isReverseFlex flag is set, always clear it (entering forward flex territory).
            // Burn any reverse flex balance first.
            if (isReverseFlex) {
                if (currentFlex > 0) {
                    ushToken.burn(flexWallet, currentFlex);
                    uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                    emit ReverseFlexBurned(currentFlex, newBalance);
                    currentFlex = 0;
                }
                isReverseFlex = false;
            }

            // Standard forward flex accounting
            uint256 flexNeeded = calculateFlexBurnedToTarget(key);
            if (flexNeeded > currentFlex) {
                uint256 toMint = flexNeeded - currentFlex;
                ushToken.mint(flexWallet, toMint, 3);
                uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                emit FlexMinted(toMint, newBalance);
            } else if (currentFlex > flexNeeded) {
                uint256 toBurn = currentFlex - flexNeeded;
                if (toBurn > 0) {
                    ushToken.burn(flexWallet, toBurn);
                    uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                    emit FlexBurned(toBurn, newBalance);
                }
            }
        } else {
            // Price >= target
            if (currentPrice > targetPrice) {
                // Still above target after the arb step: engage reverse flex
                uint256 currentFlex = IERC20(address(ushToken)).balanceOf(flexWallet);

                // If holding forward flex, burn it first (price crossed above target)
                if (!isReverseFlex && currentFlex > 0) {
                    ushToken.burn(flexWallet, currentFlex);
                    uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                    emit FlexBurned(currentFlex, newBalance);
                    currentFlex = 0;
                }

                // Calculate reverse flex needed and mint/burn difference
                uint256 reverseFlexNeeded = calculateFlexMintedToTarget(key);
                if (reverseFlexNeeded > 0) {
                    isReverseFlex = true;
                    if (reverseFlexNeeded > currentFlex) {
                        uint256 toMint = reverseFlexNeeded - currentFlex;
                        ushToken.mint(flexWallet, toMint, 3);
                        uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                        emit ReverseFlexMinted(toMint, newBalance);
                    } else if (currentFlex > reverseFlexNeeded) {
                        uint256 toBurn = currentFlex - reverseFlexNeeded;
                        if (toBurn > 0) {
                            ushToken.burn(flexWallet, toBurn);
                            uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                            emit ReverseFlexBurned(toBurn, newBalance);
                        }
                    }
                } else {
                    // Price is above target, but the flex estimate came back zero, which is not the same as
                    // the pool being at target: rounding, a tick walk that met no liquidity, and a sub-wei
                    // surplus each return zero. A walk that ran out of steps is the risky one, since the
                    // gap can be real while the estimate is zero: the burn below then drops a buffer the
                    // pool still needs, and clearing the flag switches off the flex check on liquidity
                    // adds until the next swap.
                    if (currentFlex > 0) {
                        ushToken.burn(flexWallet, currentFlex);
                        uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                        if (isReverseFlex) {
                            emit ReverseFlexBurned(currentFlex, newBalance);
                        } else {
                            emit FlexBurned(currentFlex, newBalance);
                        }
                    }
                    isReverseFlex = false;
                }
            } else {
                // Price == target exactly: clean up any remaining flex
                uint256 flexBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                if (flexBalance > 0) {
                    ushToken.burn(flexWallet, flexBalance);
                    uint256 newBalance = IERC20(address(ushToken)).balanceOf(flexWallet);
                    if (isReverseFlex) {
                        emit ReverseFlexBurned(flexBalance, newBalance);
                    } else {
                        emit FlexBurned(flexBalance, newBalance);
                    }
                }
                isReverseFlex = false;
            }
        }

        // Record the gas used so far for any later user swap in this transaction.
        assembly ("memory-safe") {
            tstore(TX_SPENT_SLOT, sub(clock, gas()))
        }

        return (BaseHook.afterSwap.selector, 0);
    }

    /// @notice Hook callback before donation to the pool
    /// @dev Validates sender is trusted and user is authorized via AuthManager
    function _beforeDonate(address sender, PoolKey calldata, uint256, uint256, bytes calldata)
        internal
        view
        override
        returns (bytes4)
    {
        _checkAllowed(sender);
        authManager.checkManifestAccount(_getSender(sender));
        return BaseHook.beforeDonate.selector;
    }

    /* ========================================================================== */
    /*                            ARBITRAGE FUNCTIONS                             */
    /* ========================================================================== */

    /// @notice Arbitrage dispatch shared by _beforeSwap (the catch-up on a residual an earlier swap left) and
    ///         _afterSwap (this swap's own dislocation). Returns the post-arb price.
    /// @dev Runs at most one direction per call: upward if the price is above target and upward arb is
    ///      enabled; otherwise downward if the price is below arbTarget - swapPriceTolerance, the hard breaker
    ///      is not tripped and no upward arb ran in this call. That last condition stops a treasury ping-pong
    ///      within one call: an upward arb stops at target - swapPriceTolerance at the latest, so only a
    ///      non-zero tolerance lets it end below target. The tolerance deadband on the downward trigger stops
    ///      the same ping-pong across the two callbacks. Persists isReverseFlex through the upward wrapper.
    ///      Does not reconcile flex: _afterSwap does that once per user swap, so the ceiling rounding applies
    ///      once per swap, not once per transaction. A route the treasury cannot fund at all is reported as
    ///      DownwardArbitrageExecuted(0, 0, 0, true). The leg's gas comes from the clock and flags the
    ///      callback stored: HookMath.legBudget turns the gas used so far into what the leg may add. A leg
    ///      left with no gas emits ArbitrageSkippedForBudget.
    /// @dev The caller decides whether ArbExec caps each take by the PoolManager's balance: _afterSwap sets
    ///      INVENTORY_BOUND_SLOT around its call; the _beforeSwap catch-up leaves it clear.
    function _runArbitrage(PoolKey calldata key) internal returns (uint256 currentPrice) {
        currentPrice = getCurrentPrice(key);
        uint256 spent;
        uint256 flags;
        assembly ("memory-safe") {
            spent := sub(tload(LEG_CLOCK_SLOT), gas())
            flags := tload(LEG_FLAGS_SLOT)
        }
        uint256 legGas = HookMath.legBudget(spent, externalGasReserve, flags);

        bool upwardArbExecuted = false;
        if (currentPrice > targetPrice && upwardArbitrageEnabled) {
            (uint256 ushToSell, bool profitable, bool starved) = _calculateUshForArbitrage(key, legGas, flags);
            if (ushToSell > 0 && profitable) {
                _executeUpwardArbitrage(key, ushToSell);
                currentPrice = getCurrentPrice(key);
                upwardArbExecuted = true;
            } else if (ushToSell > 0) {
                // Selling USH: the actual direction is zeroForOne only when USH is currency0.
                emit ArbitrageSkippedUnprofitable(true, _getProtocolFeeForDirection(key, _isUshCurrency0(key)));
            } else if (starved) {
                emit ArbitrageSkippedForBudget(true);
            }
        }

        if (!upwardArbExecuted && !hardBreakerTripped && currentPrice < targetPrice && downwardArbitrageEnabled) {
            // Clamp the arb push target to the fair NAV/p targetPrice: a static targetArbPrice at or above
            // it (set there, or drifted there as targetPrice moves) must never push the pool above par,
            // which would spend treasury to over-prop USH.
            uint256 arbTarget = (targetArbPrice > 0 && targetArbPrice < targetPrice) ? targetArbPrice : targetPrice;
            // Deadband the trigger by the same tolerance the upward arb is allowed to stop inside. A
            // non-zero swapPriceTolerance lets an upward arb finish at targetPrice - tolerance, and a
            // bare `currentPrice < arbTarget` trigger then buys straight back into that margin: a
            // break-even round trip paid out of the treasury. The SIZING still targets arbTarget, so
            // an arb that does fire pushes as far as it would without the deadband.
            // arbTarget <= tolerance needs no NAV collapse to reach, since setTargetArbPrice is
            // unbounded. Falling back to the bare arbTarget there keeps the subtraction from
            // panicking and keeps a zero threshold from silently disabling the downward defense.
            uint256 arbTrigger = arbTarget > swapPriceTolerance ? arbTarget - swapPriceTolerance : arbTarget;
            if (currentPrice < arbTrigger) {
                (uint256 usdeNeeded, bool profitable, bool stoppedShort) =
                    _calculateUsdeForArbitrage(key, arbTarget, legGas, flags);
                if (profitable && usdeNeeded > 0) {
                    uint256 usdeAvailable = usdeToken.balanceOf(treasury);
                    uint256 spendable = usdeAvailable > minTreasuryBalance ? usdeAvailable - minTreasuryBalance : 0;
                    uint256 usdeToSpend = usdeNeeded < spendable ? usdeNeeded : spendable;
                    // isPartial: the route stops short of the bound because of the treasury cap, the backing
                    // check under a protocol fee, the gas budget or the step cap. An unfunded route goes to
                    // ArbExec as a zero spend, which reports DownwardArbitrageExecuted(0, 0, 0, true).
                    _executeDownwardArbitrage(key, usdeToSpend, usdeToSpend < usdeNeeded || stoppedShort);
                    currentPrice = getCurrentPrice(key);
                } else if (usdeNeeded > 0) {
                    // Buying USH: the actual direction is zeroForOne only when USH is currency1.
                    emit ArbitrageSkippedUnprofitable(false, _getProtocolFeeForDirection(key, !_isUshCurrency0(key)));
                } else if (stoppedShort) {
                    emit ArbitrageSkippedForBudget(false);
                }
            }
        }
    }

    /// @dev Sells USH to bring price back down toward target, as far as the sized route reaches
    function _executeUpwardArbitrage(PoolKey calldata key, uint256 ushToSell) internal {
        isReverseFlex = ArbExec.executeUpwardArbitrage(_arbCtx(), key, ushToSell, isReverseFlex);
    }

    function _executeDownwardArbitrage(PoolKey calldata key, uint256 usdeToSpend, bool isPartial) internal {
        ArbExec.executeDownwardArbitrage(_arbCtx(), key, usdeToSpend, isPartial);
    }

    /// @dev Snapshot the hook state the arb execution library reads. Built per call (the executing
    ///      branch runs at most once per swap); a private view helper so the IR optimizer inlines it.
    function _arbCtx() private view returns (ArbExec.Ctx memory) {
        return ArbExec.Ctx({
            poolManager: poolManager,
            ushToken: ushToken,
            usdeToken: usdeToken,
            treasury: treasury,
            rewardsWallet: rewardsWallet,
            flexWallet: flexWallet,
            targetPrice: targetPrice,
            targetArbPrice: targetArbPrice,
            swapPriceTolerance: swapPriceTolerance
        });
    }

    /// @notice USH to sell for an upward arbitrage (price above target).
    /// @dev Returns the largest route, within the leg's gas budget, whose USDe covers the minted USH at target.
    ///      The input is grossed up by 1e6 / (1e6 - fee) to cover the protocol fee. `profitable` is false when
    ///      the walked route fails and the search finds no passing part that reaches `BackingCheck.MIN_PARTIAL_ROUTE`.
    ///      `stoppedShort` is true when the route ends before target; the upward event does not report it.
    function _calculateUshForArbitrage(PoolKey calldata key, uint256 legGas, uint256 flags)
        internal
        view
        returns (uint256 ushToSell, bool profitable, bool stoppedShort)
    {
        return HookMath.calcUshForArbitrage(poolManager, key, address(ushToken), targetPrice, legGas, flags);
    }

    /// @notice USDe to spend for a downward arbitrage (price below target).
    /// @dev Returns the largest route, within the leg's gas budget, whose USH covers the USDe spent at target,
    ///      with the same protocol-fee gross-up as _calculateUshForArbitrage. `profitable` is false when the
    ///      walked route fails and the search finds no passing part that reaches `BackingCheck.MIN_PARTIAL_ROUTE`.
    ///      `stoppedShort` is true when the route ends before `arbTarget`; the downward event reports it through
    ///      `isPartial`.
    function _calculateUsdeForArbitrage(PoolKey calldata key, uint256 arbTarget, uint256 legGas, uint256 flags)
        internal
        view
        returns (uint256 usdeToSpend, bool profitable, bool stoppedShort)
    {
        return HookMath.calcUsdeForArbitrage(poolManager, key, address(ushToken), targetPrice, arbTarget, legGas, flags);
    }

    /* ========================================================================== */
    /*                             ADMIN FUNCTIONS                                */
    /* ========================================================================== */

    // There is no targetPrice setter by design: targetPrice is oracle-derived (targetPrice = NAV / p) and
    // refreshed at the start of every non-view entry point, so a manual value would be overwritten on the
    // next swap or liquidity op. Change the NAV source via setUshPriceOracle and p via setUsdeUsdPeg.

    /// @notice Set flex wallet
    /// @dev Migrates any existing USH balance from old wallet to new wallet via burn/mint.
    ///      Uses try-catch to ensure atomic migration - if mint fails after burn,
    ///      the entire transaction reverts to prevent USH loss.
    function setFlexWallet(address newFlexWallet) external onlyOwner {
        if (newFlexWallet == address(0)) revert ZeroFlexWallet();
        address oldWallet = flexWallet;

        // Migrate USH balance from old wallet to new wallet
        uint256 oldBalance = IERC20(address(ushToken)).balanceOf(oldWallet);
        if (oldBalance > 0) {
            // Burn from old wallet (hook has BURNER role)
            ushToken.burn(oldWallet, oldBalance);

            // Mint to new wallet with try-catch for atomic migration
            // If mint fails (e.g., newFlexWallet is blocked), revert entire transaction
            try ushToken.mint(newFlexWallet, oldBalance, 3) {
            // Migration successful
            }
            catch {
                // Mint failed - revert to prevent USH loss from burn
                // Note: This revert will roll back the burn as well
                revert FlexWalletMigrationFailed();
            }
        }

        flexWallet = newFlexWallet;
        emit FlexWalletUpdated(oldWallet, newFlexWallet);
    }

    /// @notice Set treasury
    function setTreasury(address newTreasury) external onlyOwner {
        if (newTreasury == address(0)) revert ZeroTreasury();
        address oldTreasury = treasury;
        treasury = newTreasury;
        emit TreasuryUpdated(oldTreasury, newTreasury);
    }

    /// @notice Set rewards wallet
    function setRewardsWallet(address newRewardsWallet) external onlyOwner {
        if (newRewardsWallet == address(0)) revert ZeroRewardsWallet();
        address oldWallet = rewardsWallet;
        rewardsWallet = newRewardsWallet;
        emit RewardsWalletUpdated(oldWallet, newRewardsWallet);
    }

    /// @notice Set USDe/USD oracle
    function setUsdeUsdOracle(address newOracle) external onlyOwner {
        if (newOracle == address(0)) revert ZeroOracle();
        address oldOracle = address(usdeUsdOracle);
        usdeUsdOracle = AggregatorV3Interface(newOracle);
        usdeUsdOracleDecimals = AggregatorV3Interface(newOracle).decimals();
        emit UsdeUsdOracleUpdated(oldOracle, newOracle);
    }

    /// @notice Set the USH NAV price oracle (source of targetPrice = NAV / p)
    function setUshPriceOracle(address newOracle) external onlyOwner {
        if (newOracle == address(0)) revert ZeroUshPriceOracle();
        _probeUshPriceOracle(newOracle);
        address oldOracle = address(ushPriceOracle);
        ushPriceOracle = IUSHPriceOracle(newOracle);
        // Recompute targetPrice from the NEW feed in the same tx, so public views never serve a
        // target derived from the old oracle.
        _refreshTargetPrice();
        emit UshPriceOracleUpdated(oldOracle, newOracle);
    }

    /// @dev Probe that `oracle` answers the two reads the hook depends on (getCurrentPrice for NAV,
    ///      getConfiguration for the pause flag), so a non-compliant address is rejected at wiring
    ///      time (constructor / setUshPriceOracle) instead of bricking every swap later.
    function _probeUshPriceOracle(address oracle) internal view {
        IUSHPriceOracle(oracle).getCurrentPrice();
        IUSHPriceOracle(oracle).getConfiguration();
    }

    /* ========================================================================== */
    /*                         DYNAMIC FEE ADMIN FUNCTIONS                        */
    /* ========================================================================== */

    /// @notice Batch-update all dynamic fee parameters in a single call
    function setDynamicFeeParams(
        uint24 _baseBuyFee,
        uint24 _baseSellFee,
        uint24 _maxSellFee,
        uint256 _surchargeMultiplier,
        uint256 _pressureHalfLife,
        bool _surchargeEnabled
    ) external onlyOwner {
        if (_baseBuyFee > MAX_BASE_FEE) revert FeeTooHigh();
        if (_baseSellFee > MAX_BASE_FEE) revert FeeTooHigh();
        // maxSellFee must leave room for the protocol fee on top of it, not merely stay below MAX_LP_FEE:
        // the exact-output gross-up divides by MAX_LP_FEE - combined, where V4 takes the protocol fee
        // off the input first and the LP fee off the remainder, so combined = p + f -
        // floor(p*f/MAX_LP_FEE). At f = MAX_LP_FEE - 1 the floor term returns the pip the subtraction
        // removed (floor(p*f/1e6) = p - 1), so combined is exactly MAX_LP_FEE for EVERY p >= 1 and the
        // gross-up divides by zero: one pip of protocol fee bricks every exact-output sell until governance
        // rewrites the config. Reserving the full protocol-fee FIELD width makes combined <= p + f <
        // MAX_LP_FEE hold by plain addition, and the FIELD width rather than V4's MAX_PROTOCOL_FEE policy
        // cap is deliberate: _getProtocolFeeForDirection masks the raw slot0 field and does not clamp, so
        // this invariant must not rest on another contract's validator.
        if (uint256(_maxSellFee) + PROTOCOL_FEE_FIELD_MAX >= LPFeeLibrary.MAX_LP_FEE) revert FeeTooHigh();
        // baseSellFee must be STRICTLY below maxSellFee. Equality is just as fatal as exceeding it: the
        // latch fires on `dynamicFee >= maxSellFee`, so the fee would sit at the ceiling at zero pressure
        // and the very first sell of any size would silently disable the downward peg-defense arb until
        // resetHardBreaker. The latch must stay `>=`: the fee is clamped to maxSellFee, so a strict `>`
        // latch could never fire.
        if (_baseSellFee >= _maxSellFee) revert FeeTooHigh();
        if (_surchargeMultiplier > MAX_SURCHARGE_MULTIPLIER) revert SurchargeMultiplierTooHigh();
        if (_pressureHalfLife < MIN_PRESSURE_HALF_LIFE) revert HalfLifeTooLow();
        if (_pressureHalfLife > MAX_PRESSURE_HALF_LIFE) revert HalfLifeTooHigh();
        // Settle pressure under the outgoing half-life and restamp the clock before writing, so a new
        // half-life applies only from now on and the quoted fee does not jump at the retune. With the
        // half-life unchanged this is a no-op up to rounding.
        uint256 settled = DynamicFeeLib.getDecayedPressure(netSellPressure, lastPressureUpdateTime, pressureHalfLife);
        netSellPressure = settled;
        lastPressureUpdateTime = block.timestamp;
        baseBuyFee = _baseBuyFee;
        baseSellFee = _baseSellFee;
        maxSellFee = _maxSellFee;
        surchargeMultiplier = _surchargeMultiplier;
        pressureHalfLife = _pressureHalfLife;
        surchargeEnabled = _surchargeEnabled;
        emit DynamicFeeParamsUpdated(
            _baseBuyFee, _baseSellFee, _maxSellFee, _surchargeMultiplier, _pressureHalfLife, _surchargeEnabled, settled
        );
    }

    /// @notice Manually set net sell pressure (also updates lastPressureUpdateTime)
    function setNetSellPressure(uint256 _pressure) external onlyOwner {
        netSellPressure = _pressure;
        lastPressureUpdateTime = block.timestamp;
        emit NetSellPressureSet(_pressure);
    }

    /// @notice Correct the pool-USH baseline by hand after it has drifted from real pool inventory.
    /// @dev The counter only moves on liquidity operations, so swaps walk it away from the pool's actual
    ///      USH over time. This is the recovery path, and the contract has no upgrade path, so it must
    ///      exist.
    function setPoolUshBaseline(uint256 newBaseline) external onlyOwner {
        // Two bounds covering OPPOSITE failures, and neither subsumes the other. At or above supply the
        // float is zero, `_surchargeDenominator` returns 0 and the fee degrades to `baseSellFee`, so it
        // goes permanently inert. One wei below supply the float is 1 wei, any pressure prices at the
        // ceiling, and the next sell latches the owner-reset-only breaker. The first check rejects the
        // inert end; the second rejects the latching end by pricing the CURRENT pressure against the
        // proposed float. A correction that genuinely belongs at that level needs `setNetSellPressure`
        // first, which is the same owner.
        uint256 supply = IERC20(address(ushToken)).totalSupply();
        if (newBaseline >= supply) revert BaselineExceedsSupply();
        // Prices stored pressure, which is never below its decayed value: the check never admits a
        // baseline that latches, but it can reject one the decayed pressure would allow, by a factor of
        // 2^(elapsed / pressureHalfLife) since the last pressure write. Calling setDynamicFeeParams with
        // the current values first settles pressure and makes the check exact.
        // The predicate reproduces `_feeFor`'s base-plus-surcharge comparison against `maxSellFee`,
        // inlined rather than called, so it must move whenever that clamp or the 1e12 conversion does.
        if (
            surchargeEnabled
                && FullMath.mulDiv(surchargeMultiplier, netSellPressure, supply - newBaseline) / 1e12
                    >= uint256(maxSellFee) - uint256(baseSellFee)
        ) revert BaselineWouldLatchBreaker();
        uint256 oldBaseline = poolUshBaseline;
        poolUshBaseline = newBaseline;
        emit PoolUshBaselineUpdated(oldBaseline, newBaseline);
    }

    /* ========================================================================== */
    /*                          DYNAMIC FEE VIEW GETTERS                          */
    /* ========================================================================== */

    /// @notice Quote current (or previewed) dynamic fees in a single call
    /// @dev Pass 0 for current fees, or the USH a sell requests, fee included, to price that sell; the amount moves
    ///      the sell side only. An exact-output sell is priced off a grossed-up input, so the curve amount its output
    ///      needs can read below the fee that sell is charged: pass what a V4 quoter says the swap sends instead. The
    ///      fee is set after the hook's catch-up arbitrage, so a sell quote can move before the swap runs.
    /// @param additionalUshSellPressure USH-denominated sell size to simulate (18 decimals)
    /// @return buyFee  V4 fee units (hundredths of a bip) for USDe->USH swaps, LP fee only
    /// @return sellFee V4 fee units (hundredths of a bip) for USH->USDe swaps, LP fee only; with a protocol
    ///         fee `p` on that direction the trader's rate is `p + f - p * f / MAX_LP_FEE`, `f` being this value
    function quoteFees(uint256 additionalUshSellPressure) external view returns (uint24 buyFee, uint24 sellFee) {
        buyFee = baseBuyFee;
        sellFee = DynamicFeeLib.previewFee(
            netSellPressure,
            lastPressureUpdateTime,
            pressureHalfLife,
            additionalUshSellPressure,
            address(ushToken),
            poolUshBaseline,
            baseSellFee,
            maxSellFee,
            surchargeMultiplier,
            surchargeEnabled
        );
    }

    /* ========================================================================== */
    /*                             INTERNAL FUNCTIONS                             */
    /* ========================================================================== */

    /// @notice Resolves the actual user address from a router/periphery sender
    /// @dev Security note: uses tx.origin as fallback for EOA detection. Acceptable because auth checks
    ///      are for allowlist verification and not fund transfers, the hook operates within Uniswap V4's
    ///      lock mechanism, and routers implementing IMsgSender provide the actual user. Risk: a phishing
    ///      contract could relay a victim through this hook, with the AuthManager allowlist as the
    ///      additional protection layer.
    /// @param sender The immediate caller (usually a router contract)
    /// @return The resolved user address for auth checks
    function _getSender(address sender) internal view returns (address) {
        // Resolve plain EOA senders to tx.origin BEFORE the IMsgSender staticcall: for an EOA the
        // staticcall "succeeds" with empty returndata, and decoding that into an address reverts in a way
        // the try/catch does NOT catch (under via-IR), so the whole hook callback fails with
        // HookCallFailed. Genuine contract senders fall through unchanged.
        if (sender.code.length == 0) {
            return tx.origin;
        }

        address user = sender;
        try IMsgSender(sender).msgSender() returns (address u) {
            if (u != address(0)) {
                user = u;
            } else {
                user = tx.origin;
            }
        } catch {
            return tx.origin;
        }
        return user;
    }

    /// @notice Validates that the sender is in the trusted senders allowlist
    /// @dev Trusted senders are typically Uniswap routers and periphery contracts
    /// @param sender The address to validate
    function _checkAllowed(address sender) internal view {
        if (!trustedSenders[sender]) {
            revert InvalidUniswapSender();
        }
    }

    /// @notice Refresh targetPrice from the live NAV oracle: targetPrice = NAV / p, where p is the
    ///         configurable usdeUsdPeg (default 1e18, owner-settable within [MIN, MAX]_USDE_USD_PEG).
    /// @dev Fail-closed refresh for the swap/add entry points and the governance setters: an oracle revert
    ///      propagates and blocks the operation. The LP-exit path uses fail-open _tryRefreshTargetPrice
    ///      instead; the keep-last-good guards live in the shared _applyNavToTarget. USHPriceOracle
    ///      rate-limits price WRITES (min interval, max % change, bounds). A stale (un-updated) oracle
    ///      serves its last-known NAV, which we keep by design rather than halt; an emergency-PAUSED
    ///      oracle IS halted, via the circuit breaker (see isCircuitBreakerActive).
    function _refreshTargetPrice() internal returns (uint256 nav) {
        nav = ushPriceOracle.getCurrentPrice();
        _applyNavToTarget(nav);
    }

    /// @dev Best-effort variant for the LP-exit path: a reverting NAV oracle keeps the stored targetPrice
    ///      instead of propagating. Exits never price against NAV and only reduce the flex requirement, so
    ///      an oracle failure must not block them; swap/add paths keep the hard, fail-closed refresh.
    function _tryRefreshTargetPrice() internal {
        (bool ok, bytes memory ret) =
            address(ushPriceOracle).staticcall(abi.encodeCall(IUSHPriceOracle.getCurrentPrice, ()));
        // A codeless target also lands here (staticcall to no code succeeds with empty returndata).
        if (!ok || ret.length < 32) return;
        _applyNavToTarget(abi.decode(ret, (uint256)));
    }

    /// @dev Shared tail of both refresh variants: targetPrice = NAV / p with the keep-last-good guards.
    function _applyNavToTarget(uint256 nav) private {
        if (nav == 0) return; // zero NAV: keep the last-good targetPrice
        uint256 newTarget = FullMath.mulDiv(nav, 1e18, usdeUsdPeg);
        // Round-to-zero guard: a tiny non-zero NAV with usdeUsdPeg > 1e18 can floor to 0. Keep the
        // last-good target so no read site (flex/arb) ever divides by a zero targetPrice.
        if (newTarget == 0) return;
        // Emit only on an actual change: off-chain services track the live peg from this event, and a
        // swap-time refresh with NAV/p unchanged logs nothing.
        if (newTarget != targetPrice) {
            uint256 oldTarget = targetPrice;
            targetPrice = newTarget;
            emit TargetPriceUpdated(oldTarget, newTarget);
        }
    }

    /// @notice Revert unless the flex constraint holds, naming the stale direction when that is the cause
    function _requireFlexForAdd(PoolKey calldata key) internal view {
        (bool ok, bool staleDirection,,) = _flexState(key);
        if (!ok) {
            if (staleDirection) revert FlexDirectionStale();
            revert InsufficientFlexForLiquidity();
        }
    }

    /// @notice Evaluate the flex constraint for the current pool price
    /// @dev Returns (true, false, 0, 0) when no flex check applies (price at target, or above
    ///      target without active reverse-flex). Callers decide whether to revert or emit.
    /// @return ok              True when flexBalance >= flexNeeded (or no check applies); below target a
    ///                         balance still marked reverse counts as zero
    /// @return staleDirection  True below target while isReverseFlex is set, so a failed check means the
    ///                         direction awaits a swap rather than a short balance
    /// @return balance         Current flexWallet USH balance (only set when a check applies)
    /// @return needed          Required flex amount (only set when a check applies)
    function _flexState(PoolKey calldata key)
        internal
        view
        returns (bool ok, bool staleDirection, uint256 balance, uint256 needed)
    {
        uint256 currentPrice = getCurrentPrice(key);
        if (currentPrice < targetPrice) {
            balance = IERC20(address(ushToken)).balanceOf(flexWallet);
            needed = calculateFlexBurnedToTarget(key);
            // A target move between swaps can leave reverse flex below target. It is not forward buffer, so
            // it counts as zero until a swap reconciles the direction.
            staleDirection = isReverseFlex;
            ok = (staleDirection ? 0 : balance) >= needed;
        } else if (currentPrice > targetPrice && isReverseFlex) {
            balance = IERC20(address(ushToken)).balanceOf(flexWallet);
            needed = calculateFlexMintedToTarget(key);
            ok = balance >= needed;
        } else {
            ok = true;
        }
    }

    // --- Dynamic Fee Internal Helpers ---

    /// @notice Compute dynamic fee for a user swap based on direction and sell pressure
    /// @dev Single DELEGATECALL to DynamicFeeLib for all heavy math.
    function _computeDynamicFee(PoolKey calldata key, SwapParams calldata params) internal returns (uint24) {
        bool sellingUsh = (params.zeroForOne == _isUshCurrency0(key));

        // Fold this swap's own USH volume into its own fee. This is the ONLY place the requested amount is
        // read, and it reaches the fee only: stored pressure and the hard breaker both move on the
        // realized delta in _afterSwap, so a request that never fills cannot move either.
        uint256 currentSellTerm;
        bool grossUp;
        if (sellingUsh && params.amountSpecified < 0) {
            // Negating int256.min overflows. Reject it explicitly rather than relying on the
            // checked-arithmetic panic, which is not a useful error at the call site.
            if (params.amountSpecified == type(int256).min) revert InvalidSwapAmount();
            currentSellTerm = uint256(-params.amountSpecified);
        } else if (sellingUsh && params.amountSpecified > 0) {
            // Exact output: the USH input is not in the request, so walk the real curve for it. The
            // walk ends when the output is filled or the swap's price limit is reached; running out of
            // its iteration budget first reverts the swap. The result is fee-exclusive; the library
            // grosses it up.
            currentSellTerm = SwapEstimation.estimateInputForOutput(
                poolManager, key, uint256(params.amountSpecified), params.zeroForOne, params.sqrtPriceLimitX96
            );
            grossUp = true;
        }

        uint256 baseline = poolUshBaseline;
        DynamicFeeLib.FeeOutput memory o = DynamicFeeLib.computeSellFee(
            DynamicFeeLib.FeeInput({
                currentPressure: netSellPressure,
                lastUpdateTime: lastPressureUpdateTime,
                halfLife: pressureHalfLife,
                sellingUsh: sellingUsh,
                currentSellTerm: currentSellTerm,
                grossUpSellTerm: grossUp,
                protocolFeePips: uint24(_getProtocolFeeForDirection(key, params.zeroForOne)),
                ushToken: address(ushToken),
                poolUshBaseline: baseline,
                baseBuyFee: baseBuyFee,
                baseSellFee: baseSellFee,
                maxSellFee: maxSellFee,
                surchargeMultiplier: surchargeMultiplier,
                surchargeEnabled: surchargeEnabled
            })
        );

        // No storage write here by design: this is a quote.
        emit DynamicFeeQuoted(sellingUsh, o.fee, o.updatedPressure, o.denominator, baseline);
        return o.fee;
    }

    /// @notice Check if USH is currency0 in the pool
    function _isUshCurrency0(PoolKey calldata key) internal view returns (bool) {
        return Currency.unwrap(key.currency0) == address(ushToken);
    }

    /// @dev Convert a USH-frame price (USDe per USH, 1e18) into the pool's raw sqrtPriceX96, reciprocating
    ///      first when USH sorts as currency1 (the raw pool price is then USH-per-USDe). Callers pass a
    ///      non-zero price (targetPrice is never zero; arb bounds derive from it).
    function _ushFrameToPoolSqrt(PoolKey calldata key, uint256 ushFramePrice) internal view returns (uint160) {
        uint256 rawPrice = _isUshCurrency0(key) ? ushFramePrice : FullMath.mulDiv(1e18, 1e18, ushFramePrice);
        return PriceMath.priceToSqrtPriceX96(rawPrice);
    }

    /// @notice Read V4 protocol fee for a given swap direction from pool slot0
    /// @dev Protocol fee is packed as: lower 12 bits = zeroForOne, upper 12 bits = oneForZero.
    ///      Returns 0 when no protocol fee is set (current default).
    function _getProtocolFeeForDirection(PoolKey calldata key, bool zeroForOne) internal view returns (uint256) {
        (,, uint24 protocolFee,) = poolManager.getSlot0(key.toId());
        return zeroForOne ? uint256(protocolFee & 0xfff) : uint256(protocolFee >> 12);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "contracts/hooks/ManifestHook.sol": {
      "ArbExec": "0x3fe68e30fc4c66118c026a9dea699cd050e4df0d",
      "HookMath": "0xcafdefbdce43e077b7f0806b61b6b08450cf1d36",
      "DynamicFeeLib": "0x8c9db5785f011b649bbd59749cb7b576939b3bb7",
      "SwapEstimation": "0xf075a327c53e70b46954af50b3326433f7e5a769"
    }
  },
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "@layerzerolabs/lz-evm-protocol-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/protocol/",
    "@layerzerolabs/lz-evm-messagelib-v2/=lib/LayerZero-v2/packages/layerzero-v2/evm/messagelib/",
    "@layerzerolabs/oapp-evm/=lib/LayerZero-v2/packages/layerzero-v2/evm/oapp/",
    "@layerzerolabs/oapp-evm-devtools/=lib/devtools/packages/oapp-evm/",
    "@layerzerolabs/oft-evm/=lib/devtools/packages/oft-evm/",
    "@layerzerolabs/ovault-evm/=lib/devtools/packages/ovault-evm/",
    "@layerzerolabs/test-devtools-evm-foundry/=lib/devtools/packages/test-devtools-evm-foundry/",
    "solidity-bytes-utils/=lib/solidity-bytes-utils/",
    "solady/=lib/solady/src/",
    "@perimetersec/fuzzlib/=lib/fuzzlib/",
    "solmate/=lib/solmate/",
    "@safe-global/safe-smart-account/=lib/safe-smart-account/",
    "@chainlink/contracts/=node_modules/@chainlink/contracts/",
    "@SKYBITDev3/=node_modules/@SKYBITDev3/",
    "@Vectorized/=node_modules/@Vectorized/",
    "@arbitrum/=node_modules/@arbitrum/",
    "@axelar-network/=node_modules/@axelar-network/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@eth-optimism/=node_modules/@eth-optimism/",
    "@offchainlabs/=node_modules/@offchainlabs/",
    "@scroll-tech/=node_modules/@scroll-tech/",
    "@transmissions11/=node_modules/@transmissions11/",
    "@zksync/=node_modules/@zksync/",
    "LayerZero-v2/=lib/LayerZero-v2/",
    "devtools/=lib/devtools/packages/toolbox-foundry/src/",
    "ds-test/=lib/solmate/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "forge-std/=lib/forge-std/src/",
    "fuzzlib/=lib/fuzzlib/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "safe-smart-account/=lib/safe-smart-account/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.