Skip to content
Verified contractPartialMIT

FeeRouterV2

Address0x0b2400542258d3452678956fd15b9cfb76fc6b48
Balance

0 ETH

 

Transactions

25

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,129,027
Creation transaction
0x861099036c…66b65d34ac

49 files

src/pad/FeeRouterV2.sol

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

import {RouteExecutor} from "./base/RouteExecutor.sol";
import {TwoStepOwned} from "../base/TwoStepOwned.sol";
import {SafeReads} from "../libraries/SafeReads.sol";
import {Hop} from "./libraries/PadTypes.sol";
import {PadHook} from "./PadHook.sol";
import {PadHookLib} from "./libraries/PadHookLib.sol";
import {IERC4626Min} from "../interfaces/IExternal.sol";

interface IVaultAsset {
    function asset() external view returns (address);
}

/// @title FeeRouterV2 (pad)
/// @notice Receives the pad's platform share (0.2% of volume, in every district quote), KINEKO's creator share, the
///         MetaMorpho vault's fee shares and Buy Gold fees. `distribute()` (anyone; the keeper calls it at random
///         times):
///           1. redeems vault fee shares to XAUT;
///           2. converts every other asset to XAUT through a FIXED per-asset route (set at deploy, no setter), in the
///              configured order (JPYC first, so yen never sits here), each leg size-capped per run and bounded by an
///              oracle floor (Chainlink or 30-min v3 TWAP, never the spot price); a leg that fails (issuer freeze,
///              burn, pause, stale oracle, floor not met) is SKIPPED, never fatal;
///           2b. converts KINEKO (the house coin: fees of KINEKO-paired coins) to XAUT through the KINEKO pool, at
///              most 0.3% of that pool's quote reserve per run and >= 97% of its value at the converter's reference;
///           3. splits the XAUT (the 1.00% platform slice of KINEKO's 2% fee): buffer 30 / KINEKO floor 0 / GOLD ENGINE 20 /
///              HARDWIRE 20 / treasury 30 (the floor already gets 0.5% of the 2% straight from the pool); once the buffer
///              holds its target the buffer drops to 10 and the treasury gets 50. Weights and the target change only through
///              a 24 h timelock, inside hard bounds (buffer >= 10%, engine <= 25%, hardwire <= 25%, treasury <= 50%). The engine and hardwire legs go to bind-once
///              reserves (EngineReserve, HardwireReserve). On a War day (WarChest, Phase 3, off at launch) the floor
///              leg of that day goes to the WarChest, which can only feed it to the posted winner's floor.
///              The treasury is paid in XAUT (user decision; TREASURY_ASSET == XAUT is enforced).
///         No KINEKO burn. No withdraw function: every outflow is fixed by code.
contract FeeRouterV2 is RouteExecutor, TwoStepOwned {
    using SafeTransferLib for address;

    uint256 public constant TIMELOCK = 24 hours;
    uint256 public constant MIN_BUFFER_BPS = 1000;
    uint256 internal constant BPS = 10_000;
    uint32 public constant TWAP_WINDOW = 30 minutes;
    uint256 public constant MAX_ASSETS = 12;

    // price source kinds (USD value of ONE whole unit of the asset, 1e18 = $1)
    uint8 public constant SRC_CHAINLINK = 1; // a = feed (8 dec), maxAge
    uint8 public constant SRC_TWAP_USD = 2; // a = v3 pool vs a $1 stable, b = the stable
    uint8 public constant SRC_TWAP_ETH = 3; // a = v3 pool vs WETH, then Chainlink ETH/USD (b = feed)
    uint8 public constant SRC_ERC4626 = 4; // a = the vault (the asset itself), valued at convertToAssets x $1
    uint8 public constant SRC_PEG = 5; // $1

    struct PriceSource {
        uint8 kind;
        address a;
        address b;
        uint32 maxAge; // Chainlink staleness bound (seconds)
    }

    struct AssetConfig {
        address asset; // address(0) = ETH
        uint8 decimals;
        Hop[] route; // asset -> XAUT
        PriceSource source;
        uint16 floorBps; // min out = fair XAUT x floorBps
        uint256 maxInPerRun;
    }

    struct Weights {
        uint16 buffer;
        uint16 floor; // KINEKO floor (fed through FeeConverter.feedFloor)
        uint16 engine; // Gold Engine (EngineReserve -> GoldEngine.fund)
        uint16 hardwire; // Hardwire (HardwireReserve -> HardwireVault.fund)
        uint16 treasury;
    }

    // hard bounds for every weight set (timelocked changes stay inside them)
    uint256 public constant MAX_ENGINE_BPS = 2500;
    uint256 public constant MAX_HARDWIRE_BPS = 2500;
    uint256 public constant MAX_TREASURY_BPS = 5000;
    /// house-coin leg: at most 0.3% of the KINEKO pool's quote reserve per run, >= 97% of its value at the reference
    uint256 public constant HOUSE_CHUNK_BPS = 30;
    uint256 public constant HOUSE_MIN_OUT_BPS = 9700;

    address public immutable XAUT;
    address public immutable BUFFER;
    address public immutable ENGINE; // EngineReserve
    address public immutable HARDWIRE; // HardwireReserve
    /// WarChest (Phase 3; 0 = none). Only ever receives the floor leg of a posted War day.
    IWarChest public immutable WAR;
    address public immutable TREASURY;
    address public immutable TREASURY_ASSET;
    IERC4626Min public immutable VAULT;
    /// XAUT/USDT 0.05% v3 pool: the XAUT side of every floor (30-min TWAP)
    address public immutable XAUT_USD_POOL;

    AssetConfig[] internal _assets;
    /// route XAUT -> treasury asset (empty when the treasury is paid in XAUT)

    Weights public normalWeights;
    Weights public fullWeights;
    uint256 public bufferTargetXaut;
    Weights public pendingNormal;
    Weights public pendingFull;
    uint256 public weightsEta;
    uint256 public pendingBufferTarget;
    uint256 public bufferTargetEta;

    /// XAUT earmarked for the treasury but not yet converted to the payout asset
    uint256 public treasuryXautPot;
    /// XAUT earmarked for the KINEKO floor but not yet fed (house coin not set yet, or a failed feed)
    uint256 public floorXautPot;
    /// engine / hardwire legs whose payment failed: retried next run, never sent anywhere else
    uint256 public engineXautPot;
    uint256 public hardwireXautPot;
    /// the pad's house coin (KINEKO): set once, by anyone, only to a HOUSE pool whose quote is XAUT
    address public houseCoin;
    /// the pad hook and fee converter (floor feed path; 0 disables the floor leg, which then stays potted)
    PadHook public immutable HOOK;
    IFloorFeeder public immutable FEEDER;

    /// district MetaMorpho vaults (fixed at deploy): their fee shares are redeemed to the underlying, which the asset
    /// legs then convert to XAUT
    address[] public extraVaults;
    address public pendingVault;
    uint256 public vaultEta;

    event Converted(address indexed asset, uint256 amountIn, uint256 xautOut, uint256 minOut);
    event LegSkipped(address indexed asset, bytes reason);
    event Distributed(
        uint256 xautIn, uint256 toBuffer, uint256 toFloor, uint256 toEngine, uint256 toHardwire, uint256 toTreasuryXaut
    );
    event WarPrize(uint256 indexed day, uint256 xaut);
    event HouseConverted(uint256 coinsIn, uint256 xautOut, uint256 minOut);
    event TreasuryPaid(address indexed asset, uint256 amount);
    event HouseCoinSet(address indexed coin);
    event FloorFed(address indexed coin, uint256 xaut);
    event VaultSharesRedeemed(uint256 shares, uint256 xaut);
    event WeightsProposed(Weights normal, Weights full, uint256 eta);
    event WeightsExecuted(Weights normal, Weights full);
    event BufferTargetProposed(uint256 target, uint256 eta);
    event VaultProposed(address indexed vault, uint256 eta);
    event VaultAdded(address indexed vault);
    event BufferTargetExecuted(uint256 target);

    error BadWeights();
    error BadConfig();
    error NothingPending();
    error TimelockNotElapsed(uint256 eta);
    error OracleUnavailable();
    error OnlySelf();

    struct Init {
        address owner;
        IPoolManager poolManager;
        address weth;
        address xaut;
        address xautUsdPool;
        address buffer;
        address engine; // EngineReserve
        address hardwire; // HardwireReserve
        address war; // WarChest (0 = none)
        address treasury;
        address treasuryAsset; // must be XAUT (user decision)
        address vault; // MetaMorpho XAUT vault (0 = none)
        address[] extraVaults; // district MetaMorpho vaults (Floor Loans lenders) whose fee shares are paid here
        address hook; // PadHook (0 = no floor leg yet)
        address feeder; // FeeConverter (floor feed)
        uint256 bufferTargetXaut;
        AssetConfig[] assets;
    }

    constructor(Init memory c) RouteExecutor(c.poolManager, c.weth) TwoStepOwned(c.owner) {
        if (
            c.xaut == address(0) || c.xautUsdPool == address(0) || c.buffer == address(0) || c.treasury == address(0)
                || c.engine == address(0) || c.hardwire == address(0) || c.treasuryAsset != c.xaut
                || c.assets.length > MAX_ASSETS
        ) revert BadConfig();
        ENGINE = c.engine;
        HARDWIRE = c.hardwire;
        WAR = IWarChest(c.war);
        XAUT = c.xaut;
        XAUT_USD_POOL = c.xautUsdPool;
        BUFFER = c.buffer;
        TREASURY = c.treasury;
        TREASURY_ASSET = c.treasuryAsset;
        VAULT = IERC4626Min(c.vault);
        HOOK = PadHook(c.hook);
        FEEDER = IFloorFeeder(c.feeder);
        if (c.extraVaults.length > MAX_ASSETS) revert BadConfig();
        for (uint256 i; i < c.extraVaults.length; ++i) {
            if (c.extraVaults[i] == address(0)) revert BadConfig();
            extraVaults.push(c.extraVaults[i]);
        }
        bufferTargetXaut = c.bufferTargetXaut;
        for (uint256 i; i < c.assets.length; ++i) {
            AssetConfig memory a = c.assets[i];
            if (a.asset == c.xaut || a.route.length == 0 || a.floorBps == 0 || a.floorBps > BPS || a.maxInPerRun == 0) {
                revert BadConfig();
            }
            _assets.push();
            AssetConfig storage s = _assets[i];
            s.asset = a.asset;
            s.decimals = a.decimals;
            s.source = a.source;
            s.floorBps = a.floorBps;
            s.maxInPerRun = a.maxInPerRun;
            for (uint256 k; k < a.route.length; ++k) {
                s.route.push(a.route[k]);
            }
        }
        Weights memory n = Weights(3000, 0, 2000, 2000, 3000); // buffer 30 / floor 0 (the floor gets its 0.5% straight from the pool) / engine 20 / hardwire 20 / treasury 30
        Weights memory f = Weights(1000, 0, 2000, 2000, 5000); // buffer full: 10 / floor 0 / 20 / 20 / treasury 50
        _validate(n);
        _validate(f);
        normalWeights = n;
        fullWeights = f;
    }

    /// @notice ETH revenue (e.g. Buy Gold fees) is always welcome; it is converted on the next distribute.
    receive() external payable override {}

    // ================================================================== distribute

    /// @notice One-time: the house coin whose floor receives the floor share. Anyone may call; only a HOUSE pool of
    ///         the pad hook with XAUT as its quote qualifies (only the factory's immutable HOUSE can launch one).
    function setHouseCoin(address coin) external {
        if (houseCoin != address(0) || address(HOOK) == address(0)) revert BadConfig();
        PadHook.PoolInfo memory p = PadHookLib.poolInfo(HOOK, coin);
        if (p.coin != coin || !p.house || p.quote != XAUT) revert BadConfig();
        houseCoin = coin;
        emit HouseCoinSet(coin);
    }

    function distribute() external nonReentrant {
        // (house coins have no creator share, so there is no creator claim leg any more)
        // 1. MetaMorpho fee shares -> XAUT (skip on failure)
        for (uint256 i; i <= extraVaults.length; ++i) {
            address v = i == 0 ? address(VAULT) : extraVaults[i - 1];
            if (v == address(0)) continue;
            try this.selfRedeem{gas: 300_000}(v) {} catch (bytes memory err) {
                emit LegSkipped(v, err);
            }
        }
        // 2. every asset -> XAUT, in configured order (JPYC first)
        uint256 n = _assets.length;
        for (uint256 i; i < n; ++i) {
            AssetConfig storage a = _assets[i];
            uint256 bal = _balanceOfSafe(a.asset);
            uint256 amt = bal < a.maxInPerRun ? bal : a.maxInPerRun;
            if (amt == 0) continue;
            try this.selfConvert(i, amt) {} catch (bytes memory err) {
                emit LegSkipped(a.asset, err);
            }
        }
        // 2b. the house coin (KINEKO, fees of KINEKO-paired coins) -> XAUT through the KINEKO pool (skip on failure)
        if (houseCoin != address(0)) {
            uint256 hb = _balanceOfSafe(houseCoin);
            if (hb > 0) {
                try this.selfConvertHouse(hb) {} catch (bytes memory err) {
                    emit LegSkipped(houseCoin, err);
                }
            }
        }
        // 3. split new XAUT (the pots waiting for a payout are not new)
        uint256 xBal = _balanceOfSafe(XAUT);
        uint256 pots = treasuryXautPot + floorXautPot + engineXautPot + hardwireXautPot;
        if (xBal < pots) {
            // e.g. an issuer burn: never brick; shrink every pot pro rata to what is really here
            floorXautPot = FullMath.mulDiv(floorXautPot, xBal, pots);
            engineXautPot = FullMath.mulDiv(engineXautPot, xBal, pots);
            hardwireXautPot = FullMath.mulDiv(hardwireXautPot, xBal, pots);
            treasuryXautPot = xBal - floorXautPot - engineXautPot - hardwireXautPot;
            pots = xBal;
        }
        uint256 x = xBal - pots;
        Split memory s;
        if (x > 0) {
            Weights memory w = currentWeights();
            s.buffer = x * w.buffer / BPS;
            s.floor = x * w.floor / BPS;
            s.engine = x * w.engine / BPS;
            s.hardwire = x * w.hardwire / BPS;
            s.treasury = x - s.buffer - s.floor - s.engine - s.hardwire;
            treasuryXautPot += s.treasury;
            engineXautPot += s.engine;
            hardwireXautPot += s.hardwire;
            if (s.buffer > 0) {
                try this.selfPay(XAUT, BUFFER, s.buffer) {
                    // BUFFER is the BufferReserve: best-effort push on to the bound desk SafetyBuffer. Never fatal.
                    (bool rel,) = BUFFER.call(abi.encodeWithSelector(IBufferReserve.release.selector));
                    rel;
                } catch (bytes memory err) {
                    emit LegSkipped(XAUT, err);
                    s.buffer = 0; // stays here, split again next run
                }
            }
            // the floor leg: KINEKO's floor, or (on a posted War day) the WarChest for the day's winner
            uint256 day = _warDay();
            if (day != 0 && s.floor > 0) {
                try this.selfWar(day, s.floor) {
                    emit WarPrize(day, s.floor);
                } catch (bytes memory err) {
                    emit LegSkipped(address(WAR), err);
                    floorXautPot += s.floor;
                }
            } else {
                floorXautPot += s.floor;
            }
        }
        emit Distributed(x, s.buffer, s.floor, s.engine, s.hardwire, s.treasury);
        // 3a. engine / hardwire legs (each pot retried until its reserve takes it; never sent anywhere else)
        uint256 ep = engineXautPot;
        if (ep > 0) {
            try this.selfPayReserve(ENGINE, ep) {
                engineXautPot = 0;
            } catch (bytes memory err) {
                emit LegSkipped(ENGINE, err);
            }
        }
        uint256 hp = hardwireXautPot;
        if (hp > 0) {
            try this.selfPayReserve(HARDWIRE, hp) {
                hardwireXautPot = 0;
            } catch (bytes memory err) {
                emit LegSkipped(HARDWIRE, err);
            }
        }
        // 3b. KINEKO floor feed (skipped, never fatal, while no house coin is set or the feed fails)
        uint256 fp = floorXautPot;
        if (fp > 0 && houseCoin != address(0)) {
            try this.selfFeedFloor(fp) {
                floorXautPot = 0;
                emit FloorFed(houseCoin, fp);
            } catch (bytes memory err) {
                emit LegSkipped(houseCoin, err);
            }
        }
        // 4. treasury payout
        uint256 pot = treasuryXautPot;
        if (pot > 0) {
            try this.selfPay(XAUT, TREASURY, pot) {
                treasuryXautPot = 0;
                emit TreasuryPaid(XAUT, pot);
            } catch (bytes memory err) {
                emit LegSkipped(XAUT, err);
            }
        }
    }

    // ------------------------------------------------------------------ self-call legs (skippable)

    modifier onlySelfLocked() {
        if (msg.sender != address(this) || !_isLocked()) revert OnlySelf();
        _;
    }

    function selfRedeem(address vault) external onlySelfLocked {
        IERC4626Min v = IERC4626Min(vault);
        uint256 sh = v.balanceOf(address(this));
        uint256 r = v.maxRedeem(address(this));
        if (r > sh) r = sh;
        if (r > 0) {
            uint256 got = v.redeem(r, address(this), address(this));
            emit VaultSharesRedeemed(r, got);
        }
    }

    function selfConvert(uint256 i, uint256 amountIn) external onlySelfLocked {
        AssetConfig storage a = _assets[i];
        uint256 fair = _fairXaut(a.source, a.decimals, amountIn);
        uint256 minOut = fair * a.floorBps / BPS;
        uint256 x0 = XAUT.balanceOf(address(this));
        Hop[] memory route = a.route;
        _runHops(route, false, a.asset, XAUT, amountIn);
        uint256 got = XAUT.balanceOf(address(this)) - x0;
        if (got < minOut || got == 0) revert OracleUnavailable();
        emit Converted(a.asset, amountIn, got, minOut);
    }

    /// pays a bind-once reserve and lets it push on to its bound target (best effort: unbound reserves just hold)
    function selfPayReserve(address reserve, uint256 amount) external onlySelfLocked {
        XAUT.safeTransfer(reserve, amount);
        (bool rel,) = reserve.call(abi.encodeWithSelector(IBufferReserve.release.selector));
        rel;
    }

    function selfWar(uint256 day, uint256 amount) external onlySelfLocked {
        XAUT.safeApproveWithRetry(address(WAR), amount);
        WAR.deposit(day, amount);
        XAUT.safeApproveWithRetry(address(WAR), 0);
    }

    /// KINEKO -> XAUT through the KINEKO pool, chunk-capped and floored at the converter's reference (like FeeConverter)
    function selfConvertHouse(uint256 bal) external onlySelfLocked {
        address hc = houseCoin;
        PadHook.PoolInfo memory p = PadHookLib.poolInfo(HOOK, hc);
        (, uint256 bandQ,, uint256 mainQ,) = PadHookLib.floorBacking(HOOK, hc);
        int24 ref = IRefSource(address(FEEDER)).refTickOf(p);
        uint256 capQ = (bandQ + mainQ) * HOUSE_CHUNK_BPS / BPS;
        uint256 coinsIn = bal;
        uint256 value = _quoteAtTick(p.coinIsToken0 ? ref : -ref, coinsIn, p.coinIsToken0);
        if (value > capQ) {
            coinsIn = FullMath.mulDiv(coinsIn, capQ, value);
            value = capQ;
        }
        // the pool's own fee (KINEKO: 2%) is not slippage: >= 97% of the reference value net of that fee
        uint256 minOut = value * (1_000_000 - p.storedFee) / 1_000_000 * HOUSE_MIN_OUT_BPS / BPS;
        if (coinsIn == 0 || minOut == 0) revert OracleUnavailable();
        uint256 x0 = XAUT.balanceOf(address(this));
        Hop[] memory route = new Hop[](1);
        route[0] = Hop({kind: 4, pool: address(HOOK), tokenIn: hc, tokenOut: XAUT, fee: 0, tickSpacing: 60, curveI: 0, curveJ: 0});
        _runHops(route, false, hc, XAUT, coinsIn);
        uint256 got = XAUT.balanceOf(address(this)) - x0;
        if (got < minOut) revert OracleUnavailable();
        emit HouseConverted(coinsIn, got, minOut);
    }

    /// today's UTC day if a War winner is posted and live for it (WarChest decides), else 0
    function _warDay() internal view returns (uint256) {
        if (address(WAR) == address(0)) return 0;
        (bool s, bytes memory r) = address(WAR).staticcall(abi.encodeWithSelector(IWarChest.activeDay.selector));
        if (!s || r.length != 32) return 0;
        return abi.decode(r, (uint256));
    }

    function selfFeedFloor(uint256 amount) external onlySelfLocked {
        XAUT.safeApproveWithRetry(address(FEEDER), amount);
        FEEDER.feedFloor(houseCoin, amount);
        XAUT.safeApproveWithRetry(address(FEEDER), 0);
    }

    function selfPay(address token, address to, uint256 amount) external onlySelfLocked {
        token.safeTransfer(to, amount);
    }

    // ------------------------------------------------------------------ pricing (never the spot price)

    /// Fair XAUT (raw) for `amountIn` raw units of an asset.
    function _fairXaut(PriceSource memory src, uint8 dec, uint256 amountIn) internal view returns (uint256) {
        uint256 unitUsd = _unitUsd(src, dec); // USD (1e18) per whole unit
        uint256 usd = FullMath.mulDiv(amountIn, unitUsd, 10 ** uint256(dec));
        uint256 xautUnitUsd = _xautUnitUsd(); // USD (1e18) per whole XAUT
        return FullMath.mulDiv(usd, 1e6, xautUnitUsd);
    }

    /// XAUT (6 dec) priced from the XAUT/USDT v3 30-min TWAP (XAUT is token0: USDT raw per XAUT raw).
    function _xautUnitUsd() internal view returns (uint256) {
        (bool ok, int24 t) = SafeReads.meanTick(XAUT_USD_POOL, TWAP_WINDOW);
        if (!ok) revert OracleUnavailable();
        // 1e6 raw XAUT -> USDT raw (6 dec) -> 1e18 USD
        return _quoteAtTick(t, 1e6, true) * 1e12;
    }

    function _unitUsd(PriceSource memory src, uint8 dec) internal view returns (uint256 usd) {
        if (src.kind == SRC_CHAINLINK) {
            (bool ok, uint256 ans, uint256 upd) = SafeReads.chainlink(src.a);
            if (!ok || block.timestamp - upd > src.maxAge) revert OracleUnavailable();
            return ans * 1e10; // 8-dec feed -> 1e18
        }
        if (src.kind == SRC_TWAP_USD || src.kind == SRC_TWAP_ETH) {
            (bool ok, int24 t) = SafeReads.meanTick(src.a, TWAP_WINDOW);
            if (!ok) revert OracleUnavailable();
            address t0 = _token0(src.a);
            address other = src.kind == SRC_TWAP_USD ? src.b : WETH;
            bool assetIs0 = t0 != other;
            uint256 otherRaw = _quoteAtTick(t, 10 ** uint256(dec), assetIs0); // raw units of the other token per unit
            if (src.kind == SRC_TWAP_USD) return otherRaw * 1e12; // 6-dec stable
            (bool ok2, uint256 ethAns, uint256 upd) = SafeReads.chainlink(src.b);
            if (!ok2 || block.timestamp - upd > src.maxAge) revert OracleUnavailable();
            return FullMath.mulDiv(otherRaw, ethAns * 1e10, 1e18); // WETH 18 dec
        }
        if (src.kind == SRC_ERC4626) {
            return IERC4626Rate(src.a).convertToAssets(10 ** uint256(dec)); // assets (18 dec) at $1
        }
        if (src.kind == SRC_PEG) return 1e18;
        revert OracleUnavailable();
    }

    /// Amount of the other token for `amount` of the base at tick `t` (token1/token0 raw price).
    function _quoteAtTick(int24 t, uint256 amount, bool baseIsToken0) internal pure returns (uint256) {
        uint256 sp = TickMath.getSqrtPriceAtTick(t);
        uint256 pX96 = FullMath.mulDiv(sp, sp, 1 << 96);
        return baseIsToken0 ? FullMath.mulDiv(amount, pX96, 1 << 96) : FullMath.mulDiv(amount, 1 << 96, pX96);
    }

    function _token0(address pool) internal view returns (address t0) {
        (bool s, bytes memory r) = pool.staticcall(abi.encodeWithSelector(0x0dfe1681)); // token0()
        if (!s || r.length < 32) revert OracleUnavailable();
        t0 = abi.decode(r, (address));
    }

    function _balanceOfSafe(address token) internal view returns (uint256) {
        if (token == address(0)) return address(this).balance;
        (bool s, bytes memory r) = token.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
        if (!s || r.length < 32) return 0;
        return abi.decode(r, (uint256));
    }

    // ================================================================== timelocked config

    function proposeWeights(Weights calldata normal, Weights calldata full) external onlyOwner {
        _validate(normal);
        _validate(full);
        pendingNormal = normal;
        pendingFull = full;
        weightsEta = block.timestamp + TIMELOCK;
        emit WeightsProposed(normal, full, weightsEta);
    }

    function executeWeights() external {
        uint256 eta = weightsEta;
        if (eta == 0) revert NothingPending();
        if (block.timestamp < eta) revert TimelockNotElapsed(eta);
        normalWeights = pendingNormal;
        fullWeights = pendingFull;
        weightsEta = 0;
        emit WeightsExecuted(normalWeights, fullWeights);
    }

    function cancelWeights() external onlyOwner {
        if (weightsEta == 0) revert NothingPending();
        weightsEta = 0;
    }

    /// @notice Owner: register one more MetaMorpho vault whose fee shares are paid here (24 h notice). Its asset must be
    ///         XAUT or an asset this router already converts.
    function proposeVault(address v) external onlyOwner {
        if (v == address(0) || v.code.length == 0 || extraVaults.length >= MAX_ASSETS) revert BadConfig();
        address a = IVaultAsset(v).asset();
        bool ok = a == XAUT;
        for (uint256 i; !ok && i < _assets.length; ++i) {
            ok = _assets[i].asset == a;
        }
        if (!ok) revert BadConfig();
        pendingVault = v;
        vaultEta = block.timestamp + TIMELOCK;
        emit VaultProposed(v, vaultEta);
    }

    /// @notice Owner: stop collecting from an extra vault at once (removal can only reduce income, never move funds).
    function removeVault(uint256 i) external onlyOwner {
        uint256 n = extraVaults.length;
        if (i >= n) revert BadConfig();
        extraVaults[i] = extraVaults[n - 1];
        extraVaults.pop();
    }

    function executeVault() external {
        uint256 eta = vaultEta;
        if (eta == 0) revert NothingPending();
        if (block.timestamp < eta) revert TimelockNotElapsed(eta);
        if (pendingVault.code.length == 0) revert BadConfig();
        extraVaults.push(pendingVault);
        emit VaultAdded(pendingVault);
        pendingVault = address(0);
        vaultEta = 0;
    }

    function proposeBufferTarget(uint256 target) external onlyOwner {
        pendingBufferTarget = target;
        bufferTargetEta = block.timestamp + TIMELOCK;
        emit BufferTargetProposed(target, bufferTargetEta);
    }

    function executeBufferTarget() external {
        uint256 eta = bufferTargetEta;
        if (eta == 0) revert NothingPending();
        if (block.timestamp < eta) revert TimelockNotElapsed(eta);
        bufferTargetXaut = pendingBufferTarget;
        bufferTargetEta = 0;
        emit BufferTargetExecuted(bufferTargetXaut);
    }

    function _validate(Weights memory w) internal pure {
        if (
            uint256(w.buffer) + w.floor + w.engine + w.hardwire + w.treasury != BPS || w.buffer < MIN_BUFFER_BPS
                || w.engine > MAX_ENGINE_BPS || w.hardwire > MAX_HARDWIRE_BPS
                || w.treasury > MAX_TREASURY_BPS
        ) revert BadWeights();
    }

    // ================================================================== views

    /// XAUT the last-resort liquidator has: BufferReserve.totalXaut() (reserve + bound desk SafetyBuffer), or the plain
    /// XAUT balance of BUFFER if it is not a reserve.
    function bufferXaut() public view returns (uint256) {
        (bool s, bytes memory r) = BUFFER.staticcall(abi.encodeWithSelector(IBufferReserve.totalXaut.selector));
        if (s && r.length == 32) return abi.decode(r, (uint256));
        return _balanceOfExt(XAUT, BUFFER);
    }

    function bufferFull() public view returns (bool) {
        return bufferXaut() >= bufferTargetXaut;
    }

    function currentWeights() public view returns (Weights memory) {
        return bufferFull() ? fullWeights : normalWeights;
    }

    function assetCount() external view returns (uint256) {
        return _assets.length;
    }

    function assetConfig(uint256 i) external view returns (AssetConfig memory) {
        return _assets[i];
    }

    function fairXaut(uint256 i, uint256 amountIn) external view returns (uint256) {
        AssetConfig storage a = _assets[i];
        return _fairXaut(a.source, a.decimals, amountIn);
    }

    function _balanceOfExt(address token, address who) internal view returns (uint256) {
        (bool s, bytes memory r) = token.staticcall(abi.encodeWithSelector(0x70a08231, who));
        if (!s || r.length < 32) return 0;
        return abi.decode(r, (uint256));
    }
}

interface IBufferReserve {
    function release() external returns (uint256);
    function totalXaut() external view returns (uint256);
}

struct Split {
    uint256 buffer;
    uint256 floor;
    uint256 engine;
    uint256 hardwire;
    uint256 treasury;
}

interface IWarChest {
    /// today's UTC day if a winner is posted, matured and not vetoed (and the War is switched on), else 0
    function activeDay() external view returns (uint256);
    function deposit(uint256 day, uint256 amount) external;
}

interface IRefSource {
    function refTickOf(PadHook.PoolInfo memory p) external view returns (int24);
}

interface IFloorFeeder {
    function feedFloor(address coin, uint256 amount) external;
}

interface IERC4626Rate {
    function convertToAssets(uint256 shares) external view returns (uint256);
}

lib/solady/src/utils/FixedPointMathLib.sol

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

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error ExpOverflow();

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error FactorialOverflow();

    /// @dev The operation failed, due to an overflow.
    error RPowOverflow();

    /// @dev The mantissa is too big to fit.
    error MantissaOverflow();

    /// @dev The operation failed, due to an multiplication overflow.
    error MulWadFailed();

    /// @dev The operation failed, due to an multiplication overflow.
    error SMulWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error DivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error SDivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error MulDivFailed();

    /// @dev The division failed, as the denominator is zero.
    error DivFailed();

    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @dev The output is undefined, as the input is less-than-or-equal to zero.
    error LnWadUndefined();

    /// @dev The input outside the acceptable domain.
    error OutOfDomain();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The scalar of ETH and most ERC20s.
    uint256 internal constant WAD = 1e18;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              SIMPLIFIED FIXED POINT OPERATIONS             */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if gt(x, div(not(0), y)) {
                if y {
                    mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded towards zero.
    function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
            if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded towards zero, but without overflow checks.
    function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up.
    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if iszero(eq(div(z, y), x)) {
                if y {
                    mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
    function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
            if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded towards zero.
    function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, WAD)
            // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
            if iszero(mul(y, eq(sdiv(z, WAD), x))) {
                mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded towards zero, but without overflow and divide by zero checks.
    function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up.
    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
            if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
    function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `x` to the power of `y`.
    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
    /// Note: This function is an approximation.
    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Using `ln(x)` means `x` must be greater than 0.
        return expWad((lnWad(x) * y) / int256(WAD));
    }

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
            if (x <= -41446531673892822313) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                if iszero(slt(x, 135305999368893231589)) {
                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                    revert(0x1c, 0x04)
                }
            }

            // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96`
            // for more intermediate precision and a binary basis. This base conversion
            // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
            x = (x << 78) / 5 ** 18;

            // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
            // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
            // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
            int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96;
            x = x - k * 54916777467707473351141471128;

            // `k` is in the range `[-61, 195]`.

            // Evaluate using a (6, 7)-term rational approximation.
            // `p` is made monic, we'll multiply by a scale factor later.
            int256 y = x + 1346386616545796478920950773328;
            y = ((y * x) >> 96) + 57155421227552351082224309758442;
            int256 p = y + x - 94201549194550492254356042504812;
            p = ((p * y) >> 96) + 28719021644029726153956944680412240;
            p = p * x + (4385272521454847904659076985693276 << 96);

            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.
            int256 q = x - 2855989394907223263936484059900;
            q = ((q * x) >> 96) + 50020603652535783019961831881945;
            q = ((q * x) >> 96) - 533845033583426703283633433725380;
            q = ((q * x) >> 96) + 3604857256930695427073651918091429;
            q = ((q * x) >> 96) - 14423608567350463180887372962807573;
            q = ((q * x) >> 96) + 26449188498355588339934803723976023;

            /// @solidity memory-safe-assembly
            assembly {
                // Div in assembly because solidity adds a zero check despite the unchecked.
                // The q polynomial won't have zeros in the domain as all its roots are complex.
                // No scaling is necessary because p is already `2**96` too large.
                r := sdiv(p, q)
            }

            // r should be in the range `(0.09, 0.25) * 2**96`.

            // We now need to multiply r by:
            // - The scale factor `s ≈ 6.031367120`.
            // - The `2**k` factor from the range reduction.
            // - The `1e18 / 2**96` factor for base conversion.
            // We do this all at once, with an intermediate result in `2**213`
            // basis, so the final right shift is always by a positive amount.
            r = int256(
                (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k)
            );
        }
    }

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
            p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
            // Base conversion: mul `2**18 / 2**192`.
            r := sar(174, p)
        }
    }

    /// @dev Returns `W_0(x)`, denominated in `WAD`.
    /// See: https://en.wikipedia.org/wiki/Lambert_W_function
    /// a.k.a. Product log function. This is an approximation of the principal branch.
    /// Note: This function is an approximation. Monotonically increasing.
    function lambertW0Wad(int256 x)
        internal
        pure
        returns (int256 w)
    {

        // forgefmt: disable-next-item
        unchecked {
            if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
            (int256 wad, int256 p) = (int256(WAD), x);
            uint256 c; // Whether we need to avoid catastrophic cancellation.
            uint256 i = 4; // Number of iterations.
            if (w <= 0x1ffffffffffff) {
                if (-0x4000000000000 <= w) {
                    i = 1; // Inputs near zero only take one step to converge.
                } else if (w <= -0x3ffffffffffffff) {
                    i = 32; // Inputs near `-1/e` take very long to converge.
                }
            } else if (uint256(w >> 63) == uint256(0)) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Inline log2 for more performance, since the range is small.
                    let v := shr(49, w)
                    let l := shl(3, lt(0xff, v))
                    l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                    w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                    c := gt(l, 60)
                    i := add(2, add(gt(l, 53), c))
                }
            } else {
                int256 ll = lnWad(w = lnWad(w));
                /// @solidity memory-safe-assembly
                assembly {
                    // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                    w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                    i := add(3, iszero(shr(68, x)))
                    c := iszero(shr(143, x))
                }
                if (c == uint256(0)) {
                    do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := mul(w, div(e, wad))
                            w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != uint256(0));
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    return w;
                }
            }
            do { // Otherwise, use Halley's for faster convergence.
                int256 e = expWad(w);
                /// @solidity memory-safe-assembly
                assembly {
                    let t := add(w, wad)
                    let s := sub(mul(w, e), mul(x, wad))
                    w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                }
                if (p <= w) break;
                p = w;
            } while (--i != c);
            /// @solidity memory-safe-assembly
            assembly {
                w := sub(w, sgt(w, 2))
            }
            // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
            // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
            if (c == uint256(0)) return w;
            int256 t = w | 1;
            /// @solidity memory-safe-assembly
            assembly {
                x := sdiv(mul(x, wad), t)
            }
            x = (t * (wad + lnWad(x)));
            /// @solidity memory-safe-assembly
            assembly {
                w := sdiv(x, add(wad, t))
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  GENERAL NUMBER UTILITIES                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `a * b == x * y`, with full precision.
    function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // 512-bit multiply `[p1 p0] = x * y`.
            // Compute the product mod `2**256` and mod `2**256 - 1`
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that `product = p1 * 2**256 + p0`.

            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`.
            for {} 1 {} {
                // If overflows.
                if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.

                    /*------------------- 512 by 256 division --------------------*/

                    // Make division exact by subtracting the remainder from `[p1 p0]`.
                    let r := mulmod(x, y, d) // Compute remainder using mulmod.
                    let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
                    // Make sure `z` is less than `2**256`. Also prevents `d == 0`.
                    // Placing the check here seems to give more optimal stack operations.
                    if iszero(gt(d, p1)) {
                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    d := div(d, t) // Divide `d` by `t`, which is a power of two.
                    // Invert `d mod 2**256`
                    // Now that `d` is an odd number, it has an inverse
                    // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                    // Compute the inverse by starting with a seed that is
                    // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                    let inv := xor(2, mul(3, d))
                    // Now use Newton-Raphson iteration to improve the precision.
                    // Thanks to Hensel's lifting lemma, this also works in modular
                    // arithmetic, doubling the correct bits in each step.
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                    z := mul(
                        // Divide [p1 p0] by the factors of two.
                        // Shift in bits from `p1` into `p0`. For this we need
                        // to flip `t` such that it is `2**256 / t`.
                        or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                        mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
                    )
                    break
                }
                z := div(z, d)
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
    /// Performs the full 512 bit calculation regardless.
    function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            let mm := mulmod(x, y, not(0))
            let p1 := sub(mm, add(z, lt(mm, z)))
            let t := and(d, sub(0, d))
            let r := mulmod(x, y, d)
            d := div(d, t)
            let inv := xor(2, mul(3, d))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            z := mul(
                or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                mul(sub(2, mul(d, inv)), inv)
            )
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Uniswap-v3-core under MIT license:
    /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        z = fullMulDiv(x, y, d);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, d) {
                z := add(z, 1)
                if iszero(z) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
    /// Throws if result overflows a uint256.
    /// Credit to Philogy under MIT license:
    /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
    function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
            for {} 1 {} {
                if iszero(or(iszero(x), eq(div(z, x), y))) {
                    let k := and(n, 0xff) // `n`, cleaned.
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
                    //         |      p1     |      z     |
                    // Before: | p1_0 ¦ p1_1 | z_0  ¦ z_1 |
                    // Final:  |   0  ¦ p1_0 | p1_1 ¦ z_0 |
                    // Check that final `z` doesn't overflow by checking that p1_0 = 0.
                    if iszero(shr(k, p1)) {
                        z := add(shl(sub(256, k), p1), shr(k, z))
                        break
                    }
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
                z := shr(and(n, 0xff), z)
                break
            }
        }
    }

    /// @dev Returns `floor(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(z, d)
        }
    }

    /// @dev Returns `ceil(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(z, d))), div(z, d))
        }
    }

    /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
    function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
        /// @solidity memory-safe-assembly
        assembly {
            let g := n
            let r := mod(a, n)
            for { let y := 1 } 1 {} {
                let q := div(g, r)
                let t := g
                g := r
                r := sub(t, mul(r, q))
                let u := x
                x := y
                y := sub(u, mul(y, q))
                if iszero(r) { break }
            }
            x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
        }
    }

    /// @dev Returns `ceil(x / d)`.
    /// Reverts if `d` is zero.
    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(d) {
                mstore(0x00, 0x65244e4e) // `DivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(x, d))), div(x, d))
        }
    }

    /// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns `max(0, x - y)`.
    function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns `min(2 ** 256 - 1, x + y)`.
    function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(0, lt(add(x, y), x)), add(x, y))
        }
    }

    /// @dev Returns `min(2 ** 256 - 1, x * y)`.
    function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `x != 0 ? x : y`, without branching.
    function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != bytes32(0) ? x : y`, without branching.
    function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != address(0) ? x : y`, without branching.
    function coalesce(address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(shl(96, x))))
        }
    }

    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
    /// Reverts if the computation overflows.
    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
            if x {
                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                let half := shr(1, b) // Divide `b` by 2.
                // Divide `y` by 2 every iteration.
                for { y := shr(1, y) } y { y := shr(1, y) } {
                    let xx := mul(x, x) // Store x squared.
                    let xxRound := add(xx, half) // Round to the nearest number.
                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                    if or(lt(xxRound, xx), shr(128, x)) {
                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                    // If `y` is odd:
                    if and(y, 1) {
                        let zx := mul(z, x) // Compute `z * x`.
                        let zxRound := add(zx, half) // Round to the nearest number.
                        // If `z * x` overflowed or `zx + half` overflowed:
                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                            // Revert if `x` is non-zero.
                            if x {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                        }
                        z := div(zxRound, b) // Return properly scaled `zxRound`.
                    }
                }
            }
        }
    }

    /// @dev Returns the square root of `x`, rounded down.
    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
            // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffffff, shr(r, x))))
            z := shl(shr(1, r), z)

            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
            // That's not possible if `x < 256` but we can just verify those cases exhaustively.

            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.

            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
            // with largest error when `s = 1` and when `s = 256` or `1/256`.

            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
            // Then we can estimate `sqrt(y)` using
            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.

            // There is no overflow risk here since `y < 2**136` after the first branch above.
            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`, rounded down.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // Makeshift lookup table to nudge the approximate log2 result.
            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
            // Newton-Raphson's.
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            // Round down.
            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
    function sqrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
            z = (1 + sqrt(x)) * 10 ** 9;
            z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
        }
        /// @solidity memory-safe-assembly
        assembly {
            z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
        }
    }

    /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
            z = (1 + cbrt(x)) * 10 ** 12;
            z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
        }
        /// @solidity memory-safe-assembly
        assembly {
            let p := x
            for {} 1 {} {
                if iszero(shr(229, p)) {
                    if iszero(shr(199, p)) {
                        p := mul(p, 100000000000000000) // 10 ** 17.
                        break
                    }
                    p := mul(p, 100000000) // 10 ** 8.
                    break
                }
                if iszero(shr(249, p)) { p := mul(p, 100) }
                break
            }
            let t := mulmod(mul(z, z), z, p)
            z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
        }
    }

    /// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
    function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
        if (x == y) return x;
        uint256 p = rawMul(x, y);
        if (y == rawDiv(p, x)) return sqrt(p);
        for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
            if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
        }
    }

    /// @dev Returns the factorial of `x`.
    function factorial(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := 1
            if iszero(lt(x, 58)) {
                mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                revert(0x1c, 0x04)
            }
            for {} x { x := sub(x, 1) } { z := mul(z, x) }
        }
    }

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    /// Returns 0 if `x` is zero.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        r = log2(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(r, 1), x))
        }
    }

    /// @dev Returns the log10 of `x`.
    /// Returns 0 if `x` is zero.
    function log10(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 100000000000000000000000000000000000000)) {
                x := div(x, 100000000000000000000000000000000000000)
                r := 38
            }
            if iszero(lt(x, 100000000000000000000)) {
                x := div(x, 100000000000000000000)
                r := add(r, 20)
            }
            if iszero(lt(x, 10000000000)) {
                x := div(x, 10000000000)
                r := add(r, 10)
            }
            if iszero(lt(x, 100000)) {
                x := div(x, 100000)
                r := add(r, 5)
            }
            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
        }
    }

    /// @dev Returns the log10 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log10Up(uint256 x) internal pure returns (uint256 r) {
        r = log10(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(exp(10, r), x))
        }
    }

    /// @dev Returns the log256 of `x`.
    /// Returns 0 if `x` is zero.
    function log256(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(shr(3, r), lt(0xff, shr(r, x)))
        }
    }

    /// @dev Returns the log256 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log256Up(uint256 x) internal pure returns (uint256 r) {
        r = log256(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(shl(3, r), 1), x))
        }
    }

    /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
    /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
    function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
        /// @solidity memory-safe-assembly
        assembly {
            mantissa := x
            if mantissa {
                if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                    mantissa := div(mantissa, 1000000000000000000000000000000000)
                    exponent := 33
                }
                if iszero(mod(mantissa, 10000000000000000000)) {
                    mantissa := div(mantissa, 10000000000000000000)
                    exponent := add(exponent, 19)
                }
                if iszero(mod(mantissa, 1000000000000)) {
                    mantissa := div(mantissa, 1000000000000)
                    exponent := add(exponent, 12)
                }
                if iszero(mod(mantissa, 1000000)) {
                    mantissa := div(mantissa, 1000000)
                    exponent := add(exponent, 6)
                }
                if iszero(mod(mantissa, 10000)) {
                    mantissa := div(mantissa, 10000)
                    exponent := add(exponent, 4)
                }
                if iszero(mod(mantissa, 100)) {
                    mantissa := div(mantissa, 100)
                    exponent := add(exponent, 2)
                }
                if iszero(mod(mantissa, 10)) {
                    mantissa := div(mantissa, 10)
                    exponent := add(exponent, 1)
                }
            }
        }
    }

    /// @dev Convenience function for packing `x` into a smaller number using `sci`.
    /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
    /// The `exponent` will be in bits [0..6] (the lower 7 bits).
    /// Use `SafeCastLib` to safely ensure that the `packed` number is small
    /// enough to fit in the desired unsigned integer type:
    /// ```
    ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
    /// ```
    function packSci(uint256 x) internal pure returns (uint256 packed) {
        (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
        /// @solidity memory-safe-assembly
        assembly {
            if shr(249, x) {
                mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                revert(0x1c, 0x04)
            }
            packed := or(shl(7, x), packed)
        }
    }

    /// @dev Convenience function for unpacking a packed number from `packSci`.
    function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
        unchecked {
            unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards zero.
    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = (x & y) + ((x ^ y) >> 1);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
    function avg(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = (x >> 1) + (y >> 1) + (x & y & 1);
        }
    }

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        unchecked {
            z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(int256 x, int256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), slt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), sgt(y, x)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
        }
    }

    /// @dev Returns greatest common divisor of `x` and `y`.
    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            for { z := x } y {} {
                let t := y
                y := mod(z, y)
                z := t
            }
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begin == end`, returns `t <= begin ? a : b`.
    function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
        internal
        pure
        returns (uint256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        unchecked {
            if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
            return a - fullMulDiv(a - b, t - begin, end - begin);
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begin == end`, returns `t <= begin ? a : b`.
    function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
        internal
        pure
        returns (int256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        // forgefmt: disable-next-item
        unchecked {
            if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
                uint256(t - begin), uint256(end - begin)));
            return int256(uint256(a) - fullMulDiv(uint256(a - b),
                uint256(t - begin), uint256(end - begin)));
        }
    }

    /// @dev Returns if `x` is an even number. Some people may need this.
    function isEven(uint256 x) internal pure returns (bool) {
        return x & uint256(1) == uint256(0);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RAW NUMBER OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(x, y)
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mod(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := smod(x, y)
        }
    }

    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := addmod(x, y, d)
        }
    }

    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mulmod(x, y, d)
        }
    }
}

lib/solady/src/utils/SafeTransferLib.sol

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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) {
                    revert(codesize(), codesize())
                } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {

            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount := mul( // The arguments of `mul` are evaluated from right to left.
                mload(0x20),
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` implements `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented := and( // The arguments of `and` are evaluated from right to left.
                gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
            )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
                mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
            ) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

lib/v4-core/src/interfaces/IExtsload.sol

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

/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
    /// @notice Called by external contracts to access granular pool state
    /// @param slot Key of slot to sload
    /// @return value The value of the slot as bytes32
    function extsload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access granular pool state
    /// @param startSlot Key of slot to start sloading from
    /// @param nSlots Number of slots to load into return value
    /// @return values List of loaded values.
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);

    /// @notice Called by external contracts to access sparse pool state
    /// @param slots List of slots to SLOAD from.
    /// @return values List of loaded values.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

lib/v4-core/src/interfaces/IExttload.sol

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

/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
    /// @notice Called by external contracts to access transient storage of the contract
    /// @param slot Key of slot to tload
    /// @return value The value of the slot as bytes32
    function exttload(bytes32 slot) external view returns (bytes32 value);

    /// @notice Called by external contracts to access sparse transient pool state
    /// @param slots List of slots to tload
    /// @return values List of loaded values
    function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}

lib/v4-core/src/interfaces/IHooks.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
    /// @notice The hook called before the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @return bytes4 The function selector for the hook
    function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);

    /// @notice The hook called after the state of a pool is initialized
    /// @param sender The initial msg.sender for the initialize call
    /// @param key The key for the pool being initialized
    /// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
    /// @param tick The current tick after the state of a pool is initialized
    /// @return bytes4 The function selector for the hook
    function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
        external
        returns (bytes4);

    /// @notice The hook called before liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is added
    /// @param sender The initial msg.sender for the add liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for adding liquidity
    /// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterAddLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after liquidity is removed
    /// @param sender The initial msg.sender for the remove liquidity call
    /// @param key The key for the pool
    /// @param params The parameters for removing liquidity
    /// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
    /// @param feesAccrued The fees accrued since the last time fees were collected from this position
    /// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterRemoveLiquidity(
        address sender,
        PoolKey calldata key,
        ModifyLiquidityParams calldata params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) external returns (bytes4, BalanceDelta);

    /// @notice The hook called before a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    /// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
    function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        returns (bytes4, BeforeSwapDelta, uint24);

    /// @notice The hook called after a swap
    /// @param sender The initial msg.sender for the swap call
    /// @param key The key for the pool
    /// @param params The parameters for the swap
    /// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
    /// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    /// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata hookData
    ) external returns (bytes4, int128);

    /// @notice The hook called before donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function beforeDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);

    /// @notice The hook called after donate
    /// @param sender The initial msg.sender for the donate call
    /// @param key The key for the pool
    /// @param amount0 The amount of token0 being donated
    /// @param amount1 The amount of token1 being donated
    /// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
    /// @return bytes4 The function selector for the hook
    function afterDonate(
        address sender,
        PoolKey calldata key,
        uint256 amount0,
        uint256 amount1,
        bytes calldata hookData
    ) external returns (bytes4);
}

lib/v4-core/src/interfaces/IPoolManager.sol

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

import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";

/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
    /// @notice Thrown when a currency is not netted out after the contract is unlocked
    error CurrencyNotSettled();

    /// @notice Thrown when trying to interact with a non-initialized pool
    error PoolNotInitialized();

    /// @notice Thrown when unlock is called, but the contract is already unlocked
    error AlreadyUnlocked();

    /// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
    error ManagerLocked();

    /// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
    error TickSpacingTooLarge(int24 tickSpacing);

    /// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
    error TickSpacingTooSmall(int24 tickSpacing);

    /// @notice PoolKey must have currencies where address(currency0) < address(currency1)
    error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);

    /// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
    /// or on a pool that does not have a dynamic swap fee.
    error UnauthorizedDynamicLPFeeUpdate();

    /// @notice Thrown when trying to swap amount of 0
    error SwapAmountCannotBeZero();

    ///@notice Thrown when native currency is passed to a non native settlement
    error NonzeroNativeValue();

    /// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
    error MustClearExactPositiveDelta();

    /// @notice Emitted when a new pool is initialized
    /// @param id The abi encoded hash of the pool key struct for the new pool
    /// @param currency0 The first currency of the pool by address sort order
    /// @param currency1 The second currency of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param hooks The hooks contract address for the pool, or address(0) if none
    /// @param sqrtPriceX96 The price of the pool on initialization
    /// @param tick The initial tick of the pool corresponding to the initialized price
    event Initialize(
        PoolId indexed id,
        Currency indexed currency0,
        Currency indexed currency1,
        uint24 fee,
        int24 tickSpacing,
        IHooks hooks,
        uint160 sqrtPriceX96,
        int24 tick
    );

    /// @notice Emitted when a liquidity position is modified
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that modified the pool
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param liquidityDelta The amount of liquidity that was added or removed
    /// @param salt The extra data to make positions unique
    event ModifyLiquidity(
        PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
    );

    /// @notice Emitted for swaps between currency0 and currency1
    /// @param id The abi encoded hash of the pool key struct for the pool that was modified
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param amount0 The delta of the currency0 balance of the pool
    /// @param amount1 The delta of the currency1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of the price of the pool after the swap
    /// @param fee The swap fee in hundredths of a bip
    event Swap(
        PoolId indexed id,
        address indexed sender,
        int128 amount0,
        int128 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick,
        uint24 fee
    );

    /// @notice Emitted for donations
    /// @param id The abi encoded hash of the pool key struct for the pool that was donated to
    /// @param sender The address that initiated the donate call
    /// @param amount0 The amount donated in currency0
    /// @param amount1 The amount donated in currency1
    event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);

    /// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
    /// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
    /// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
    /// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
    /// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
    function unlock(bytes calldata data) external returns (bytes memory);

    /// @notice Initialize the state for a given pool ID
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The pool key for the pool to initialize
    /// @param sqrtPriceX96 The initial square root price
    /// @return tick The initial tick of the pool
    function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);

    /// @notice Modify the liquidity for the given pool
    /// @dev Poke by calling with a zero liquidityDelta
    /// @param key The pool to modify liquidity in
    /// @param params The parameters for modifying the liquidity
    /// @param hookData The data to pass through to the add/removeLiquidity hooks
    /// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
    /// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
    /// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
    /// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
    /// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
    function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);

    /// @notice Swap against the given pool
    /// @param key The pool to swap in
    /// @param params The parameters for swapping
    /// @param hookData The data to pass through to the swap hooks
    /// @return swapDelta The balance delta of the address swapping
    /// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
    /// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
    /// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        external
        returns (BalanceDelta swapDelta);

    /// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
    /// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
    /// Donors should keep this in mind when designing donation mechanisms.
    /// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
    /// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
    /// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
    /// Read the comments in `Pool.swap()` for more information about this.
    /// @param key The key of the pool to donate to
    /// @param amount0 The amount of currency0 to donate
    /// @param amount1 The amount of currency1 to donate
    /// @param hookData The data to pass through to the donate hooks
    /// @return BalanceDelta The delta of the caller after the donate
    function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        external
        returns (BalanceDelta);

    /// @notice Writes the current ERC20 balance of the specified currency to transient storage
    /// This is used to checkpoint balances for the manager and derive deltas for the caller.
    /// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
    /// for native tokens because the amount to settle is determined by the sent value.
    /// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
    /// native funds, this function can be called with the native currency to then be able to settle the native currency
    function sync(Currency currency) external;

    /// @notice Called by the user to net out some value owed to the user
    /// @dev Will revert if the requested amount is not available, consider using `mint` instead
    /// @dev Can also be used as a mechanism for free flash loans
    /// @param currency The currency to withdraw from the pool manager
    /// @param to The address to withdraw to
    /// @param amount The amount of currency to withdraw
    function take(Currency currency, address to, uint256 amount) external;

    /// @notice Called by the user to pay what is owed
    /// @return paid The amount of currency settled
    function settle() external payable returns (uint256 paid);

    /// @notice Called by the user to pay on behalf of another address
    /// @param recipient The address to credit for the payment
    /// @return paid The amount of currency settled
    function settleFor(address recipient) external payable returns (uint256 paid);

    /// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
    /// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
    /// @dev This could be used to clear a balance that is considered dust.
    /// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
    function clear(Currency currency, uint256 amount) external;

    /// @notice Called by the user to move value into ERC6909 balance
    /// @param to The address to mint the tokens to
    /// @param id The currency address to mint to ERC6909s, as a uint256
    /// @param amount The amount of currency to mint
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function mint(address to, uint256 id, uint256 amount) external;

    /// @notice Called by the user to move value from ERC6909 balance
    /// @param from The address to burn the tokens from
    /// @param id The currency address to burn from ERC6909s, as a uint256
    /// @param amount The amount of currency to burn
    /// @dev The id is converted to a uint160 to correspond to a currency address
    /// If the upper 12 bytes are not 0, they will be 0-ed out
    function burn(address from, uint256 id, uint256 amount) external;

    /// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
    /// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
    /// @param key The key of the pool to update dynamic LP fees for
    /// @param newDynamicLPFee The new dynamic pool LP fee
    function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}

lib/v4-core/src/interfaces/IProtocolFees.sol

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

import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";

/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
    /// @notice Thrown when protocol fee is set too high
    error ProtocolFeeTooLarge(uint24 fee);

    /// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
    error InvalidCaller();

    /// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
    error ProtocolFeeCurrencySynced();

    /// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
    event ProtocolFeeControllerUpdated(address indexed protocolFeeController);

    /// @notice Emitted when the protocol fee is updated for a pool.
    event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);

    /// @notice Given a currency address, returns the protocol fees accrued in that currency
    /// @param currency The currency to check
    /// @return amount The amount of protocol fees accrued in the currency
    function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);

    /// @notice Sets the protocol fee for the given pool
    /// @param key The key of the pool to set a protocol fee for
    /// @param newProtocolFee The fee to set
    function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;

    /// @notice Sets the protocol fee controller
    /// @param controller The new protocol fee controller
    function setProtocolFeeController(address controller) external;

    /// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
    /// @dev This will revert if the contract is unlocked
    /// @param recipient The address to receive the protocol fees
    /// @param currency The currency to withdraw
    /// @param amount The amount of currency to withdraw
    /// @return amountCollected The amount of currency successfully withdrawn
    function collectProtocolFees(address recipient, Currency currency, uint256 amount)
        external
        returns (uint256 amountCollected);

    /// @notice Returns the current protocol fee controller address
    /// @return address The current protocol fee controller address
    function protocolFeeController() external view returns (address);
}

lib/v4-core/src/interfaces/callback/IUnlockCallback.sol

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

/// @notice Interface for the callback executed when an address unlocks the pool manager
interface IUnlockCallback {
    /// @notice Called by the pool manager on `msg.sender` when the manager is unlocked
    /// @param data The data that was passed to the call to unlock
    /// @return Any data that you want to be returned from the unlock call
    function unlockCallback(bytes calldata data) external returns (bytes memory);
}

lib/v4-core/src/interfaces/external/IERC20Minimal.sol

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

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns an account's balance in the token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

lib/v4-core/src/interfaces/external/IERC6909Claims.sol

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

/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
    /*//////////////////////////////////////////////////////////////
                                 EVENTS
    //////////////////////////////////////////////////////////////*/

    event OperatorSet(address indexed owner, address indexed operator, bool approved);

    event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);

    event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);

    /*//////////////////////////////////////////////////////////////
                                 FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    /// @notice Owner balance of an id.
    /// @param owner The address of the owner.
    /// @param id The id of the token.
    /// @return amount The balance of the token.
    function balanceOf(address owner, uint256 id) external view returns (uint256 amount);

    /// @notice Spender allowance of an id.
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @return amount The allowance of the token.
    function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);

    /// @notice Checks if a spender is approved by an owner as an operator
    /// @param owner The address of the owner.
    /// @param spender The address of the spender.
    /// @return approved The approval status.
    function isOperator(address owner, address spender) external view returns (bool approved);

    /// @notice Transfers an amount of an id from the caller to a receiver.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Transfers an amount of an id from a sender to a receiver.
    /// @param sender The address of the sender.
    /// @param receiver The address of the receiver.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always, unless the function reverts
    function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);

    /// @notice Approves an amount of an id to a spender.
    /// @param spender The address of the spender.
    /// @param id The id of the token.
    /// @param amount The amount of the token.
    /// @return bool True, always
    function approve(address spender, uint256 id, uint256 amount) external returns (bool);

    /// @notice Sets or removes an operator for the caller.
    /// @param operator The address of the operator.
    /// @param approved The approval status.
    /// @return bool True, always
    function setOperator(address operator, bool approved) external returns (bool);
}

lib/v4-core/src/libraries/BitMath.sol

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

/// @title BitMath
/// @dev This library provides functionality for computing bit properties of an unsigned integer
/// @author Solady (https://github.com/Vectorized/solady/blob/8200a70e8dc2a77ecb074fc2e99a2a0d36547522/src/utils/LibBit.sol)
library BitMath {
    /// @notice Returns the index of the most significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the most significant bit, must be greater than 0
    /// @return r the index of the most significant bit
    function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020500060203020504000106050205030304010505030400000000))
        }
    }

    /// @notice Returns the index of the least significant bit of the number,
    ///     where the least significant bit is at index 0 and the most significant bit is at index 255
    /// @param x the value for which to compute the least significant bit, must be greater than 0
    /// @return r the index of the least significant bit
    function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
        require(x > 0);

        assembly ("memory-safe") {
            // Isolate the least significant bit.
            x := and(x, sub(0, x))
            // For the upper 3 bits of the result, use a De Bruijn-like lookup.
            // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/
            // forgefmt: disable-next-item
            r := shl(5, shr(252, shl(shl(2, shr(250, mul(x,
                0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))),
                0x8040405543005266443200005020610674053026020000107506200176117077)))
            // For the lower 5 bits of the result, use a De Bruijn lookup.
            // forgefmt: disable-next-item
            r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f),
                0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405))
        }
    }
}

lib/v4-core/src/libraries/CurrencyReserves.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

import {Currency} from "../types/Currency.sol";
import {CustomRevert} from "./CustomRevert.sol";

library CurrencyReserves {
    using CustomRevert for bytes4;

    /// bytes32(uint256(keccak256("ReservesOf")) - 1)
    bytes32 constant RESERVES_OF_SLOT = 0x1e0745a7db1623981f0b2a5d4232364c00787266eb75ad546f190e6cebe9bd95;
    /// bytes32(uint256(keccak256("Currency")) - 1)
    bytes32 constant CURRENCY_SLOT = 0x27e098c505d44ec3574004bca052aabf76bd35004c182099d8c575fb238593b9;

    function getSyncedCurrency() internal view returns (Currency currency) {
        assembly ("memory-safe") {
            currency := tload(CURRENCY_SLOT)
        }
    }

    function resetCurrency() internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, 0)
        }
    }

    function syncCurrencyAndReserves(Currency currency, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(CURRENCY_SLOT, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            tstore(RESERVES_OF_SLOT, value)
        }
    }

    function getSyncedReserves() internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(RESERVES_OF_SLOT)
        }
    }
}

lib/v4-core/src/libraries/CustomRevert.sol

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

/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
    /// @dev ERC-7751 error for wrapping bubbled up reverts
    error WrappedError(address target, bytes4 selector, bytes reason, bytes details);

    /// @dev Reverts with the selector of a custom error in the scratch space
    function revertWith(bytes4 selector) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            revert(0, 0x04)
        }
    }

    /// @dev Reverts with a custom error with an address argument in the scratch space
    function revertWith(bytes4 selector, address addr) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with an int24 argument in the scratch space
    function revertWith(bytes4 selector, int24 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, signextend(2, value))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with a uint160 argument in the scratch space
    function revertWith(bytes4 selector, uint160 value) internal pure {
        assembly ("memory-safe") {
            mstore(0, selector)
            mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(0, 0x24)
        }
    }

    /// @dev Reverts with a custom error with two int24 arguments
    function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), signextend(2, value1))
            mstore(add(fmp, 0x24), signextend(2, value2))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two uint160 arguments
    function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @dev Reverts with a custom error with two address arguments
    function revertWith(bytes4 selector, address value1, address value2) internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(fmp, selector)
            mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
            revert(fmp, 0x44)
        }
    }

    /// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
    /// @dev this method can be vulnerable to revert data bombs
    function bubbleUpAndRevertWith(
        address revertingContract,
        bytes4 revertingFunctionSelector,
        bytes4 additionalContext
    ) internal pure {
        bytes4 wrappedErrorSelector = WrappedError.selector;
        assembly ("memory-safe") {
            // Ensure the size of the revert data is a multiple of 32 bytes
            let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)

            let fmp := mload(0x40)

            // Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
            mstore(fmp, wrappedErrorSelector)
            mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(
                add(fmp, 0x24),
                and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            // offset revert reason
            mstore(add(fmp, 0x44), 0x80)
            // offset additional context
            mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
            // size revert reason
            mstore(add(fmp, 0x84), returndatasize())
            // revert reason
            returndatacopy(add(fmp, 0xa4), 0, returndatasize())
            // size additional context
            mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
            // additional context
            mstore(
                add(fmp, add(0xc4, encodedDataSize)),
                and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
            )
            revert(fmp, add(0xe4, encodedDataSize))
        }
    }
}

lib/v4-core/src/libraries/FixedPoint128.sol

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

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}

lib/v4-core/src/libraries/FixedPoint96.sol

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

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

lib/v4-core/src/libraries/FullMath.sol

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

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2**256 + prod0
            uint256 prod0 = a * b; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly ("memory-safe") {
                let mm := mulmod(a, b, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

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

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

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

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

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

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

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

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            result = mulDiv(a, b, denominator);
            if (mulmod(a, b, denominator) != 0) {
                require(++result > 0);
            }
        }
    }
}

lib/v4-core/src/libraries/Hooks.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
library Hooks {
    using LPFeeLibrary for uint24;
    using Hooks for IHooks;
    using SafeCast for int256;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using ParseBytes for bytes;
    using CustomRevert for bytes4;

    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);

    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;

    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;

    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;

    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;

    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;

    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;

    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 Thrown if the address will not lead to the specified hook calls being called
    /// @param hooks The address of the hooks contract
    error HookAddressNotValid(address hooks);

    /// @notice Hook did not return its selector
    error InvalidHookResponse();

    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails
    error HookCallFailed();

    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
    error HookDeltaExceedsSwapAmount();

    /// @notice Utility function intended to be used in hook constructors to ensure
    /// the deployed hooks address causes the intended hooks to be called
    /// @param permissions The hooks that are intended to be called
    /// @dev permissions param is memory as the function will be called from constructors
    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
        if (
            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                || permissions.afterRemoveLiquidityReturnDelta
                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) {
            HookAddressNotValid.selector.revertWith(address(self));
        }
    }

    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
    /// @param self The hook to verify
    /// @param fee The fee of the pool the hook is used with
    /// @return bool True if the hook address is valid
    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
        {
            return false;
        }
        if (
            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) return false;

        // If there is no hook contract set, then fee cannot be dynamic
        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
        return address(self) == address(0)
            ? !fee.isDynamicFee()
            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
    }

    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
    /// @return result The complete data returned by the hook
    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
        bool success;
        assembly ("memory-safe") {
            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
        }
        // Revert with FailedHookCall, containing any error message to bubble up
        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);

        // The call was successful, fetch the returned data
        assembly ("memory-safe") {
            // allocate result byte array from the free memory pointer
            result := mload(0x40)
            // store new free memory pointer at the end of the array padded to 32 bytes
            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
            // store length in memory
            mstore(result, returndatasize())
            // copy return data to result
            returndatacopy(add(result, 0x20), 0, returndatasize())
        }

        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
            InvalidHookResponse.selector.revertWith();
        }
    }

    /// @notice performs a hook call using the given calldata on the given hook
    /// @return int256 The delta returned by the hook
    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
        bytes memory result = callHook(self, data);

        // If this hook wasn't meant to return something, default to 0 delta
        if (!parseReturn) return 0;

        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta
        if (result.length != 64) InvalidHookResponse.selector.revertWith();
        return result.parseReturnDelta();
    }

    /// @notice modifier to prevent calling a hook if they initiated the action
    modifier noSelfCall(IHooks self) {
        if (msg.sender != address(self)) {
            _;
        }
    }

    /// @notice calls beforeInitialize hook if permissioned and validates return value
    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
        }
    }

    /// @notice calls afterInitialize hook if permissioned and validates return value
    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
        }
    }

    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
    function beforeModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        bytes calldata hookData
    ) internal noSelfCall(self) {
        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
        }
    }

    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value
    function afterModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);

        callerDelta = delta;
        if (params.liquidityDelta > 0) {
            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        } else {
            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        }
    }

    /// @notice calls beforeSwap hook if permissioned and validates return value
    function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        internal
        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
    {
        amountToSwap = params.amountSpecified;
        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);

        if (self.hasPermission(BEFORE_SWAP_FLAG)) {
            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));

            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
            if (result.length != 96) InvalidHookResponse.selector.revertWith();

            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();

            // skip this logic for the case where the hook return is 0
            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());

                // any return in unspecified is passed to the afterSwap hook for handling
                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();

                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
                if (hookDeltaSpecified != 0) {
                    bool exactInput = amountToSwap < 0;
                    amountToSwap += hookDeltaSpecified;
                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
                        HookDeltaExceedsSwapAmount.selector.revertWith();
                    }
                }
            }
        }
    }

    /// @notice calls afterSwap hook if permissioned and validates return value
    function afterSwap(
        IHooks self,
        PoolKey memory key,
        SwapParams memory params,
        BalanceDelta swapDelta,
        bytes calldata hookData,
        BeforeSwapDelta beforeSwapHookReturn
    ) internal returns (BalanceDelta, BalanceDelta) {
        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);

        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();

        if (self.hasPermission(AFTER_SWAP_FLAG)) {
            hookDeltaUnspecified += self.callHookWithReturnDelta(
                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
            ).toInt128();
        }

        BalanceDelta hookDelta;
        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);

            // the caller has to pay for (or receive) the hook's delta
            swapDelta = swapDelta - hookDelta;
        }
        return (swapDelta, hookDelta);
    }

    /// @notice calls beforeDonate hook if permissioned and validates return value
    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(BEFORE_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    /// @notice calls afterDonate hook if permissioned and validates return value
    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
        return uint160(address(self)) & flag != 0;
    }
}

lib/v4-core/src/libraries/LPFeeLibrary.sol

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

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

/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
    using LPFeeLibrary for uint24;
    using CustomRevert for bytes4;

    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
    error LPFeeTooLarge(uint24 fee);

    /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;

    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
    uint24 public constant MAX_LP_FEE = 1000000;

    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
    /// @param self The fee to check
    /// @return bool True of the fee is dynamic
    function isDynamicFee(uint24 self) internal pure returns (bool) {
        return self == DYNAMIC_FEE_FLAG;
    }

    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
    /// @param self The fee to check
    /// @return bool True of the fee is valid
    function isValid(uint24 self) internal pure returns (bool) {
        return self <= MAX_LP_FEE;
    }

    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
    /// @param self The fee to validate
    function validate(uint24 self) internal pure {
        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
    }

    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
    /// @param self The fee to get the initial LP from
    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
    function getInitialLPFee(uint24 self) internal pure returns (uint24) {
        // the initial fee for a dynamic fee pool is 0
        if (self.isDynamicFee()) return 0;
        self.validate();
        return self;
    }

    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
    /// @param self The fee to check
    /// @return bool True of the fee has the override flag set
    function isOverride(uint24 self) internal pure returns (bool) {
        return self & OVERRIDE_FEE_FLAG != 0;
    }

    /// @notice returns a fee with the override flag removed
    /// @param self The fee to remove the override flag from
    /// @return fee The fee without the override flag set
    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
        return self & REMOVE_OVERRIDE_MASK;
    }

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
        fee = self.removeOverrideFlag();
        fee.validate();
    }
}

lib/v4-core/src/libraries/LiquidityMath.sol

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

/// @title Math library for liquidity
library LiquidityMath {
    /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows
    /// @param x The liquidity before change
    /// @param y The delta by which liquidity should be changed
    /// @return z The liquidity delta
    function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {
        assembly ("memory-safe") {
            z := add(and(x, 0xffffffffffffffffffffffffffffffff), signextend(15, y))
            if shr(128, z) {
                // revert SafeCastOverflow()
                mstore(0, 0x93dafdf1)
                revert(0x1c, 0x04)
            }
        }
    }
}

lib/v4-core/src/libraries/Lock.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library Lock {
    // The slot holding the unlocked state, transiently. bytes32(uint256(keccak256("Unlocked")) - 1)
    bytes32 internal constant IS_UNLOCKED_SLOT = 0xc090fc4683624cfc3884e9d8de5eca132f2d0ec062aff75d43c0465d5ceeab23;

    function unlock() internal {
        assembly ("memory-safe") {
            // unlock
            tstore(IS_UNLOCKED_SLOT, true)
        }
    }

    function lock() internal {
        assembly ("memory-safe") {
            tstore(IS_UNLOCKED_SLOT, false)
        }
    }

    function isUnlocked() internal view returns (bool unlocked) {
        assembly ("memory-safe") {
            unlocked := tload(IS_UNLOCKED_SLOT)
        }
    }
}

lib/v4-core/src/libraries/NonzeroDeltaCount.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;

/// @notice This is a temporary library that allows us to use transient storage (tstore/tload)
/// for the nonzero delta count.
/// TODO: This library can be deleted when we have the transient keyword support in solidity.
library NonzeroDeltaCount {
    // The slot holding the number of nonzero deltas. bytes32(uint256(keccak256("NonzeroDeltaCount")) - 1)
    bytes32 internal constant NONZERO_DELTA_COUNT_SLOT =
        0x7d4b3164c6e45b97e7d87b7125a44c5828d005af88f9d751cfd78729c5d99a0b;

    function read() internal view returns (uint256 count) {
        assembly ("memory-safe") {
            count := tload(NONZERO_DELTA_COUNT_SLOT)
        }
    }

    function increment() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := add(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }

    /// @notice Potential to underflow. Ensure checks are performed by integrating contracts to ensure this does not happen.
    /// Current usage ensures this will not happen because we call decrement with known boundaries (only up to the number of times we call increment).
    function decrement() internal {
        assembly ("memory-safe") {
            let count := tload(NONZERO_DELTA_COUNT_SLOT)
            count := sub(count, 1)
            tstore(NONZERO_DELTA_COUNT_SLOT, count)
        }
    }
}

lib/v4-core/src/libraries/ParseBytes.sol

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            selector := mload(add(result, 0x20))
        }
    }

    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
        assembly ("memory-safe") {
            lpFee := mload(add(result, 0x60))
        }
    }

    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            hookReturn := mload(add(result, 0x40))
        }
    }
}

lib/v4-core/src/libraries/Position.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;

import {FullMath} from "./FullMath.sol";
import {FixedPoint128} from "./FixedPoint128.sol";
import {LiquidityMath} from "./LiquidityMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Position
/// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary
/// @dev Positions store additional state for tracking fees owed to the position
library Position {
    using CustomRevert for bytes4;

    /// @notice Cannot update a position with no liquidity
    error CannotUpdateEmptyPosition();

    // info stored for each user's position
    struct State {
        // the amount of liquidity owned by this position
        uint128 liquidity;
        // fee growth per unit of liquidity as of the last update to liquidity or fees owed
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
    }

    /// @notice Returns the State struct of a position, given an owner and position boundaries
    /// @param self The mapping containing all user positions
    /// @param owner The address of the position owner
    /// @param tickLower The lower tick boundary of the position
    /// @param tickUpper The upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range
    /// @return position The position info struct of the given owners' position
    function get(mapping(bytes32 => State) storage self, address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        view
        returns (State storage position)
    {
        bytes32 positionKey = calculatePositionKey(owner, tickLower, tickUpper, salt);
        position = self[positionKey];
    }

    /// @notice A helper function to calculate the position key
    /// @param owner The address of the position owner
    /// @param tickLower the lower tick boundary of the position
    /// @param tickUpper the upper tick boundary of the position
    /// @param salt A unique value to differentiate between multiple positions in the same range, by the same owner. Passed in by the caller.
    function calculatePositionKey(address owner, int24 tickLower, int24 tickUpper, bytes32 salt)
        internal
        pure
        returns (bytes32 positionKey)
    {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(add(fmp, 0x26), salt) // [0x26, 0x46)
            mstore(add(fmp, 0x06), tickUpper) // [0x23, 0x26)
            mstore(add(fmp, 0x03), tickLower) // [0x20, 0x23)
            mstore(fmp, owner) // [0x0c, 0x20)
            positionKey := keccak256(add(fmp, 0x0c), 0x3a) // len is 58 bytes

            // now clean the memory we used
            mstore(add(fmp, 0x40), 0) // fmp+0x40 held salt
            mstore(add(fmp, 0x20), 0) // fmp+0x20 held tickLower, tickUpper, salt
            mstore(fmp, 0) // fmp held owner
        }
    }

    /// @notice Credits accumulated fees to a user's position
    /// @param self The individual position to update
    /// @param liquidityDelta The change in pool liquidity as a result of the position update
    /// @param feeGrowthInside0X128 The all-time fee growth in currency0, per unit of liquidity, inside the position's tick boundaries
    /// @param feeGrowthInside1X128 The all-time fee growth in currency1, per unit of liquidity, inside the position's tick boundaries
    /// @return feesOwed0 The amount of currency0 owed to the position owner
    /// @return feesOwed1 The amount of currency1 owed to the position owner
    function update(
        State storage self,
        int128 liquidityDelta,
        uint256 feeGrowthInside0X128,
        uint256 feeGrowthInside1X128
    ) internal returns (uint256 feesOwed0, uint256 feesOwed1) {
        uint128 liquidity = self.liquidity;

        if (liquidityDelta == 0) {
            // disallow pokes for 0 liquidity positions
            if (liquidity == 0) CannotUpdateEmptyPosition.selector.revertWith();
        } else {
            self.liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta);
        }

        // calculate accumulated fees. overflow in the subtraction of fee growth is expected
        unchecked {
            feesOwed0 =
                FullMath.mulDiv(feeGrowthInside0X128 - self.feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128);
            feesOwed1 =
                FullMath.mulDiv(feeGrowthInside1X128 - self.feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128);
        }

        // update the position
        self.feeGrowthInside0LastX128 = feeGrowthInside0X128;
        self.feeGrowthInside1LastX128 = feeGrowthInside1X128;
    }
}

lib/v4-core/src/libraries/SafeCast.sol

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

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

/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
    using CustomRevert for bytes4;

    error SafeCastOverflow();

    /// @notice Cast a uint256 to a uint160, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint160
    function toUint160(uint256 x) internal pure returns (uint160 y) {
        y = uint160(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a uint128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return y The downcasted integer, now type uint128
    function toUint128(uint256 x) internal pure returns (uint128 y) {
        y = uint128(x);
        if (x != y) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a int128 to a uint128, revert on overflow or underflow
    /// @param x The int128 to be casted
    /// @return y The casted integer, now type uint128
    function toUint128(int128 x) internal pure returns (uint128 y) {
        if (x < 0) SafeCastOverflow.selector.revertWith();
        y = uint128(x);
    }

    /// @notice Cast a int256 to a int128, revert on overflow or underflow
    /// @param x The int256 to be downcasted
    /// @return y The downcasted integer, now type int128
    function toInt128(int256 x) internal pure returns (int128 y) {
        y = int128(x);
        if (y != x) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int256, revert on overflow
    /// @param x The uint256 to be casted
    /// @return y The casted integer, now type int256
    function toInt256(uint256 x) internal pure returns (int256 y) {
        y = int256(x);
        if (y < 0) SafeCastOverflow.selector.revertWith();
    }

    /// @notice Cast a uint256 to a int128, revert on overflow
    /// @param x The uint256 to be downcasted
    /// @return The downcasted integer, now type int128
    function toInt128(uint256 x) internal pure returns (int128) {
        if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
        return int128(int256(x));
    }
}

lib/v4-core/src/libraries/SqrtPriceMath.sol

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

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

import {FullMath} from "./FullMath.sol";
import {UnsafeMath} from "./UnsafeMath.sol";
import {FixedPoint96} from "./FixedPoint96.sol";

/// @title Functions based on Q64.96 sqrt price and liquidity
/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas
library SqrtPriceMath {
    using SafeCast for uint256;

    error InvalidPriceOrLiquidity();
    error InvalidPrice();
    error NotEnoughLiquidity();
    error PriceOverflow();

    /// @notice Gets the next sqrt price given a delta of currency0
    /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the
    /// price less in order to not send too much output.
    /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),
    /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).
    /// @param sqrtPX96 The starting price, i.e. before accounting for the currency0 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency0 to add or remove from virtual reserves
    /// @param add Whether to add or remove the amount of currency0
    /// @return The price after adding or removing amount, depending on add
    function getNextSqrtPriceFromAmount0RoundingUp(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price
        if (amount == 0) return sqrtPX96;
        uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;

        if (add) {
            unchecked {
                uint256 product = amount * sqrtPX96;
                if (product / amount == sqrtPX96) {
                    uint256 denominator = numerator1 + product;
                    if (denominator >= numerator1) {
                        // always fits in 160 bits
                        return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));
                    }
                }
            }
            // denominator is checked for overflow
            return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96) + amount));
        } else {
            unchecked {
                uint256 product = amount * sqrtPX96;
                // if the product overflows, we know the denominator underflows
                // in addition, we must check that the denominator does not underflow
                // equivalent: if (product / amount != sqrtPX96 || numerator1 <= product) revert PriceOverflow();
                assembly ("memory-safe") {
                    if iszero(
                        and(
                            eq(div(product, amount), and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                            gt(numerator1, product)
                        )
                    ) {
                        mstore(0, 0xf5c787f1) // selector for PriceOverflow()
                        revert(0x1c, 0x04)
                    }
                }
                uint256 denominator = numerator1 - product;
                return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();
            }
        }
    }

    /// @notice Gets the next sqrt price given a delta of currency1
    /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least
    /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the
    /// price less in order to not send too much output.
    /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity
    /// @param sqrtPX96 The starting price, i.e., before accounting for the currency1 delta
    /// @param liquidity The amount of usable liquidity
    /// @param amount How much of currency1 to add, or remove, from virtual reserves
    /// @param add Whether to add, or remove, the amount of currency1
    /// @return The price after adding or removing `amount`
    function getNextSqrtPriceFromAmount1RoundingDown(uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add)
        internal
        pure
        returns (uint160)
    {
        // if we're adding (subtracting), rounding down requires rounding the quotient down (up)
        // in both cases, avoid a mulDiv for most inputs
        if (add) {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? (amount << FixedPoint96.RESOLUTION) / liquidity
                    : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)
            );

            return (uint256(sqrtPX96) + quotient).toUint160();
        } else {
            uint256 quotient = (
                amount <= type(uint160).max
                    ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)
                    : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)
            );

            // equivalent: if (sqrtPX96 <= quotient) revert NotEnoughLiquidity();
            assembly ("memory-safe") {
                if iszero(gt(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff), quotient)) {
                    mstore(0, 0x4323a555) // selector for NotEnoughLiquidity()
                    revert(0x1c, 0x04)
                }
            }
            // always fits 160 bits
            unchecked {
                return uint160(sqrtPX96 - quotient);
            }
        }
    }

    /// @notice Gets the next sqrt price given an input amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds
    /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountIn How much of currency0, or currency1, is being swapped in
    /// @param zeroForOne Whether the amount in is currency0 or currency1
    /// @return uint160 The price after adding the input amount to currency0 or currency1
    function getNextSqrtPriceFromInput(uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(
                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we don't pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)
            : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);
    }

    /// @notice Gets the next sqrt price given an output amount of currency0 or currency1
    /// @dev Throws if price or liquidity are 0 or the next price is out of bounds
    /// @param sqrtPX96 The starting price before accounting for the output amount
    /// @param liquidity The amount of usable liquidity
    /// @param amountOut How much of currency0, or currency1, is being swapped out
    /// @param zeroForOne Whether the amount out is currency1 or currency0
    /// @return uint160 The price after removing the output amount of currency0 or currency1
    function getNextSqrtPriceFromOutput(uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne)
        internal
        pure
        returns (uint160)
    {
        // equivalent: if (sqrtPX96 == 0 || liquidity == 0) revert InvalidPriceOrLiquidity();
        assembly ("memory-safe") {
            if or(
                iszero(and(sqrtPX96, 0xffffffffffffffffffffffffffffffffffffffff)),
                iszero(and(liquidity, 0xffffffffffffffffffffffffffffffff))
            ) {
                mstore(0, 0x4f2461b8) // selector for InvalidPriceOrLiquidity()
                revert(0x1c, 0x04)
            }
        }

        // round to make sure that we pass the target price
        return zeroForOne
            ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)
            : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);
    }

    /// @notice Gets the amount0 delta between two prices
    /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
    /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up or down
    /// @return uint256 Amount of currency0 required to cover a position of size liquidity between the two passed prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
        internal
        pure
        returns (uint256)
    {
        unchecked {
            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);

            // equivalent: if (sqrtPriceAX96 == 0) revert InvalidPrice();
            assembly ("memory-safe") {
                if iszero(and(sqrtPriceAX96, 0xffffffffffffffffffffffffffffffffffffffff)) {
                    mstore(0, 0x00bfc921) // selector for InvalidPrice()
                    revert(0x1c, 0x04)
                }
            }

            uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;
            uint256 numerator2 = sqrtPriceBX96 - sqrtPriceAX96;

            return roundUp
                ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtPriceBX96), sqrtPriceAX96)
                : FullMath.mulDiv(numerator1, numerator2, sqrtPriceBX96) / sqrtPriceAX96;
        }
    }

    /// @notice Equivalent to: `a >= b ? a - b : b - a`
    function absDiff(uint160 a, uint160 b) internal pure returns (uint256 res) {
        assembly ("memory-safe") {
            let diff :=
                sub(and(a, 0xffffffffffffffffffffffffffffffffffffffff), and(b, 0xffffffffffffffffffffffffffffffffffffffff))
            // mask = 0 if a >= b else -1 (all 1s)
            let mask := sar(255, diff)
            // if a >= b, res = a - b = 0 ^ (a - b)
            // if a < b, res = b - a = ~~(b - a) = ~(-(b - a) - 1) = ~(a - b - 1) = (-1) ^ (a - b - 1)
            // either way, res = mask ^ (a - b + mask)
            res := xor(mask, add(mask, diff))
        }
    }

    /// @notice Gets the amount1 delta between two prices
    /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The amount of usable liquidity
    /// @param roundUp Whether to round the amount up, or down
    /// @return amount1 Amount of currency1 required to cover a position of size liquidity between the two passed prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint128 liquidity, bool roundUp)
        internal
        pure
        returns (uint256 amount1)
    {
        uint256 numerator = absDiff(sqrtPriceAX96, sqrtPriceBX96);
        uint256 denominator = FixedPoint96.Q96;
        uint256 _liquidity = uint256(liquidity);

        /**
         * Equivalent to:
         *   amount1 = roundUp
         *       ? FullMath.mulDivRoundingUp(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96)
         *       : FullMath.mulDiv(liquidity, sqrtPriceBX96 - sqrtPriceAX96, FixedPoint96.Q96);
         * Cannot overflow because `type(uint128).max * type(uint160).max >> 96 < (1 << 192)`.
         */
        amount1 = FullMath.mulDiv(_liquidity, numerator, denominator);
        assembly ("memory-safe") {
            amount1 := add(amount1, and(gt(mulmod(_liquidity, numerator, denominator), 0), roundUp))
        }
    }

    /// @notice Helper that gets signed currency0 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount0 delta
    /// @return int256 Amount of currency0 corresponding to the passed liquidityDelta between the two prices
    function getAmount0Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount0Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }

    /// @notice Helper that gets signed currency1 delta
    /// @param sqrtPriceAX96 A sqrt price
    /// @param sqrtPriceBX96 Another sqrt price
    /// @param liquidity The change in liquidity for which to compute the amount1 delta
    /// @return int256 Amount of currency1 corresponding to the passed liquidityDelta between the two prices
    function getAmount1Delta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity)
        internal
        pure
        returns (int256)
    {
        unchecked {
            return liquidity < 0
                ? getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(-liquidity), false).toInt256()
                : -getAmount1Delta(sqrtPriceAX96, sqrtPriceBX96, uint128(liquidity), true).toInt256();
        }
    }
}

lib/v4-core/src/libraries/StateLibrary.sol

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

import {PoolId} from "../types/PoolId.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Position} from "./Position.sol";

/// @notice A helper library to provide state getters that use extsload
library StateLibrary {
    /// @notice index of pools mapping in the PoolManager
    bytes32 public constant POOLS_SLOT = bytes32(uint256(6));

    /// @notice index of feeGrowthGlobal0X128 in Pool.State
    uint256 public constant FEE_GROWTH_GLOBAL0_OFFSET = 1;

    // feeGrowthGlobal1X128 offset in Pool.State = 2

    /// @notice index of liquidity in Pool.State
    uint256 public constant LIQUIDITY_OFFSET = 3;

    /// @notice index of TicksInfo mapping in Pool.State: mapping(int24 => TickInfo) ticks;
    uint256 public constant TICKS_OFFSET = 4;

    /// @notice index of tickBitmap mapping in Pool.State
    uint256 public constant TICK_BITMAP_OFFSET = 5;

    /// @notice index of Position.State mapping in Pool.State: mapping(bytes32 => Position.State) positions;
    uint256 public constant POSITIONS_OFFSET = 6;

    /**
     * @notice Get Slot0 of the pool: sqrtPriceX96, tick, protocolFee, lpFee
     * @dev Corresponds to pools[poolId].slot0
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return sqrtPriceX96 The square root of the price of the pool, in Q96 precision.
     * @return tick The current tick of the pool.
     * @return protocolFee The protocol fee of the pool.
     * @return lpFee The swap fee of the pool.
     */
    function getSlot0(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint160 sqrtPriceX96, int24 tick, uint24 protocolFee, uint24 lpFee)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        bytes32 data = manager.extsload(stateSlot);

        //   24 bits  |24bits|24bits      |24 bits|160 bits
        // 0x000000   |000bb8|000000      |ffff75 |0000000000000000fe3aa841ba359daa0ea9eff7
        // ---------- | fee  |protocolfee | tick  | sqrtPriceX96
        assembly ("memory-safe") {
            // bottom 160 bits of data
            sqrtPriceX96 := and(data, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            // next 24 bits of data
            tick := signextend(2, shr(160, data))
            // next 24 bits of data
            protocolFee := and(shr(184, data), 0xFFFFFF)
            // last 24 bits of data
            lpFee := and(shr(208, data), 0xFFFFFF)
        }
    }

    /**
     * @notice Retrieves the tick information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve information for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickInfo(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128
        )
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // read all 3 words of the TickInfo struct
        bytes32[] memory data = manager.extsload(slot, 3);
        assembly ("memory-safe") {
            let firstWord := mload(add(data, 32))
            liquidityNet := sar(128, firstWord)
            liquidityGross := and(firstWord, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
            feeGrowthOutside0X128 := mload(add(data, 64))
            feeGrowthOutside1X128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity information of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].ticks[tick].liquidityGross and pools[poolId].ticks[tick].liquidityNet. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve liquidity for.
     * @return liquidityGross The total position liquidity that references this tick
     * @return liquidityNet The amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left)
     */
    function getTickLiquidity(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint128 liquidityGross, int128 liquidityNet)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        bytes32 value = manager.extsload(slot);
        assembly ("memory-safe") {
            liquidityNet := sar(128, value)
            liquidityGross := and(value, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
        }
    }

    /**
     * @notice Retrieves the fee growth outside a tick range of a pool
     * @dev Corresponds to pools[poolId].ticks[tick].feeGrowthOutside0X128 and pools[poolId].ticks[tick].feeGrowthOutside1X128. A more gas efficient version of getTickInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve fee growth for.
     * @return feeGrowthOutside0X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     * @return feeGrowthOutside1X128 fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)
     */
    function getTickFeeGrowthOutside(IPoolManager manager, PoolId poolId, int24 tick)
        internal
        view
        returns (uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128)
    {
        bytes32 slot = _getTickInfoSlot(poolId, tick);

        // offset by 1 word, since the first word is liquidityGross + liquidityNet
        bytes32[] memory data = manager.extsload(bytes32(uint256(slot) + 1), 2);
        assembly ("memory-safe") {
            feeGrowthOutside0X128 := mload(add(data, 32))
            feeGrowthOutside1X128 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves the global fee growth of a pool.
     * @dev Corresponds to pools[poolId].feeGrowthGlobal0X128 and pools[poolId].feeGrowthGlobal1X128
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return feeGrowthGlobal0 The global fee growth for token0.
     * @return feeGrowthGlobal1 The global fee growth for token1.
     * @dev Note that feeGrowthGlobal can be artificially inflated
     * For pools with a single liquidity position, actors can donate to themselves to freely inflate feeGrowthGlobal
     * atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
     */
    function getFeeGrowthGlobals(IPoolManager manager, PoolId poolId)
        internal
        view
        returns (uint256 feeGrowthGlobal0, uint256 feeGrowthGlobal1)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State, `uint256 feeGrowthGlobal0X128`
        bytes32 slot_feeGrowthGlobal0X128 = bytes32(uint256(stateSlot) + FEE_GROWTH_GLOBAL0_OFFSET);

        // read the 2 words of feeGrowthGlobal
        bytes32[] memory data = manager.extsload(slot_feeGrowthGlobal0X128, 2);
        assembly ("memory-safe") {
            feeGrowthGlobal0 := mload(add(data, 32))
            feeGrowthGlobal1 := mload(add(data, 64))
        }
    }

    /**
     * @notice Retrieves total the liquidity of a pool.
     * @dev Corresponds to pools[poolId].liquidity
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @return liquidity The liquidity of the pool.
     */
    function getLiquidity(IPoolManager manager, PoolId poolId) internal view returns (uint128 liquidity) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `uint128 liquidity`
        bytes32 slot = bytes32(uint256(stateSlot) + LIQUIDITY_OFFSET);

        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Retrieves the tick bitmap of a pool at a specific tick.
     * @dev Corresponds to pools[poolId].tickBitmap[tick]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tick The tick to retrieve the bitmap for.
     * @return tickBitmap The bitmap of the tick.
     */
    function getTickBitmap(IPoolManager manager, PoolId poolId, int16 tick)
        internal
        view
        returns (uint256 tickBitmap)
    {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int16 => uint256) tickBitmap;`
        bytes32 tickBitmapMapping = bytes32(uint256(stateSlot) + TICK_BITMAP_OFFSET);

        // slot id of the mapping key: `pools[poolId].tickBitmap[tick]
        bytes32 slot = keccak256(abi.encodePacked(int256(tick), tickBitmapMapping));

        tickBitmap = uint256(manager.extsload(slot));
    }

    /**
     * @notice Retrieves the position information of a pool without needing to calculate the `positionId`.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param poolId The ID of the pool.
     * @param owner The owner of the liquidity position.
     * @param tickLower The lower tick of the liquidity range.
     * @param tickUpper The upper tick of the liquidity range.
     * @param salt The bytes32 randomness to further distinguish position state.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(
        IPoolManager manager,
        PoolId poolId,
        address owner,
        int24 tickLower,
        int24 tickUpper,
        bytes32 salt
    ) internal view returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128) {
        // positionKey = keccak256(abi.encodePacked(owner, tickLower, tickUpper, salt))
        bytes32 positionKey = Position.calculatePositionKey(owner, tickLower, tickUpper, salt);

        (liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128) = getPositionInfo(manager, poolId, positionKey);
    }

    /**
     * @notice Retrieves the position information of a pool at a specific position ID.
     * @dev Corresponds to pools[poolId].positions[positionId]
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     * @return feeGrowthInside0LastX128 The fee growth inside the position for token0.
     * @return feeGrowthInside1LastX128 The fee growth inside the position for token1.
     */
    function getPositionInfo(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);

        // read all 3 words of the Position.State struct
        bytes32[] memory data = manager.extsload(slot, 3);

        assembly ("memory-safe") {
            liquidity := mload(add(data, 32))
            feeGrowthInside0LastX128 := mload(add(data, 64))
            feeGrowthInside1LastX128 := mload(add(data, 96))
        }
    }

    /**
     * @notice Retrieves the liquidity of a position.
     * @dev Corresponds to pools[poolId].positions[positionId].liquidity. More gas efficient for just retrieiving liquidity as compared to getPositionInfo
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param positionId The ID of the position.
     * @return liquidity The liquidity of the position.
     */
    function getPositionLiquidity(IPoolManager manager, PoolId poolId, bytes32 positionId)
        internal
        view
        returns (uint128 liquidity)
    {
        bytes32 slot = _getPositionInfoSlot(poolId, positionId);
        liquidity = uint128(uint256(manager.extsload(slot)));
    }

    /**
     * @notice Calculate the fee growth inside a tick range of a pool
     * @dev pools[poolId].feeGrowthInside0LastX128 in Position.State is cached and can become stale. This function will calculate the up to date feeGrowthInside
     * @param manager The pool manager contract.
     * @param poolId The ID of the pool.
     * @param tickLower The lower tick of the range.
     * @param tickUpper The upper tick of the range.
     * @return feeGrowthInside0X128 The fee growth inside the tick range for token0.
     * @return feeGrowthInside1X128 The fee growth inside the tick range for token1.
     */
    function getFeeGrowthInside(IPoolManager manager, PoolId poolId, int24 tickLower, int24 tickUpper)
        internal
        view
        returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)
    {
        (uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128) = getFeeGrowthGlobals(manager, poolId);

        (uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickLower);
        (uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128) =
            getTickFeeGrowthOutside(manager, poolId, tickUpper);
        (, int24 tickCurrent,,) = getSlot0(manager, poolId);
        unchecked {
            if (tickCurrent < tickLower) {
                feeGrowthInside0X128 = lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            } else if (tickCurrent >= tickUpper) {
                feeGrowthInside0X128 = upperFeeGrowthOutside0X128 - lowerFeeGrowthOutside0X128;
                feeGrowthInside1X128 = upperFeeGrowthOutside1X128 - lowerFeeGrowthOutside1X128;
            } else {
                feeGrowthInside0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128 - upperFeeGrowthOutside0X128;
                feeGrowthInside1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128 - upperFeeGrowthOutside1X128;
            }
        }
    }

    function _getPoolStateSlot(PoolId poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(PoolId.unwrap(poolId), POOLS_SLOT));
    }

    function _getTickInfoSlot(PoolId poolId, int24 tick) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(int24 => TickInfo) ticks`
        bytes32 ticksMappingSlot = bytes32(uint256(stateSlot) + TICKS_OFFSET);

        // slot key of the tick key: `pools[poolId].ticks[tick]
        return keccak256(abi.encodePacked(int256(tick), ticksMappingSlot));
    }

    function _getPositionInfoSlot(PoolId poolId, bytes32 positionId) internal pure returns (bytes32) {
        // slot key of Pool.State value: `pools[poolId]`
        bytes32 stateSlot = _getPoolStateSlot(poolId);

        // Pool.State: `mapping(bytes32 => Position.State) positions;`
        bytes32 positionMapping = bytes32(uint256(stateSlot) + POSITIONS_OFFSET);

        // slot of the mapping key: `pools[poolId].positions[positionId]
        return keccak256(abi.encodePacked(positionId, positionMapping));
    }
}

lib/v4-core/src/libraries/TickMath.sol

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

import {BitMath} from "./BitMath.sol";
import {CustomRevert} from "./CustomRevert.sol";

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    using CustomRevert for bytes4;

    /// @notice Thrown when the tick passed to #getSqrtPriceAtTick is not between MIN_TICK and MAX_TICK
    error InvalidTick(int24 tick);
    /// @notice Thrown when the price passed to #getTickAtSqrtPrice does not correspond to a price between MIN_TICK and MAX_TICK
    error InvalidSqrtPrice(uint160 sqrtPriceX96);

    /// @dev The minimum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**-128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtPriceAtTick computed from log base 1.0001 of 2**128
    /// @dev If ever MIN_TICK and MAX_TICK are not centered around 0, the absTick logic in getSqrtPriceAtTick cannot be used
    int24 internal constant MAX_TICK = 887272;

    /// @dev The minimum tick spacing value drawn from the range of type int16 that is greater than 0, i.e. min from the range [1, 32767]
    int24 internal constant MIN_TICK_SPACING = 1;
    /// @dev The maximum tick spacing value drawn from the range of type int16, i.e. max from the range [1, 32767]
    int24 internal constant MAX_TICK_SPACING = type(int16).max;

    /// @dev The minimum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_PRICE = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtPriceAtTick. Equivalent to getSqrtPriceAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_PRICE = 1461446703485210103287273052203988822378723970342;
    /// @dev A threshold used for optimized bounds check, equals `MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1`
    uint160 internal constant MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE =
        1461446703485210103287273052203988822378723970342 - 4295128739 - 1;

    /// @notice Given a tickSpacing, compute the maximum usable tick
    function maxUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MAX_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Given a tickSpacing, compute the minimum usable tick
    function minUsableTick(int24 tickSpacing) internal pure returns (int24) {
        unchecked {
            return (MIN_TICK / tickSpacing) * tickSpacing;
        }
    }

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the price of the two assets (currency1/currency0)
    /// at the given tick
    function getSqrtPriceAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick;
            assembly ("memory-safe") {
                tick := signextend(2, tick)
                // mask = 0 if tick >= 0 else -1 (all 1s)
                let mask := sar(255, tick)
                // if tick >= 0, |tick| = tick = 0 ^ tick
                // if tick < 0, |tick| = ~~|tick| = ~(-|tick| - 1) = ~(tick - 1) = (-1) ^ (tick - 1)
                // either way, |tick| = mask ^ (tick + mask)
                absTick := xor(mask, add(mask, tick))
            }

            if (absTick > uint256(int256(MAX_TICK))) InvalidTick.selector.revertWith(tick);

            // The tick is decomposed into bits, and for each bit with index i that is set, the product of 1/sqrt(1.0001^(2^i))
            // is calculated (using Q128.128). The constants used for this calculation are rounded to the nearest integer

            // Equivalent to:
            //     price = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
            //     or price = int(2**128 / sqrt(1.0001)) if (absTick & 0x1) else 1 << 128
            uint256 price;
            assembly ("memory-safe") {
                price := xor(shl(128, 1), mul(xor(shl(128, 1), 0xfffcb933bd6fad37aa2d162d1a594001), and(absTick, 0x1)))
            }
            if (absTick & 0x2 != 0) price = (price * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0) price = (price * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0) price = (price * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0) price = (price * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0) price = (price * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0) price = (price * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0) price = (price * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0) price = (price * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0) price = (price * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0) price = (price * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0) price = (price * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0) price = (price * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0) price = (price * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0) price = (price * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0) price = (price * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0) price = (price * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0) price = (price * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0) price = (price * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0) price = (price * 0x48a170391f7dc42444e8fa2) >> 128;

            assembly ("memory-safe") {
                // if (tick > 0) price = type(uint256).max / price;
                if sgt(tick, 0) { price := div(not(0), price) }

                // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
                // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
                // we round up in the division so getTickAtSqrtPrice of the output price is always consistent
                // `sub(shl(32, 1), 1)` is `type(uint32).max`
                // `price + type(uint32).max` will not overflow because `price` fits in 192 bits
                sqrtPriceX96 := shr(32, add(price, sub(shl(32, 1), 1)))
            }
        }
    }

    /// @notice Calculates the greatest tick value such that getSqrtPriceAtTick(tick) <= sqrtPriceX96
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_PRICE, as MIN_SQRT_PRICE is the lowest value getSqrtPriceAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt price for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the getSqrtPriceAtTick(tick) is less than or equal to the input sqrtPriceX96
    function getTickAtSqrtPrice(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        unchecked {
            // Equivalent: if (sqrtPriceX96 < MIN_SQRT_PRICE || sqrtPriceX96 >= MAX_SQRT_PRICE) revert InvalidSqrtPrice();
            // second inequality must be >= because the price can never reach the price at the max tick
            // if sqrtPriceX96 < MIN_SQRT_PRICE, the `sub` underflows and `gt` is true
            // if sqrtPriceX96 >= MAX_SQRT_PRICE, sqrtPriceX96 - MIN_SQRT_PRICE > MAX_SQRT_PRICE - MIN_SQRT_PRICE - 1
            if ((sqrtPriceX96 - MIN_SQRT_PRICE) > MAX_SQRT_PRICE_MINUS_MIN_SQRT_PRICE_MINUS_ONE) {
                InvalidSqrtPrice.selector.revertWith(sqrtPriceX96);
            }

            uint256 price = uint256(sqrtPriceX96) << 32;

            uint256 r = price;
            uint256 msb = BitMath.mostSignificantBit(r);

            if (msb >= 128) r = price >> (msb - 127);
            else r = price << (127 - msb);

            int256 log_2 = (int256(msb) - 128) << 64;

            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(63, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(62, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(61, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(60, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(59, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(58, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(57, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(56, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(55, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(54, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(53, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(52, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(51, f))
                r := shr(f, r)
            }
            assembly ("memory-safe") {
                r := shr(127, mul(r, r))
                let f := shr(128, r)
                log_2 := or(log_2, shl(50, f))
            }

            int256 log_sqrt10001 = log_2 * 255738958999603826347141; // Q22.128 number

            // Magic number represents the ceiling of the maximum value of the error when approximating log_sqrt10001(x)
            int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);

            // Magic number represents the minimum value of the error when approximating log_sqrt10001(x), when
            // sqrtPrice is from the range (2^-64, 2^64). This is safe as MIN_SQRT_PRICE is more than 2^-64. If MIN_SQRT_PRICE
            // is changed, this may need to be changed too
            int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

            tick = tickLow == tickHi ? tickLow : getSqrtPriceAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
        }
    }
}

lib/v4-core/src/libraries/TransientStateLibrary.sol

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

import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {Currency} from "../types/Currency.sol";
import {CurrencyReserves} from "./CurrencyReserves.sol";
import {NonzeroDeltaCount} from "./NonzeroDeltaCount.sol";
import {Lock} from "./Lock.sol";

/// @notice A helper library to provide state getters that use exttload
library TransientStateLibrary {
    /// @notice returns the reserves for the synced currency
    /// @param manager The pool manager contract.

    /// @return uint256 The reserves of the currency.
    /// @dev returns 0 if the reserves are not synced or value is 0.
    /// Checks the synced currency to only return valid reserve values (after a sync and before a settle).
    function getSyncedReserves(IPoolManager manager) internal view returns (uint256) {
        if (getSyncedCurrency(manager).isAddressZero()) return 0;
        return uint256(manager.exttload(CurrencyReserves.RESERVES_OF_SLOT));
    }

    function getSyncedCurrency(IPoolManager manager) internal view returns (Currency) {
        return Currency.wrap(address(uint160(uint256(manager.exttload(CurrencyReserves.CURRENCY_SLOT)))));
    }

    /// @notice Returns the number of nonzero deltas open on the PoolManager that must be zeroed out before the contract is locked
    function getNonzeroDeltaCount(IPoolManager manager) internal view returns (uint256) {
        return uint256(manager.exttload(NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT));
    }

    /// @notice Get the current delta for a caller in the given currency
    /// @param target The credited account address
    /// @param currency The currency for which to lookup the delta
    function currencyDelta(IPoolManager manager, address target, Currency currency) internal view returns (int256) {
        bytes32 key;
        assembly ("memory-safe") {
            mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            key := keccak256(0, 64)
        }
        return int256(uint256(manager.exttload(key)));
    }

    /// @notice Returns whether the contract is unlocked or not
    function isUnlocked(IPoolManager manager) internal view returns (bool) {
        return manager.exttload(Lock.IS_UNLOCKED_SLOT) != 0x0;
    }
}

lib/v4-core/src/libraries/UnsafeMath.sol

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

/// @title Math functions that do not check inputs or outputs
/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks
library UnsafeMath {
    /// @notice Returns ceil(x / y)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param x The dividend
    /// @param y The divisor
    /// @return z The quotient, ceil(x / y)
    function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        assembly ("memory-safe") {
            z := add(div(x, y), gt(mod(x, y), 0))
        }
    }

    /// @notice Calculates floor(a×b÷denominator)
    /// @dev division by 0 will return 0, and should be checked externally
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result, floor(a×b÷denominator)
    function simpleMulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
        assembly ("memory-safe") {
            result := div(mul(a, b), denominator)
        }
    }
}

lib/v4-core/src/types/BalanceDelta.sol

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

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

/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;

using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;

function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
    assembly ("memory-safe") {
        balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
    }
}

function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := add(a0, b0)
        res1 := add(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
    int256 res0;
    int256 res1;
    assembly ("memory-safe") {
        let a0 := sar(128, a)
        let a1 := signextend(15, a)
        let b0 := sar(128, b)
        let b1 := signextend(15, b)
        res0 := sub(a0, b0)
        res1 := sub(a1, b1)
    }
    return toBalanceDelta(res0.toInt128(), res1.toInt128());
}

function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}

function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
    return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}

/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
    /// @notice A BalanceDelta of 0
    BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);

    function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
        assembly ("memory-safe") {
            _amount0 := sar(128, balanceDelta)
        }
    }

    function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
        assembly ("memory-safe") {
            _amount1 := signextend(15, balanceDelta)
        }
    }
}

lib/v4-core/src/types/BeforeSwapDelta.sol

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

// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;

// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
    pure
    returns (BeforeSwapDelta beforeSwapDelta)
{
    assembly ("memory-safe") {
        beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
    }
}

/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
    /// @notice A BeforeSwapDelta of 0
    BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);

    /// extracts int128 from the upper 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap
    function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
        assembly ("memory-safe") {
            deltaSpecified := sar(128, delta)
        }
    }

    /// extracts int128 from the lower 128 bits of the BeforeSwapDelta
    /// returned by beforeSwap and afterSwap
    function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
        assembly ("memory-safe") {
            deltaUnspecified := signextend(15, delta)
        }
    }
}

lib/v4-core/src/types/Currency.sol

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

import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";

type Currency is address;

using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;

function equals(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) == Currency.unwrap(other);
}

function greaterThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) > Currency.unwrap(other);
}

function lessThan(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) < Currency.unwrap(other);
}

function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
    return Currency.unwrap(currency) >= Currency.unwrap(other);
}

/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
    /// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
    error NativeTransferFailed();

    /// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
    error ERC20TransferFailed();

    /// @notice A constant to represent the native currency
    Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));

    function transfer(Currency currency, address to, uint256 amount) internal {
        // altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
        // modified custom error selectors

        bool success;
        if (currency.isAddressZero()) {
            assembly ("memory-safe") {
                // Transfer the ETH and revert if it fails.
                success := call(gas(), to, amount, 0, 0, 0, 0)
            }
            // revert with NativeTransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
            }
        } else {
            assembly ("memory-safe") {
                // Get a pointer to some free memory.
                let fmp := mload(0x40)

                // Write the abi-encoded calldata into memory, beginning with the function selector.
                mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
                mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
                mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.

                success :=
                    and(
                        // Set success to whether the call reverted, if not we check it either
                        // returned exactly 1 (can't just be non-zero data), or had no return data.
                        or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
                        // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
                        // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
                        // Counterintuitively, this call must be positioned second to the or() call in the
                        // surrounding and() call or else returndatasize() will be zero during the computation.
                        call(gas(), currency, 0, fmp, 68, 0, 32)
                    )

                // Now clean the memory we used
                mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
                mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
                mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
            }
            // revert with ERC20TransferFailed, containing the bubbled up error as an argument
            if (!success) {
                CustomRevert.bubbleUpAndRevertWith(
                    Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
                );
            }
        }
    }

    function balanceOfSelf(Currency currency) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return address(this).balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
        }
    }

    function balanceOf(Currency currency, address owner) internal view returns (uint256) {
        if (currency.isAddressZero()) {
            return owner.balance;
        } else {
            return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
        }
    }

    function isAddressZero(Currency currency) internal pure returns (bool) {
        return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
    }

    function toId(Currency currency) internal pure returns (uint256) {
        return uint160(Currency.unwrap(currency));
    }

    // If the upper 12 bytes are non-zero, they will be zero-ed out
    // Therefore, fromId() and toId() are not inverses of each other
    function fromId(uint256 id) internal pure returns (Currency) {
        return Currency.wrap(address(uint160(id)));
    }
}

lib/v4-core/src/types/PoolId.sol

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

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

type PoolId is bytes32;

/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
    /// @notice Returns value equal to keccak256(abi.encode(poolKey))
    function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
        assembly ("memory-safe") {
            // 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
            poolId := keccak256(poolKey, 0xa0)
        }
    }
}

lib/v4-core/src/types/PoolKey.sol

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

import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";

using PoolIdLibrary for PoolKey global;

/// @notice Returns the key for identifying a pool
struct PoolKey {
    /// @notice The lower currency of the pool, sorted numerically
    Currency currency0;
    /// @notice The higher currency of the pool, sorted numerically
    Currency currency1;
    /// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
    uint24 fee;
    /// @notice Ticks that involve positions must be a multiple of tick spacing
    int24 tickSpacing;
    /// @notice The hooks of the pool
    IHooks hooks;
}

lib/v4-core/src/types/PoolOperation.sol

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

import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";

/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
    // the lower and upper tick of the position
    int24 tickLower;
    int24 tickUpper;
    // how to modify the liquidity
    int256 liquidityDelta;
    // a value to set if you want unique liquidity positions at the same range
    bytes32 salt;
}

/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
    /// Whether to swap token0 for token1 or vice versa
    bool zeroForOne;
    /// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
    int256 amountSpecified;
    /// The sqrt price at which, if reached, the swap will stop executing
    uint160 sqrtPriceLimitX96;
}

src/base/TransientLock.sol

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

/// @title TransientLock
/// @notice One reentrancy lock per contract plus transient "callback expected" flags (EIP-1153, Cancun).
/// @dev Slots are fixed random constants so they cannot collide with anything else a contract stores in transient
///      storage. Every flag is set immediately before the external call that must call us back and cleared right after.
abstract contract TransientLock {
    error Reentrancy();
    error UnexpectedCallback();

    /// keccak256("kineko.transient.lock") - 1
    uint256 internal constant LOCK_SLOT = 0x1c8f6d4b0f1f86e4a2b0f7c7b1b3f8c5d0a8a3c6e1b8f5a2c7d4e9f0a1b2c3d4;

    modifier nonReentrant() {
        if (_tload(LOCK_SLOT) != 0) revert Reentrancy();
        _tstore(LOCK_SLOT, 1);
        _;
        _tstore(LOCK_SLOT, 0);
    }

    function _isLocked() internal view returns (bool) {
        return _tload(LOCK_SLOT) != 0;
    }

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

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

    /// @dev Reverts unless `msg.sender == expected` and the flag at `slot` is set; clears the flag so the same
    ///      expectation can be consumed only once.
    function _consumeCallback(uint256 slot, address expected) internal {
        if (msg.sender != expected || _tload(slot) == 0) revert UnexpectedCallback();
        _tstore(slot, 0);
    }
}

src/base/TwoStepOwned.sol

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

/// @title TwoStepOwned
/// @notice Minimal two-step ownership. The owner is expected to be a multisig (behind a timelock on mainnet).
abstract contract TwoStepOwned {
    error NotOwner();
    error NotPendingOwner();
    error ZeroAddress();

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    address public owner;
    address public pendingOwner;

    constructor(address owner_) {
        if (owner_ == address(0)) revert ZeroAddress();
        owner = owner_;
        emit OwnershipTransferred(address(0), owner_);
    }

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

    function transferOwnership(address newOwner) external onlyOwner {
        pendingOwner = newOwner; // zero cancels a pending transfer
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotPendingOwner();
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        pendingOwner = address(0);
    }
}

src/interfaces/IExternal.sol

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

/// @notice Minimal, ABI-compatible views of the external contracts KINEKO touches. Kept local so the production code
///         does not depend on library versions of Uniswap v4 / ELA / MetaMorpho.

/// Uniswap v4 PoolKey (Currency and IHooks are address-typed in v4, so the ABI is identical).
struct PoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

/// Uniswap v4 swap params (v4-core `SwapParams`).
struct SwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

interface IPoolManagerMin {
    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData) external returns (int256);
    function settle() external payable returns (uint256);
    function sync(address currency) external;
    function take(address currency, address to, uint256 amount) external;
    function extsload(bytes32 slot) external view returns (bytes32);
}

/// ELA hook (verified source: reference/ela/src__ElaHook.sol).
interface IElaHook {
    function migrated() external view returns (bool);
    function isCurve() external view returns (bool);
    function reserves() external view returns (uint256 e, uint256 t);
    function quoteBuy(uint256 ethIn) external view returns (uint256);
    function quoteSell(uint256 tokenIn) external view returns (uint256);
    function curveBuy(uint256 minTokens) external payable returns (uint256);
    function curveSell(uint256 dTok, uint256 minEth) external returns (uint256);
    function curveQuoteBuy(uint256 ethIn) external view returns (uint256);
    function curveQuoteSell(uint256 tokIn) external view returns (uint256);
    function raised() external view returns (uint256);
    function curveTarget() external view returns (uint256);
    function tokenReserve() external view returns (uint256);
}

interface IElaEngine {
    function oracleStale() external view returns (bool);
    function navETH() external view returns (uint256);
    function claimCreatorFees(address to) external;
}

interface IBurnableERC20 {
    function burn(uint256 amount) external;
}

interface IWETH9 {
    function deposit() external payable;
    function withdraw(uint256 amount) external;
    function balanceOf(address) external view returns (uint256);
}

/// Uniswap SwapRouter02 (IV3SwapRouter: no deadline field).
interface ISwapRouter02 {
    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

interface IUniswapV3PoolObserve {
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
}

interface IChainlinkFeed {
    function latestRoundData() external view returns (uint80, int256, uint256, uint256, uint80);
    function decimals() external view returns (uint8);
}

/// MetaMorpho v1.1 (only what the FeeRouter uses).
interface IERC4626Min {
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256);
    function maxRedeem(address owner) external view returns (uint256);
    function balanceOf(address) external view returns (uint256);
    function asset() external view returns (address);
}

/// ELA builder registry / pad (verified source: reference/ela-builders).
interface IBuilderRegistry {
    function isPad(address account) external view returns (bool);
    function padOf(string calldata code) external view returns (address);
    function register(string calldata code, uint16 builderBps, address payout) external returns (address pad);
}

interface IBuilderPad {
    function acceptPayout() external;
    function proposePayout(address next) external;
    function withdrawBuilder(address asset, address to) external returns (uint256);
    function withdrawCreator(address asset, address to) external returns (uint256);
    function claim(address token) external returns (uint256 received, uint256 creatorShare, uint256 builderShare);
    function payout() external view returns (address);
    function builderOwed(address asset) external view returns (uint256);
    function creatorOwed(address asset, address creator) external view returns (uint256);
    function predictProxy(address creator) external view returns (address);
}

src/libraries/SafeReads.sol

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

import {TickMath} from "v4-core/libraries/TickMath.sol";
import {FixedPointMathLib} from "solady/utils/FixedPointMathLib.sol";

/// @title SafeReads
/// @notice External reads that never revert: every call is a length-checked `staticcall`, return data is decoded by
///         hand, and every failure is reported as `ok = false`. Used by the oracle (whose `price()` / `update()` must never
///         revert) and by the FeeRouter's TWAP bounds.
library SafeReads {
    /// Answers outside (0, MAX_FEED_ANSWER) are treated as invalid, which also bounds all later arithmetic.
    uint256 internal constant MAX_FEED_ANSWER = 1e18;

    /// @notice Chainlink `latestRoundData` → (ok, answer, updatedAt). ok == false on any failure or non-positive /
    ///         absurd answer, or an `updatedAt` in the future.
    function chainlink(address feed) internal view returns (bool ok, uint256 answer, uint256 updatedAt) {
        (bool s, bytes memory r) = feed.staticcall(abi.encodeWithSelector(0xfeaf968c)); // latestRoundData()
        if (!s || r.length < 160) return (false, 0, 0);
        int256 a;
        uint256 u;
        assembly ("memory-safe") {
            a := mload(add(r, 0x40)) // word 1: answer
            u := mload(add(r, 0x80)) // word 3: updatedAt
        }
        if (a <= 0 || uint256(a) >= MAX_FEED_ANSWER || u == 0 || u > block.timestamp) return (false, 0, 0);
        return (true, uint256(a), u);
    }

    /// @notice Arithmetic-mean tick of a Uniswap v3 pool over `window` seconds (rounded to -inf, like OracleLibrary).
    function meanTick(address pool, uint32 window) internal view returns (bool ok, int24 tick) {
        if (window == 0) return (false, 0);
        uint32[] memory ago = new uint32[](2);
        ago[0] = window;
        (bool s, bytes memory r) = pool.staticcall(abi.encodeWithSelector(0x883bdbfd, ago)); // observe(uint32[])
        // Standard encoding of (int56[2], uint160[2]): off1, off2, len1, c0, c1, len2, s0, s1 = 8 words.
        if (!s || r.length < 256) return (false, 0);
        uint256 off1;
        uint256 len1;
        int256 c0;
        int256 c1;
        assembly ("memory-safe") {
            off1 := mload(add(r, 0x20))
            len1 := mload(add(r, 0x60))
            c0 := mload(add(r, 0x80))
            c1 := mload(add(r, 0xa0))
        }
        if (off1 != 0x40 || len1 != 2) return (false, 0);
        // int56 values: reject anything that is not a sign-extended int56.
        if (c0 != int256(int56(c0)) || c1 != int256(int56(c1))) return (false, 0);
        int256 delta = c1 - c0;
        int256 t = delta / int256(uint256(window));
        if (delta < 0 && delta % int256(uint256(window)) != 0) t--;
        if (t < int256(TickMath.MIN_TICK) || t > int256(TickMath.MAX_TICK)) return (false, 0);
        return (true, int24(t));
    }

    /// @notice TWAP price of token0 in token1 raw units, times `mul` (e.g. 1e8 for USDT(6)/XAUT(6) → 8-dec USD).
    function twapPrice(address pool, uint32 window, uint256 mul) internal view returns (bool ok, uint256 p) {
        int24 t;
        (ok, t) = meanTick(pool, window);
        if (!ok) return (false, 0);
        uint256 sp = TickMath.getSqrtPriceAtTick(t);
        // price * 2^96 fits for every valid tick (price <= 2^128); mul <= 1e20 keeps the second step in range
        // (fullMulDiv only reverts when the result exceeds 256 bits, which these bounds rule out).
        uint256 pX96 = FixedPointMathLib.fullMulDiv(sp, sp, 1 << 96);
        p = FixedPointMathLib.fullMulDiv(pX96, mul, 1 << 96);
        // same bound as feed answers, so every product of two of them fits comfortably in 256 bits
        if (p == 0 || p >= MAX_FEED_ANSWER) return (false, 0);
        ok = true;
    }

    /// @notice `bool` view call that reports failure as `failValue`.
    function boolCall(address target, bytes4 selector, bool failValue) internal view returns (bool) {
        (bool s, bytes memory r) = target.staticcall(abi.encodeWithSelector(selector));
        if (!s || r.length < 32) return failValue;
        uint256 v;
        assembly ("memory-safe") {
            v := mload(add(r, 0x20))
        }
        if (v > 1) return failValue;
        return v == 1;
    }
}

src/pad/DistrictRegistry.sol

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {TwoStepOwned} from "../base/TwoStepOwned.sol";
import {Hop, HopKind, DistrictConfig, RouteSpec, StreakParams} from "./libraries/PadTypes.sol";
import {IUniswapV3FactoryMin, IUniswapV3PoolMin, ICurvePoolMin} from "./interfaces/IPadExternal.sol";

interface IPadHookRoute {
    function REGISTRY() external view returns (address);
    function poolIdOf(address coin) external view returns (bytes32);
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory);
}

/// @title DistrictRegistry
/// @notice One entry per district (quote asset). Districts are added only through a timelock (propose the hash of the
///         full config + routes, execute the same calldata after `TIMELOCK`). Once added, a district's config and routes
///         are immutable. There are no buy caps. The guardian can only freeze / unfreeze BUYS (issuer freeze or pause);
///         allowlisted watcher bots can only freeze buys (one call); only the guardian unfreezes. Nothing here can touch a pool, its fees or its reserves, and nothing here is ever read on a sell.
contract DistrictRegistry is TwoStepOwned {
    using StateLibrary for IPoolManager;
    using PoolIdLibrary for PoolKey;

    uint256 public constant TIMELOCK = 24 hours;
    uint256 public constant GUARDIAN_TIMELOCK = 24 hours;
    uint256 public constant MAX_HOPS = 4;
    int24 public constant TICK_SPACING = 60;
    uint24 public constant BASE_FEE = 10_000; // 1%
    uint24 public constant MAX_SNIPE_FEE = 990_000; // 99%
    uint16 public constant MAX_SNIPE_BLOCKS = 100;

    IPoolManager public immutable POOL_MANAGER;
    IUniswapV3FactoryMin public immutable V3_FACTORY;
    address public immutable WETH;

    address public guardian;
    address public pendingGuardian;
    uint256 public pendingGuardianEta;
    mapping(address => bool) public isWatcher;

    uint256 public districtCount;

    // ---- creator streak parameters (timelocked >= 24 h; the hook applies them from each coin's next epoch boundary)
    uint256 public constant STREAK_TIMELOCK = 24 hours;
    uint32 public constant MIN_WINDOW = 1; // days
    uint32 public constant MAX_WINDOW = 14; // days
    uint16 public constant MAX_TIER_EPOCHS = 10_000;
    /// global default (key 0) and per-district overrides (key = districtId)
    mapping(uint256 => StreakParams) internal _streak;
    mapping(uint256 => bool) public hasStreakOverride;
    mapping(uint256 => StreakParams) public pendingStreak;
    mapping(uint256 => uint256) public pendingStreakEta;
    /// when the current params of `key` were executed (0 = since deployment): coins switch at their first epoch
    /// boundary at or after this time, never earlier (no retroactive change)
    mapping(uint256 => uint256) public streakEffectiveAt;
    mapping(uint256 => DistrictConfig) internal _config;
    /// @notice Buys blocked in a district (issuer freeze/pause). Read by the hook on buys only, never on sells.
    mapping(uint256 => bool) public buysFrozen;
    mapping(uint256 => mapping(address => Hop[])) internal _routes;
    mapping(uint256 => address[]) internal _payTokens;
    mapping(uint256 => string) public districtName;

    /// proposal hash => earliest execution time
    mapping(bytes32 => uint256) public proposalEta;

    event DistrictProposed(bytes32 indexed proposalHash, uint256 eta);
    event DistrictProposalCancelled(bytes32 indexed proposalHash);
    event DistrictAdded(uint256 indexed districtId, address indexed quote, string name, bytes32 proposalHash);
    event RouteAdded(uint256 indexed districtId, address indexed payToken, uint256 hops);
    event BuysFrozen(uint256 indexed districtId, bool frozen, address indexed by);
    event WatcherSet(address indexed watcher, bool allowed);
    event GuardianProposed(address indexed next, uint256 eta);
    event GuardianChanged(address indexed previous, address indexed next);
    event StreakProposed(uint256 indexed key, StreakParams params, uint256 eta);
    event StreakExecuted(uint256 indexed key, StreakParams params);
    event StreakCancelled(uint256 indexed key);

    error NotGuardian();
    error NotWatcherOrGuardian();
    error BadConfig();
    error BadRoute(uint256 routeIndex, uint256 hopIndex);
    error NotProposed();
    error TooEarly();
    error UnknownDistrict();

    error DuplicatePayToken();
    error GenesisOver();
    error BadStreak();

    /// @notice Launch-day shortcut: until this time the owner (the deployer, inside the deploy script) may add the starting
    ///         districts at once, with no 24 h wait. After it, every district goes through the timelocked proposal.
    uint256 public immutable GENESIS_END;

    constructor(address owner_, address guardian_, address watcher_, IPoolManager poolManager, address v3Factory, address weth)
        TwoStepOwned(owner_)
    {
        GENESIS_END = block.timestamp + 12 hours;
        if (watcher_ != address(0)) {
            isWatcher[watcher_] = true; // initial freeze-only watcher bot (the guardian manages the list afterwards)
            emit WatcherSet(watcher_, true);
        }
        if (guardian_ == address(0) || address(poolManager) == address(0) || v3Factory == address(0) || weth == address(0))
        {
            revert ZeroAddress();
        }
        guardian = guardian_;
        // defaults (STREAK_VOLUME_CHECK.md): a day is alive if the rolling 7-day volume >= $50K; tiers at 28 / 84 days
        _streak[0] = StreakParams({windowDays: 7, aliveUsd: 50_000e18, tier1Epochs: 28, tier2Epochs: 84});
        POOL_MANAGER = poolManager;
        V3_FACTORY = IUniswapV3FactoryMin(v3Factory);
        WETH = weth;
        emit GuardianChanged(address(0), guardian_);
    }

    modifier onlyGuardian() {
        if (msg.sender != guardian) revert NotGuardian();
        _;
    }

    // ------------------------------------------------------------------ timelocked add

    function proposalHash(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
        public
        pure
        returns (bytes32)
    {
        return keccak256(abi.encode(name, cfg, routes));
    }

    /// @notice Owner proposes a district. Everything is validated now and again at execution.
    function proposeDistrict(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
        external
        onlyOwner
        returns (bytes32 h)
    {
        _validate(cfg, routes);
        h = proposalHash(name, cfg, routes);
        uint256 eta = block.timestamp + TIMELOCK;
        proposalEta[h] = eta;
        emit DistrictProposed(h, eta);
    }

    function cancelDistrict(bytes32 h) external onlyOwner {
        if (proposalEta[h] == 0) revert NotProposed();
        delete proposalEta[h];
        emit DistrictProposalCancelled(h);
    }

    /// @notice Anyone can execute a matured proposal (same calldata as proposed).
    function executeDistrict(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
        external
        returns (uint256 id)
    {
        bytes32 h = proposalHash(name, cfg, routes);
        uint256 eta = proposalEta[h];
        if (eta == 0) revert NotProposed();
        if (block.timestamp < eta) revert TooEarly();
        delete proposalEta[h];
        _validate(cfg, routes);
        id = _add(name, cfg, routes, h);
    }

    /// @notice Genesis window only (see GENESIS_END): add a starting district immediately. Same validation as a proposal.
    function seedDistrict(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes)
        external
        onlyOwner
        returns (uint256 id)
    {
        if (block.timestamp > GENESIS_END) revert GenesisOver();
        _validate(cfg, routes);
        id = _add(name, cfg, routes, proposalHash(name, cfg, routes));
    }

    function _add(string calldata name, DistrictConfig calldata cfg, RouteSpec[] calldata routes, bytes32 h)
        internal
        returns (uint256 id)
    {
        id = ++districtCount;
        _config[id] = cfg;
        districtName[id] = name;
        for (uint256 r; r < routes.length; ++r) {
            Hop[] storage dst = _routes[id][routes[r].payToken];
            for (uint256 k; k < routes[r].hops.length; ++k) {
                dst.push(routes[r].hops[k]);
            }
            _payTokens[id].push(routes[r].payToken);
            emit RouteAdded(id, routes[r].payToken, routes[r].hops.length);
        }
        emit DistrictAdded(id, cfg.quote, name, h);
    }

    // ------------------------------------------------------------------ guardian / watchers

    /// @notice One call to block new BUYS in a district (issuer pause/freeze). Guardian or an allowlisted watcher.
    ///         Sells are never read from here, so they cannot be affected.
    function freezeBuys(uint256 id) external {
        if (msg.sender != guardian && !isWatcher[msg.sender]) revert NotWatcherOrGuardian();
        if (_config[id].quote == address(0)) revert UnknownDistrict();
        buysFrozen[id] = true;
        emit BuysFrozen(id, true, msg.sender);
    }

    /// @notice Only the guardian unfreezes.
    function unfreezeBuys(uint256 id) external onlyGuardian {
        if (_config[id].quote == address(0)) revert UnknownDistrict();
        buysFrozen[id] = false;
        emit BuysFrozen(id, false, msg.sender);
    }

    function setWatcher(address watcher, bool allowed) external onlyGuardian {
        if (watcher == address(0)) revert ZeroAddress();
        isWatcher[watcher] = allowed;
        emit WatcherSet(watcher, allowed);
    }

    function proposeGuardian(address next) external onlyOwner {
        if (next == address(0)) revert ZeroAddress();
        pendingGuardian = next;
        pendingGuardianEta = block.timestamp + GUARDIAN_TIMELOCK;
        emit GuardianProposed(next, pendingGuardianEta);
    }

    function acceptGuardian() external {
        address next = pendingGuardian;
        if (next == address(0) || msg.sender != next) revert NotGuardian();
        if (block.timestamp < pendingGuardianEta) revert TooEarly();
        emit GuardianChanged(guardian, next);
        guardian = next;
        pendingGuardian = address(0);
        pendingGuardianEta = 0;
    }

    // ------------------------------------------------------------------ streak parameters (timelocked)

    /// @notice Owner proposes new streak params for a district (`key` = id) or the global default (`key` = 0).
    function proposeStreakParams(uint256 key, StreakParams calldata sp) external onlyOwner {
        _validateStreak(sp);
        // a key may name a district that is not executed yet (e.g. OIL's $15K bar queued at deploy): owner-only,
        // timelocked, and it only ever changes future creator tiers
        pendingStreak[key] = sp;
        pendingStreakEta[key] = block.timestamp + STREAK_TIMELOCK;
        emit StreakProposed(key, sp, pendingStreakEta[key]);
    }

    function cancelStreakParams(uint256 key) external onlyOwner {
        if (pendingStreakEta[key] == 0) revert NotProposed();
        pendingStreakEta[key] = 0;
        emit StreakCancelled(key);
    }

    /// @notice Anyone executes a matured proposal.
    function executeStreakParams(uint256 key) external {
        uint256 eta = pendingStreakEta[key];
        if (eta == 0) revert NotProposed();
        if (block.timestamp < eta) revert TooEarly();
        pendingStreakEta[key] = 0;
        _streak[key] = pendingStreak[key];
        streakEffectiveAt[key] = block.timestamp;
        if (key != 0) hasStreakOverride[key] = true;
        emit StreakExecuted(key, _streak[key]);
    }

    /// @notice Effective streak params for a district (override if set, else the global default).
    function streakParams(uint256 id) external view returns (StreakParams memory) {
        return hasStreakOverride[id] ? _streak[id] : _streak[0];
    }

    /// @notice Effective params plus the time they took effect (hook hot path: 5 words).
    function streakParamsAt(uint256 id)
        external
        view
        returns (uint32 windowDays, uint96 aliveUsd, uint16 tier1Epochs, uint16 tier2Epochs, uint256 effectiveAt)
    {
        uint256 k = hasStreakOverride[id] ? id : 0;
        StreakParams storage sp = _streak[k];
        return (sp.windowDays, sp.aliveUsd, sp.tier1Epochs, sp.tier2Epochs, streakEffectiveAt[k]);
    }

    function _validateStreak(StreakParams calldata sp) internal pure {
        if (
            sp.windowDays < MIN_WINDOW || sp.windowDays > MAX_WINDOW || sp.aliveUsd == 0 || sp.tier1Epochs == 0
                || sp.tier2Epochs <= sp.tier1Epochs || sp.tier2Epochs > MAX_TIER_EPOCHS
        ) revert BadStreak();
    }

    // ------------------------------------------------------------------ views

    function exists(uint256 id) external view returns (bool) {
        return _config[id].quote != address(0);
    }

    function config(uint256 id) external view returns (DistrictConfig memory) {
        return _config[id];
    }

    function route(uint256 id, address payToken) external view returns (Hop[] memory) {
        return _routes[id][payToken];
    }

    function payTokens(uint256 id) external view returns (address[] memory) {
        return _payTokens[id];
    }

    // ------------------------------------------------------------------ validation

    function _validate(DistrictConfig calldata cfg, RouteSpec[] calldata routes) internal view {
        if (cfg.quote == address(0) || cfg.quote.code.length == 0) revert BadConfig();
        if (cfg.quoteDecimals > 36) revert BadConfig();
        if (cfg.launchTick % TICK_SPACING != 0) revert BadConfig();
        // both orientations must leave room for the full range and the floor band
        int24 maxUsable = TickMath.maxUsableTick(TICK_SPACING);
        if (cfg.launchTick <= -maxUsable + TICK_SPACING * 10 || cfg.launchTick >= maxUsable - TICK_SPACING * 10) {
            revert BadConfig();
        }
        if (cfg.snipeStartFee < BASE_FEE || cfg.snipeStartFee > MAX_SNIPE_FEE) revert BadConfig();
        if (cfg.snipeBlocks > MAX_SNIPE_BLOCKS) revert BadConfig();
        if (cfg.usdPerQuoteE18 == 0) revert BadConfig();

        for (uint256 r; r < routes.length; ++r) {
            address pay = routes[r].payToken;
            if (pay == cfg.quote) revert BadRoute(r, 0); // paying in the quote needs no route
            for (uint256 q; q < r; ++q) {
                if (routes[q].payToken == pay) revert DuplicatePayToken();
            }
            Hop[] calldata hops = routes[r].hops;
            if (hops.length == 0 || hops.length > MAX_HOPS) revert BadRoute(r, 0);
            address cur = pay;
            for (uint256 k; k < hops.length; ++k) {
                Hop calldata h = hops[k];
                if (!_same(cur, h.tokenIn) || h.tokenIn == h.tokenOut) revert BadRoute(r, k);
                _validateHop(h, r, k);
                cur = h.tokenOut;
            }
            if (cur != cfg.quote) revert BadRoute(r, hops.length);
        }
    }

    /// `coin` has a pad pool on `hook` whose quote is `other` and whose house flag is set (PadHook storage layout:
    /// PoolInfo word 0 = coin, word 1 = quote, word 2 byte 18 = house; see PadHookLib).
    function _isHousePool(address hook, address coin, address other) internal view returns (bool) {
        bytes32 id = IPadHookRoute(hook).poolIdOf(coin);
        if (id == bytes32(0)) return false;
        bytes32[] memory w = IPadHookRoute(hook).extsload(keccak256(abi.encode(id, uint256(0))), 3);
        return address(uint160(uint256(w[0]))) == coin && address(uint160(uint256(w[1]))) == other
            && (uint256(w[2]) >> 144) & 0xff != 0;
    }

    /// ETH (address(0)) and WETH are interchangeable at hop boundaries; the executor wraps/unwraps.
    function _same(address a, address b) internal view returns (bool) {
        if (a == b) return true;
        return (a == address(0) && b == WETH) || (a == WETH && b == address(0));
    }

    function _validateHop(Hop calldata h, uint256 r, uint256 k) internal view {
        if (h.kind == HopKind.V3) {
            if (h.tokenIn == address(0) || h.tokenOut == address(0)) revert BadRoute(r, k);
            address p = V3_FACTORY.getPool(h.tokenIn, h.tokenOut, h.fee);
            if (p == address(0) || p != h.pool) revert BadRoute(r, k);
        } else if (h.kind == HopKind.V4) {
            if (h.pool != address(0)) revert BadRoute(r, k);
            (address c0, address c1) = h.tokenIn < h.tokenOut ? (h.tokenIn, h.tokenOut) : (h.tokenOut, h.tokenIn);
            PoolKey memory key = PoolKey({
                currency0: Currency.wrap(c0),
                currency1: Currency.wrap(c1),
                fee: h.fee,
                tickSpacing: h.tickSpacing,
                hooks: IHooks(address(0)) // routes never use hooked pools (so never our own pad pools)
            });
            (uint160 sqrtP,,,) = POOL_MANAGER.getSlot0(key.toId());
            if (sqrtP == 0) revert BadRoute(r, k);
        } else if (h.kind == HopKind.PAD) {
            // only a HOUSE pool (KINEKO) of a pad hook bound to THIS registry; both tokens ERC20 (no native ETH)
            if (h.pool == address(0) || h.pool.code.length == 0) revert BadRoute(r, k);
            if (h.tokenIn == address(0) || h.tokenOut == address(0)) revert BadRoute(r, k);
            if (IPadHookRoute(h.pool).REGISTRY() != address(this)) revert BadRoute(r, k);
            if (!_isHousePool(h.pool, h.tokenIn, h.tokenOut) && !_isHousePool(h.pool, h.tokenOut, h.tokenIn)) {
                revert BadRoute(r, k);
            }
        } else if (h.kind == HopKind.CURVE) {
            if (h.pool == address(0) || h.pool.code.length == 0) revert BadRoute(r, k);
            if (h.tokenIn == address(0) || h.tokenOut == address(0)) revert BadRoute(r, k);
            if (h.curveI < 0 || h.curveJ < 0 || h.curveI == h.curveJ) revert BadRoute(r, k);
            if (ICurvePoolMin(h.pool).coins(uint256(uint8(h.curveI))) != h.tokenIn) revert BadRoute(r, k);
            if (ICurvePoolMin(h.pool).coins(uint256(uint8(h.curveJ))) != h.tokenOut) revert BadRoute(r, k);
        } else {
            revert BadRoute(r, k);
        }
    }
}

src/pad/PadFloorMath.sol

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

import {PadMath} from "./libraries/PadMath.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.sol";

/// @title PadFloorMath
/// @notice Stateless floor-band search used by PadHook (split out for contract size). Pure functions only, no storage,
///         called with STATICCALL; deployed once by the hook's constructor.
contract PadFloorMath {
    int24 public constant BAND_WIDTH = 60;
    int24 public constant MAX_COIN_TICK = 887_220;
    /// liquidity above this is never placed in one band (stays far below v4's per-tick maximum)
    uint128 public constant MAX_BAND_LIQUIDITY = 1e32;

    /// Highest band [u, u+W] (u = launchTick + k*W) entirely below the current price such that MAIN plus the band
    /// hold at least `H` coins at price u, i.e. the dump floor is at or above u. Returns ok=false if none.
    function bestBand(bool coin0, uint128 Lm, int24 tl, uint256 Q, uint256 H, int24 poolTick, int24 refTick)
        external
        pure
        returns (bool ok, int24 u, uint128 L)
    {
        if (Q < 3) return (false, 0, 0);
        // coin0: band pool range [u, u+W] is quote-only iff poolTick >= u+W
        // coin1: band pool range [-u-W, -u] is quote-only iff poolTick < -u-W
        int24 maxTop = coin0 ? poolTick : -poolTick - 1;
        if (maxTop > refTick) maxTop = refTick; // never above the slow reference (anti-sandwich)
        if (maxTop > MAX_COIN_TICK) maxTop = MAX_COIN_TICK;
        if (maxTop - BAND_WIDTH < tl) return (false, 0, 0);
        int256 kMax = (int256(maxTop) - BAND_WIDTH - tl) / BAND_WIDTH;
        uint256 q = Q - 2; // leave rounding room for the add
        int256 lo = 0;
        int256 hi = kMax;
        if (!_bandHolds(coin0, Lm, tl, q, H, tl)) return (false, 0, 0);
        while (lo < hi) {
            int256 mid = (lo + hi + 1) / 2;
            if (_bandHolds(coin0, Lm, tl, q, H, int24(int256(tl) + mid * BAND_WIDTH))) lo = mid;
            else hi = mid - 1;
        }
        u = int24(int256(tl) + lo * BAND_WIDTH);
        L = PadMath.liquidityForQuote(coin0, q, u, u + BAND_WIDTH);
        if (L == 0 || L > MAX_BAND_LIQUIDITY) return (false, 0, 0);
        ok = true;
    }

    function _bandHolds(bool coin0, uint128 Lm, int24 tl, uint256 q, uint256 H, int24 u) internal pure returns (bool) {
        uint128 L = PadMath.liquidityForQuote(coin0, q, u, u + BAND_WIDTH);
        uint256 r = PadMath.coinsAt(coin0, Lm, tl, MAX_COIN_TICK, u) + PadMath.coinsBetween(coin0, L, u, u + BAND_WIDTH);
        return r >= H;
    }

    /// Dump floor as a coin-tick: the highest coin-tick u at which MAIN + band would hold >= H coins. It depends only
    /// on the liquidity layout and H, never on the current price, so trades cannot move it.
    function floorTick(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, uint256 H)
        external
        pure
        returns (int24)
    {
        return _floorTick(coin0, Lm, tl, bandL, bandLower, H);
    }

    function _floorTick(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, uint256 H)
        internal
        pure
        returns (int24)
    {
        if (_reservesAt(coin0, Lm, tl, bandL, bandLower, tl) < H) return tl;
        int24 lo = tl;
        int24 hi = MAX_COIN_TICK;
        while (lo < hi) {
            int24 mid = int24((int256(lo) + int256(hi) + 1) / 2);
            if (_reservesAt(coin0, Lm, tl, bandL, bandLower, mid) >= H) lo = mid;
            else hi = mid - 1;
        }
        return lo;
    }

    // ------------------------------------------------------------------ Floor Pawn helpers
    // The floor lends from its band. Lent principal is counted as VIRTUAL band quote at the band's current range, so the
    // published floor = floorTick(Lm, bandL_physical + L(lentQuote), H). Safe because every loan is backed by escrowed
    // coins worth >= its principal at the floor price (FLOOR_TECH_REPORT.md, theorem T1).

    /// Liquidity that `q` quote buys over coin-ticks [a, a+W] placed below the price (rounded down).
    function liqForQuote(bool coin0, uint256 q, int24 a) external pure returns (uint128) {
        return PadMath.liquidityForQuote(coin0, q, a, a + BAND_WIDTH);
    }

    /// Liquidity a repaid principal restores so that physical + virtual stays exactly constant:
    /// L(lent) - L(lent - principal) at the band's range.
    function liqDelta(bool coin0, uint256 lent, uint256 principal, int24 a) external pure returns (uint128) {
        return PadMath.liquidityForQuote(coin0, lent, a, a + BAND_WIDTH)
            - PadMath.liquidityForQuote(coin0, lent - principal, a, a + BAND_WIDTH);
    }

    /// Virtual band liquidity: physical band + the liquidity the outstanding lent quote would buy at the band's range.
    function virtualL(bool coin0, uint128 bandL, int24 bandLower, uint256 lentQ) public pure returns (uint128) {
        uint256 v = uint256(bandL) + PadMath.liquidityForQuote(coin0, lentQ, bandLower, bandLower + BAND_WIDTH);
        return v > type(uint128).max ? type(uint128).max : uint128(v);
    }

    /// Quote needed to add liquidity `L` over [a, a+W] below the price, rounded UP (what a repayment must bring).
    function quoteForLiqUp(bool coin0, uint128 L, int24 a) external pure returns (uint256) {
        (int24 lo, int24 hi) = PadMath.poolRange(coin0, a, a + BAND_WIDTH);
        uint160 sA = TickMath.getSqrtPriceAtTick(lo);
        uint160 sB = TickMath.getSqrtPriceAtTick(hi);
        return coin0 ? SqrtPriceMath.getAmount1Delta(sA, sB, L, true) : SqrtPriceMath.getAmount0Delta(sA, sB, L, true);
    }

    /// Published dump floor with lent quote counted as virtual band quote.
    function floorTickLent(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, uint256 H, uint256 lentQ)
        external
        pure
        returns (int24)
    {
        return _floorTick(coin0, Lm, tl, virtualL(coin0, bandL, bandLower, lentQ), bandLower, H);
    }

    function _reservesAt(bool coin0, uint128 Lm, int24 tl, uint128 bandL, int24 bandLower, int24 u)
        internal
        pure
        returns (uint256)
    {
        return PadMath.coinsAt(coin0, Lm, tl, MAX_COIN_TICK, u)
            + PadMath.coinsAt(coin0, bandL, bandLower, bandLower + BAND_WIDTH, u);
    }

}

src/pad/PadHook.sol

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

import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import {Hooks} from "v4-core/libraries/Hooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "v4-core/types/BeforeSwapDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "v4-core/types/PoolOperation.sol";
import {LPFeeLibrary} from "v4-core/libraries/LPFeeLibrary.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {TransientStateLibrary} from "v4-core/libraries/TransientStateLibrary.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

import {TransientLock} from "../base/TransientLock.sol";
import {DistrictRegistry} from "./DistrictRegistry.sol";
import {DistrictConfig, StreakParams} from "./libraries/PadTypes.sol";
import {PadMath} from "./libraries/PadMath.sol";
import {PadFloorMath} from "./PadFloorMath.sol";
import {PadStreakMath} from "./PadStreakMath.sol";
import {IPadToken} from "./interfaces/IPadExternal.sol";

interface ICreatorVaultMin {
    function register(address coin, address creator, address quote) external;
    function accrue(address coin, uint256 amount) external;
    function isActive(address coin) external view returns (bool);
}

/// @title PadHook
/// @notice The single Uniswap v4 hook behind every KINEKO Pad pool (COIN/QUOTE, dynamic fee, tick spacing 60).
///
/// Standard v4 accounting only: no return deltas, no virtual legs, no hook-initiated swaps. Every trade is a plain
/// PoolManager `Swap`; the fee is v4's native dynamic LP fee, written into pool state with `updateDynamicLPFee`
/// (never the per-swap override flag), so simulators and indexers see the real stored fee.
///
/// Liquidity: the hook owns exactly two positions per pool and nobody else can add or remove liquidity:
///   - MAIN: the whole coin supply, single-sided, from the district launch tick to the max usable tick (never touched
///     again: it alone can buy back every coin ever sold out of it, so sells always clear).
///   - FLOOR BAND: one tick-spacing-wide quote-only band funded by fees, placed by `collect()` right above the pool's
///     dump floor (the price reached if every circulating coin were sold), and re-placed only if that does not lower
///     the floor. See `PAD_NOTES.md` for the design and proofs.
///
/// There are no buy caps. Sells never read the registry or frozen mode, and their hook code cannot revert.
/// Phase 1: the Floor Pawn primitive (`deskOp` + the FloorWouldFall guard + lent / virtual-band accounting, design E of
/// FLOOR_TECH_REPORT.md). Views live in PadReader (reads this hook's storage through `extsload`) to fit EIP-170.
contract PadHook is IHooks, IUnlockCallback, TransientLock {
    using PoolIdLibrary for PoolKey;
    using StateLibrary for IPoolManager;
    using TransientStateLibrary for IPoolManager;
    using BalanceDeltaLibrary for BalanceDelta;

    // ------------------------------------------------------------------ constants

    int24 public constant TICK_SPACING = 60;
    int24 public constant BAND_WIDTH = 60;
    int24 public constant MAX_COIN_TICK = 887_220; // TickMath.maxUsableTick(60)
    uint24 public constant BASE_FEE = 10_000; // 1% in pips (the standard tier)
    uint24 public constant BASE_FEE_2 = 20_000; // 2% tier (chosen by the creator at launch, immutable per coin)
    /// house coin (KINEKO) fixed split of its 2% fee: platform 50% (1.00%), rewards 25% (0.50%), floor 25% (0.50%), creator 0 (no streak)
    uint256 public constant HOUSE_PLATFORM_BPS = 5000;
    uint256 public constant HOUSE_REWARDS_BPS = 2500;
    uint256 internal constant PIPS = 1_000_000;
    uint256 internal constant BPS = 10_000;

    // ---- FEE SPLIT (adjust here before deploy; shares are bps of the 1% base fee, must sum to <= 10_000) ----
    /// creator 0.40% / 0.50% / 0.60% by CREATOR STREAK (consecutive "alive" weeks), rewards 0.30%, platform 0.10%
    /// (FeeRouterV2), the floor gets the remainder (0.20% / 0.10% / 0%) plus 100% of the anti-snipe surplus.
    uint256 public constant CREATOR_BPS_T0 = 4000;
    uint256 public constant CREATOR_BPS_T1 = 5000;
    uint256 public constant CREATOR_BPS_T2 = 6000;
    uint256 public constant REWARDS_BPS = 3000;
    uint256 public constant PLATFORM_BPS = 1000;
    // creator shares are fixed to exactly these three tiers (0.40 / 0.50 / 0.60%); only the streak thresholds, epoch
    // length and "alive" volume come from the registry (timelocked, next-boundary)

    /// the floor band may never sit above the slow reference price, which can rise at most this many ticks per block
    /// (~0.2%): a same-block pump cannot move it at all, a multi-block pump must be held in the open market
    int24 public constant REF_RISE_PER_BLOCK = 20;


    bytes32 internal constant SALT_MAIN = bytes32(0);
    bytes32 internal constant SALT_BAND = bytes32(uint256(1));

    uint8 internal constant ACT_SEED = 1;
    uint8 internal constant ACT_COLLECT = 2;
    uint8 internal constant ACT_CLAIM = 3;
    uint8 internal constant ACT_DESK = 4;

    /// keccak256("kineko.pad.hook.unlock") - 1
    uint256 internal constant UNLOCK_FLAG = 0x2b6a8f1d0c4e7a93b5d2e6f1a7c3b9d8e4f0a1b2c3d4e5f60718293a4b5c6d7e;
    /// transient: fee applied to the current swap (set in beforeSwap, read in afterSwap)
    uint256 internal constant FEE_SLOT = 0x5d1e3a7b9c2f4e6a8b0c1d3e5f7a9b2c4d6e8f0a1b3c5d7e9f1a2b4c6d8e0f12;
    /// transient: pool id whose NEXT swap is the creator's bundled first buy (base fee), set only by the factory
    uint256 internal constant CREATOR_BUY_SLOT = 0x7c9e1b3d5f7a2c4e6b8d0f1a3c5e7b9d2f4a6c8e0b1d3f5a7c9e2b4d6f8a0c13;

    // ------------------------------------------------------------------ immutables

    IPoolManager public immutable POOL_MANAGER;
    DistrictRegistry public immutable REGISTRY;
    address public immutable FACTORY;
    /// platform share (0.2%) -> FeeRouterV2 (buffer + treasury)
    address public immutable PLATFORM;
    /// rewards pot (0.3%) -> RewardsVault
    address public immutable REWARDS;
    /// sell-side (coin) fees are handed to this contract, which sells them through the pool as normal swaps
    address public immutable CONVERTER;
    /// creator shares accrue here ("use it or lose it"); lapsed creators' new shares go to the floor
    ICreatorVaultMin public immutable CREATOR_VAULT;
    /// stateless floor-search math (deployed by this constructor, called with STATICCALL)
    PadFloorMath public immutable FLOOR_MATH;
    /// stateless streak evaluation (deployed by this constructor, called with STATICCALL)
    PadStreakMath public immutable STREAK_MATH;
    /// the floor desk (pawn + redemption policy); the only caller of deskOp
    address public immutable DESK;


    // ------------------------------------------------------------------ state

    struct PoolInfo {
        address coin;
        address quote;
        uint32 districtId;
        uint64 launchBlock;
        bool coinIsToken0;
        int24 launchTick; // coin-tick of the opening price = MAIN lower bound
        int24 bandLower; // coin-tick lower bound of the floor band (valid when bandLiquidity > 0)
        uint24 snipeStartFee;
        uint16 snipeBlocks;
        uint24 storedFee; // mirror of the pool's stored dynamic LP fee
        uint24 baseFee; // 1% or 2%: the coin's fee tier, fixed at launch
        bool house; // KINEKO: fixed split, no creator share, no streak tiers (set only by the house launch path)
        uint8 quoteDecimals;
        uint128 liquidityMain;
        uint128 bandLiquidity;
        uint128 usdPerQuoteE18; // tier reference only
        uint256 volumeUsdE18; // lifetime volume (both sides) in USD at the district reference
        uint256 quoteVolume; // lifetime volume in quote units
        uint256 pendingSurplus; // anti-snipe surplus not yet collected (goes 100% to the floor)
        uint256 pendingFloor; // floor quote held as ERC-6909 claims until it can be placed
        int24 refCoinTick; // slow reference price: follows the price down at once, rises <= REF_RISE_PER_BLOCK per block
        uint64 refBlock;
        int24 stickyTick; // converter reference: follows the pre-swap price by at most REF_RISE_PER_BLOCK per block, both ways
        uint64 stickyBlock;
        int24 openTick; // pre-swap price at the first swap of `openBlock` (block-open price)
        uint64 openBlock;
        // creator streak (see PAD_NOTES "Creator streak"): daily buckets, rolling-window alive test
        uint32 lastDay; // every day before this one has been judged
        uint16 streak; // consecutive alive days (with tier drops)
        uint8 window; // params in force (snapshotted; switch at the next day boundary after a registry change)
        uint16 tier1;
        uint16 tier2;
        uint96 aliveUsd;
        // floor quote lent out by the desk (principal, rounded up); counted as VIRTUAL band quote
        uint128 lentQuote;
    }

    mapping(PoolId => PoolInfo) internal _pools;
    mapping(address coin => PoolId) public poolIdOf;
    /// 14 daily USD-volume buckets per pool, two per word: [day:32][usd:96]
    mapping(PoolId => uint256[7]) internal _dayRing;

    /// fee shares whose push failed (e.g. recipient frozen by the issuer), held as ERC-6909 claims in the PoolManager
    mapping(address recipient => mapping(address currency => uint256)) public owed;
    /// ERC-6909 claims the hook holds per currency = sum(owed) + sum(pendingFloor)  (invariant)
    mapping(address currency => uint256) public claimsLedger;

    // ------------------------------------------------------------------ events

    event PoolSeeded(
        PoolId indexed poolId, address indexed coin, uint32 indexed districtId, address creator, uint128 liquidity, uint256 coinsDeposited
    );
    event Referral(address indexed trader, address indexed referrer, PoolId indexed poolId, uint256 quoteVolume);
    event Collected(
        PoolId indexed poolId,
        uint256 quoteFees,
        uint256 coinFeesBurned,
        uint256 toCreator,
        uint256 toRewards,
        uint256 toPlatform,
        uint256 toFloor
    );
    event FloorPlaced(PoolId indexed poolId, int24 bandLower, uint128 bandLiquidity, uint256 bandQuote, int24 floorTick);
    event FloorDeferred(PoolId indexed poolId, uint256 pendingFloor);
    event CoinsBurned(PoolId indexed poolId, uint256 amount);
    event CoinFeesToConverter(PoolId indexed poolId, uint256 amount);
    event PayoutPushed(address indexed recipient, address indexed currency, uint256 amount);
    event PayoutOwed(address indexed recipient, address indexed currency, uint256 amount);
    event Claimed(address indexed recipient, address indexed currency, uint256 amount);
    event StoredFeeSet(PoolId indexed poolId, uint24 fee);

    // ------------------------------------------------------------------ errors

    error NotPoolManager();
    error NotFactory();
    error UnknownPool();
    error BadPoolKey();
    error AlreadySeeded();
    error BuysFrozen();
    error LiquidityLocked();
    error NothingOwed();
    error AccountingError();

    constructor(
        IPoolManager poolManager,
        DistrictRegistry registry,
        address factory,
        address platform,
        address rewards,
        address converter,
        address creatorVault,
        address desk
    ) {
        DESK = desk;
        if (converter == address(0) || creatorVault == address(0)) revert BadPoolKey();
        CONVERTER = converter;
        CREATOR_VAULT = ICreatorVaultMin(creatorVault);
        FLOOR_MATH = new PadFloorMath();
        STREAK_MATH = new PadStreakMath();
        if (
            address(poolManager) == address(0) || address(registry) == address(0) || factory == address(0)
                || platform == address(0) || rewards == address(0)
        ) revert BadPoolKey();
        POOL_MANAGER = poolManager;
        REGISTRY = registry;
        FACTORY = factory;
        PLATFORM = platform;
        REWARDS = rewards;
        Hooks.validateHookPermissions(IHooks(address(this)), getHookPermissions());
    }

    function getHookPermissions() public pure returns (Hooks.Permissions memory) {
        return Hooks.Permissions({
            beforeInitialize: true,
            afterInitialize: false,
            beforeAddLiquidity: true,
            afterAddLiquidity: false,
            beforeRemoveLiquidity: true,
            afterRemoveLiquidity: false,
            beforeSwap: true,
            afterSwap: true,
            beforeDonate: false,
            afterDonate: false,
            beforeSwapReturnDelta: false,
            afterSwapReturnDelta: false,
            afterAddLiquidityReturnDelta: false,
            afterRemoveLiquidityReturnDelta: false
        });
    }

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

    modifier onlyFactory() {
        if (msg.sender != FACTORY) revert NotFactory();
        _;
    }

    // ================================================================== factory entry points

    /// @notice Registers a freshly initialized pool and deposits the whole coin supply (held by this hook) as the MAIN
    ///         position. Factory only, once per pool.
    function seed(PoolKey calldata key, address coin, uint32 districtId, address creator, int24 launchTick, uint24 baseFee, bool house)
        external
        onlyFactory
        nonReentrant
        returns (PoolId id)
    {
        id = key.toId();
        if (_pools[id].coin != address(0) || PoolId.unwrap(poolIdOf[coin]) != bytes32(0)) revert AlreadySeeded();
        DistrictConfig memory cfg = REGISTRY.config(districtId);
        bool coin0 = Currency.unwrap(key.currency0) == coin;
        address quote = coin0 ? Currency.unwrap(key.currency1) : Currency.unwrap(key.currency0);
        if (
            (!coin0 && Currency.unwrap(key.currency1) != coin) || quote != cfg.quote || address(key.hooks) != address(this)
                || key.fee != LPFeeLibrary.DYNAMIC_FEE_FLAG || key.tickSpacing != TICK_SPACING || creator == address(0)
                || launchTick < cfg.launchTick || launchTick % TICK_SPACING != 0
                || (baseFee != BASE_FEE && baseFee != BASE_FEE_2) || cfg.snipeStartFee < baseFee
        ) revert BadPoolKey();
        // the factory must have initialized the pool exactly at the launch price
        (uint160 sqrtP,,,) = POOL_MANAGER.getSlot0(id);
        if (sqrtP != TickMath.getSqrtPriceAtTick(coin0 ? launchTick : -launchTick)) revert BadPoolKey();

        PoolInfo storage p = _pools[id];
        p.coin = coin;
        p.quote = quote;
        p.districtId = districtId;
        p.launchBlock = uint64(block.number);
        p.refCoinTick = launchTick;
        p.refBlock = uint64(block.number);
        p.stickyTick = launchTick;
        p.stickyBlock = uint64(block.number);
        p.openTick = launchTick;
        p.openBlock = uint64(block.number);
        {
            StreakParams memory sp = REGISTRY.streakParams(districtId);
            p.lastDay = uint32(block.timestamp / 1 days);
            p.window = uint8(sp.windowDays);
            p.tier1 = sp.tier1Epochs;
            p.tier2 = sp.tier2Epochs;
            p.aliveUsd = sp.aliveUsd;
        }
        p.coinIsToken0 = coin0;
        p.launchTick = launchTick;
        p.snipeStartFee = cfg.snipeStartFee;
        p.snipeBlocks = cfg.snipeBlocks;
        p.baseFee = baseFee;
        p.house = house;
        p.quoteDecimals = cfg.quoteDecimals;
        p.usdPerQuoteE18 = cfg.usdPerQuoteE18;
        poolIdOf[coin] = id;
        CREATOR_VAULT.register(coin, creator, quote);

        // stored fee starts at the anti-snipe level (dynamic pools start at 0)
        _setStoredFee(key, p, cfg.snipeBlocks == 0 ? baseFee : cfg.snipeStartFee);

        uint256 supply = IPadToken(coin).balanceOf(address(this));
        uint128 L = PadMath.liquidityForCoins(coin0, supply, launchTick, MAX_COIN_TICK);
        p.liquidityMain = L;
        _unlock(abi.encode(ACT_SEED, abi.encode(id)));
        emit PoolSeeded(id, coin, districtId, creator, L, supply - IPadToken(coin).balanceOf(address(this)));
        _burnHeldCoins(id, coin); // rounding dust
    }

    /// @notice Marks the next swap on `id` (in this transaction) as the creator's bundled first buy: it pays the
    ///         base fee instead of the anti-snipe fee. Factory only; the flag lives in transient storage.
    function openCreatorBuy(PoolId id) external onlyFactory {
        _tstore(CREATOR_BUY_SLOT, uint256(PoolId.unwrap(id)));
    }

    // ================================================================== hook callbacks

    function beforeInitialize(address sender, PoolKey calldata key, uint160) external view onlyPoolManager returns (bytes4) {
        // only the factory creates pools with this hook (anyone else's initialize reverts)
        if (sender != FACTORY) revert NotFactory();
        if (key.fee != LPFeeLibrary.DYNAMIC_FEE_FLAG || key.tickSpacing != TICK_SPACING) revert BadPoolKey();
        return IHooks.beforeInitialize.selector;
    }

    function afterInitialize(address, PoolKey calldata, uint160, int24) external pure returns (bytes4) {
        revert LiquidityLocked();
    }

    /// No external LPs: the hook's own modifyLiquidity calls never reach here (v4 skips self-calls).
    function beforeAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, bytes calldata)
        external
        view
        onlyPoolManager
        returns (bytes4)
    {
        revert LiquidityLocked();
    }

    function afterAddLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
        external
        pure
        returns (bytes4, BalanceDelta)
    {
        revert LiquidityLocked();
    }

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

    function afterRemoveLiquidity(address, PoolKey calldata, ModifyLiquidityParams calldata, BalanceDelta, BalanceDelta, bytes calldata)
        external
        pure
        returns (bytes4, BalanceDelta)
    {
        revert LiquidityLocked();
    }

    function beforeSwap(address, PoolKey calldata key, SwapParams calldata params, bytes calldata)
        external
        onlyPoolManager
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        PoolId id = key.toId();
        PoolInfo storage p = _pools[id];
        if (p.coin == address(0)) revert UnknownPool(); // unreachable: only seeded pools use this hook
        bool isBuy = p.coinIsToken0 ? !params.zeroForOne : params.zeroForOne;
        uint24 fee = p.baseFee;
        if (isBuy) {
            if (REGISTRY.buysFrozen(p.districtId)) revert BuysFrozen();
            if (_tload(CREATOR_BUY_SLOT) == uint256(PoolId.unwrap(id))) {
                _tstore(CREATOR_BUY_SLOT, 0);
            } else {
                fee = _buyFee(p);
            }
        }
        if (fee != p.storedFee) _setStoredFee(key, p, fee);
        _updateRef(id, p);
        _tstore(FEE_SLOT, fee);
        return (IHooks.beforeSwap.selector, BeforeSwapDeltaLibrary.ZERO_DELTA, 0);
    }

    /// @dev Never reverts (no caps): volume, anti-snipe surplus and the streak day ring only.
    function afterSwap(address sender, PoolKey calldata key, SwapParams calldata params, BalanceDelta delta, bytes calldata hookData)
        external
        onlyPoolManager
        returns (bytes4, int128)
    {
        PoolId id = key.toId();
        PoolInfo storage p = _pools[id];
        bool isBuy = p.coinIsToken0 ? !params.zeroForOne : params.zeroForOne;
        int128 dq = p.coinIsToken0 ? delta.amount1() : delta.amount0(); // swapper's quote delta
        uint256 vol;
        if (isBuy) {
            vol = dq < 0 ? uint256(uint128(-dq)) : 0;
            uint256 fee = _tload(FEE_SLOT);
            uint256 bf = p.baseFee;
            if (fee > bf) p.pendingSurplus += FullMath.mulDiv(vol, fee - bf, PIPS);
        } else {
            vol = dq > 0 ? uint256(uint128(dq)) : 0;
        }
        unchecked {
            // volume is bounded by int128 per swap; sums cannot realistically wrap, and wrapping would only
            // affect creator tiers (never solvency), so it must not be able to revert a sell
            p.quoteVolume += vol;
            uint256 usd = FullMath.mulDiv(vol, p.usdPerQuoteE18, 10 ** uint256(p.quoteDecimals));
            p.volumeUsdE18 += usd;
            _addDayVolume(id, p, usd);
        }
        // optional referral: event only (hookData = abi.encode(referrer[, trader])); never used for logic
        if (hookData.length >= 32) {
            address referrer;
            address trader = sender;
            assembly ("memory-safe") {
                referrer := and(calldataload(hookData.offset), 0xffffffffffffffffffffffffffffffffffffffff)
            }
            if (hookData.length >= 64) {
                assembly ("memory-safe") {
                    trader := and(calldataload(add(hookData.offset, 32)), 0xffffffffffffffffffffffffffffffffffffffff)
                }
            }
            if (referrer != address(0)) emit Referral(trader, referrer, id, vol);
        }
        return (IHooks.afterSwap.selector, 0);
    }

    function beforeDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {
        revert LiquidityLocked();
    }

    function afterDonate(address, PoolKey calldata, uint256, uint256, bytes calldata) external pure returns (bytes4) {
        revert LiquidityLocked();
    }

    // ================================================================== permissionless fee handling

    /// @notice Collects the pool's LP fees and splits them: quote fees -> creator / rewards / platform (pushed out
    ///         immediately; a failed push is kept as an ERC-6909 claim) and the floor; coin fees are burned; the floor
    ///         band is re-placed at the dump floor when that raises (never lowers) the floor. Anyone can call it.
    function collect(address coin) external nonReentrant {
        PoolId id = poolIdOf[coin];
        if (_pools[id].coin == address(0)) revert UnknownPool();
        bytes memory ret = _unlock(abi.encode(ACT_COLLECT, abi.encode(id)));
        uint256 feeCoins = abi.decode(ret, (uint256));
        if (feeCoins > 0) emit CoinFeesToConverter(id, feeCoins); // already taken to the converter in the unlock
        _burnHeldCoins(id, coin); // floor-bought band coins / donations burn
    }

    /// @notice Pays `recipient` its owed `currency` (fee shares whose push failed). Anyone can call; pays only the recipient.
    function claim(address recipient, address currency) external nonReentrant returns (uint256 amount) {
        amount = owed[recipient][currency];
        if (amount == 0) revert NothingOwed();
        owed[recipient][currency] = 0;
        claimsLedger[currency] -= amount;
        _unlock(abi.encode(ACT_CLAIM, abi.encode(recipient, currency, amount)));
        emit Claimed(recipient, currency, amount);
    }

    /// @notice Syncs the pool's stored fee with the schedule (e.g. to 1% right after the anti-snipe window) so that
    ///         simulators see the current buy fee before the next swap. Anyone can call.
    function pokeFee(address coin) external nonReentrant {
        PoolId id = poolIdOf[coin];
        PoolInfo storage p = _pools[id];
        if (p.coin == address(0)) revert UnknownPool();
        uint24 fee = _buyFee(p);
        if (fee != p.storedFee) _setStoredFee(_key(p), p, fee);
    }

    // ================================================================== converter credits

    /// @notice The converter minted `floorAmt` quote claims to this hook (floor share of converted sell fees) and
    ///         `owedAmts` for recipients whose push failed. Verified against the real claim balance (ledger invariant).
    function creditFromConverter(address coin, uint256 floorAmt, address[3] calldata to, uint256[3] calldata owedAmts)
        external
        nonReentrant
    {
        if (msg.sender != CONVERTER) revert NotFactory();
        PoolInfo storage p = _pools[poolIdOf[coin]];
        if (p.coin == address(0)) revert UnknownPool();
        address q = p.quote;
        uint256 total = floorAmt + owedAmts[0] + owedAmts[1] + owedAmts[2];
        if (POOL_MANAGER.balanceOf(address(this), uint256(uint160(q))) < claimsLedger[q] + total) revert AccountingError();
        claimsLedger[q] += total;
        p.pendingFloor += floorAmt;
        for (uint256 i; i < 3; ++i) {
            if (owedAmts[i] > 0) {
                owed[to[i]][q] += owedAmts[i];
                emit PayoutOwed(to[i], q, owedAmts[i]);
            }
        }
    }

    // ================================================================== floor desk primitive

    error NotDesk();
    error FloorWouldFall();

    /// @notice DESK only. One atomic desk operation, then the GUARD: the published floor (MAIN + physical band + lent
    ///         quote, over H) must not have fallen, whatever the desk asked for.
    ///   credit/extra: the desk minted credit + extra quote claims to this hook first; credit (repaid principal) goes back
    ///                 into the band (exact virtual-liquidity restore, lentQuote -= credit); extra -> pendingFloor
    ///   burnCoins:    pulled from the desk and burned (redemptions, defaulted pawn collateral)
    ///   pay/keep/to:  removes pay quote from the quote-only band, sends pay - keep to `to` (keep + rounding -> floor claims)
    ///   lend:         the principal owed for that payout (rounded UP) is added to lentQuote
    ///   writeOff:     lent principal of a defaulted loan dropped (its coins are in burnCoins)
    function deskOp(
        address coin,
        uint256 burnCoins,
        uint256 pay,
        uint256 keep,
        address to,
        bool lend,
        uint256 writeOff,
        uint256 credit,
        uint256 extra
    ) external nonReentrant returns (uint256 owedQ) {
        if (msg.sender != DESK) revert NotDesk();
        PoolId id = poolIdOf[coin];
        PoolInfo storage p = _pools[id];
        address q = p.quote;
        if (p.coin == address(0) || POOL_MANAGER.balanceOf(address(this), uint256(uint160(q))) < claimsLedger[q] + credit + extra) {
            revert AccountingError();
        }
        int24 f0 = _pubFloor(p);
        if (burnCoins > 0) {
            SafeTransferLib.safeTransferFrom(coin, msg.sender, address(this), burnCoins);
            _burnHeldCoins(id, coin);
        }
        owedQ = abi.decode(_unlock(abi.encode(ACT_DESK, abi.encode(id, pay, keep, to, credit, extra))), (uint256));
        if (lend) p.lentQuote += uint128(owedQ);
        p.lentQuote -= uint128(writeOff);
        if (_pubFloor(p) < f0) revert FloorWouldFall();
    }

    function _pubFloor(PoolInfo storage p) internal view returns (int24) {
        return _floorTickFor(p, _vL(p), p.bandLower, _effectiveSupply(p.coin));
    }

    function _doDesk(PoolId id, uint256 pay, uint256 keep, address to, uint256 credit, uint256 extra)
        internal
        returns (uint256 owedUp)
    {
        PoolInfo storage p = _pools[id];
        if (credit + extra > 0) POOL_MANAGER.burn(address(this), uint256(uint160(p.quote)), credit + extra);
        if (credit > 0) {
            uint256 lent = p.lentQuote;
            // exactly the virtual liquidity the principal leaves: physical + virtual stays constant
            uint128 l = FLOOR_MATH.liqDelta(p.coinIsToken0, lent, credit, p.bandLower);
            p.lentQuote = uint128(lent - credit);
            if (l > 0) _bandMod(p, int256(uint256(l)));
        }
        if (pay > 0) {
            uint128 dL = FLOOR_MATH.liqForQuote(p.coinIsToken0, pay, p.bandLower) + 1;
            _bandMod(p, -int256(uint256(dL))); // over-draw underflows; a short payout makes _pendFloorDelta revert
            POOL_MANAGER.take(Currency.wrap(p.quote), to, pay - keep);
            owedUp = FLOOR_MATH.quoteForLiqUp(p.coinIsToken0, dL, p.bandLower);
        }
        _pendFloorDelta(p); // net quote left -> floor claims; reverts if the credit did not cover the add
    }

    /// Modifies the band by dL (quote-only: reverts if coins would move). Band position fees realised by the modify:
    /// coin fees -> converter (as in collect), quote fees stay in the delta (-> floor claims).
    function _bandMod(PoolInfo storage p, int256 dL) internal {
        bool coin0 = p.coinIsToken0;
        (int24 lo, int24 hi) = PadMath.poolRange(coin0, p.bandLower, p.bandLower + BAND_WIDTH);
        (BalanceDelta d, BalanceDelta fees) = POOL_MANAGER.modifyLiquidity(
            _key(p), ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: dL, salt: SALT_BAND}), ""
        );
        BalanceDelta prin = d - fees;
        if ((coin0 ? prin.amount0() : prin.amount1()) != 0) revert AccountingError();
        int128 fc = coin0 ? fees.amount0() : fees.amount1();
        if (fc > 0) POOL_MANAGER.take(Currency.wrap(p.coin), CONVERTER, uint256(uint128(fc)));
        p.bandLiquidity = uint128(uint256(int256(uint256(p.bandLiquidity)) + dL));
    }

    /// Net positive quote delta of this hook -> floor claims (pendingFloor); a negative delta reverts.
    function _pendFloorDelta(PoolInfo storage p) internal {
        int256 dq = POOL_MANAGER.currencyDelta(address(this), Currency.wrap(p.quote));
        if (dq < 0) revert AccountingError();
        if (dq > 0) {
            POOL_MANAGER.mint(address(this), uint256(uint160(p.quote)), uint256(dq));
            p.pendingFloor += uint256(dq);
            claimsLedger[p.quote] += uint256(dq);
        }
    }

    // ================================================================== unlock

    function _unlock(bytes memory data) internal returns (bytes memory ret) {
        _tstore(UNLOCK_FLAG, 1);
        ret = POOL_MANAGER.unlock(data);
        _tstore(UNLOCK_FLAG, 0);
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        _consumeCallback(UNLOCK_FLAG, address(POOL_MANAGER));
        (uint8 act, bytes memory rest) = abi.decode(data, (uint8, bytes));
        if (act == ACT_SEED) {
            _doSeed(abi.decode(rest, (PoolId)));
        } else if (act == ACT_COLLECT) {
            return abi.encode(_doCollect(abi.decode(rest, (PoolId))));
        } else if (act == ACT_DESK) {
            (PoolId id, uint256 pay, uint256 keep, address to, uint256 credit, uint256 extra) =
                abi.decode(rest, (PoolId, uint256, uint256, address, uint256, uint256));
            return abi.encode(_doDesk(id, pay, keep, to, credit, extra));
        } else if (act == ACT_CLAIM) {
            (address recipient, address currency, uint256 amount) = abi.decode(rest, (address, address, uint256));
            uint256 cid = uint256(uint160(currency));
            POOL_MANAGER.burn(address(this), cid, amount);
            POOL_MANAGER.take(Currency.wrap(currency), recipient, amount);
        } else {
            revert AccountingError();
        }
        return "";
    }

    function _doSeed(PoolId id) internal {
        PoolInfo storage p = _pools[id];
        PoolKey memory key = _key(p);
        (int24 lo, int24 hi) = PadMath.poolRange(p.coinIsToken0, p.launchTick, MAX_COIN_TICK);
        (BalanceDelta d,) = POOL_MANAGER.modifyLiquidity(
            key,
            ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: int256(uint256(p.liquidityMain)), salt: SALT_MAIN}),
            ""
        );
        int128 dCoin = p.coinIsToken0 ? d.amount0() : d.amount1();
        int128 dQuote = p.coinIsToken0 ? d.amount1() : d.amount0();
        if (dQuote != 0 || dCoin >= 0) revert AccountingError();
        Currency c = Currency.wrap(p.coin);
        POOL_MANAGER.sync(c);
        SafeTransferLib.safeTransfer(p.coin, address(POOL_MANAGER), uint256(uint128(-dCoin)));
        POOL_MANAGER.settle();
    }

    struct CollectVars {
        uint256 qFees;
        uint256 cFees;
        uint256 surplusUsed;
        uint256 toCreator;
        uint256 toRewards;
        uint256 toPlatform;
        uint256 toFloor;
    }

    function _doCollect(PoolId id) internal returns (uint256 feeCoins) {
        PoolInfo storage p = _pools[id];
        PoolKey memory key = _key(p);
        bool coin0 = p.coinIsToken0;
        CollectVars memory v;

        // 1. fees of both positions (liquidityDelta 0 = fee collection only)
        {
            (int24 lo, int24 hi) = PadMath.poolRange(coin0, p.launchTick, MAX_COIN_TICK);
            (BalanceDelta f,) = POOL_MANAGER.modifyLiquidity(
                key, ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: 0, salt: SALT_MAIN}), ""
            );
            _addFees(v, f, coin0);
            if (p.bandLiquidity > 0) {
                (lo, hi) = PadMath.poolRange(coin0, p.bandLower, p.bandLower + BAND_WIDTH);
                (f,) = POOL_MANAGER.modifyLiquidity(
                    key, ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: 0, salt: SALT_BAND}), ""
                );
                _addFees(v, f, coin0);
            }
        }
        // sell-side coin fees go straight from the PoolManager to the converter (never held here), so the floor
        // math keeps counting them as circulating: moving them can never lower the floor
        if (v.cFees > 0) POOL_MANAGER.take(Currency.wrap(p.coin), CONVERTER, v.cFees);

        // 2. split quote fees: anti-snipe surplus first (100% floor), the rest by the base shares
        {
            v.surplusUsed = p.pendingSurplus < v.qFees ? p.pendingSurplus : v.qFees;
            p.pendingSurplus -= v.surplusUsed;
            uint256 base = v.qFees - v.surplusUsed;
            v.toRewards = base * (p.house ? HOUSE_REWARDS_BPS : REWARDS_BPS) / BPS;
            if (p.house) {
                v.toPlatform = base * HOUSE_PLATFORM_BPS / BPS; // KINEKO fixed split: creator 0, floor 25%
            } else {
                v.toCreator = base * _creatorBps(id) / BPS;
                v.toPlatform = base * PLATFORM_BPS / BPS;
                // use it or lose it: a lapsed creator's new share goes to the floor
                if (!CREATOR_VAULT.isActive(p.coin)) v.toCreator = 0;
            }
            v.toFloor = v.qFees - v.toCreator - v.toRewards - v.toPlatform;
        }

        // 3. floor band
        _placeFloor(id, p, key, v.toFloor);

        // 4. push the fee shares out (a frozen recipient only blocks its own share, which stays owed)
        if (v.toCreator > 0) {
            // creator fees accrue as claims in the vault (not pushed)
            POOL_MANAGER.mint(address(CREATOR_VAULT), uint256(uint160(p.quote)), v.toCreator);
            CREATOR_VAULT.accrue(p.coin, v.toCreator);
        }
        _push(REWARDS, p.quote, v.toRewards);
        _push(PLATFORM, p.quote, v.toPlatform);

        // 5. settle: remaining coin deltas (band coins) are taken for the burn; net quote becomes / uses claims
        {
            int256 dc = POOL_MANAGER.currencyDelta(address(this), Currency.wrap(p.coin));
            if (dc < 0) revert AccountingError();
            if (dc > 0) POOL_MANAGER.take(Currency.wrap(p.coin), address(this), uint256(dc));
            int256 dqd = POOL_MANAGER.currencyDelta(address(this), Currency.wrap(p.quote));
            uint256 cid = uint256(uint160(p.quote));
            if (dqd > 0) POOL_MANAGER.mint(address(this), cid, uint256(dqd));
            else if (dqd < 0) POOL_MANAGER.burn(address(this), cid, uint256(-dqd));
        }
        emit Collected(id, v.qFees, v.cFees, v.toCreator, v.toRewards, v.toPlatform, v.toFloor);
        feeCoins = v.cFees;
    }

    function _addFees(CollectVars memory v, BalanceDelta f, bool coin0) internal pure {
        int128 fc = coin0 ? f.amount0() : f.amount1();
        int128 fq = coin0 ? f.amount1() : f.amount0();
        if (fc < 0 || fq < 0) revert AccountingError();
        v.cFees += uint256(uint128(fc));
        v.qFees += uint256(uint128(fq));
    }

    function _push(address to, address currency, uint256 amount) internal {
        if (amount == 0) return;
        try POOL_MANAGER.take(Currency.wrap(currency), to, amount) {
            emit PayoutPushed(to, currency, amount);
        } catch {
            owed[to][currency] += amount;
            claimsLedger[currency] += amount;
            emit PayoutOwed(to, currency, amount);
        }
    }

    // ------------------------------------------------------------------ floor band

    struct FloorVars {
        uint160 sqrtP;
        int24 poolTick;
        uint256 H; // coins the pool must hold at the floor (all non-burned coins not held by the hook)
        int24 fOld;
        uint256 bandQuote;
        uint256 bandCoins;
        uint256 Q;
        int24 u;
        uint128 L;
        bool ok;
    }

    function _placeFloor(PoolId id, PoolInfo storage p, PoolKey memory key, uint256 floorAdd) internal {
        FloorVars memory f;
        (f.sqrtP, f.poolTick,,) = POOL_MANAGER.getSlot0(id);
        bool coin0 = p.coinIsToken0;
        // coins held by the hook (just-taken fee coins, donations) are burned after this unlock
        f.H = _effectiveSupply(p.coin);
        f.fOld = _floorTickFor(p, _vL(p), p.bandLower, f.H); // virtual band

        if (p.bandLiquidity > 0) {
            f.bandQuote = PadMath.quoteAtSqrt(coin0, p.bandLiquidity, p.bandLower, p.bandLower + BAND_WIDTH, f.sqrtP);
            f.bandCoins = PadMath.coinsAtSqrt(coin0, p.bandLiquidity, p.bandLower, p.bandLower + BAND_WIDTH, f.sqrtP);
        }
        uint256 H2 = f.H > f.bandCoins ? f.H - f.bandCoins : 0; // band coins are burned on a re-place
        f.Q = f.bandQuote + p.pendingFloor + floorAdd + p.lentQuote; // lent quote counts
        (f.ok, f.u, f.L) = _bestBand(p, f.Q, H2, f.poolTick, _refNow(p, PadMath.coinTickOf(coin0, f.poolTick)));

        if (!f.ok || f.u < f.fOld) {
            // cannot raise the floor now: keep the new floor quote as claims for the next collect
            p.pendingFloor += floorAdd;
            claimsLedger[p.quote] += floorAdd;
            emit FloorDeferred(id, p.pendingFloor);
            return;
        }

        uint256 removedQ;
        if (p.bandLiquidity > 0) {
            (int24 lo, int24 hi) = PadMath.poolRange(coin0, p.bandLower, p.bandLower + BAND_WIDTH);
            (BalanceDelta d,) = POOL_MANAGER.modifyLiquidity(
                key,
                ModifyLiquidityParams({
                    tickLower: lo,
                    tickUpper: hi,
                    liquidityDelta: -int256(uint256(p.bandLiquidity)),
                    salt: SALT_BAND
                }),
                ""
            );
            int128 rq = coin0 ? d.amount1() : d.amount0();
            if (rq < 0) revert AccountingError();
            removedQ = uint256(uint128(rq));
        }
        uint256 used;
        // physical part = total minus the liquidity the lent quote represents at the new range
        {
            uint128 lentL = FLOOR_MATH.liqForQuote(coin0, p.lentQuote, f.u);
            f.L = f.L > lentL ? f.L - lentL : 0;
        }
        if (f.L > 0) {
            (int24 lo, int24 hi) = PadMath.poolRange(coin0, f.u, f.u + BAND_WIDTH);
            (BalanceDelta d,) = POOL_MANAGER.modifyLiquidity(
                key,
                ModifyLiquidityParams({tickLower: lo, tickUpper: hi, liquidityDelta: int256(uint256(f.L)), salt: SALT_BAND}),
                ""
            );
            int128 aq = coin0 ? d.amount1() : d.amount0();
            int128 ac = coin0 ? d.amount0() : d.amount1();
            if (aq > 0 || ac != 0) revert AccountingError(); // must be quote-only
            used = uint256(uint128(-aq));
        }
        uint256 avail = removedQ + p.pendingFloor + floorAdd;
        if (used > avail) revert AccountingError();
        uint256 newPending = avail - used;
        claimsLedger[p.quote] = claimsLedger[p.quote] - p.pendingFloor + newPending;
        p.pendingFloor = newPending;
        p.bandLower = f.u;
        p.bandLiquidity = f.L;
        emit FloorPlaced(id, f.u, f.L, used, f.u);
    }

    /// virtual band liquidity = physical + lent quote at the band's range
    function _vL(PoolInfo storage p) internal view returns (uint128) {
        return FLOOR_MATH.virtualL(p.coinIsToken0, p.bandLiquidity, p.bandLower, p.lentQuote);
    }

    function _bestBand(PoolInfo storage p, uint256 Q, uint256 H, int24 poolTick, int24 refTick)
        internal
        view
        returns (bool, int24, uint128)
    {
        return FLOOR_MATH.bestBand(p.coinIsToken0, p.liquidityMain, p.launchTick, Q, H, poolTick, refTick);
    }

    function _floorTickFor(PoolInfo storage p, uint128 bandL, int24 bandLower, uint256 H) internal view returns (int24) {
        return FLOOR_MATH.floorTick(p.coinIsToken0, p.liquidityMain, p.launchTick, bandL, bandLower, H);
    }

    /// Slow reference as of now, given the current coin-tick: min(current, stored + rise allowance since refBlock).
    function _refNow(PoolInfo storage p, int24 cur) internal view returns (int24) {
        uint256 rb = p.refBlock;
        uint256 elapsed = block.number > rb ? block.number - rb : 0; // saturating: must never revert on a sell
        if (elapsed > 100_000) elapsed = 100_000;
        int256 cap = int256(p.refCoinTick) + int256(elapsed) * REF_RISE_PER_BLOCK;
        return int256(cur) < cap ? cur : int24(cap);
    }

    /// Called before every swap (buys and sells) with the pre-swap price. Pure arithmetic + storage writes; cannot revert.
    function _updateRef(PoolId id, PoolInfo storage p) internal {
        (, int24 t,,) = POOL_MANAGER.getSlot0(id);
        int24 cur = PadMath.coinTickOf(p.coinIsToken0, t);
        if (p.stickyBlock != block.number) {
            p.stickyTick = _stickyNow(p, cur);
            p.stickyBlock = uint64(block.number);
            p.openTick = cur;
            p.openBlock = uint64(block.number);
        }
        int24 r = _refNow(p, cur);
        if (r != p.refCoinTick || p.refBlock != block.number) {
            p.refCoinTick = r;
            p.refBlock = uint64(block.number);
        }
    }

    function _effectiveSupply(address coin) internal view returns (uint256) {
        uint256 ts = IPadToken(coin).totalSupply();
        uint256 held = IPadToken(coin).balanceOf(address(this));
        return ts > held ? ts - held : 0;
    }

    function _burnHeldCoins(PoolId id, address coin) internal {
        uint256 bal = IPadToken(coin).balanceOf(address(this));
        if (bal > 0) {
            IPadToken(coin).burn(bal);
            emit CoinsBurned(id, bal);
        }
    }

    // ------------------------------------------------------------------ fees

    function _buyFee(PoolInfo storage p) internal view returns (uint24) {
        uint256 n = p.snipeBlocks;
        uint256 lb = p.launchBlock;
        uint256 elapsed = block.number > lb ? block.number - lb : 0;
        uint256 bf = p.baseFee;
        if (elapsed >= n) return uint24(bf);
        uint256 start = p.snipeStartFee;
        return uint24(start - (start - bf) * elapsed / n);
    }

    function _creatorBps(PoolId id) internal view returns (uint256) {
        (uint16 streak, PadStreakMath.Params memory cur) = _streakNow(id, _pools[id]);
        uint256 t = STREAK_MATH.tier(streak, cur.t1, cur.t2);
        return t == 2 ? CREATOR_BPS_T2 : (t == 1 ? CREATOR_BPS_T1 : CREATOR_BPS_T0);
    }

    /// Lazy close-out of every fully elapsed day (see PadStreakMath). View; never reverts on its own.
    function _streakNow(PoolId id, PoolInfo storage p) internal view returns (uint16 streak, PadStreakMath.Params memory cur) {
        cur = PadStreakMath.Params(p.window, p.aliveUsd, p.tier1, p.tier2);
        streak = p.streak;
        uint256 today = block.timestamp / 1 days;
        if (today <= p.lastDay) return (streak, cur);
        (streak, cur) = STREAK_MATH.close(address(REGISTRY), p.districtId, _dayRing[id], p.lastDay, today, streak, cur);
    }

    /// On every swap: close out elapsed days (first trade of a new day), then add the volume to today's bucket.
    function _addDayVolume(PoolId id, PoolInfo storage p, uint256 usd) internal {
        uint256 today = block.timestamp / 1 days;
        if (today > p.lastDay) {
            (uint16 streak, PadStreakMath.Params memory cur) = _streakNow(id, p);
            p.streak = streak;
            p.window = cur.window;
            p.aliveUsd = cur.bar;
            p.tier1 = cur.t1;
            p.tier2 = cur.t2;
            p.lastDay = uint32(today);
        }
        unchecked {
            uint256 slot = today % 14;
            uint256 shift = (slot & 1) * 128;
            uint256 w = _dayRing[id][slot >> 1];
            uint256 half = (w >> shift) & ((1 << 128) - 1);
            uint256 v = (half >> 96) == (today & 0xffffffff) ? half & ((1 << 96) - 1) : 0;
            v = v + usd >= (1 << 96) ? (1 << 96) - 1 : v + usd;
            _dayRing[id][slot >> 1] = (w & ~(((1 << 128) - 1) << shift)) | ((((today & 0xffffffff) << 96) | v) << shift);
        }
    }

    function _setStoredFee(PoolKey memory key, PoolInfo storage p, uint24 fee) internal {
        POOL_MANAGER.updateDynamicLPFee(key, fee);
        p.storedFee = fee;
        emit StoredFeeSet(key.toId(), fee);
    }

    function _key(PoolInfo storage p) internal view returns (PoolKey memory) {
        (address c0, address c1) = p.coinIsToken0 ? (p.coin, p.quote) : (p.quote, p.coin);
        return PoolKey({
            currency0: Currency.wrap(c0),
            currency1: Currency.wrap(c1),
            fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
            tickSpacing: TICK_SPACING,
            hooks: IHooks(address(this))
        });
    }

    // ================================================================== views

    function _stickyNow(PoolInfo storage p, int24 cur) internal view returns (int24) {
        uint256 sb = p.stickyBlock;
        uint256 elapsed = block.number > sb ? block.number - sb : 0;
        if (elapsed > 100_000) elapsed = 100_000;
        int256 step = int256(elapsed) * REF_RISE_PER_BLOCK;
        int256 st = p.stickyTick;
        int256 c = cur;
        if (c > st + step) return int24(st + step);
        if (c < st - step) return int24(st - step);
        return cur;
    }


    /// @notice Raw storage words [startSlot, startSlot + nSlots) for PadHookLib / PadReader (all views live there).
    function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory) {
        assembly ("memory-safe") {
            let memptr := mload(0x40)
            let start := memptr
            mstore(memptr, 0x20)
            mstore(add(memptr, 0x20), nSlots)
            memptr := add(memptr, 0x40)
            let end := add(memptr, shl(5, nSlots))
            for {} lt(memptr, end) {} {
                mstore(memptr, sload(startSlot))
                memptr := add(memptr, 0x20)
                startSlot := add(startSlot, 1)
            }
            return(start, sub(end, start))
        }
    }
}

src/pad/PadStreakMath.sol

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

interface IStreakRegistry {
    function streakParamsAt(uint256 id) external view returns (uint32, uint96, uint16, uint16, uint256);
}

/// @title PadStreakMath
/// @notice Stateless creator-streak evaluation used by PadHook (split out for contract size). Pure functions only,
///         called with STATICCALL; deployed once by the hook's constructor.
///
/// Data: a ring of 14 daily buckets per coin, two per word: bucket = [day:32][usd:96] (usd in 1e18, saturating),
/// slot = day % 14. Day index = block.timestamp / 1 days (UTC days).
///
/// Rule (STREAK_VOLUME_CHECK.md): each fully elapsed day `d` is judged once, lazily, on the first trade/collect of a later
/// day: ALIVE if the rolling sum of the `window` days ending at `d` is >= `bar`. Alive -> streak + 1. Dead -> drop one
/// tier and reset to that tier's threshold (streak >= t2 -> t1; otherwise 0). Tiers: >= t2 -> T2, >= t1 -> T1, else T0.
/// Parameters come with the time they took effect; a day is judged with the new parameters only if it STARTS at or
/// after that time (next day boundary, never retroactive). At the switch an earned tier is never lost.
contract PadStreakMath {
    uint256 internal constant RING = 14;

    struct Params {
        uint8 window;
        uint96 bar;
        uint16 t1;
        uint16 t2;
    }

    function bucketDay(uint256[7] memory ring, uint256 slot) internal pure returns (uint256 day, uint256 usd) {
        uint256 w = ring[slot >> 1];
        uint256 half = (w >> ((slot & 1) * 128)) & ((1 << 128) - 1);
        return (half >> 96, half & ((1 << 96) - 1));
    }

    /// Rolling USD sum of the `window` days ending at day `d` (inclusive).
    function rollingSum(uint256[7] memory ring, uint256 d, uint256 window) public pure returns (uint256 sum) {
        unchecked {
            for (uint256 s; s < RING; ++s) {
                (uint256 bd, uint256 usd) = bucketDay(ring, s);
                if (usd != 0 && bd <= d && d - bd < window) sum += usd;
            }
        }
    }

    function tier(uint16 streak, uint16 t1, uint16 t2) public pure returns (uint256) {
        return streak >= t2 ? 2 : (streak >= t1 ? 1 : 0);
    }

    function _dead(uint16 streak, uint16 t1, uint16 t2) internal pure returns (uint16) {
        return streak >= t2 ? t1 : 0;
    }

    /// Registry params + effective time via a failure-tolerant staticcall (on failure: keep the running params).
    function newParams(address registry, uint256 districtId, Params memory old)
        public
        view
        returns (Params memory n, uint256 effAt)
    {
        n = old;
        effAt = type(uint256).max;
        (bool ok, bytes memory r) = registry.staticcall{gas: 50_000}(
            abi.encodeWithSelector(IStreakRegistry.streakParamsAt.selector, districtId)
        );
        if (!ok || r.length != 160) return (n, effAt);
        (uint256 w, uint256 bar, uint256 t1, uint256 t2, uint256 e) = abi.decode(r, (uint256, uint256, uint256, uint256, uint256));
        if (w == 0 || w > 14 || bar == 0 || bar > type(uint96).max || t1 == 0 || t2 <= t1 || t2 > type(uint16).max) {
            return (n, effAt);
        }
        n = Params(uint8(w), uint96(bar), uint16(t1), uint16(t2));
        effAt = e;
    }

    /// Judges days [lastDay, today) and returns the new streak and the params in force for `today`.
    function close(
        address registry,
        uint256 districtId,
        uint256[7] memory ring,
        uint256 lastDay,
        uint256 today,
        uint16 streak,
        Params memory oldP
    ) external view returns (uint16, Params memory) {
        (Params memory newP, uint256 effAt) = newParams(registry, districtId, oldP);
        return _close(ring, lastDay, today, streak, oldP, newP, effAt);
    }

    function _close(
        uint256[7] memory ring,
        uint256 lastDay,
        uint256 today,
        uint16 streak,
        Params memory oldP,
        Params memory newP,
        uint256 effAt
    ) internal pure returns (uint16, Params memory) {
        unchecked {
            Params memory cur = oldP;
            bool switched = !_differs(oldP, newP);
            uint256 d = lastDay;
            // days with possible volume in their window: at most 14 + 1 iterations
            uint256 end = today;
            uint256 hardStop = lastDay + RING + 1;
            for (; d < end && d < hardStop; ++d) {
                if (!switched && d * 1 days >= effAt) {
                    streak = _switch(streak, cur, newP);
                    cur = newP;
                    switched = true;
                }
                bool alive = rollingSum(ring, d, cur.window) >= cur.bar;
                streak = alive ? (streak < type(uint16).max ? streak + 1 : streak) : _dead(streak, cur.t1, cur.t2);
            }
            // any remaining days have empty windows: all dead (two drops reach 0)
            if (d < end) {
                if (!switched) {
                    streak = _switch(streak, cur, newP);
                    cur = newP;
                }
                streak = _dead(_dead(streak, cur.t1, cur.t2), cur.t1, cur.t2);
            } else if (!switched && today * 1 days >= effAt) {
                streak = _switch(streak, cur, newP);
                cur = newP;
            }
            return (streak, cur);
        }
    }

    function _differs(Params memory a, Params memory b) internal pure returns (bool) {
        return a.window != b.window || a.bar != b.bar || a.t1 != b.t1 || a.t2 != b.t2;
    }

    /// Streak counts days in both regimes; only the thresholds change. Never lose an earned tier.
    function _switch(uint16 streak, Params memory o, Params memory n) internal pure returns (uint16) {
        uint256 t = tier(streak, o.t1, o.t2);
        uint16 minS = t == 2 ? n.t2 : (t == 1 ? n.t1 : 0);
        return streak < minS ? minS : streak;
    }
}

src/pad/base/RouteExecutor.sol

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IUnlockCallback} from "v4-core/interfaces/callback/IUnlockCallback.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {BalanceDelta, BalanceDeltaLibrary} from "v4-core/types/BalanceDelta.sol";
import {SwapParams} from "v4-core/types/PoolOperation.sol";
import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

import {TransientLock} from "../../base/TransientLock.sol";
import {Hop, HopKind} from "../libraries/PadTypes.sol";
import {IUniswapV3PoolMin, ICurvePoolMin, IWETH9Min} from "../interfaces/IPadExternal.sol";

/// @title RouteExecutor
/// @notice Executes fixed routes over Uniswap v3 pools, hookless (or explicitly given) v4 pools and Curve int128 pools.
///         Exact input only; every hop must consume its whole input (else revert, so nothing is left behind); every
///         output is a balance delta; the only approval (Curve) is exact and reset to zero; callbacks are accepted
///         only from the pool / PoolManager we are calling right now, while our lock is held (transient flags).
abstract contract RouteExecutor is IUnlockCallback, TransientLock {
    using BalanceDeltaLibrary for BalanceDelta;

    uint160 internal constant MIN_SQRT_LIMIT = TickMath.MIN_SQRT_PRICE + 1;
    uint160 internal constant MAX_SQRT_LIMIT = TickMath.MAX_SQRT_PRICE - 1;
    /// keccak256("kineko.pad.swapper.unlock") - 1
    uint256 internal constant SW_UNLOCK_FLAG = 0x3e1d5c7b9a2f4e6d8c0b1a3f5e7d9c2b4a6f8e0d1c3b5a7f9e2d4c6b8a0f1e23;
    /// transient: the v3 pool we are swapping in right now
    uint256 internal constant V3_POOL_SLOT = 0x4f2e6d8c0b1a3f5e7d9c2b4a6f8e0d1c3b5a7f9e2d4c6b8a0f1e3d5c7b9a2f34;

    IPoolManager public immutable POOL_MANAGER;
    address public immutable WETH;

    error PartialFill();
    error NoRoute();
    error BadHop();
    error EthNotAccepted();
    error UnexpectedCallback3();

    constructor(IPoolManager pm, address weth) {
        POOL_MANAGER = pm;
        WETH = weth;
    }

    /// ETH only arrives from our own swaps (PoolManager take, WETH unwrap) while an operation holds the lock.
    receive() external payable virtual {
        if (!_isLocked()) revert EthNotAccepted();
    }

    function _runHops(Hop[] memory hops, bool reverse, address startToken, address endToken, uint256 amount)
        internal
        returns (uint256)
    {
        address cur = startToken;
        uint256 n = hops.length;
        for (uint256 i; i < n; ++i) {
            Hop memory h = reverse ? _flip(hops[n - 1 - i]) : hops[i];
            // ETH <-> WETH at hop boundaries
            if (h.tokenIn == WETH && cur == address(0)) {
                IWETH9Min(WETH).deposit{value: amount}();
            } else if (h.tokenIn == address(0) && cur == WETH) {
                IWETH9Min(WETH).withdraw(amount);
            } else if (h.tokenIn != cur) {
                revert BadHop();
            }
            amount = _hop(h, amount);
            cur = h.tokenOut;
        }
        if (endToken == address(0) && cur == WETH) {
            IWETH9Min(WETH).withdraw(amount); // ETH receivers get native ETH
        } else if (cur != endToken) {
            revert BadHop();
        }
        return amount;
    }

    /// @dev Returns a NEW struct (assigning `r = h` would alias the same memory and corrupt the swap).
    function _flip(Hop memory h) internal pure returns (Hop memory) {
        return Hop({
            kind: h.kind,
            pool: h.pool,
            tokenIn: h.tokenOut,
            tokenOut: h.tokenIn,
            fee: h.fee,
            tickSpacing: h.tickSpacing,
            curveI: h.curveJ,
            curveJ: h.curveI
        });
    }

    function _hop(Hop memory h, uint256 amountIn) internal returns (uint256 out) {
        if (amountIn == 0 || amountIn > uint256(uint128(type(int128).max))) revert BadHop();
        if (h.kind == HopKind.V3) {
            uint256 b0 = SafeTransferLib.balanceOf(h.tokenOut, address(this));
            bool zfo = h.tokenIn < h.tokenOut;
            _tstore(V3_POOL_SLOT, uint256(uint160(h.pool)));
            (int256 a0, int256 a1) = IUniswapV3PoolMin(h.pool).swap(
                address(this), zfo, int256(amountIn), zfo ? MIN_SQRT_LIMIT_V3 : MAX_SQRT_LIMIT_V3, abi.encode(h.tokenIn)
            );
            _tstore(V3_POOL_SLOT, 0);
            if ((zfo ? a0 : a1) != int256(amountIn)) revert PartialFill();
            out = SafeTransferLib.balanceOf(h.tokenOut, address(this)) - b0;
        } else if (h.kind == HopKind.V4) {
            (address c0, address c1) = h.tokenIn < h.tokenOut ? (h.tokenIn, h.tokenOut) : (h.tokenOut, h.tokenIn);
            PoolKey memory key = PoolKey({
                currency0: Currency.wrap(c0),
                currency1: Currency.wrap(c1),
                fee: h.fee,
                tickSpacing: h.tickSpacing,
                hooks: IHooks(address(0))
            });
            uint256 b0 = _selfBalance(h.tokenOut);
            _v4Swap(key, h.tokenIn == c0, amountIn, "", address(this));
            out = _selfBalance(h.tokenOut) - b0;
        } else if (h.kind == HopKind.PAD) {
            // a house pad pool (our hook; validated at registration): standard dynamic-fee v4 swap through the hook
            (address c0, address c1) = h.tokenIn < h.tokenOut ? (h.tokenIn, h.tokenOut) : (h.tokenOut, h.tokenIn);
            PoolKey memory key = PoolKey({
                currency0: Currency.wrap(c0),
                currency1: Currency.wrap(c1),
                fee: 0x800000, // LPFeeLibrary.DYNAMIC_FEE_FLAG
                tickSpacing: 60,
                hooks: IHooks(h.pool)
            });
            uint256 b0 = _selfBalance(h.tokenOut);
            _v4Swap(key, h.tokenIn == c0, amountIn, "", address(this));
            out = _selfBalance(h.tokenOut) - b0;
        } else if (h.kind == HopKind.CURVE) {
            uint256 b0 = SafeTransferLib.balanceOf(h.tokenOut, address(this));
            uint256 in0 = SafeTransferLib.balanceOf(h.tokenIn, address(this));
            SafeTransferLib.safeApproveWithRetry(h.tokenIn, h.pool, amountIn);
            ICurvePoolMin(h.pool).exchange(int128(h.curveI), int128(h.curveJ), amountIn, 0);
            SafeTransferLib.safeApproveWithRetry(h.tokenIn, h.pool, 0);
            if (in0 - SafeTransferLib.balanceOf(h.tokenIn, address(this)) != amountIn) revert PartialFill();
            out = SafeTransferLib.balanceOf(h.tokenOut, address(this)) - b0;
        } else {
            revert BadHop();
        }
        if (out == 0) revert PartialFill();
    }

    /// v3 limits (TickMath v3: MIN_SQRT_RATIO = 4295128739, MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342)
    uint160 internal constant MIN_SQRT_LIMIT_V3 = 4295128739 + 1;
    uint160 internal constant MAX_SQRT_LIMIT_V3 = 1461446703485210103287273052203988822378723970342 - 1;

    /// @notice Uniswap v3 callback: only the pool we are calling right now, only while locked.
    function uniswapV3SwapCallback(int256 a0, int256 a1, bytes calldata data) external {
        if (!_isLocked() || msg.sender != address(uint160(_tload(V3_POOL_SLOT))) || msg.sender == address(0)) {
            revert UnexpectedCallback3();
        }
        address tokenIn = abi.decode(data, (address));
        uint256 pay = a0 > 0 ? uint256(a0) : uint256(a1);
        SafeTransferLib.safeTransfer(tokenIn, msg.sender, pay);
    }

    function _selfBalance(address token) internal view returns (uint256) {
        return token == address(0) ? address(this).balance : SafeTransferLib.balanceOf(token, address(this));
    }

    // ------------------------------------------------------------------ v4 swaps (route hops and pad pools)

    /// @dev Exact-input swap in one v4 pool. Input is paid from this contract; output is taken to `recipient`.
    function _v4Swap(PoolKey memory key, bool zeroForOne, uint256 amountIn, bytes memory hookData, address recipient)
        internal
    {
        _tstore(SW_UNLOCK_FLAG, 1);
        POOL_MANAGER.unlock(abi.encode(key, zeroForOne, amountIn, hookData, recipient, uint256(0)));
        _tstore(SW_UNLOCK_FLAG, 0);
    }

    /// @dev Exact-output swap: receive exactly `amountOut` to `recipient`, paying at most `maxIn` from this contract.
    ///      Returns the input actually paid.
    function _v4SwapExactOut(PoolKey memory key, bool zeroForOne, uint256 amountOut, uint256 maxIn, bytes memory hookData, address recipient)
        internal
        returns (uint256 paid)
    {
        _tstore(SW_UNLOCK_FLAG, 1);
        paid = abi.decode(POOL_MANAGER.unlock(abi.encode(key, zeroForOne, amountOut, hookData, recipient, maxIn)), (uint256));
        _tstore(SW_UNLOCK_FLAG, 0);
    }

    function unlockCallback(bytes calldata data) external returns (bytes memory) {
        _consumeCallback(SW_UNLOCK_FLAG, address(POOL_MANAGER));
        (PoolKey memory key, bool zfo, uint256 amount, bytes memory hookData, address recipient, uint256 maxIn) =
            abi.decode(data, (PoolKey, bool, uint256, bytes, address, uint256));
        bool exactOut = maxIn != 0;
        BalanceDelta d = POOL_MANAGER.swap(
            key,
            SwapParams({
                zeroForOne: zfo,
                amountSpecified: exactOut ? int256(amount) : -int256(amount),
                sqrtPriceLimitX96: zfo ? MIN_SQRT_LIMIT : MAX_SQRT_LIMIT
            }),
            hookData
        );
        int128 dIn = zfo ? d.amount0() : d.amount1();
        int128 dOut = zfo ? d.amount1() : d.amount0();
        if (dIn >= 0 || dOut < 0) revert PartialFill();
        uint256 amountIn = uint256(uint128(-dIn));
        if (exactOut ? (uint256(uint128(dOut)) != amount || amountIn > maxIn) : amountIn != amount) revert PartialFill();
        Currency cIn = zfo ? key.currency0 : key.currency1;
        Currency cOut = zfo ? key.currency1 : key.currency0;
        if (cIn.isAddressZero()) {
            POOL_MANAGER.settle{value: amountIn}();
        } else {
            POOL_MANAGER.sync(cIn);
            SafeTransferLib.safeTransfer(Currency.unwrap(cIn), address(POOL_MANAGER), amountIn);
            POOL_MANAGER.settle();
        }
        if (dOut > 0) POOL_MANAGER.take(cOut, recipient, uint256(uint128(dOut)));
        return abi.encode(amountIn);
    }

}

src/pad/interfaces/IPadExternal.sol

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

/// Minimal external interfaces used by the pad contracts (only what we call).

interface IUniswapV3PoolMin {
    function token0() external view returns (address);
    function token1() external view returns (address);
    function fee() external view returns (uint24);
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );
    function swap(address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data)
        external
        returns (int256 amount0, int256 amount1);
}

interface IUniswapV3FactoryMin {
    function getPool(address tokenA, address tokenB, uint24 fee) external view returns (address);
}

/// Curve plain / stableswap pools with int128 indices (e.g. tBTC/WBTC `0xB7EC…6726`).
interface ICurvePoolMin {
    function coins(uint256 i) external view returns (address);
    function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external returns (uint256);
    function get_dy(int128 i, int128 j, uint256 dx) external view returns (uint256);
}

interface IWETH9Min {
    function deposit() external payable;
    function withdraw(uint256) external;
    function balanceOf(address) external view returns (uint256);
}

/// Permit2 SignatureTransfer (Uniswap), only what we use.
interface IPermit2Transfer {
    struct TokenPermissions {
        address token;
        uint256 amount;
    }

    struct PermitTransferFrom {
        TokenPermissions permitted;
        uint256 nonce;
        uint256 deadline;
    }

    struct SignatureTransferDetails {
        address to;
        uint256 requestedAmount;
    }

    function permitTransferFrom(
        PermitTransferFrom calldata permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;
}

/// Morpho UrdFactory (mainnet `0x9baA51245CDD28D8D74Afe8B3959b616E9ee7c8D`, verified on-chain 29 Sep 2026).
interface IUrdFactory {
    function createUrd(
        address initialOwner,
        uint256 initialTimelock,
        bytes32 initialRoot,
        bytes32 initialIpfsHash,
        bytes32 salt
    ) external returns (address);
    function isUrd(address) external view returns (bool);
}

/// Morpho Universal Rewards Distributor (only what the vault calls or reads).
interface IUniversalRewardsDistributor {
    function owner() external view returns (address);
    function timelock() external view returns (uint256);
    function root() external view returns (bytes32);
    function pendingRoot() external view returns (bytes32 root, bytes32 ipfsHash, uint256 validAt);
    function submitRoot(bytes32 newRoot, bytes32 newIpfsHash) external;
    function acceptRoot() external;
    function revokePendingRoot() external;
    function claim(address account, address reward, uint256 claimable, bytes32[] calldata proof)
        external
        returns (uint256 amount);
    function claimed(address account, address reward) external view returns (uint256);
}

interface IPadToken {
    function burn(uint256 amount) external;
    function totalSupply() external view returns (uint256);
    function balanceOf(address) external view returns (uint256);
}

src/pad/libraries/PadHookLib.sol

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

import {IPoolManager} from "v4-core/interfaces/IPoolManager.sol";
import {IHooks} from "v4-core/interfaces/IHooks.sol";
import {PoolKey} from "v4-core/types/PoolKey.sol";
import {PoolId} from "v4-core/types/PoolId.sol";
import {Currency} from "v4-core/types/Currency.sol";
import {StateLibrary} from "v4-core/libraries/StateLibrary.sol";
import {LPFeeLibrary} from "v4-core/libraries/LPFeeLibrary.sol";

import {PadHook} from "../PadHook.sol";
import {PadMath} from "./PadMath.sol";
import {PadStreakMath} from "../PadStreakMath.sol";
import {IPadToken} from "../interfaces/IPadExternal.sol";

/// @title PadHookLib
/// @notice PadHook's views, computed by the CALLER from the hook's storage (`PadHook.extsload`), so the hook fits EIP-170
///         with the Floor Pawn primitive ("view diet"). Internal library: every consumer only needs the hook address.
///         The layout is pinned by test/pad/PadReader.t.sol (every field written by real pad actions and read back) and
///         must change together with PadHook.PoolInfo.
library PadHookLib {
    using StateLibrary for IPoolManager;

    // forge inspect PadHook storageLayout: _pools @0, poolIdOf @1, _dayRing @2; PoolInfo = 12 words
    uint256 internal constant POOLS_SLOT = 0;
    uint256 internal constant DAY_RING_SLOT = 2;
    uint256 internal constant POOL_INFO_WORDS = 12;
    int24 internal constant BAND_WIDTH = 60;
    int24 internal constant MAX_COIN_TICK = 887_220;
    int24 internal constant TICK_SPACING = 60;

    error UnknownPool();

    function _u(bytes32 w, uint256 off, uint256 n) private pure returns (uint256) {
        return (uint256(w) >> (off * 8)) & ((1 << (n * 8)) - 1);
    }

    function _i24(bytes32 w, uint256 off) private pure returns (int24) {
        return int24(uint24(uint256(w) >> (off * 8)));
    }

    function slotOf(PoolId id) internal pure returns (bytes32) {
        return keccak256(abi.encode(PoolId.unwrap(id), POOLS_SLOT));
    }

    /// The full PoolInfo of `coin` (all zero for an unknown coin).
    function poolInfo(PadHook hook, address coin) internal view returns (PadHook.PoolInfo memory p) {
        return poolInfoOf(hook, hook.poolIdOf(coin));
    }

    function poolInfoOf(PadHook hook, PoolId id) internal view returns (PadHook.PoolInfo memory p) {
        bytes32[] memory w = hook.extsload(slotOf(id), POOL_INFO_WORDS);
        p.coin = address(uint160(uint256(w[0])));
        p.quote = address(uint160(uint256(w[1])));
        p.districtId = uint32(_u(w[1], 20, 4));
        p.launchBlock = uint64(_u(w[1], 24, 8));
        p.coinIsToken0 = _u(w[2], 0, 1) != 0;
        p.launchTick = _i24(w[2], 1);
        p.bandLower = _i24(w[2], 4);
        p.snipeStartFee = uint24(_u(w[2], 7, 3));
        p.snipeBlocks = uint16(_u(w[2], 10, 2));
        p.storedFee = uint24(_u(w[2], 12, 3));
        p.baseFee = uint24(_u(w[2], 15, 3));
        p.house = _u(w[2], 18, 1) != 0;
        p.quoteDecimals = uint8(_u(w[2], 19, 1));
        p.liquidityMain = uint128(uint256(w[3]));
        p.bandLiquidity = uint128(uint256(w[3]) >> 128);
        p.usdPerQuoteE18 = uint128(uint256(w[4]));
        p.volumeUsdE18 = uint256(w[5]);
        p.quoteVolume = uint256(w[6]);
        p.pendingSurplus = uint256(w[7]);
        p.pendingFloor = uint256(w[8]);
        p.refCoinTick = _i24(w[9], 0);
        p.refBlock = uint64(_u(w[9], 3, 8));
        p.stickyTick = _i24(w[9], 11);
        p.stickyBlock = uint64(_u(w[9], 14, 8));
        p.openTick = _i24(w[9], 22);
        p.openBlock = uint64(_u(w[10], 0, 8));
        p.lastDay = uint32(_u(w[10], 8, 4));
        p.streak = uint16(_u(w[10], 12, 2));
        p.window = uint8(_u(w[10], 14, 1));
        p.tier1 = uint16(_u(w[10], 15, 2));
        p.tier2 = uint16(_u(w[10], 17, 2));
        p.aliveUsd = uint96(_u(w[10], 19, 12));
        p.lentQuote = uint128(uint256(w[11]));
    }

    /// The pool's coin and quote only (2 words): cheap "is this a pad coin" check for hot paths.
    function coinAndQuote(PadHook hook, address coin) internal view returns (address c, address q) {
        bytes32[] memory w = hook.extsload(slotOf(hook.poolIdOf(coin)), 2);
        return (address(uint160(uint256(w[0]))), address(uint160(uint256(w[1]))));
    }

    function known(PadHook hook, address coin) internal view returns (PadHook.PoolInfo memory p) {
        p = poolInfo(hook, coin);
        if (p.coin == address(0)) revert UnknownPool();
    }

    function keyOf(PadHook hook, PadHook.PoolInfo memory p) internal pure returns (PoolKey memory) {
        (address c0, address c1) = p.coinIsToken0 ? (p.coin, p.quote) : (p.quote, p.coin);
        return PoolKey({
            currency0: Currency.wrap(c0),
            currency1: Currency.wrap(c1),
            fee: LPFeeLibrary.DYNAMIC_FEE_FLAG,
            tickSpacing: TICK_SPACING,
            hooks: IHooks(address(hook))
        });
    }

    function poolKeyOf(PadHook hook, address coin) internal view returns (PoolKey memory) {
        return keyOf(hook, known(hook, coin));
    }

    function dayRing(PadHook hook, address coin) internal view returns (uint256[7] memory r) {
        bytes32[] memory w =
            hook.extsload(keccak256(abi.encode(PoolId.unwrap(hook.poolIdOf(coin)), DAY_RING_SLOT)), 7);
        for (uint256 i; i < 7; ++i) {
            r[i] = uint256(w[i]);
        }
    }

    function effectiveSupply(PadHook hook, address coin) internal view returns (uint256) {
        uint256 ts = IPadToken(coin).totalSupply();
        uint256 held = IPadToken(coin).balanceOf(address(hook));
        return ts > held ? ts - held : 0;
    }

    /// Published dump floor (coin-tick; lent quote counted as virtual band, exactly as the hook's guard computes it),
    /// band quote physically in the pool, floor claims waiting, MAIN's quote, and their sum.
    function floorBacking(PadHook hook, address coin)
        internal
        view
        returns (int24 floorCoinTick, uint256 bandQuote, uint256 pendingFloorQuote, uint256 mainQuote, uint256 poolQuote)
    {
        PadHook.PoolInfo memory p = known(hook, coin);
        (uint160 sqrtP,,,) = hook.POOL_MANAGER().getSlot0(hook.poolIdOf(coin));
        bool coin0 = p.coinIsToken0;
        floorCoinTick = hook.FLOOR_MATH().floorTickLent(
            coin0, p.liquidityMain, p.launchTick, p.bandLiquidity, p.bandLower, effectiveSupply(hook, coin), p.lentQuote
        );
        bandQuote = PadMath.quoteAtSqrt(coin0, p.bandLiquidity, p.bandLower, p.bandLower + BAND_WIDTH, sqrtP);
        pendingFloorQuote = p.pendingFloor;
        mainQuote = PadMath.quoteAtSqrt(coin0, p.liquidityMain, p.launchTick, MAX_COIN_TICK, sqrtP);
        poolQuote = bandQuote + pendingFloorQuote + mainQuote;
    }

    /// Current streak and creator share (bps of the base fee), lazy close-out applied (house coins: share 0).
    function streakAndBps(PadHook hook, address coin) internal view returns (uint16 streak, uint256 creatorBps) {
        PadHook.PoolInfo memory p = known(hook, coin);
        PadStreakMath.Params memory cur = PadStreakMath.Params(p.window, p.aliveUsd, p.tier1, p.tier2);
        streak = p.streak;
        PadStreakMath sm = hook.STREAK_MATH();
        uint256 today = block.timestamp / 1 days;
        if (today > p.lastDay) {
            (streak, cur) = sm.close(address(hook.REGISTRY()), p.districtId, dayRing(hook, coin), p.lastDay, today, streak, cur);
        }
        if (p.house) return (streak, 0);
        uint256 t = sm.tier(streak, cur.t1, cur.t2);
        creatorBps = t == 2 ? 6000 : (t == 1 ? 5000 : 4000); // PadHook.CREATOR_BPS_T2 / T1 / T0
    }
}

src/pad/libraries/PadMath.sol

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

import {TickMath} from "v4-core/libraries/TickMath.sol";
import {SqrtPriceMath} from "v4-core/libraries/SqrtPriceMath.sol";
import {FullMath} from "v4-core/libraries/FullMath.sol";
import {FixedPoint96} from "v4-core/libraries/FixedPoint96.sol";

/// @title PadMath
/// @notice Liquidity math for pad pools, written in "coin-tick" orientation: coin-tick `u` is the tick of the price
///         (raw quote per raw coin). If the coin is currency0 the pool tick is `u`; if it is currency1 the pool tick
///         is `-u`. A position over coin-ticks [a, b] maps to pool ticks [a, b] (coin0) or [-b, -a] (coin1).
///         All reserve estimates round DOWN, so floor figures are conservative.
library PadMath {
    /// pool tick range of a coin-tick range
    function poolRange(bool coin0, int24 a, int24 b) internal pure returns (int24 lower, int24 upper) {
        return coin0 ? (a, b) : (-b, -a);
    }

    /// Coins held by liquidity `L` spread over coin-ticks [x, y] (x < y), i.e. the full coin capacity of that slice.
    function coinsBetween(bool coin0, uint128 L, int24 x, int24 y) internal pure returns (uint256) {
        if (L == 0 || x >= y) return 0;
        if (coin0) {
            return SqrtPriceMath.getAmount0Delta(TickMath.getSqrtPriceAtTick(x), TickMath.getSqrtPriceAtTick(y), L, false);
        }
        return SqrtPriceMath.getAmount1Delta(TickMath.getSqrtPriceAtTick(-y), TickMath.getSqrtPriceAtTick(-x), L, false);
    }

    /// Coins a position [a, b] would hold if the price were exactly at coin-tick u.
    function coinsAt(bool coin0, uint128 L, int24 a, int24 b, int24 u) internal pure returns (uint256) {
        if (u >= b) return 0;
        return coinsBetween(coin0, L, u > a ? u : a, b);
    }

    /// Liquidity bought by `quoteAmt` of quote placed over coin-ticks [a, b] entirely BELOW the price (quote-only).
    function liquidityForQuote(bool coin0, uint256 quoteAmt, int24 a, int24 b) internal pure returns (uint128) {
        if (quoteAmt == 0) return 0;
        (int24 lo, int24 hi) = poolRange(coin0, a, b);
        uint160 sA = TickMath.getSqrtPriceAtTick(lo);
        uint160 sB = TickMath.getSqrtPriceAtTick(hi);
        uint256 L;
        if (coin0) {
            // quote = token1: L = amount1 * Q96 / (sB - sA)
            L = FullMath.mulDiv(quoteAmt, FixedPoint96.Q96, sB - sA);
        } else {
            // quote = token0: L = amount0 * sA * sB / Q96 / (sB - sA)
            uint256 inter = FullMath.mulDiv(sA, sB, FixedPoint96.Q96);
            L = FullMath.mulDiv(quoteAmt, inter, sB - sA);
        }
        return L > type(uint128).max ? type(uint128).max : uint128(L);
    }

    /// Liquidity for `coinAmt` coins placed over coin-ticks [a, b] entirely ABOVE the price (coin-only).
    function liquidityForCoins(bool coin0, uint256 coinAmt, int24 a, int24 b) internal pure returns (uint128) {
        (int24 lo, int24 hi) = poolRange(coin0, a, b);
        uint160 sA = TickMath.getSqrtPriceAtTick(lo);
        uint160 sB = TickMath.getSqrtPriceAtTick(hi);
        uint256 L;
        if (coin0) {
            uint256 inter = FullMath.mulDiv(sA, sB, FixedPoint96.Q96);
            L = FullMath.mulDiv(coinAmt, inter, sB - sA);
        } else {
            L = FullMath.mulDiv(coinAmt, FixedPoint96.Q96, sB - sA);
        }
        return L > type(uint128).max ? type(uint128).max : uint128(L);
    }

    /// Quote held by a position [a, b] at pool sqrt price `sqrtP` (rounded down).
    function quoteAtSqrt(bool coin0, uint128 L, int24 a, int24 b, uint160 sqrtP) internal pure returns (uint256) {
        if (L == 0) return 0;
        (int24 lo, int24 hi) = poolRange(coin0, a, b);
        uint160 sA = TickMath.getSqrtPriceAtTick(lo);
        uint160 sB = TickMath.getSqrtPriceAtTick(hi);
        if (coin0) {
            // quote = token1, present below the price
            if (sqrtP <= sA) return 0;
            uint160 top = sqrtP < sB ? sqrtP : sB;
            return SqrtPriceMath.getAmount1Delta(sA, top, L, false);
        }
        // quote = token0, present above the price
        if (sqrtP >= sB) return 0;
        uint160 bot = sqrtP > sA ? sqrtP : sA;
        return SqrtPriceMath.getAmount0Delta(bot, sB, L, false);
    }

    /// Coins held by a position [a, b] at pool sqrt price `sqrtP` (rounded down).
    function coinsAtSqrt(bool coin0, uint128 L, int24 a, int24 b, uint160 sqrtP) internal pure returns (uint256) {
        if (L == 0) return 0;
        (int24 lo, int24 hi) = poolRange(coin0, a, b);
        uint160 sA = TickMath.getSqrtPriceAtTick(lo);
        uint160 sB = TickMath.getSqrtPriceAtTick(hi);
        if (coin0) {
            // coin = token0, present above the price
            if (sqrtP >= sB) return 0;
            uint160 bot = sqrtP > sA ? sqrtP : sA;
            return SqrtPriceMath.getAmount0Delta(bot, sB, L, false);
        }
        if (sqrtP <= sA) return 0;
        uint160 top = sqrtP < sB ? sqrtP : sB;
        return SqrtPriceMath.getAmount1Delta(sA, top, L, false);
    }

    /// Current price as a coin-tick (conservative: rounds towards the lower coin price).
    function coinTickOf(bool coin0, int24 poolTick) internal pure returns (int24) {
        // coin1: pool tick t means pool price in [t, t+1); coin price in (-(t+1), -t]; use -(t+1)
        return coin0 ? poolTick : -poolTick - 1;
    }
}

src/pad/libraries/PadTypes.sol

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

/// @notice One hop of a fixed district route, written in the forward direction (pay token -> district quote).
///         The reverse direction (quote -> receive token) walks the same hops backwards.
/// kind 1 = Uniswap v3 pool (checked against the v3 factory), 2 = Uniswap v4 pool WITHOUT hooks,
/// kind 3 = Curve int128-index pool (coins checked at registration), kind 4 = a HOUSE pad pool through the pad hook.
/// Native ETH: v4 hops use address(0); v3 and Curve hops use WETH. The executor wraps/unwraps between hops.
struct Hop {
    uint8 kind;
    address pool; // v3 / Curve pool address; unused (0) for v4
    address tokenIn;
    address tokenOut;
    uint24 fee; // v3 fee tier or v4 static fee
    int24 tickSpacing; // v4 only
    int8 curveI; // Curve index of tokenIn
    int8 curveJ; // Curve index of tokenOut
}

/// @notice Immutable district parameters (set once through the registry's timelock).
struct DistrictConfig {
    address quote; // district quote asset (never native ETH)
    uint8 quoteDecimals;
    /// Opening price as a tick of (raw quote units per raw coin unit), i.e. in "coin = token0" orientation.
    /// Must be a multiple of the pad tick spacing.
    int24 launchTick;
    uint24 snipeStartFee; // pips (1e6 = 100%), e.g. 800_000 = 80%
    uint16 snipeBlocks; // blocks for the linear decay to the base fee
    /// USD value (1e18 = $1) of ONE whole quote unit; used ONLY for the creator fee tiers, never for pricing.
    uint128 usdPerQuoteE18;
    // no buy caps of any kind (user decision): no per-trade, per-coin or district-wide ceiling
}

/// @notice Creator-streak parameters (per district, or the registry's global default). Days are UTC days.
struct StreakParams {
    uint32 windowDays; // rolling window, 1 .. 14 days
    uint96 aliveUsd; // a day is "alive" if the coin's USD-referenced volume over the window ending that day >= this
    uint16 tier1Epochs; // streak (days) >= tier1 -> creator 0.50%
    uint16 tier2Epochs; // streak (days) >= tier2 -> creator 0.60%
}

/// @notice A route for one pay/receive token of a district.
struct RouteSpec {
    address payToken; // address(0) = ETH
    Hop[] hops;
}

library HopKind {
    uint8 internal constant V3 = 1;
    uint8 internal constant V4 = 2;
    uint8 internal constant CURVE = 3;
    /// a HOUSE pad pool (KINEKO/XAUT) through the pad hook: `pool` = the hook, dynamic fee, tick spacing 60. Used by
    /// the GOLD/KINEKO district (ETH/USDC/USDT -> XAUT -> KINEKO) and by FeeRouterV2 / WarChest conversions.
    uint8 internal constant PAD = 4;
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "morpho-blue/=lib/morpho-blue/src/",
    "metamorpho/=lib/metamorpho-v1.1/src/",
    "solady/=lib/solady/src/",
    "v4-core/=lib/v4-core/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/:ds-test/=lib/metamorpho-v1.1/lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
    "lib/metamorpho-v1.1/lib/morpho-blue-irm/:solmate/=lib/metamorpho-v1.1/lib/morpho-blue-irm/lib/solmate/src/",
    "lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/metamorpho-v1.1/lib/openzeppelin-contracts/:erc4626-tests/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/morpho-blue/lib/forge-std/:ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
    "lib/metamorpho-v1.1/:erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
    "lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
    "lib/metamorpho-v1.1/:openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/metamorpho-v1.1/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "metamorpho-v1.1/=lib/metamorpho-v1.1/",
    "morpho-blue-irm/=lib/metamorpho-v1.1/lib/morpho-blue-irm/src/",
    "openzeppelin-contracts/=lib/metamorpho-v1.1/lib/openzeppelin-contracts/",
    "solmate/=lib/v4-core/lib/solmate/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.