Skip to content
Verified contractPartialMIT

MetricFixedHook

Address0x21d7bfa2d40d558d37dd76c552bb457c7b162888
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.37

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.37+commit.f401782d
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,450,168
Creation transaction
0x24655e1da9…911900e880

src/MetricFixedHook.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.37;

/// @title MetricFixedHook
/// @notice Zero-liquidity Uniswap v4 hook that fills swaps against a small fixed set of Metric OMM pools. No owner,
///         registrar or any other privileged role: the hook itself bounds its pools and tokens.
/// @dev Design notes:
///      - Holds no liquidity and no balances between transactions; every token moves PoolManager <-> Metric
///        inside the same swap. No owner, no proxy, no sweep, no fee or parameter setters.
///      - One v4 pool per Metric pool. PoolKey = (currency0, currency1, fee 0, tickSpacing = local id, this). The local
///        id is assigned by the hook at registration, so the v4 key does not depend on Metric's factory index.
///      - Fixed pool set: the Metric pools are passed to the constructor, which checks on-chain that each comes from the
///        immutable Metric factory, that the pair has two distinct token contracts, that its price provider is
///        immutable and that its Metric admin is the trusted `metricAdmin` with no pending transfer, then links and
///        initializes its v4 pool. The set can never change: there is no registrar, owner or other privileged role,
///        and any other PoolManager.initialize with this hook reverts. Every swap and quote re-checks the admin and
///        pending transfer. Serving another pool requires a new deployment.
///      - Fail-fast: before calling Metric, swaps check Metric's pause level and bin liquidity (via Metric's extsload)
///        and, for exact-in, the PoolManager's balance of the input token, so a pool that cannot fill reverts cheaply
///        and deterministically. `poolHealth()` exposes the same checks as a view.
///      - A visible author fee (`feePips`, fixed at 3 bp) is taken from the output side and credited to
///        `feeRecipient` as a PoolManager ERC-6909 claim (cannot be blocked by a token blacklist).
///      - The Uniswap protocol fee is honoured: whatever the protocol fee controller sets in this pool's slot0
///        (times the immutable `protocolFeeMultiplier`) is charged on the unspecified side and sent to the
///        TokenJar, both in execution and in `quote()`, with the same formula as Uniswap's ProtocolFees.
///        `protocolFeeFlags()` returns a fixed classification (zero).
///      - The hook applies the same fee formula during quoting and execution and requires no hookData.
contract MetricFixedHook {
    // ---------------------------------------------------------------------------------------------------------
    // Minimal Uniswap v4 types (ABI-identical to v4-core)
    // ---------------------------------------------------------------------------------------------------------

    struct PoolKey {
        address currency0;
        address currency1;
        uint24 fee;
        int24 tickSpacing;
        address hooks;
    }

    struct SwapParams {
        bool zeroForOne;
        int256 amountSpecified;
        uint160 sqrtPriceLimitX96;
    }

    struct ModifyLiquidityParams {
        int24 tickLower;
        int24 tickUpper;
        int256 liquidityDelta;
        bytes32 salt;
    }

    /// @dev Same layout as v4-core Hooks.Permissions.
    struct Permissions {
        bool beforeInitialize;
        bool afterInitialize;
        bool beforeAddLiquidity;
        bool afterAddLiquidity;
        bool beforeRemoveLiquidity;
        bool afterRemoveLiquidity;
        bool beforeSwap;
        bool afterSwap;
        bool beforeDonate;
        bool afterDonate;
        bool beforeSwapReturnDelta;
        bool afterSwapReturnDelta;
        bool afterAddLiquidityReturnDelta;
        bool afterRemoveLiquidityReturnDelta;
    }

    /// @notice Metric pool linked to a v4 pool.
    /// @notice Health of a v4 pool as seen by this hook. `reason`: 0 ok, 1 unknown, 4 Metric admin changed or
    ///         pending, 5 Metric pool paused, 6 no Metric bin liquidity on either side.
    struct PoolHealth {
        bool routable;
        uint8 reason;
        uint8 metricPauseLevel;
        address metricPool;
        uint128 binTotal0; // Metric scaled bin totals, oriented to v4 currency0 / currency1
        uint128 binTotal1;
    }

    struct LinkedPool {
        address pool;
        bool flipped; // true when Metric token0 is v4 currency1
    }

    // ---------------------------------------------------------------------------------------------------------
    // Errors / events
    // ---------------------------------------------------------------------------------------------------------

    error NotPoolManager();
    error PoolSetFixed();
    error MetricPoolPaused(uint8 pauseLevel);
    error MetricNoLiquidity();
    error InsufficientSettlementInventory(address token, uint256 required, uint256 available);
    error EmptyPoolSet();
    error LengthMismatch();
    error InvalidHookAddress();
    error PoolDoesNotExist();
    error LiquidityNotAllowed();
    error TokenNotAllowed();
    error ExternalPoolNotFound();
    error ExternalPoolMismatch();
    error MutablePriceProvider();
    error UntrustedPoolAdmin();
    error PendingPoolAdminTransfer();
    error PairAlreadyHasCanonicalPool(bytes32 existingPoolId);
    error TooManyPools();
    error AmountTooLarge();
    error PartialFill();
    error UnexpectedSwapDelta();
    error UnauthorizedCallback();
    error Reentrancy();
    error UnsupportedPriceLimit();
    error QuoteRevert(bytes32 tag, int256 amount0Delta, int256 amount1Delta);
    error UnexpectedQuoteBehavior();
    error ZeroAddress();

    event AggregatorPoolRegistered(bytes32 indexed poolId);
    event MetricPoolLinked(bytes32 indexed poolId, address indexed metricPool, int24 tickSpacing);
    /// @dev Same signature and amount signs as Uniswap's IAggregatorHook; `swapFee` is the protocol fee applied.
    event HookSwap(bytes32 indexed poolId, address indexed sender, int256 amount0, int256 amount1, uint24 swapFee);
    event HookFeeCollected(bytes32 indexed poolId, address indexed currency, address indexed recipient, uint256 amount);
    event ProtocolFeesCollected(address indexed recipient, address indexed currency, uint256 amount);

    // ---------------------------------------------------------------------------------------------------------
    // Constants / immutables
    // ---------------------------------------------------------------------------------------------------------

    string public constant aggregatorHookVersion = "MetricFixedHook v1.0.0";

    uint256 internal constant PIPS = 1_000_000;
    uint24 public constant MAX_FEE_PIPS = 500; // 5 bp hard ceiling on the author fee
    uint24 public constant MAX_PROTOCOL_FEE_MULTIPLIER = 25; // same as Uniswap's aggregator hooks
    int24 internal constant MAX_TICK_SPACING = type(int16).max; // v4-core TickMath.MAX_TICK_SPACING

    uint256 internal constant METRIC_SLOT0 = 0; // low byte: pauseLevel (Metric PoolStateLibrary)
    uint256 internal constant METRIC_SLOT1 = 1; // binTotals.scaledToken0 (low 128) | scaledToken1 (high 128)

    uint160 internal constant V4_MIN_LIMIT = 4295128740;
    uint160 internal constant V4_MAX_LIMIT = 1461446703485210103287273052203988822378723970341;

    uint128 internal constant PRICE_LIMIT_ZERO_FOR_ONE = 1;
    uint128 internal constant PRICE_LIMIT_ONE_FOR_ZERO = type(uint128).max;

    bytes32 internal constant QUOTE_FLAG = keccak256("MetricFixedHook.quote");
    uint256 internal constant POOLS_SLOT = 6; // v4-core StateLibrary.POOLS_SLOT

    /// @notice Hook address bits: beforeInitialize | beforeAddLiquidity | beforeSwap | beforeSwapReturnDelta.
    uint160 public constant HOOK_FLAGS = (1 << 13) | (1 << 11) | (1 << 7) | (1 << 3);
    uint160 internal constant ALL_HOOK_MASK = (1 << 14) - 1;

    // bytes32(uint256(keccak256("MetricAggregatorHook.transient.expectedPool")) - 1)
    bytes32 internal constant T_EXPECTED_POOL = 0x09a507a7dd36d49fdff2c1d8ca94b17f8c686e3347779aba3334f1c82f83363b;
    // bytes32(uint256(keccak256("MetricAggregatorHook.transient.inputPaid")) - 1)
    bytes32 internal constant T_INPUT_PAID = 0xa1ec3f468b21809df8d616d554912a8b6b6c92cf3d03758dedf188a4ad556dac;
    // bytes32(uint256(keccak256("MetricAggregatorHook.transient.expectedInput")) - 1); low 160 bits token, bit 255 = token0 side
    bytes32 internal constant T_EXPECTED_INPUT = 0x8c4d5b3fec83cde6e7f6b6564ef7d7eef362626134dc29dff97d6b0c563bdd5b;
    // bytes32(uint256(keccak256("MetricAggregatorHook.transient.quoteNonce")) - 1)
    bytes32 internal constant T_QUOTE_NONCE = 0x6d9846730fee243462a29a292c35cdb5cc1c7bab46e2bb5364dd15ac210aa5d1;

    address public immutable poolManager;
    address public immutable metricFactory;
    address public immutable metricAdmin;
    address public immutable feeRecipient;
    uint24 public immutable feePips;
    uint24 public immutable protocolFeeMultiplier;
    uint256 internal immutable _protocolFeeFlags;

    // ---------------------------------------------------------------------------------------------------------
    // Storage (written only by the constructor)
    // ---------------------------------------------------------------------------------------------------------

    mapping(bytes32 => LinkedPool) public linkedPool;
    mapping(address => bytes32) public canonicalPoolId;
    mapping(bytes32 => PoolKey) internal _poolKeys;
    bytes32[] public initializedPoolIds;
    int24 public lastTickSpacing;

    /// @dev Each chain has its own deployment. Configuration and the pool set are immutable after construction.
    /// @param metricPools The fixed set of Metric pools; each is linked and its v4 pool initialized here.
    /// @param sqrtPricesX96 Initial v4 price per pool; cosmetic (the pools hold no liquidity), set near Metric's price.
    constructor(
        address manager_,
        address factory_,
        address admin_,
        address feeRecipient_,
        address[] memory metricPools,
        uint160[] memory sqrtPricesX96
    ) {
        if (admin_ == address(0) || feeRecipient_ == address(0)) revert ZeroAddress();
        if (manager_.code.length == 0 || factory_.code.length == 0) revert ExternalPoolMismatch();
        if (uint160(address(this)) & ALL_HOOK_MASK != HOOK_FLAGS) revert InvalidHookAddress();
        if (metricPools.length == 0) revert EmptyPoolSet();
        if (metricPools.length != sqrtPricesX96.length) revert LengthMismatch();
        poolManager = manager_;
        metricFactory = factory_;
        metricAdmin = admin_;
        feeRecipient = feeRecipient_;
        feePips = 300;
        protocolFeeMultiplier = 1;
        _protocolFeeFlags = 0;
        for (uint256 i; i < metricPools.length; ++i) {
            _link(metricPools[i], sqrtPricesX96[i]);
        }
    }

    modifier onlyPoolManager() {
        if (msg.sender != poolManager) revert NotPoolManager();
        _;
    }

    // ---------------------------------------------------------------------------------------------------------
    // Fixed pool set (constructor only)
    // ---------------------------------------------------------------------------------------------------------

    /// @dev Link one Metric pool and initialize its v4 pool. Called only from the constructor.
    function _link(address pool, uint160 sqrtPriceX96) private {
        if (pool == address(0) || pool.code.length == 0) revert ExternalPoolNotFound();
        (address token0, address token1) = _checkMetricPool(pool);
        if (!_allowedPair(token0, token1)) revert TokenNotAllowed();
        bytes32 existing = canonicalPoolId[pool];
        if (existing != bytes32(0)) revert PairAlreadyHasCanonicalPool(existing);
        uint8 r = _metricReason(pool);
        if (r == 5) revert MetricPoolPaused(_pauseLevel(pool));
        if (r == 6) revert MetricNoLiquidity();

        if (lastTickSpacing == MAX_TICK_SPACING) revert TooManyPools();
        int24 tickSpacing = ++lastTickSpacing;
        bool flipped = token0 > token1;
        PoolKey memory key = PoolKey({
            currency0: flipped ? token1 : token0,
            currency1: flipped ? token0 : token1,
            fee: 0,
            tickSpacing: tickSpacing,
            hooks: address(this)
        });
        bytes32 poolId = keccak256(abi.encode(key));
        canonicalPoolId[pool] = poolId;
        linkedPool[poolId] = LinkedPool({pool: pool, flipped: flipped});
        _poolKeys[poolId] = key;
        initializedPoolIds.push(poolId);
        emit MetricPoolLinked(poolId, pool, tickSpacing);

        // v4-core does not call a pool's hook when the hook itself is the caller (Hooks.noSelfCall), so this
        // initialize skips beforeInitialize; the registration event is emitted here instead.
        IPoolManager(poolManager).initialize(key, sqrtPriceX96);
        emit AggregatorPoolRegistered(poolId);
    }

    // ---------------------------------------------------------------------------------------------------------
    // IHooks
    // ---------------------------------------------------------------------------------------------------------

    /// @dev The constructor's own PoolManager.initialize never reaches here (v4-core skips self-calls), so any call
    ///      is someone else initializing a pool with this hook: rejected.
    function beforeInitialize(address, PoolKey calldata, uint160) external view onlyPoolManager returns (bytes4) {
        revert PoolSetFixed();
    }

    function beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        external
        view
        onlyPoolManager
        returns (bytes4)
    {
        revert LiquidityNotAllowed();
    }

    /// @dev Exact-in (amountSpecified < 0): the whole input goes to Metric, the user gets Metric output minus fees.
    ///      Exact-out (amountSpecified > 0): Metric is asked for output grossed up by the author fee, the user pays
    ///      Metric input plus the protocol fee (if any).
    ///      Settlement: Metric sends output straight to the PoolManager (sync/settle), the callback pays Metric
    ///      with `take` from the PoolManager, the author fee is minted to `feeRecipient` as an ERC-6909 claim, the
    ///      protocol fee is taken to the TokenJar. The hook's own token balance is never used.
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata)
        external
        onlyPoolManager
        returns (bytes4, int256, uint24)
    {
        if (params.sqrtPriceLimitX96 != (params.zeroForOne ? V4_MIN_LIMIT : V4_MAX_LIMIT)) {
            revert UnsupportedPriceLimit();
        }
        return (this.beforeSwap.selector, _swap(sender, key, params.zeroForOne, params.amountSpecified), 0);
    }

    struct SwapCtx {
        bytes32 poolId;
        bool exactIn;
        uint256 specifiedAbs;
        uint256 metricAbs;
        address inCur;
        address outCur;
        uint256 inputPaid;
        uint256 grossOut;
        uint24 protocolFee;
    }

    function _swap(address sender, PoolKey calldata key, bool zeroForOne, int256 amountSpecified)
        internal
        returns (int256 beforeSwapDelta)
    {
        SwapCtx memory c;
        c.poolId = _toId(key);
        LinkedPool memory lp = _activePool(c.poolId);
        if (_tload(T_EXPECTED_POOL) != 0) revert Reentrancy();

        (c.exactIn, c.specifiedAbs, c.metricAbs) = _amounts(amountSpecified);
        c.inCur = zeroForOne ? key.currency0 : key.currency1;
        c.outCur = zeroForOne ? key.currency1 : key.currency0;
        _requireMetricLive(lp.pool, zeroForOne != lp.flipped);
        if (c.exactIn) {
            // Metric is paid with `take` from the PoolManager, so the input must already be there (settle-first
            // routers) or be covered by its reserves. Same outcome as without this check, only cheaper.
            uint256 available = IERC20(c.inCur).balanceOf(poolManager);
            if (available < c.specifiedAbs) revert InsufficientSettlementInventory(c.inCur, c.specifiedAbs, available);
        }
        c.protocolFee = _protocolFee(c.poolId, zeroForOne);

        (c.inputPaid, c.grossOut) = _fillOnMetric(lp, zeroForOne != lp.flipped, c);
        (int128 specifiedDelta, int128 unspecifiedDelta, uint256 fee) =
            _userAmounts(c.exactIn, c.specifiedAbs, c.metricAbs, c.inputPaid, c.grossOut);

        if (fee != 0) {
            IPoolManager(poolManager).mint(feeRecipient, uint256(uint160(c.outCur)), fee);
            emit HookFeeCollected(c.poolId, c.outCur, feeRecipient, fee);
        }
        unspecifiedDelta = _chargeProtocolFee(c, unspecifiedDelta);

        _emitHookSwap(c.poolId, sender, zeroForOne == c.exactIn, specifiedDelta, unspecifiedDelta, c.protocolFee);
        beforeSwapDelta = _toBeforeSwapDelta(specifiedDelta, unspecifiedDelta);
    }

    /// @dev Runs the real Metric swap with output delivered to the PoolManager and returns (input paid, gross output).
    function _fillOnMetric(LinkedPool memory lp, bool metricZeroForOne, SwapCtx memory c)
        internal
        returns (uint256 inputPaid, uint256 grossOut)
    {
        _tstore(T_EXPECTED_POOL, uint256(uint160(lp.pool)));
        _tstore(T_EXPECTED_INPUT, uint256(uint160(c.inCur)) | (metricZeroForOne ? (1 << 255) : 0));
        _tstore(T_INPUT_PAID, 0);

        IPoolManager(poolManager).sync(c.outCur);
        (int128 m0, int128 m1) = IMetricOmmPool(lp.pool).swap(
            poolManager,
            metricZeroForOne,
            c.exactIn ? int128(int256(c.metricAbs)) : -int128(int256(c.metricAbs)),
            metricZeroForOne ? PRICE_LIMIT_ZERO_FOR_ONE : PRICE_LIMIT_ONE_FOR_ZERO,
            "",
            ""
        );

        inputPaid = _tload(T_INPUT_PAID);
        _tstore(T_EXPECTED_POOL, 0);
        _tstore(T_EXPECTED_INPUT, 0);
        _tstore(T_INPUT_PAID, 0);

        // Metric deltas are from the Metric pool's view: + received, - sent.
        int128 mIn = metricZeroForOne ? m0 : m1;
        int128 mOut = metricZeroForOne ? m1 : m0;
        if (mIn < 0 || mOut > 0) revert UnexpectedSwapDelta();
        if (uint256(int256(mIn)) != inputPaid) revert UnexpectedSwapDelta();
        grossOut = uint256(int256(-mOut));

        if (IPoolManager(poolManager).settle() != grossOut) revert UnexpectedSwapDelta();
    }

    /// @dev Splits the Metric fill into the user's amounts and the author fee, and builds the hook's
    ///      BeforeSwapDelta: exact-in -> (+input taken, -output owed); exact-out -> (-output owed, +input taken).
    function _userAmounts(bool exactIn, uint256 specifiedAbs, uint256 metricAbs, uint256 inputPaid, uint256 grossOut)
        internal
        view
        returns (int128 specifiedDelta, int128 unspecifiedDelta, uint256 fee)
    {
        if (exactIn) {
            if (inputPaid != specifiedAbs) revert PartialFill();
            fee = grossOut * feePips / PIPS; // rounds down, in the user's favour
            specifiedDelta = int128(int256(specifiedAbs));
            unspecifiedDelta = -int128(int256(grossOut - fee));
        } else {
            if (grossOut != metricAbs) revert PartialFill();
            fee = grossOut - specifiedAbs;
            specifiedDelta = -int128(int256(specifiedAbs));
            unspecifiedDelta = int128(int256(inputPaid));
        }
    }

    /// @dev Uniswap protocol fee on the unspecified side, same formula as Uniswap's ProtocolFees: exact-in reduces the
    ///      user's output, exact-out increases the user's input. No TokenJar -> no fee (same as the reference).
    function _chargeProtocolFee(SwapCtx memory c, int128 unspecifiedDelta) internal returns (int128) {
        if (c.protocolFee == 0) return unspecifiedDelta;
        address jar = _tokenJar();
        if (jar == address(0)) {
            c.protocolFee = 0;
            return unspecifiedDelta;
        }
        uint256 absU = uint256(int256(unspecifiedDelta < 0 ? -unspecifiedDelta : unspecifiedDelta));
        uint256 pf = _protocolFeeAmount(c.protocolFee, c.exactIn, absU);
        address cur = c.exactIn ? c.outCur : c.inCur;
        IPoolManager(poolManager).take(cur, jar, pf);
        emit ProtocolFeesCollected(jar, cur, pf);
        return unspecifiedDelta + int128(int256(pf));
    }

    function _emitHookSwap(
        bytes32 poolId,
        address sender,
        bool specifiedIsZero,
        int128 specifiedDelta,
        int128 unspecifiedDelta,
        uint24 protocolFee
    ) internal {
        (int256 amount0, int256 amount1) = specifiedIsZero
            ? (int256(specifiedDelta), int256(unspecifiedDelta))
            : (int256(unspecifiedDelta), int256(specifiedDelta));
        emit HookSwap(poolId, sender, amount0, amount1, protocolFee);
    }

    // ---------------------------------------------------------------------------------------------------------
    // Metric callback
    // ---------------------------------------------------------------------------------------------------------

    function metricOmmSwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external {
        address expected = address(uint160(_tload(T_EXPECTED_POOL)));
        if (expected == address(0)) {
            // Quote mode: report the deltas with the caller's tag and unwind everything (incl. Metric's output transfer).
            if (data.length == 64 && bytes32(data[0:32]) == QUOTE_FLAG) {
                revert QuoteRevert(bytes32(data[32:64]), amount0Delta, amount1Delta);
            }
            revert UnauthorizedCallback();
        }
        if (msg.sender != expected) revert UnauthorizedCallback();

        uint256 ei = _tload(T_EXPECTED_INPUT);
        bool inputIsToken0 = (ei >> 255) == 1;
        uint256 owed;
        if (inputIsToken0) {
            if (amount0Delta <= 0 || amount1Delta > 0) revert UnexpectedSwapDelta();
            owed = uint256(amount0Delta);
        } else {
            if (amount1Delta <= 0 || amount0Delta > 0) revert UnexpectedSwapDelta();
            owed = uint256(amount1Delta);
        }
        _tstore(T_INPUT_PAID, owed);
        IPoolManager(poolManager).take(address(uint160(ei)), msg.sender, owed);
    }

    // ---------------------------------------------------------------------------------------------------------
    // IAggregatorHook-style views (not marked view: they simulate a reverted Metric swap)
    // ---------------------------------------------------------------------------------------------------------

    /// @notice Unspecified amount for a swap, including the author fee and the Uniswap protocol fee. Same sign
    ///         convention as v4 (negative = exact-in). Returns the output for exact-in and the input for exact-out.
    function quote(bool zeroToOne, int256 amountSpecified, bytes32 poolId) external returns (uint256 amountUnspecified) {
        LinkedPool memory lp = _activePool(poolId);
        if (_tload(T_EXPECTED_POOL) != 0) revert Reentrancy();

        (bool exactIn, uint256 specifiedAbs, uint256 metricAbs) = _amounts(amountSpecified);
        bool mz = zeroToOne != lp.flipped;
        _requireMetricLive(lp.pool, mz);

        (uint256 mIn, uint256 mOut) = _quoteMetric(lp.pool, mz, exactIn, metricAbs);
        if (exactIn) {
            if (mIn != specifiedAbs) revert PartialFill();
            amountUnspecified = mOut - mOut * feePips / PIPS;
        } else {
            if (mOut != metricAbs) revert PartialFill();
            amountUnspecified = mIn;
        }
        uint24 pfee = _protocolFee(poolId, zeroToOne);
        if (pfee != 0 && _tokenJar() != address(0)) {
            uint256 pf = _protocolFeeAmount(pfee, exactIn, amountUnspecified);
            amountUnspecified = exactIn ? amountUnspecified - pf : amountUnspecified + pf;
        }
    }

    /// @dev Metric swap with the real recipient (PoolManager), reverted inside the callback. The revert carries a
    ///      per-call tag that only this hook's callback echoes (Metric passes callbackData to the callback only), so a
    ///      look-alike revert from elsewhere in the Metric call cannot be taken for the quote. Other reverts bubble up.
    function _quoteMetric(address pool, bool mz, bool exactIn, uint256 metricAbs)
        internal
        returns (uint256 mIn, uint256 mOut)
    {
        uint256 nonce = _tload(T_QUOTE_NONCE) + 1;
        _tstore(T_QUOTE_NONCE, nonce);
        bytes32 tag = keccak256(abi.encode(address(this), nonce, gasleft(), pool, metricAbs));
        (bool ok, bytes memory ret) = pool.call(
            abi.encodeCall(
                IMetricOmmPool.swap,
                (
                    poolManager,
                    mz,
                    exactIn ? int128(int256(metricAbs)) : -int128(int256(metricAbs)),
                    mz ? PRICE_LIMIT_ZERO_FOR_ONE : PRICE_LIMIT_ONE_FOR_ZERO,
                    abi.encode(QUOTE_FLAG, tag),
                    ""
                )
            )
        );
        if (ok) revert UnexpectedQuoteBehavior();
        if (ret.length != 100 || bytes4(ret) != QuoteRevert.selector) {
            assembly ("memory-safe") {
                revert(add(ret, 32), mload(ret))
            }
        }
        bytes32 gotTag;
        int256 a0;
        int256 a1;
        assembly ("memory-safe") {
            gotTag := mload(add(ret, 36))
            a0 := mload(add(ret, 68))
            a1 := mload(add(ret, 100))
        }
        if (gotTag != tag) revert UnexpectedQuoteBehavior();
        int256 i = mz ? a0 : a1;
        int256 o = mz ? a1 : a0;
        if (i < 0 || o > 0) revert UnexpectedSwapDelta();
        (mIn, mOut) = (uint256(i), uint256(-o));
    }

    /// @notice Tokens of the v4 pool held by the linked Metric pool (honest depth, no fake liquidity).
    ///         Zero while the pool is not routable, so indexers do not rank a stopped pool by stale depth.
    function pseudoTotalValueLocked(bytes32 poolId) external view returns (uint256 amount0, uint256 amount1) {
        LinkedPool memory lp = linkedPool[poolId];
        if (lp.pool == address(0)) revert PoolDoesNotExist();
        if (!_health(poolId).routable) return (0, 0);
        PoolKey memory key = _poolKeys[poolId];
        amount0 = IERC20(key.currency0).balanceOf(lp.pool);
        amount1 = IERC20(key.currency1).balanceOf(lp.pool);
    }

    /// @notice Same checks swaps run before calling Metric, as a view (for monitors).
    ///         `routable` does not cover the oracle: a Metric feed can still stall at swap time.
    function poolHealth(bytes32 poolId) external view returns (PoolHealth memory) {
        return _health(poolId);
    }

    /// @notice IFeeClassifiedHook: self-reported protocol-fee classification flags (fixed at zero).
    function protocolFeeFlags() external view returns (uint256) {
        return _protocolFeeFlags;
    }

    /// @notice TokenJar that receives the Uniswap protocol fee (read live from the protocol fee controller).
    function tokenJar() external view returns (address) {
        return _tokenJar();
    }

    function poolKeyOf(bytes32 poolId) external view returns (PoolKey memory) {
        return _poolKeys[poolId];
    }

    function initialized(uint256 index) external view returns (PoolKey memory) {
        return _poolKeys[initializedPoolIds[index]];
    }

    function initializedLength() external view returns (uint256) {
        return initializedPoolIds.length;
    }

    function getHookPermissions() external pure returns (Permissions memory permissions) {
        permissions.beforeInitialize = true;
        permissions.beforeAddLiquidity = true;
        permissions.beforeSwap = true;
        permissions.beforeSwapReturnDelta = true;
    }

    /// @dev No native ETH: v4 pools here are ERC-20 only.
    receive() external payable {
        revert TokenNotAllowed();
    }

    // ---------------------------------------------------------------------------------------------------------
    // Internal
    // ---------------------------------------------------------------------------------------------------------

    /// @dev Linked, and its Metric admin is still the trusted team admin.
    function _activePool(bytes32 poolId) internal view returns (LinkedPool memory lp) {
        lp = linkedPool[poolId];
        if (lp.pool == address(0)) revert PoolDoesNotExist();
        if (IMetricFactory(metricFactory).pendingPoolAdmin(lp.pool) != address(0)) revert PendingPoolAdminTransfer();
        if (IMetricFactory(metricFactory).poolAdmin(lp.pool) != metricAdmin) revert UntrustedPoolAdmin();
    }

    /// @dev (exactIn, |specified|, amount asked from Metric). Exact-out asks for the output grossed up by the fee.
    function _amounts(int256 amountSpecified) internal view returns (bool exactIn, uint256 specifiedAbs, uint256 metricAbs) {
        if (amountSpecified == type(int256).min) revert AmountTooLarge();
        exactIn = amountSpecified < 0;
        specifiedAbs = exactIn ? uint256(-amountSpecified) : uint256(amountSpecified);
        if (specifiedAbs > uint256(uint128(type(int128).max))) revert AmountTooLarge();
        metricAbs = exactIn ? specifiedAbs : _grossUp(specifiedAbs);
        if (metricAbs > uint256(uint128(type(int128).max))) revert AmountTooLarge();
    }

    /// @dev Checks a Metric pool before linking it; returns its tokens.
    function _checkMetricPool(address pool) internal view returns (address token0, address token1) {
        address factory_;
        address provider;
        (factory_, token0, token1, provider) = _metricImmutables(pool);
        if (factory_ != metricFactory) revert ExternalPoolMismatch();
        if (provider == address(0)) revert MutablePriceProvider();
        if (IMetricFactory(metricFactory).poolAdmin(pool) != metricAdmin) revert UntrustedPoolAdmin();
        if (IMetricFactory(metricFactory).pendingPoolAdmin(pool) != address(0)) revert PendingPoolAdminTransfer();
    }

    /// @dev 0 if the Metric pool is usable as far as on-chain state shows, else the PoolHealth reason (4, 5 or 6).
    function _metricReason(address pool) internal view returns (uint8) {
        if (IMetricFactory(metricFactory).pendingPoolAdmin(pool) != address(0)) return 4;
        if (IMetricFactory(metricFactory).poolAdmin(pool) != metricAdmin) return 4;
        if (_pauseLevel(pool) != 0) return 5;
        if (uint256(IMetricOmmPool(pool).extsload(bytes32(METRIC_SLOT1))) == 0) return 6;
        return 0;
    }

    /// @dev Pre-swap check: Metric pool not paused and holds output-side liquidity (Metric zeroForOne pays token1).
    function _requireMetricLive(address pool, bool metricZeroForOne) internal view {
        uint8 level = _pauseLevel(pool);
        if (level != 0) revert MetricPoolPaused(level);
        uint256 s1 = uint256(IMetricOmmPool(pool).extsload(bytes32(METRIC_SLOT1)));
        if ((metricZeroForOne ? s1 >> 128 : uint128(s1)) == 0) revert MetricNoLiquidity();
    }

    function _pauseLevel(address pool) internal view returns (uint8) {
        return uint8(uint256(IMetricOmmPool(pool).extsload(bytes32(METRIC_SLOT0))));
    }

    function _health(bytes32 poolId) internal view returns (PoolHealth memory h) {
        LinkedPool memory lp = linkedPool[poolId];
        h.metricPool = lp.pool;
        if (lp.pool == address(0)) {
            h.reason = 1;
            return h;
        }
        h.metricPauseLevel = _pauseLevel(lp.pool);
        uint256 s1 = uint256(IMetricOmmPool(lp.pool).extsload(bytes32(METRIC_SLOT1)));
        (h.binTotal0, h.binTotal1) = lp.flipped ? (uint128(s1 >> 128), uint128(s1)) : (uint128(s1), uint128(s1 >> 128));
        h.reason = _metricReason(lp.pool);
        h.routable = h.reason == 0;
    }

    /// @dev Pools are qualified off-chain before being put in the constructor set; on-chain only basic sanity.
    function _allowedPair(address token0, address token1) internal view returns (bool) {
        return token0 != token1 && token0.code.length != 0 && token1.code.length != 0;
    }

    /// @dev Smallest gross output g with g - floor(g * fee / PIPS) >= out.
    function _grossUp(uint256 out) internal view returns (uint256 g) {
        uint256 denom = PIPS - feePips;
        g = (out * PIPS + denom - 1) / denom;
        // the ceiling above can overshoot by up to two units; step down while the smaller value still delivers `out`
        while (g > 0 && (g - 1) - (g - 1) * feePips / PIPS >= out) {
            g--;
        }
    }

    /// @dev Protocol fee for the direction from this pool's PoolManager slot0 (bits 184..207), times the multiplier.
    function _protocolFee(bytes32 poolId, bool zeroForOne) internal view returns (uint24) {
        bytes32 slot0 = IPoolManager(poolManager).extsload(keccak256(abi.encode(poolId, POOLS_SLOT)));
        uint24 raw = uint24(uint256(slot0) >> 184);
        uint24 dir = zeroForOne ? raw & 0xfff : raw >> 12;
        return dir * protocolFeeMultiplier;
    }

    /// @dev Same as Uniswap's ProtocolFees._calculateProtocolFeeAmount.
    function _protocolFeeAmount(uint24 protocolFee, bool exactIn, uint256 amountUnspecified) internal pure returns (uint256) {
        uint256 denom = exactIn ? PIPS : PIPS - protocolFee;
        return (amountUnspecified * protocolFee + denom - 1) / denom;
    }

    /// @dev TokenJar of the protocol fee controller, or zero if there is none.
    function _tokenJar() internal view returns (address jar) {
        address ctrl = IPoolManager(poolManager).protocolFeeController();
        if (ctrl == address(0) || ctrl.code.length == 0) return address(0);
        try IV4FeeAdapter(ctrl).TOKEN_JAR() returns (address j) {
            jar = j;
        } catch {}
    }

    /// @dev Reads factory, token0, token1 and immutablePriceProvider from Metric's static PoolImmutables tuple.
    function _metricImmutables(address pool)
        internal
        view
        returns (address factory_, address token0, address token1, address immutableProvider)
    {
        (bool ok, bytes memory ret) = pool.staticcall(abi.encodeWithSignature("getImmutables()"));
        if (!ok || ret.length < 768) revert ExternalPoolMismatch();
        uint256 f;
        uint256 t0;
        uint256 t1;
        uint256 pp;
        assembly ("memory-safe") {
            f := mload(add(ret, 32))
            t0 := mload(add(ret, 64))
            t1 := mload(add(ret, 96))
            pp := mload(add(ret, 288))
        }
        if ((f | t0 | t1 | pp) >> 160 != 0) revert ExternalPoolMismatch();
        (factory_, token0, token1, immutableProvider) = (address(uint160(f)), address(uint160(t0)), address(uint160(t1)), address(uint160(pp)));
    }

    function _toId(PoolKey calldata key) internal pure returns (bytes32) {
        return keccak256(abi.encode(key.currency0, key.currency1, key.fee, key.tickSpacing, key.hooks));
    }

    function _toBeforeSwapDelta(int128 specified, int128 unspecified) internal pure returns (int256 d) {
        assembly ("memory-safe") {
            d := or(shl(128, specified), and(sub(shl(128, 1), 1), unspecified))
        }
    }

    function _tstore(bytes32 slot, uint256 v) internal {
        assembly ("memory-safe") {
            tstore(slot, v)
        }
    }

    function _tload(bytes32 slot) internal view returns (uint256 v) {
        assembly ("memory-safe") {
            v := tload(slot)
        }
    }
}

interface IPoolManager {
    function initialize(MetricFixedHook.PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
    function sync(address currency) external;
    function settle() external payable returns (uint256 paid);
    function take(address currency, address to, uint256 amount) external;
    function mint(address to, uint256 id, uint256 amount) external;
    function extsload(bytes32 slot) external view returns (bytes32);
    function protocolFeeController() external view returns (address);
}

interface IV4FeeAdapter {
    function TOKEN_JAR() external view returns (address);
}

interface IMetricFactory {
    function idxToPool(uint256 idx) external view returns (address);
    function poolAdmin(address pool) external view returns (address);
    function pendingPoolAdmin(address pool) external view returns (address);
}

interface IMetricOmmPool {
    function swap(
        address recipient,
        bool zeroForOne,
        int128 amountSpecified,
        uint128 priceLimitX64,
        bytes calldata callbackData,
        bytes calldata extensionData
    ) external returns (int128, int128);
    function extsload(bytes32 slot) external view returns (bytes32);
}

interface IERC20 {
    function balanceOf(address) external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "viaSSACFG": false,
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ],
  "experimental": false
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.