Перейти к содержимому
Проверенный контрактТочноеMIT

HookCold

Адрес0x13f79efa7272bfc6ebb823fdf6419446a8dabfa7
Баланс

0 ETH

 

Транзакций

0

 

Компилятор

solc 0.8.26

 

Тот же код

Только этот контракт

 

Подробности

Компилятор
solc 0.8.26+commit.8a97fa7a
Язык
solidity
Оптимизация
Да, 200 прогонов
Версия EVM
cancun
Лицензия
MIT
Совпадение
Точноекод создания: да, код в сети: да
Проверен на Sourcify
Создан в блоке
26 452 593
Транзакция создания
0x2812e116bd…abd90b9e9c

34 файла

src/libraries/HookCold.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {LPFeeLibrary} from "@uniswap/v4-core/src/libraries/LPFeeLibrary.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {
    IBankrLaunchHook, PoolConfig, PoolWorks, PoolFill, HookConfig, ExtBinding
} from "../interfaces/IBankrLaunchHook.sol";
import {PoolInit} from "../interfaces/SuiteTypes.sol";
import {PoolSide} from "./FeeMath.sol";
import {HookState, IHookPointers} from "./HookState.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";

/// @title HookCold
/// @notice The hook's launch-time and admin entry points, linked and delegatecalled so their bytes are not the hook's
///         (EIP-170). It runs on the hook's storage as the hook, at HookState's slots: msg.sender is the hook's caller.
///         No swap, liquidity callback or fee credit reaches it (test/unit/HookColdOffSwapPath.t.sol).
library HookCold {
    using PoolIdLibrary for PoolKey;
    using LPFeeLibrary for uint24;

    /// @dev The hook checks the caller is the factory, then forwards its own calldata: the same two arguments. Every
    ///      hard bound the swap path's arithmetic leans on is checked here, on what is stored, whoever resolved it.
    function registerPool(PoolKey calldata key, PoolInit calldata i) external {
        bytes32 id = PoolId.unwrap(key.toId());
        PoolConfig storage c = _pools()[id];
        if (c.registered) revert IBankrLaunchHook.AlreadyRegistered();
        if (!key.fee.isDynamicFee()) revert IBankrLaunchHook.NotDynamicFee();
        if (key.tickSpacing != K.TICK_SPACING) revert IBankrLaunchHook.WrongTickSpacing();
        if (address(key.hooks) != address(this)) revert IBankrLaunchHook.HookAddressMismatch();
        _checkSchedules(i);
        bool hasExt = i.ext != address(0);
        if (hasExt) _bindExtension(id, i);
        bool tokenIs0 = Currency.unwrap(key.currency0) == i.token;
        (c.registered, c.tokenIsCurrency0, c.token, c.hasExtension) = (true, tokenIs0, i.token, hasExt);
        // The trading start: the launch's own second, or its scheduled start. The factory passes it, never a past one.
        (c.creatorLp, c.decaySplit, c.initTimestamp) = (i.creatorLp, i.decayLp, i.startAt);
        // The floor is written in both directions' slots, so a swap finds it in the one it reads for its fee.
        c.buy = PoolSide(i.buy.startPips, i.buy.steadyPips, i.buy.decaySecs, i.compoundFloor);
        c.sell = PoolSide(i.sell.startPips, i.sell.steadyPips, i.sell.decaySecs, i.compoundFloor);
        if (i.creatorLp) {
            _storeWorks(c, i);
        } else if (i.decayLp) {
            // B12: the decay bucket is paid only while a fee decays; alone, it ends under the floor with no exit
            if ((i.buy.decaySecs | i.sell.decaySecs) != 0) revert IBankrLaunchHook.InvalidPoolInit(12);
            _storeWorks(c, i);
        }
        if (i.buyback) _storeFill(c, i);
        // B16: the audited average is the floor; a shorter one is cheaper to push.
        if (i.refTauSecs < 1_800) revert IBankrLaunchHook.InvalidPoolInit(16);
        c.refTauSecs = i.refTauSecs;
        _keys()[id] = key;
        _logRegistered(id, tokenIs0, i);
    }

    /// @dev PoolRegistered(id, token, tokenIs0, init): init is all static, so its 37 calldata words are the data as
    ///      they stand. The ABI encoder would cost several hundred bytes for the same log.
    function _logRegistered(bytes32 id, bool tokenIs0, PoolInit calldata i) private {
        bytes32 sig = IBankrLaunchHook.PoolRegistered.selector;
        address token = i.token;
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, tokenIs0)
            calldatacopy(add(m, 0x20), i, 0x4a0)
            log3(m, 0x4c0, sig, id, token)
        }
    }

    /// @dev B1: the decay subtracts steady from start and an exact-out fee divides by what is left of 100 %. With a
    ///      buyback share the buy fee stays under the fill's own reserve of 100 pips, or its money could never be spent.
    ///      A decay ends within a year: a buyback and a bound extension wait for the buy fee's to end.
    function _checkSchedules(PoolInit calldata i) private pure {
        if (
            i.buy.steadyPips > i.buy.startPips || i.buy.startPips > 999_999
                || (i.buy.decaySecs == 0) != (i.buy.startPips == i.buy.steadyPips)
                || i.sell.steadyPips > i.sell.startPips || i.sell.startPips > 999_999
                || (i.sell.decaySecs == 0) != (i.sell.startPips == i.sell.steadyPips)
                || (i.buyback && i.buy.steadyPips > 999_899) || i.buy.decaySecs > 365 days
                || i.sell.decaySecs > 365 days
        ) revert IBankrLaunchHook.InvalidPoolInit(1);
    }

    /// @dev B12 and B4: outside these every compound reverts or its gate never opens, and the auto-LP share strands.
    ///      The self-swap's cap is at least 1 and at most half the raw steady round trip in ticks (pips / 100).
    function _storeWorks(PoolConfig storage c, PoolInit calldata i) private {
        if (i.compoundShareBps > 10_000) revert IBankrLaunchHook.InvalidPoolInit(4);
        // A slice of one raw unit cannot be split into a band's two sides, so a cap under 2 never places anything;
        // an interval past a year shuts the gate behind each compound for as long as a typo says.
        if (
            i.compoundFloor == 0 || i.compoundFloor > i.compoundCap || i.compoundCap < 2 || i.compoundInterval == 0
                || i.compoundInterval > 365 days
                || i.bandHalfWidth == 0 || i.bandHalfWidth > 8_872 || i.bandGrid == 0 || i.bandGrid > 8_872
                || i.compoundDeviationTicks == 0
                || i.compoundDeviationTicks > uint256(i.bandHalfWidth) * uint24(K.TICK_SPACING)
                || i.swapCapTicks == 0
                || uint256(i.swapCapTicks) * 200 > uint256(i.buy.steadyPips) + i.sell.steadyPips
        ) revert IBankrLaunchHook.InvalidPoolInit(12);
        c.works = PoolWorks(
            i.compoundCap,
            i.compoundInterval,
            i.compoundShareBps,
            i.compoundDeviationTicks,
            i.bandHalfWidth,
            i.bandGrid,
            i.swapCapTicks
        );
    }

    /// @dev B16: a fill's travel, with the compound's own push on a pool that has one, is measured against the round
    ///      trip the pool was launched with (ticks x 100 = pips).
    function _storeFill(PoolConfig storage c, PoolInit calldata i) private {
        // A travel of 0 leaves a fill no price to reach: the buyback's share would have no exit for the pool's life.
        // An interval or a retry past a year holds it behind one fill, or one refused attempt, the same way.
        if (
            i.fillTravelTicks == 0 || i.buybackInterval > 365 days || i.buybackRetry > 365 days
                || (uint256(i.fillTravelTicks) + (i.creatorLp || i.decayLp ? i.swapCapTicks : 0)) * 100
                    > uint256(i.buy.steadyPips) + i.sell.steadyPips
        ) revert IBankrLaunchHook.InvalidPoolInit(16);
        c.fill = PoolFill(i.buybackInterval, i.buybackRetry, i.fillTravelTicks, i.fillStartGapTicks);
        c.buybackAt = 1; // due from the first swap; BankrBuyback itself refuses during the decay
    }

    /// @dev The only place a pool's extension is ever set (B3, B4, B13). Admission: code that is neither empty nor
    ///      0xEF-prefixed (a 7702 designator, EOF or Stylus), at exactly the codehash the launcher expects.
    function _bindExtension(bytes32 id, PoolInit calldata i) private {
        address e = i.ext;
        if (e.code.length == 0 || _firstCodeByte(e) == 0xEF) revert IBankrLaunchHook.ExtensionRejected();
        if (e.codehash != i.codehash) revert IBankrLaunchHook.ExtensionCodehashMismatch();
        // 0xFFFFFF is the interface's refusal value, never a fee
        if (i.maxBuyPips > 0xFFFFFE || i.maxSellPips > 0xFFFFFE) revert IBankrLaunchHook.ExtensionCapTooHigh();
        // Base plus extension stays under 100 % (B3), and under the buyback's reserve where its fills pay it (B1).
        if (i.feeCeilingPips > 999_999) revert IBankrLaunchHook.InvalidPoolInit(3);
        if (i.buyback && i.feeCeilingPips > 999_899) revert IBankrLaunchHook.InvalidPoolInit(1);
        if (i.bankrDen == 0 || i.bankrNum > i.bankrDen) revert IBankrLaunchHook.InvalidPoolInit(4);
        if (i.payee == address(0)) revert IBankrLaunchHook.ExtensionPayeeInvalid();
        // Each budget within its floor and ceiling, for life; a quote-only binding has no post-swap budget at all.
        if (
            i.quoteGas < K.EXT_QUOTE_GAS || i.quoteGas > K.EXT_QUOTE_GAS_MAX
                || (i.quoteOnly ? i.afterGas != 0 : i.afterGas < K.EXT_AFTER_GAS || i.afterGas > K.EXT_AFTER_GAS_MAX)
        ) revert IBankrLaunchHook.ExtensionGasBudget();
        ExtBinding storage b = _ext()[id];
        (b.ext, b.quoteGas, b.afterGas, b.feeCeilingPips) = (e, i.quoteGas, i.afterGas, i.feeCeilingPips);
        (b.bankrNum, b.bankrDen, b.codehash) = (i.bankrNum, i.bankrDen, i.codehash);
        (b.maxBuyPips, b.maxSellPips, b.payee) = (i.maxBuyPips, i.maxSellPips, i.payee);
        (b.quoteOnly, b.sunsetSecs, b.ownerSwitch) = (i.quoteOnly, i.sunsetSecs, i.ownerSwitch);
        emit IBankrLaunchHook.ExtensionBound(
            id, e, i.codehash, i.maxBuyPips, i.maxSellPips, i.payee, i.quoteOnly, i.sunsetSecs
        );
    }

    /// @dev The hook has no owner: the switch is the factory owner's, per hook generation, and reaches only a pool
    ///      whose binding has `ownerSwitch`. While off, `ext` is neither asked nor called there; on again, a swap needs
    ///      the binding's gas budgets once more. Never a sell, never a Bankr leg (I3-01).
    function setExtensionSwitchedOff(address ext, bool off) external {
        // The only caller check there is: the hook forwards with none, and its constructor asks only for code at the
        // linked address. That the link is this code is what VerifyChain's code comparison proves (NS-18 EXT-4).
        if (msg.sender != Ownable(IHookPointers(address(this)).factory()).owner()) {
            revert IBankrLaunchHook.NotFactoryOwner();
        }
        _switchedOff()[ext] = off;
        emit IBankrLaunchHook.ExtensionSwitchedOff(ext, off);
    }

    /// @dev Factory only, checked by the hook before it forwards.
    function syncConfig(HookConfig calldata c) external {
        HookConfig storage s;
        uint256 slot = HookState.CFG_SLOT;
        assembly ("memory-safe") {
            s.slot := slot
        }
        s.locker = c.locker;
    }

    function _firstCodeByte(address a) private view returns (uint8 b) {
        assembly ("memory-safe") {
            extcodecopy(a, 0x00, 0x00, 0x01)
            b := byte(0, mload(0x00))
        }
    }

    function _pools() private pure returns (mapping(bytes32 => PoolConfig) storage m) {
        uint256 slot = HookState.POOLS_SLOT;
        assembly ("memory-safe") {
            m.slot := slot
        }
    }

    function _keys() private pure returns (mapping(bytes32 => PoolKey) storage m) {
        uint256 slot = HookState.KEYS_SLOT;
        assembly ("memory-safe") {
            m.slot := slot
        }
    }

    function _ext() private pure returns (mapping(bytes32 => ExtBinding) storage m) {
        uint256 slot = HookState.EXT_SLOT;
        assembly ("memory-safe") {
            m.slot := slot
        }
    }

    function _switchedOff() private pure returns (mapping(address => bool) storage m) {
        uint256 slot = HookState.SWITCHED_OFF_SLOT;
        assembly ("memory-safe") {
            m.slot := slot
        }
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/v4-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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-periphery/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/interfaces/IBankrFeeLedger.sol

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

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";

/// @notice Ledger surface: the FeesManager-compatible subset (bucketId plays "poolId") plus bucket extensions.
interface IBankrFeeLedger {
    /// @dev `creatorShare` is the part of `shares` that is a launch fee recipient's own (design: several fee recipients):
    ///      the label that tells a creator entry from a pad payee, the holders, auto-LP and buyback, and what a community
    ///      takeover moves. An entry merged with a pad payee holds more than its creator part. Both fit: at most WAD.
    struct Beneficiary {
        uint128 shares;
        uint64 creatorShare;
        uint256 lastCumulatedFees0;
        uint256 lastCumulatedFees1;
    }

    /// @dev A pool's fee terms, frozen at launch: its hook (the only caller of creditSwap), the flags below, the
    ///      referrer rate, Bankr's slice (its share of the fee, its floor in pips of volume, the holders' part of it)
    ///      and the holder leg the coin keeps for life. Slot 0 is full and is all a plain swap reads.
    struct PoolTerms {
        address hook;
        // T_QUOTE_IS_0 1, T_WAIVED 2 (Bankr's own part stays in the remainder), T_DECAY_SPLIT 4, T_TREASURY_CUT 8
        // (either treasury share below is set), T_HOLDER_INTAKE 16 (`distributor` is set: decision 1's accrue)
        uint8 flags;
        uint16 referrerBps;
        uint16 bankrFeeBps;
        uint24 bankrMinPips;
        uint16 holdersShareBps;
        uint16 legId;
        // The treasury marker's shares of the steady part and decay surplus go to bankrId rounded up, since two
        // remainder-bucket floors per release left its claim up to ~1.1 wei under the ruling.
        uint64 treasuryWad;
        uint64 treasuryDecayWad;
        address distributor;
        uint64 holderWad;
    }

    /// @dev A queued community takeover of a launch's creator share (spec §9): the new recipient, when it may execute,
    ///      and the CTO authority's epoch at queue time (any rotation of the authority voids it).
    struct PendingCto {
        address newRecipient;
        uint64 executeAfter;
        uint32 epoch;
    }

    event Collect(bytes32 indexed poolId, uint256 fees0, uint256 fees1);
    event Release(bytes32 indexed poolId, address indexed beneficiary, uint256 fees0, uint256 fees1);
    event UpdateBeneficiary(bytes32 poolId, address oldBeneficiary, address newBeneficiary);
    event BucketRegistered(bytes32 indexed bucketId, bytes32 indexed poolId, address[] beneficiaries, uint256[] shares);
    /// @dev `hook` is the only crediter of a pool bucket (0 = a currency bucket: any allowlisted hook); a locked
    ///      bucket's beneficiaries can never move.
    event BucketBound(bytes32 indexed bucketId, address indexed hook, bool locked);
    event ProtocolSinkSet(address indexed sink, bool allowed);
    event HookSet(address indexed hook, bool allowed);
    event ClaimsCollectorSet(address indexed who, bool allowed);
    /// @dev The stored terms whole, so a coin's frozen split is known from its launch.
    event PoolTermsRegistered(bytes32 indexed poolId, PoolTerms terms);
    event LegAdded(uint16 indexed legId, address indexed leg);
    /// @dev One per swap fee: `bankr` is what bankrId took (Bankr's own half, plus the treasury's cut of the remainder
    ///      on Bankr's pad), `holders` the coin's holders' half, `remainder` what the creator and decay buckets took.
    event SwapFee(
        bytes32 indexed poolId,
        address indexed sender,
        uint24 feePips,
        uint256 fee,
        uint256 bankr,
        uint256 holders,
        address indexed referrer,
        uint256 referral,
        uint256 remainder
    );

    // claim all: an earner's balance per currency holds its referral slices and the bucket shares settled into it
    /// @dev A bucket share moved into the account's balance: an internal move, not a payout.
    event Settled(bytes32 indexed bucketId, address indexed account, uint256 fees0, uint256 fees1);
    /// @dev The account's balance in one currency was paid to it (a payout, as Release is).
    event Withdraw(address indexed account, Currency indexed currency, uint256 amount);
    /// @dev The currency refused the payout (frozen, halted, reverting, or it burned PAYOUT_GAS): nothing moved, the
    ///      balance stays.
    event Withheld(address indexed account, Currency indexed currency, uint256 amount);
    /// @dev Q9: the account's claim policy. Open (false, the default): anyone may settle, push and claim for it, paid
    ///      to it only. Restricted: only itself and the claim operators it names.
    event ClaimRestrictedSet(address indexed account, bool restricted);
    event ClaimOperatorSet(address indexed account, address indexed operator, bool allowed);
    /// @dev Decision 1: the pool's distributor failed its accrue with all of its stipend. The share stays in the ledger
    ///      for the distributor's next pull (a claim's, or anyone's reconcile), so it streams late, never lost.
    event HolderAccrueFailed(bytes32 indexed poolId, uint256 amount);

    // community takeover (CTO, spec §9): ops surface; a takeover moves only the creator's own share of a bucket
    /// @dev With BucketRegistered, entry by entry: each beneficiary's creator part (0: not a fee recipient), whether
    ///      the launch's creator entries can be taken over, and the notice and grace the coin keeps for life.
    event CreatorShares(bytes32 indexed bucketId, uint256[] creatorShares, bool takeover, uint32 notice, uint32 grace);
    event CtoAuthoritySet(address indexed authority, uint32 epoch);
    event CtoQueued(bytes32 indexed creatorId, address indexed newRecipient, uint64 executeAfter, uint64 expiresAt);
    event CtoCancelled(bytes32 indexed creatorId, address indexed by);
    /// @dev One per entry whose creator part moved, creatorId's then decayId's: up to 64 in each (TooManyEntries). None
    ///      when the launch has no creator part: the execute still consumes its notice (NS-18 LEDGER-4).
    event CtoExecuted(
        bytes32 indexed bucketId, address indexed oldRecipient, address indexed newRecipient, uint256 shareWad
    );
    event CtoDisabledForever();

    error NotFactory();
    error NotHook();
    error NotPoolManager();
    error BucketExists();
    error UnknownBucket();
    error SharesMismatch();
    error NotBeneficiary();
    error BeneficiaryExists();
    error NotProtocolSink();
    error ZeroAddress();
    error SentinelPayee();
    error NotClaimsCollector();
    error BeneficiaryLocked();
    /// @dev A credit the ledger's ERC-6909 balance of that currency does not back (credited − released > balance).
    error Insolvent();
    error NotPoolHook();
    error UnknownPool();
    error PoolTermsExist();
    error InvalidPoolTerms();
    error NotFactoryOwner();
    error NotCtoAuthority();
    /// @dev Not a launch's creatorId, or registered without a takeover (the coin's pad had it off at launch).
    error NotCtoEligible();
    error NoPendingCto();
    error CtoTimelockActive();
    /// @dev A queued takeover unlocked more than the coin's grace ago: it is dead, and must be queued again.
    error CtoExpired();
    /// @dev A bucket with more entries than its header's uint8 count holds (255), or than one takeover transaction
    ///      settles (64) on a coin that can be taken over, its decay bucket included.
    error TooManyEntries();
    error CtoAuthorityRotated();
    error CtoDisabled();
    /// @dev Zero, a routing marker (LedgerOps.isSentinel), a holder of more than a creator part where the takeover
    ///      moves one, or a contract that could never collect the share (LedgerOps.strands, as InvalidBeneficiary).
    error InvalidCtoRecipient();
    /// @dev A beneficiary's move to a contract that could never collect: the coin's TOKEN or quote, the PoolManager, the
    ///      ledger or the factory's suite code (H13 ECON-I2). Also a bucket bound with one of its own currencies as a
    ///      payee (NS-18 LEDGER-1): a launch that names the quote token as a recipient reverts with it.
    error InvalidBeneficiary();
    /// @dev Under PAYOUT_GAS * 64 / 63 plus the call's own cost left for a payout: the whole call reverts, never a skip.
    error InsufficientGas();
    /// @dev withdrawFor an account the caller may not push: a claims collector, a protocol sink, a suite contract, or a
    ///      restricted account that did not name the caller its claim operator.
    error NotPushable();
    error NotLeg(); // setHoldersWake or drawWindow from an address the factory never registered as a holder leg
    error LegExists(); // addLeg for a leg that has its id: an id is written once
    /// @dev A conversion that spent more of a quote than its window had left for this leg's cap.
    error WindowExceeded();

    // factory / hook surface
    /// @dev Binds the bucket to `key.hooks` (which must be allowlisted): only that hook may ever credit it. `cto`: bit 0
    ///      the launch's creator entries can be taken over, bits 8..39 the notice in seconds (at least 3,600), bits
    ///      40..71 the grace (at least 1); 0 for a bucket no takeover is queued on (a decayId, any coin with it off).
    function registerBucket(
        bytes32 bucketId,
        PoolKey calldata key,
        address[] calldata beneficiaries,
        uint256[] calldata sharesWad,
        uint256[] calldata creatorShares,
        uint256 cto
    ) external;
    /// @dev A one-payee pool bucket: `payee` at 100 %, bound to `key.hooks`; `locked` pins the payee for good (a launch's
    ///      holdersId, so nothing can redirect the holders' half of Bankr's slice).
    function registerSoleBucket(bytes32 bucketId, PoolKey calldata key, address payee, bool locked) external;
    /// @dev Chain-wide bucket keyed by a currency, not a pool (bankrId, Bankr's own half and extension cut): poolId = 0,
    ///      currency0 = `currency`, currency1 = ADDRESS_ZERO; credited with isCurrency0 == true by any allowlisted hook.
    function registerCurrencyBucket(
        bytes32 bucketId,
        Currency currency,
        address[] calldata beneficiaries,
        uint256[] calldata sharesWad
    ) external;
    function credit(bytes32 bucketId, bool isCurrency0, uint256 amount) external;
    /// @dev Binds a pool's terms once; every bucket creditSwap credits must already exist. Refused (InvalidPoolTerms)
    ///      where the split could underflow at `lowerSteadyPips`, the lower of the pool's two steady fees, or a share,
    ///      a flag or the leg id is out of range (LedgerCold.registerPoolTerms holds the checks).
    function registerPoolTerms(bytes32 poolId, PoolKey calldata key, PoolTerms calldata t, uint24 lowerSteadyPips)
        external;
    /// @dev The pool's hook, once per swap, after minting `fee` of the quote to the ledger: splits it (FeeMath.swapSplit
    ///      at `f` with the swap direction's steady rate `s`) into its buckets and the referrer's balance, then accrues
    ///      the distributor's creatorId share of it into the holders' stream (decision 1). `wake`: 1 when the swap runs
    ///      inside an extension's post-swap frame or the buyback's fill (the hook's own flag), so its accrue only buffers
    ///      and no leg wakes; 0 for an outer swap whose sender did not ask for the holder wake; 2 + n when it did
    ///      (HookData.HOLDERS_WAKE) and keeps n gas for the rest of its route.
    function creditSwap(bytes32 poolId, address sender, uint24 f, uint24 s, uint256 fee, address referrer, uint256 wake)
        external;
    /// @notice Accounting only: each account's share of each bucket into its balance (no token moves, so none can fail
    ///         it). Settles an account whose claim policy lets the caller (mayClaimFor: anyone while it is open), and
    ///         never a claims collector, protocol sink or suite contract; anything else is skipped.
    function settle(bytes32[] calldata bucketIds, address[] calldata accounts) external;
    /// @notice Settles the caller's listed buckets (none: the balance alone, a referrer's old claim), then pays its whole
    ///         balance in each named currency, ERC-20 through the ledger's own unlock (so never inside a swap). Each
    ///         payout gets exactly PAYOUT_GAS: a refusal is Withheld and the other currencies still pay.
    function withdraw(bytes32[] calldata bucketIds, Currency[] calldata currencies) external;
    /// @notice withdraw's payouts for `account`, paid to `account` only (NotPushable: whom the caller may not push; a
    ///         puller, never settled, is pushed by anyone when it holds a balance in a named currency: NS-18 LEDGER-2).
    function withdrawFor(address account, Currency[] calldata currencies) external;
    /// @notice The caller's balance in one currency with every unit of gas, reverting on refusal: the way out for a quote
    ///         whose honest transfer needs more than PAYOUT_GAS.
    function withdrawUncapped(Currency currency) external;
    /// @notice Q9: the caller's own policy, reversible. Restricted, only the caller and its claim operators may settle,
    ///         push or claim for it, on this ledger and on every holder distributor.
    function setClaimRestricted(bool restricted) external;
    /// @dev While the caller is restricted, the operator may settle it, push it its balance and claim its holder
    ///      rewards: the timing, never the destination. Revocable; it matters only while the caller is restricted.
    function setClaimOperator(address operator, bool allowed) external;
    function claimRestricted(address account) external view returns (bool);
    function isClaimOperator(address account, address operator) external view returns (bool);
    /// @notice The one claim policy (Q9) the ledger and every distributor apply: the account itself, anyone while it is
    ///         open, or an operator it named while it is restricted.
    function mayClaimFor(address account, address caller) external view returns (bool);
    function setProtocolSink(address sink, bool allowed) external;
    function setHook(address hook, bool allowed) external;
    function setClaimsCollector(address who, bool allowed) external;

    // community takeover (spec §9). The factory's owner appoints the authority, cancels and can weld the
    // feature off for good; the authority queues, cancels and, the coin's notice later under the same appointment,
    // executes.
    /// @dev Every call, a re-appointment included, starts a new epoch, so nothing queued before it can execute.
    function setCtoAuthority(address authority) external;
    /// @dev One-way: the authority is cleared and can never be set again.
    function disableCtoForever() external;
    /// @dev Replaces any earlier queue for the launch and restarts the clock. Not dismissable by a fee recipient: no
    ///      claim, beneficiary move or other recipient action stops it (a creator part is followed wherever it
    ///      moves). It unlocks the coin's own notice later and expires its grace after that (CtoExpired, ctoTermsOf).
    function queueCto(bytes32 creatorId, address newRecipient) external;
    function cancelCto(bytes32 creatorId) external;
    /// @dev Settles every fee recipient into its own balance (Settled) and moves every creator part, in creatorId and
    ///      in decayId, to the one new recipient (a merged operator part stays with its address). No token moves, so
    ///      no recipient's code or token can stop or price it: each old one withdraws as ever. CtoExpired once stale.
    function executeCto(bytes32 creatorId) external;

    // claims-collector surface (the hook's LP backlog): same bookkeeping as collectFees, paid as
    // ERC-6909 via poolManager.transfer — no unlock, so it works INSIDE a swap
    function collectFeesAsClaims(bytes32 bucketId) external returns (uint256 fees0, uint256 fees1);
    /// @notice A registered holder leg, for its own coins (decision 2): the holders' pile a swap wakes it at, in `quote`.
    function setHoldersWake(Currency quote, uint96 floor) external;
    /// @notice The wake a swap of one of `legId`'s coins checks: the leg in the low 160 bits, the pile it wakes at
    ///         above (0: unarmed).
    function holdersWake(uint16 legId, Currency quote) external view returns (uint256);
    /// @notice The factory only, once per leg: the next leg id, from 1. The id is never cleared, so the leg stays a
    ///         puller here for life (never settled, never a payee's move or a takeover's heir) whatever the factory
    ///         names later.
    function addLeg(address leg) external returns (uint16 legId);
    function legIdOf(address leg) external view returns (uint16);
    /// @notice `quote`'s conversion window, one for every leg: open until `until`, with `left` of a cap still to draw.
    function windowOf(Currency quote) external view returns (uint64 until, uint192 left);
    /// @notice A registered leg, after converting `spent` of `quote`: its room is `left` capped at `cap` while the
    ///         window is open, else `cap` (WindowExceeded above it); the window keeps the rest and stays open at least
    ///         `interval` more. A leg can use a window up or keep it shut, never widen it for another leg.
    function drawWindow(Currency quote, uint256 spent, uint256 cap, uint32 interval) external;

    // FeesManager-compatible surface
    function collectFees(bytes32 bucketId) external returns (uint128 fees0, uint128 fees1);
    function collectFeesMany(bytes32[] calldata bucketIds)
        external
        returns (uint128[] memory fees0, uint128[] memory fees1);
    function collectFeesFor(bytes32 bucketId, address beneficiary) external returns (uint128 fees0, uint128 fees1);
    function updateBeneficiary(bytes32 bucketId, address newBeneficiary) external;
    function updateBeneficiaryMany(bytes32[] calldata bucketIds, address newBeneficiary) external;
    function getShares(bytes32 bucketId, address beneficiary) external view returns (uint256);
    function getCumulatedFees0(bytes32 bucketId) external view returns (uint256);
    function getCumulatedFees1(bytes32 bucketId) external view returns (uint256);
    function getLastCumulatedFees0(bytes32 bucketId, address beneficiary) external view returns (uint256);
    function getLastCumulatedFees1(bytes32 bucketId, address beneficiary) external view returns (uint256);

    // extensions
    /// @dev One currency of the caller's share, so a quote whose transfers revert cannot hold the other leg.
    function collectFeesSide(bytes32 bucketId, bool isCurrency0) external returns (uint256 fees);
    function claimable(bytes32 bucketId, address beneficiary) external view returns (uint256 fees0, uint256 fees1);
    function bucketOf(bytes32 bucketId)
        external
        view
        returns (bytes32 poolId, Currency currency0, Currency currency1, bool exists);
    function bucketBinding(bytes32 bucketId) external view returns (address hook, bool locked);
    function beneficiariesOf(bytes32 bucketId) external view returns (address[] memory);
    function poolTerms(bytes32 poolId) external view returns (PoolTerms memory);
    /// @dev An account's pull balance in one currency (referral slices and settled shares), counted in `outstanding`.
    function balances(address account, Currency currency) external view returns (uint256);
    function PAYOUT_GAS() external view returns (uint256);
    /// @notice Gas the accrue is handed in an outer swap, and in a nested one (decision 1): short of it plus the call's
    ///         own cost, the swap reverts InsufficientGas, so an estimated gas limit always accrues.
    function ACCRUE_GAS() external view returns (uint256);
    function ACCRUE_BUFFER_GAS() external view returns (uint256);
    /// @dev Credited minus released across every bucket; never above poolManager.balanceOf(ledger, currency).
    function outstanding(Currency currency) external view returns (uint256);
    function isProtocolSink(address sink) external view returns (bool);
    function isHook(address hook) external view returns (bool);
    function isClaimsCollector(address who) external view returns (bool);
    function factory() external view returns (address);
    function poolManager() external view returns (IPoolManager);
    function ctoAuthority() external view returns (address);
    function ctoAuthorityEpoch() external view returns (uint32);
    function ctoDisabledForever() external view returns (bool);
    function pendingCto(bytes32 creatorId)
        external
        view
        returns (address newRecipient, uint64 executeAfter, uint32 epoch);
    /// @dev The creator part of `beneficiary`'s entry in `bucketId` (0: not a fee recipient's entry). It follows the
    ///      entry through its own moves.
    function creatorShareOf(bytes32 bucketId, address beneficiary) external view returns (uint256);
    /// @dev How many entries of `bucketId` hold a creator part.
    function creatorCount(bytes32 bucketId) external view returns (uint256);
    function ctoEligible(bytes32 bucketId) external view returns (bool);
    /// @dev A launch's takeover terms as frozen in its creator bucket: whether it can be taken over, the public notice
    ///      before an execute and how long after it the execute stays open, in seconds.
    function ctoTermsOf(bytes32 creatorId) external view returns (bool eligible, uint32 notice, uint32 grace);
}

src/interfaces/IBankrLaunchFactory.sol

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

import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {VestingAllocation} from "./ICreatorVestingEscrow.sol";
import {IBankrLaunchpadRegistry} from "./IBankrLaunchpadRegistry.sol";
import {FeeSchedule} from "../libraries/FeeMath.sol";


/// @dev How the factory prices a quote in USD to bound a launch's start tick (security finding 9; v2 PairRegistry).
///      NONE: the quote takes no launches. CHAINLINK: a USD feed behind the L2 sequencer gate. SIGNED: a
///      PriceAttestation from the factory's priceSigner, carried by the launch itself.
enum PricingMode {
    NONE,
    CHAINLINK,
    SIGNED
}


/// @dev EIP-712 ("Bankr Launch Pricing", "1", chainId, factory) over PriceAttestation(address quote,uint256
///      priceUsdE18,uint64 observedAt,uint64 expiresAt). Empty for a CHAINLINK quote.
struct PriceAttestation {
    uint256 priceUsdE18; // USD per whole quote token
    uint64 observedAt;
    uint64 expiresAt;
    bytes signature;
}

/// @dev A launch's extension, bound for good. `id` != 0: a Bankr preset deployed in the launch from `params` (README
///      "Presets"). `id` 0 with `ext` set: the launcher's pre-deployed code, admitted by the hook at `codehash` with
///      these maxima, quote-only flag and sunset (README "Custom extensions", DYOR). Neither: none. `payee` 0 = the
///      effective fee recipient. A preset declares its own flag and sunset, so those fields stay 0 with an `id`.
struct LaunchExtension {
    uint8 id;
    bytes params;
    address payee;
    address ext;
    bytes32 codehash;
    uint24 maxBuyPips;
    uint24 maxSellPips;
    bool quoteOnly;
    uint32 sunsetSecs;
    uint24 quoteGas; // custom code only: 0 = EXT_QUOTE_GAS, else within [EXT_QUOTE_GAS, EXT_QUOTE_GAS_MAX]
    uint24 afterGas; // custom code only: 0 = EXT_AFTER_GAS (unless quote-only), else within [.., EXT_AFTER_GAS_MAX]
}

/// @dev A launch's own economics (Launch SDK H3–H5, H8), checked against the protocol bounds by LaunchEconomics and its
///      pad's by the registry, and bound for good: one fee schedule per direction (a buy is quote in); the referrer's
///      slice of the fee, paid off the remainder to a referrer the trader names (0–500 bps, 0 = none); and the creator
///      side of the remainder after Bankr's slice, the referrer and the operators: `holdersBps` to the coin's
///      distributor, `autoLpBps` to the hook's band and `buybackBps` to BankrBuyback, in bps of that side (sum <=
///      10,000; any may be 0). `vestToHoldersBps` of supply vests to the coin's holders (H9a): a push schedule to the
///      distributor in the launch's escrow, cliff <= duration <= 365 days, counted with `vestBps` against the pad's
///      vested total.
struct LaunchEconomics {
    FeeSchedule buy;
    FeeSchedule sell;
    uint16 referrerBps;
    uint16 holdersBps;
    uint16 autoLpBps;
    uint16 buybackBps;
    uint16 vestToHoldersBps;
    uint64 vestToHoldersCliff;
    uint64 vestToHoldersDuration;
}

/// @dev One of a launch's fee recipients and its share of the creator's own take (what is left of the creator side
///      after the pad's payees and the launch's holders, auto-LP and buyback shares), in bps of that take.
struct FeeRecipient {
    address recipient;
    uint16 shareBps;
}

struct LaunchParams {
    string name;
    string symbol;
    string metadataUri;
    /// @dev May replace the token's metadata URI after launch; zero fixes it from the first block. Never defaulted.
    address metadataAdmin;
    bytes32 salt;
    address quote;
    uint256 totalSupply; // 0 => the pad's default supply
    int24 expectedStartTick; // quote per token (token-as-currency0 orientation), spacing-aligned, in startTickBounds
    uint256 deadline;
    // 0 runner_v1, 1 degen, 2 thin topside (RunnerCurve tables, H10); any other value is the launch's own table
    // (CurveTable): up to eight 32-bit rows from the top bits, each (width in 200-tick spacings << 16) | share in bps.
    uint256 curveId;
    LaunchEconomics econ; // forwarded undecoded: LaunchRegistry checks it and binds it on the hook
    // The creator's take, split: at most the pad's limit of distinct recipients, each share above 0, summing to 10,000.
    // None => the launcher alone. The first is the primary: it takes the rounding remainder, and alone it is the default
    // extension payee (a list of two or more must name the payee). A recipient with code (not an EIP-7702 account) must
    // have restricted its claims on the ledger, unless the launch waives that with `allowOpenCodeFeeRecipients`.
    FeeRecipient[] feeRecipients;
    bool allowOpenCodeFeeRecipients;
    address vestingRecipient; // 0 => launcher
    uint16 vestBps; // 0..5000
    bool allowCodeVestingRecipient;
    VestingAllocation[] extraAllocations; // builder lane; all schedules live in the launch's escrow clone
    address[] capExclusions; // the token's 2 %/24 h wallet cap skips these (the chain's aggregator settlers)
    uint256 devBuyAmountIn;
    uint256 devBuyMinOut;
    uint64 launchpadId; // 0 = Bankr's own pad (the spec §4 preset), always signed by the registry's bankrSigner (D10)
    uint16 maxOperatorShareBps; // the most of the remainder the pad's payees may take, steady and decay (audit r1 F-2)
    bytes32 operatorPayeesHash; // keccak256(abi.encode(PadTerms)) of the pad's terms the launcher expects; 0 = any (ADM-03)
    IBankrLaunchpadRegistry.LaunchAuthorization authorization; // empty (0, 0, "") for an open pad
    PriceAttestation priceAttestation; // SIGNED quotes only
    LaunchExtension extension; // a preset, custom code or none; a signed launch commits to it (LaunchpadAuth.termsHash)
    // Scheduled start: the second public trading opens. 0 = at launch; otherwise strictly after the launch's own block
    // (StartPassed) and at most the pad's start delay ahead (StartTooFar).
    // Fixed for good once the launch lands; inside the terms hash, so a signed launch commits to it.
    uint64 startTime;
    // "" (every option at its pad's default, no pin) or abi.encode(LaunchOptions): the launch's own picks of what
    // LaunchParams has no field for, and its pins on the resolved terms and the token address.
    bytes options;
}

/// @dev setSuite's wiring, as one struct (its ten addresses do not fit a frame's stack).
struct SuiteAddrs {
    address hook;
    address ledger;
    address locker;
    address holderRewardsDeployer;
    address tokenDeployer;
    address vestingEscrowImpl;
    address holderLeg;
    address buyback;
    address launchpadRegistry;
    address settings;
}

struct LaunchResult {
    address token;
    bytes32 poolId;
    address distributor;
    address vestingEscrow; // 0 when nothing vests
    uint256 devBuyOut;
}

/// @notice Factory surface: single-pool launch through the chain's ITokenDeployer + one CreatorVestingEscrow clone,
///         every term of it taken from the settings contract's resolve and frozen per coin, the launch gate, the
///         treasury protocol sink and the holder leg, pause, hook rotation. Errors of the factory's own libraries are
///         declared HERE (`IBankrLaunchFactory.X`); a launch also bubbles IBankrLaunchSettings' own, unchanged.
interface IBankrLaunchFactory {
    function launch(LaunchParams calldata p) external payable returns (LaunchResult memory);
    function computeTokenAddress(address launcher, bytes32 salt, LaunchParams calldata p)
        external
        view
        returns (address);
    function computeVestingEscrow(address launcher, bytes32 salt) external view returns (address);
    /// @notice The `pHash` a pad's signer signs for `p` sent by `launcher` with `nativeDevBuy` wei (LaunchpadAuth
    ///         .termsHash), payees resolved as launch() resolves them. Served here, not by the registry (EIP-170).
    function hashLaunchTerms(LaunchParams calldata p, address launcher, uint256 nativeDevBuy)
        external
        view
        returns (bytes32 pHash);
    /// @notice One-shot (SuiteAlreadySet). Registers the leg with the ledger as leg 1 and records it, exactly as
    ///         setHolderLeg does later.
    function setSuite(SuiteAddrs calldata a) external;
    /// @notice Every owner setter below is one call with no wait (suite 4). Future launches only: the new hook joins
    ///         the generations list; pools on an earlier generation stay there.
    function setHook(address newHook) external;
    function setPaused(bool paused) external;
    /// @notice On (the deploy default): only Bankr's id 0 may launch (plan Q15-B). Off: pads launch under their own
    ///         rules too. Id 0 always carries an authorization from the launchpad registry's bankrSigner (D10).
    function setLaunchGated(bool gated) external;
    /// @notice Bankr's own half of future quotes' buckets, the bond payee and the ledger's protocol sink (H13 GOV-1),
    ///         at once. The sink moves from the old Safe to the new one; the old Safe still collects its own.
    function setTreasury(address treasurySafe) external;
    /// @notice Suite code (every hook generation, a linked library) or a routing marker: never a
    ///         payee anything collects.
    function isSuite(address a) external view returns (bool);
    function paused() external view returns (bool);
    function launchGated() external view returns (bool);
    function weth() external view returns (address);
    function treasury() external view returns (address);
    /// @dev Sole, locked beneficiary of the holdersId bucket of every launch made while it is named here: the BNKR
    ///      holder leg in force (H17). A coin keeps the leg of its launch; setHolderLeg changes it for later ones.
    function holderLeg() external view returns (address);
    /// @notice Owner, instant: registers `leg` with the ledger and names it for every launch from now on. The leg and
    ///         its references are suite code for good.
    function setHolderLeg(address leg) external;
    /// @dev The chain's BankrBuyback (H8b): the `buyback` payee of every launch's creator bucket that opts in. Set once.
    function buyback() external view returns (address);
    function hook() external view returns (address);
    function ledger() external view returns (address);
    function locker() external view returns (address);
    function holderRewardsDeployer() external view returns (address);
    function tokenDeployer() external view returns (address);
    function vestingEscrowImpl() external view returns (address);
    function launchpadRegistry() external view returns (address);
    /// @notice The settings contract: every launch's terms are its resolve's answer. Set once, in setSuite.
    function settings() external view returns (address);
    /// @notice keccak256 of the coin's CoinTerms as stored and logged (CoinTermsFrozen); 0 for any other address.
    function termsHashOf(address token) external view returns (bytes32);
    /// @notice Every hook generation this factory wired, oldest first; a launch registers on the newest.
    function hookGenerations() external view returns (address[] memory);
    function launcherOf(address token) external view returns (address);
    function vestingEscrowOf(address token) external view returns (address);
    function poolOf(address token) external view returns (bytes32 poolId, PoolKey memory key);
    function FEES_TO_HOLDERS() external view returns (address);

    event TokenLaunched(
        address indexed token,
        address indexed launcher,
        address indexed quote,
        bytes32 poolId,
        int24 startTick,
        string metadataUri,
        uint64 launchpadId
    );
    /// @dev Only for a launch whose trading opens later than the launch itself: `startTime` is the second the hook
    ///      first lets a public swap through and the token first lets a wallet move it.
    event TradingScheduled(address indexed token, bytes32 indexed poolId, uint64 startTime);
    /// @dev The coin's record, once: `terms` is abi.encode(CoinTerms) with the words only the factory knows filled in
    ///      (the token, the trading start, a preset's binding), `termsHash` its hash (termsHashOf), `resolvedHash`
    ///      what resolve returned for the same launch (the launcher's pin). Logged before the pool is initialised.
    event CoinTermsFrozen(
        address indexed token, bytes32 indexed poolId, bytes32 termsHash, bytes32 resolvedHash, bytes terms
    );
    event LaunchResolved(
        address indexed token,
        uint256 curveId,
        address distributor,
        address vestingEscrow,
        address vestingRecipient,
        uint256 devBuyOut
    );
    event HookSet(address indexed hook);
    event PausedSet(bool paused);
    event TreasurySet(address indexed treasury);
    event HolderLegSet(address indexed holderLeg, uint16 legId);
    event LaunchGateSet(bool gated);

    error Paused();
    error Expired();
    error InvalidTick();
    error TokenSaltTaken();
    error TokenAddressChanged(address actual); // the launch pinned another token address (LaunchOptions.expectedToken)
    error MalformedLaunch(); // launch() calldata whose params offset is not the canonical one
    error TermsMismatch(); // the split's auto-LP payees or the hook are not the ones the coin's record names
    error InvalidCurve(); // neither a built-in curve id (0..2) nor a well-formed table of bands (CurveTable)
    error SentinelPayee();
    error InvalidVestingRecipient();
    error InvalidFeeRecipient();
    error InvalidFeeRecipients();
    error OpenContractFeeRecipient(address recipient);
    error DevBuyTooLarge();
    error DevBuyerExcluded(); // a scheduled launch's dev buyer is on the token's cap exclusions: it could move before the start
    error DevBuyTooLittle();
    error AmbiguousDevBuy();
    error DevBuyNativeOnlyForWeth();
    error SuiteAlreadySet();
    error SuiteUnset();
    error OwnershipCannotBeRenounced();
    error ZeroAddress();
    error NotPoolManager();
    error LaunchpadPayeeRejected(); // a pad payee is a sentinel, a suite contract, the token or the escrow
    error LaunchGated(); // the gate is on and the launch names a pad other than Bankr's id 0
    error InvalidExtensionPayee(); // a sentinel, a suite contract, the token or the escrow
    error ExtensionPayeeUnnamed(); // several fee recipients and an extension: the payee must be named
    error PresetBindingMismatch(); // the preset deployer returned a binding other than the launch asked for
    error AmbiguousExtension(); // a preset id with custom fields, or custom code with preset params
    error InvalidHook(); // setSuite's or setHook's hook is not this suite's, or names periphery that is not its own
    error InvalidHolderLeg(); // a leg not built on this factory's ledger and distributor deployer, or with no oracle
    error InvalidTreasury(); // suite code, a hook generation, a preset instance, a launched token, a quote or a marker
    error InvalidSettings(); // setSuite's settings contract was not built for this factory and its pad registry

    // Raised by LaunchEconomics' and LaunchPool's dependencies (OpenZeppelin Clones / SafeERC20, RunnerCurve) under the
    // factory's delegatecall; declared here so the factory's ABI still decodes every revert a launch can bubble (H18).
    error FailedDeployment();
    error InsufficientBalance(uint256 balance, uint256 needed);
    error SafeERC20FailedOperation(address token);
    error UnknownCurve();
    // A launch's curve (CurveTable), raised under LaunchPool's delegatecall. A table is held to its coin's own rules
    // (CurveRules, from the pad's knobs and the owner's guard); a built-in curve to no liquidity (B8), its per-tick
    // figure (B9) and its dust figure (B10) only.
    error CurveTooThin(uint256 row); // the row's band holds no liquidity, or under 1 / minDepthDiv of the flat curve's
    error CurveLiquidity(uint256 row); // the row's band puts a tick past half of v4's cap (a built-in: past its figure)
    error CurveTooDense(uint256 row); // the row's band is over maxDensity times the sale as one band from its near edge
    error CurveStep(uint256 row); // a pool that buys its own token: the row's band is over its step on those under it
    error CurvePlacement(); // under placeBps of the sale is sold by placeTicks past the start
    error CurveDust(uint256 unplaced); // the bands left more of the sale unplaced than the curve's ppm
    // B12 at the start price, raised under LaunchPool's delegatecall: a pool with an auto-LP share starts where TOKEN's
    // side of its own compound band is worth nothing to the hook's arithmetic: no compound could place until a rise.
    error CompoundStartTooDeep();
}

src/interfaces/IBankrLaunchHook.sol

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

import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolSide} from "../libraries/FeeMath.sol";
import {PoolInit} from "./SuiteTypes.sol";

/// @dev PoolConfig slot 6, a pool with an auto-LP share only: how much one compound places, how often, and where.
struct PoolWorks {
    uint128 compoundCap; // quote one execution may put to work
    uint32 compoundInterval; // seconds between compounds, at least 1
    uint16 compoundShareBps; // of the backlog per execution; 0 = no share cap
    uint16 compoundDeviationTicks; // how far under the reference TOKEN may sit
    uint16 bandHalfWidth; // tick spacings
    uint16 bandGrid; // tick spacings
    uint16 swapCapTicks; // the self-swap's push past spot and the reference
}

/// @dev PoolConfig slot 7, a pool with a buyback share only: the in-swap fill's cadence and its price rule's numbers.
struct PoolFill {
    uint32 buybackInterval;
    uint32 buybackRetry; // after a refused fill
    uint16 fillTravelTicks; // the figure for this pool, compounding or not, chosen once at launch
    uint16 fillStartGapTicks;
}

/// @dev `refTick` is the compound reference (audit M-1): a time-weighted EMA of the tick BEFORE each second's first swap
///      (weight dt / (dt + refTauSecs)), so no swap can move the reference it is gated against in its own block.
///      Keyed on block.timestamp, not block.number, which is L1's on Arbitrum and Robinhood (R7-12).
///      `refFrac` carries its fraction in 1/65,536 tick, so a fold every block never rounds to a standstill (H13 R2-2).
///      `heldQuote` is quote already pulled from the ledger but left over by the per-execution cap or by a compound's
///      band, kept as the hook's own ERC-6909 claims for this pool and counted by backlogOf; `heldToken` is the TOKEN a
///      compound bought but its band could not take, held the same way and placed by the next compound (audit r1 F-3).
///      `hasExtension` shares slot 0, so a pool without one pays only a warm read for the extension slot. `buy` and
///      `sell` are the launch's fee schedules, bound at registerPool for good; `decaySplit` / `creatorLp`: the hook is an
///      auto-LP payee of
///      the pool's decayId / creatorId, the only buckets it pulls (review B finding 2).
///      Slot 1 closes with the fill floor, the edge of the pool's locked liquidity (NS-18 CLOSURES-1) and the reference's
///      time constant; slots 4 to 7 are the pool's own terms, written at registerPool and never again.
struct PoolConfig {
    bool registered;
    bool tokenIsCurrency0;
    uint40 initTimestamp; // the trading start: the launch's own second, or its scheduled start when that is later
    int24 startTick;
    address token;
    bool hasExtension;
    bool decaySplit;
    int24 refTick;
    uint40 refTs; // the second of the last fold: at most one a second
    uint40 lastCompoundTs;
    bool creatorLp;
    uint16 refFrac; // refTick's fraction: the EMA is refTick + refFrac / 2^16
    uint40 buybackAt; // 0 = no buyback share; else the second from which a swap may run the next in-swap fill
    int24 openTick; // the tick before the first swap of second `refTs` (the launch tick in the launch second): audit F-01
    int24 floorTick; // the fill floor as last folded: the TOKEN-cheapest tick a swap started from
    int24 edgeTick; // the TOKEN-cheapest tick the pool's locked liquidity reaches
    uint16 refTauSecs; // the reference's time constant, at least 1,800
    uint256 heldQuote;
    uint256 heldToken;
    PoolSide buy;
    PoolSide sell;
    PoolWorks works;
    PoolFill fill;
}

/// @dev Factory-pushed, by setSuite / setHook only, with a locker the factory can never change. Nothing else is
///      pushed: a pool's terms are its own (PoolConfig), and only paused() is read live from the factory.
struct HookConfig {
    address locker;
}

/// @dev A launch's extension, bound once at registerPool and never changed. `codehash` is what the launcher expects at
///      `ext` (registerPool reverts on a mismatch); a later mismatch charges 0. Bankr's fee plus the extension's never
///      passes `feeCeilingPips`; Bankr takes `bankrNum / bankrDen` of every extension fee (bankrId) and the payee the
///      rest as ERC-6909 claims. `quoteOnly`: the hook only ever STATICCALLs `quote`, never the guarded post-swap call.
///      `sunsetSecs` (0 = none): from that many seconds after the trading start the extension is not asked or called.
///      `quoteGas` / `afterGas`: the gas `quote` and the post-swap call are handed, exactly, on every swap for the
///      pool's life (afterGas is 0 exactly when quote-only). `ownerSwitch`: the factory owner's switch reaches this pool.
struct ExtBinding {
    address ext;
    uint24 quoteGas;
    uint24 afterGas;
    uint24 feeCeilingPips;
    uint8 bankrNum;
    uint8 bankrDen;
    bytes32 codehash;
    uint24 maxBuyPips;
    uint24 maxSellPips;
    address payee;
    bool quoteOnly;
    uint32 sunsetSecs;
    bool ownerSwitch;
}

/// @dev Why the in-swap compound did not run. TOO_SOON / PRICE_MOVED are the M-1 gates (the pool's compoundInterval /
///      compoundDeviationTicks). NO_LIQUIDITY: the pool's in-range liquidity lets the price-limited self-swap spend under
///      1/32 of the pool's compound floor (H13 R2-3). ROUTE_ABSENT and GAS are no longer emitted: a swap too short on
///      gas for a due compound now reverts CompoundGas instead of skipping it (audit r1 ADM-02).
enum SkipReason {
    NONE,
    PAUSED,
    BELOW_THRESHOLD,
    ROUTE_ABSENT,
    NO_LIQUIDITY,
    REVERTED,
    TOO_SOON,
    PRICE_MOVED,
    GAS
}

/// @dev The guarded post-swap call's outcome (README "Post-swap call"). REVERTED: the extension reverted on its own;
///      ROLLED_BACK: the guard undid it (open deltas moved, or the frame ran out of gas); SKIPPED_FLAG: the trader's
///      HookData.SKIP_AFTER_SWAP. SKIPPED_GAS is no longer emitted: a swap that cannot hand the call its whole budget
///      reverts with ExtensionGas before it runs (audit r1 EXT-1, r2 EXT-1), so an estimated gas limit always runs it.
enum ExtCall {
    OK,
    REVERTED,
    ROLLED_BACK,
    SKIPPED_GAS,
    SKIPPED_FLAG
}

/// @notice Hook surface beyond IHooks: factory wiring, the public compound safety valve, the extension surface and
///         extsload; the views are BankrHookLens's (H18). Loop, anchor and keeper entries are gone (spec v4.1 R1).
interface IBankrLaunchHook {
    /// @dev Factory only, once per pool: everything the hook ever holds for it, never changed. `init.ext == 0`: no
    ///      extension; otherwise code that does not start with 0xEF, at the expected codehash, with a payee. Every
    ///      bound the swap path's arithmetic leans on is checked on what is stored (InvalidPoolInit names it).
    function registerPool(PoolKey calldata key, PoolInit calldata init) external;
    function syncConfig(HookConfig calldata c) external;
    /// @notice One raw storage slot (v4 Extsload). The hook's views read through it: BankrHookLens, HookState.
    function extsload(bytes32 slot) external view returns (bytes32 value);
    /// @notice v4 Extsload's batched read: BankrBuyback takes a pool's words in one call.
    function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
    /// @notice BankrHookLens, created by the hook: hookConfig, poolConfig, poolKey, currentFeePips, extensionOf,
    ///         extensionSwitchedOff, backlogOf, straddleBand and compoundGate (moved off the hook, H18).
    function hookLens() external view returns (address);
    /// @dev ANYONE; own unlock; reverts Paused / CompoundBelowThreshold (also on a pool with no auto-LP share)
    ///      / CompoundSameBlock (the pool already swapped in this second — audit L-4, R7-12) / CompoundTooSoon /
    ///      CompoundPriceMoved; same body, caps and gates as the in-swap path, no bounty.
    function compound(bytes32 poolId) external returns (uint128 liquidity, int24 lower, int24 upper);
    /// @dev Self-call target of the in-swap path (msg.sender == the hook) so a revert is caught without losing the swap.
    function compoundSelf(bytes32 poolId) external returns (uint128 liquidity, int24 lower, int24 upper);
    /// @notice TOKEN's move since launch in ticks of the block-opening reference (refTick − startTick): positive = TOKEN
    ///         dearer in quote, whichever currency it is. Raw ticks price currency1 in currency0 and flip with token order,
    ///         so extensions read this. The reference is the M-1 EMA (the pool's refTauSecs), folded once per second
    ///         before the quote runs, so no swap moves the value it is priced against.
    function launchRelativeTick(bytes32 poolId) external view returns (int24 ticksUp);
    /// @dev Self-call target of the post-swap call (msg.sender == the hook): the guard frame around the extension's CALL.
    ///      Reverts, undoing the extension's effects, if the pinned PoolManager state moved; else returns whether the
    ///      extension's own call succeeded.
    function extensionFrame(
        bytes32 poolId,
        address ext,
        bytes calldata data,
        address sender,
        Currency c0,
        Currency c1,
        address[] calldata pins
    ) external returns (bool ok);
    /// @notice The factory owner's per-extension switch (plan Q25), instant both ways. While off, no pool bound to `ext`
    ///         with `ownerSwitch` asks or calls it: no extension fee, no buy refusal, no post-swap call. A binding
    ///         without `ownerSwitch` never reads it. On again, a swap needs the lens's `extSwapGasHeadroom` more.
    function setExtensionSwitchedOff(address ext, bool off) external;

    /// @dev `init` is registerPool's own argument, logged word for word: the pool's whole record in one event.
    event PoolRegistered(bytes32 indexed poolId, address indexed token, bool tokenIsCurrency0, PoolInit init);
    /// @dev `quoteIn` is the quote this execution put to work (the part self-swapped into TOKEN plus the part paired in the
    ///      band) and `tokenIn` the TOKEN placed in the band; what the band could not take stays held (audit r1 F-3).
    event Compounded(
        bytes32 indexed poolId, int24 lower, int24 upper, uint128 liquidity, uint256 quoteIn, uint256 tokenIn
    );
    event CompoundSkipped(bytes32 indexed poolId, SkipReason reason);
    event ExtensionBound(
        bytes32 indexed poolId,
        address indexed ext,
        bytes32 codehash,
        uint24 maxBuyPips,
        uint24 maxSellPips,
        address payee,
        bool quoteOnly,
        uint32 sunsetSecs
    );
    /// @dev One per swap that charged an extension fee: `payeeQuote` minted to the payee as claims, `treasuryQuote`
    ///      credited to the quote's bankrId bucket.
    event ExtensionFeeTaken(
        bytes32 indexed poolId, address indexed ext, uint24 extPips, uint256 payeeQuote, uint256 treasuryQuote
    );
    event ExtensionSwitchedOff(address indexed ext, bool off);
    /// @dev One per outer swap on which the bound extension was due its post-swap call.
    event ExtensionAfterSwap(bytes32 indexed poolId, address indexed ext, ExtCall result);

    error NotFactory();
    error NotPoolManager();
    error NotSelf();
    error PoolNotRegistered();
    error AlreadyRegistered();
    error LiquidityNotLocker();
    error HookAddressMismatch();
    error HookNotImplemented();
    error NotDynamicFee();
    error WrongTickSpacing();
    error CompoundBelowThreshold();
    error CompoundSameBlock();
    error CompoundTooSoon();
    error CompoundPriceMoved();
    error CompoundNoLiquidity();
    error Paused();
    error NotFactoryOwner();
    error ExtensionRejected();
    error ExtensionCodehashMismatch();
    error ExtensionCapTooHigh();
    /// @dev registerPool: `bound` is the hard bound of the suite's design (section 2) the pool's terms break. 1 a fee
    ///      schedule, 3 the fee ceiling, 4 a share of a whole, 12 the compound's terms, 16 the reference or the fill.
    error InvalidPoolInit(uint8 bound);
    error ExtensionPayeeInvalid();
    /// @dev A binding's gas budget outside [EXT_QUOTE_GAS, EXT_QUOTE_GAS_MAX] / [EXT_AFTER_GAS, EXT_AFTER_GAS_MAX], or a
    ///      quote-only binding naming a post-swap budget.
    error ExtensionGasBudget();
    /// @dev Not enough gas left to hand the quote, or the post-swap call (plus the quote's slack), its whole budget: the
    ///      swap reverts instead of skipping the fee or the call (audit r1 EXT-1, r2 EXT-1).
    error ExtensionGas();
    /// @dev A due compound handed less than its stipend did not succeed: the swap reverts rather than skip it (audit r1
    ///      ADM-02), so the lowest gas limit at which the swap lands is one at which it compounds.
    error CompoundGas();
    error ExtensionRefusedBuy();
    /// @dev While an extension's post-swap frame runs, any other pool of this hook refuses to swap, and so does the
    ///      frame's own pool for any swapper but the bound extension (audit r2 EXT-2).
    error ExtensionReentrantSwap();
    /// @dev The guard frame's own revert: the extension moved the PoolManager's open deltas, so all of it is undone.
    error ExtensionGuard();
    /// @dev The router left a currency other than the pool's two synced across a swap that is due a post-swap call: the
    ///      guard lens never reads one (code the trader picked), so a buy reverts and a sell skips the call (audit r5 EXT-1).
    error ForeignCurrencySynced();
    /// @dev Scheduled start: a swap (any sender but the factory's own launch-time dev buy) or a compound before the
    ///      pool's trading start, PoolConfig.initTimestamp. It ends by itself at that second; no one can move it.
    error TradingNotStarted();
}

src/interfaces/IBankrLaunchpadRegistry.sol

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

/// @dev An extension's kind (0 = none); a pad's flags F6 to F8 in the settings contract switch each kind on.
uint8 constant EXT_KIND_PRESET = 1;
uint8 constant EXT_KIND_QUOTE_ONLY = 2; // custom code bound quote-only: a read-only quote, no post-swap call
uint8 constant EXT_KIND_CALLS_OUT = 3; // custom code with the guarded post-swap call

/// @dev Id 0's suffix, the one suffix closed to launches on every other pad (D28).
uint24 constant BANKR_VANITY = 0xba3;
uint8 constant BANKR_VANITY_NIBBLES = 3;

/// @notice The identity of every launchpad on the Bankr launch suite. One registry per chain; `register()` (bond to the
///         treasury) mints a sequential `launchpadId` from 1 and gives the pad its own rows in the settings contract.
///         Id 0 is Bankr's own pad, operated by the registry owner and always signed by `bankrSigner`. The factory
///         calls `recordLaunch` for every launch: the registry verifies and consumes the signer's one-use EIP-712
///         LaunchAuthorization (domain `("Bankr Launchpads", "1")`, verifying contract = this registry), holds the
///         pad's pause and vanity and records `launchpadOf(token)`. A pad's knobs, flags, payees, quotes, curves and
///         the extension allowlist are the settings contract's.
interface IBankrLaunchpadRegistry {
    /// @dev Empty `(0, 0, "")` for an open pad (`signer == address(0)`); id 0 always carries Bankr's.
    struct LaunchAuthorization {
        bytes32 nonce;
        uint256 deadline;
        bytes signature;
    }

    /// @dev The decay window's surplus above the steady fee (spec §3): off, it follows the steady split; on, each payee
    ///      takes its `sharesWad` of it, auto-LP `autoLpBps` of the rest and the creator what is left.
    struct DecaySplit {
        bool on;
        uint16 autoLpBps;
        uint256[] sharesWad;
    }

    /// @dev The token's last `nibbles` hex digits must be `suffix` (0 nibbles = none; otherwise 4–6, id 0's `ba3`
    ///      aside). Suffixes are prefix-free across pads, and only `…ba3` is closed to launches on other pads (D28).
    struct Vanity {
        uint24 suffix;
        uint8 nibbles;
    }

    /// @dev A pad's identity; its settings are the settings contract's and its branding `metadataUriOf`.
    struct Launchpad {
        address operator; // id 0: the registry owner
        address pendingOperator;
        address signer; // address(0) = open pad; id 0: bankrSigner
        bool paused;
        bool verified; // an off-chain badge the registry owner sets; no on-chain effect
        Vanity vanity;
    }

    /// @dev A pad's payees (distinct), each one's WAD share of the remainder and the decay split: what every launch
    ///      on the pad binds into its buckets. Held by the settings contract (`payeesOf`), which checks them.
    struct PadTerms {
        address[] payees;
        uint256[] steadySharesWad;
        DecaySplit decay;
    }

    // ── registration ─────────────────────────────────────────────────────────

    /// @notice Registers a new launchpad; `msg.sender` becomes its operator, `msg.value` must equal the bond. The pad
    ///         copies the owner's template in the settings contract (`initPad`), with these payees, no decay split,
    ///         no vanity and takeover off.
    function register(
        address signer,
        address[] calldata payees,
        uint256[] calldata steadySharesWad,
        string calldata metadataUri
    ) external payable returns (uint64 id);

    // ── operator-only config (immediate; future launches only) ───────────────

    /// @notice `address(0)` turns the pad open (no authorization required); on id 0 it is `bankrSigner`, and zero
    ///         refuses every id-0 launch.
    function setSigner(uint64 id, address signer) external;
    /// @notice `4 <= nibbles <= 6` (or 0, none) and `suffix < 16^nibbles`; reverts `VanityTaken` unless prefix-free with
    ///         every other pad's. Only `…ba3` (id 0's) binds launches from other pads.
    function setVanity(uint64 id, Vanity calldata vanity) external;
    /// @notice At most `maxPadUriBytes` bytes (`MetadataTooLong`).
    function setMetadataUri(uint64 id, string calldata uri) external;
    function setPaused(uint64 id, bool paused) external;
    function transferOperator(uint64 id, address next) external;
    function acceptOperator(uint64 id) external;

    // ── factory-only ─────────────────────────────────────────────────────────

    /// @notice Verifies + consumes the authorization over `paramsHash` (id 0: always `bankrSigner`'s), holds the
    ///         pad's pause and vanity, records `launchpadOf(token)`. The launch's terms are the settings contract's.
    function recordLaunch(
        uint64 id,
        address launcher,
        address token,
        bytes32 paramsHash,
        LaunchAuthorization calldata auth
    ) external;

    // ── owner (Bankr): the bond, the pad link's size, its own signer and the verified badge ──

    /// @notice Any amount, immediate: 0 is free registration. No pool's economics read it.
    function setRegistrationBond(uint256 wei_) external;
    /// @notice The longest link a pad may store, in bytes; 0 admits the empty link only. A stored link stands.
    function setMaxPadUriBytes(uint32 bytes_) external;
    /// @notice Id 0's signer (its `setSigner` slot): signs every id-0 launch; zero refuses them all.
    function setBankrSigner(address signer) external;
    function bankrSigner() external view returns (address);
    function setVerified(uint64 id, bool verified) external;
    /// @notice Permissionless; pays every accrued bond to the factory's treasury as it stands at the call.
    function withdrawBonds() external;

    // ── views ────────────────────────────────────────────────────────────────

    function BANKR_LAUNCHPAD_ID() external view returns (uint64);
    function maxPadUriBytes() external view returns (uint32);
    function factory() external view returns (address);
    /// @notice `factory.treasury()`, read live, so a rotated treasury takes the bonds too (audit r3 ADM-2).
    function treasury() external view returns (address);
    function registrationBondWei() external view returns (uint256);
    function accruedBonds() external view returns (uint256);
    function launchpadCount() external view returns (uint64);
    /// @notice A pad's operator; id 0's is the registry's owner.
    function operatorOf(uint64 id) external view returns (address);
    function getLaunchpad(uint64 id) external view returns (Launchpad memory);
    function metadataUriOf(uint64 id) external view returns (string memory);
    /// @notice The pad owning a vanity suffix, and whether one does (id 0 owns `0xba3`/3); a revoked suffix is owned by
    ///         `type(uint64).max` (the registry owner's) until the pad it is assigned to takes it.
    function vanityOwner(uint24 suffix, uint8 nibbles) external view returns (bool owned, uint64 id);
    /// @notice Owner only: takes a pad's suffix away (squatting, abuse); future launches of that pad carry no vanity. The
    ///         suffix stays held, by the registry owner: neither that pad nor any other can claim it (review C 4) until
    ///         `assignVanity` names the pad that may.
    function revokeVanity(uint64 id) external;
    /// @notice Owner only: a revoked suffix becomes claimable by pad `id` alone, through its own `setVanity` (the operator
    ///         opts in; nothing changes a pad's launches without it). Re-assigning replaces the designee.
    function assignVanity(uint24 suffix, uint8 nibbles, uint64 id) external;
    /// @notice The pad `token` launched on; reverts UnknownLaunch for a token the suite never launched (H13 GOV info).
    function launchpadOf(address token) external view returns (uint64);
    function isNonceUsed(uint64 id, bytes32 nonce) external view returns (bool);
    function domainSeparator() external view returns (bytes32);
    /// @notice The EIP-712 digest an operator's signer signs for one launch.
    function hashLaunchAuthorization(uint64 id, address launcher, bytes32 pHash, bytes32 nonce, uint256 deadline)
        external
        view
        returns (bytes32 digest);

    event LaunchpadRegistered(uint64 indexed id, address indexed operator, address signer, string metadataUri);
    event LaunchpadSignerSet(uint64 indexed id, address signer);
    event LaunchpadVanitySet(uint64 indexed id, uint24 suffix, uint8 nibbles);
    event VanityRevoked(uint64 indexed id, uint24 suffix, uint8 nibbles);
    event VanityAssigned(uint64 indexed id, uint24 suffix, uint8 nibbles);
    event LaunchpadVerifiedSet(uint64 indexed id, bool verified);
    event LaunchpadMetadataSet(uint64 indexed id, string metadataUri);
    event LaunchpadPausedSet(uint64 indexed id, bool paused);
    event LaunchpadOperatorTransferStarted(uint64 indexed id, address pendingOperator);
    event LaunchpadOperatorTransferred(uint64 indexed id, address operator);
    /// @dev The per-pad attribution event (D6): `TokenLaunched` keeps its three indexed slots for existing decoders.
    event LaunchRecorded(uint64 indexed launchpadId, address indexed token, address indexed launcher);
    event RegistrationBondSet(uint256 wei_);
    event MaxPadUriBytesSet(uint32 bytes_);
    event BankrSignerSet(address signer);
    event BondsWithdrawn(address indexed treasury, uint256 amount);

    error NotFactory();
    error NotOperator();
    error NotPendingOperator();
    error UnknownLaunchpad();
    error IncorrectBond();
    error ZeroAddress();
    error MetadataTooLong();
    error InvalidVanity();
    error LaunchpadPaused();
    error VanityMismatch(); // the token does not end in the pad's suffix
    error VanityTaken(); // a suffix that is not prefix-free, or a token ending in another pad's suffix
    error AuthorizationExpired();
    error NonceUsed();
    error InvalidAuthorization();
    error BankrSignerUnset();
    error NoAccruedBonds();
    error OwnershipCannotBeRenounced();
    error BondTransferFailed();
    error UnknownLaunch(); // launchpadOf: a token the suite never launched
}

src/interfaces/ICreatorVestingEscrow.sol

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

/// @dev One schedule. `push` (vest-to-holders, H9a): released by anyone to its recipient (the launch's distributor) with
///      releaseFor; only the factory adds one. Otherwise a pull schedule its recipient releases with release.
struct VestingAllocation { address recipient; uint256 amount; uint64 cliff; uint64 duration; bool push; }

/// @notice Per-launch vesting escrow exposing Doppler's ABI subset (spec v4.1 R5) so le4-03's vesting reader keeps its names,
///         plus Launch v3's push schedules (spec §9).
interface ICreatorVestingEscrow {
    /// @dev `start`: the launch's scheduled trading start; every schedule's clock runs from the later of it and now.
    function initialize(address token, VestingAllocation[] calldata schedules, uint64 start) external;
    function factory() external view returns (address);
    function token() external view returns (address);
    function vestingStart() external view returns (uint256);
    function getScheduleIdsOf(address beneficiary) external view returns (uint256[] memory);
    function vestingSchedules(uint256 scheduleId) external view returns (uint64 cliff, uint64 duration);
    function vestingOf(address beneficiary, uint256 scheduleId) external view returns (uint256 totalAmount, uint256 releasedAmount);
    function scheduleCount() external view returns (uint256);
    function scheduleOf(uint256 scheduleId)
        external
        view
        returns (address beneficiary, uint256 total, uint256 released, uint64 cliff, uint64 duration, bool push);
    /// @notice What `beneficiary` could release now across its schedules of both kinds.
    function computeAvailableVestedAmount(address beneficiary) external view returns (uint256);
    /// @notice What releaseFor(beneficiary) would push now (its push schedules only).
    function computePushableAmount(address beneficiary) external view returns (uint256);
    function release(uint256 amount) external;
    function releaseFor(address beneficiary) external returns (uint256 amount);
    event Initialized(address indexed token, uint256 vestingStart, uint256 total);
    event VestingReleased(address indexed beneficiary, uint256 amount);
    event VestingPushed(address indexed beneficiary, address indexed caller, uint256 amount);
    error NotFactory(); error AlreadyInitialized(); error NotInitialized(); error InsufficientEscrowBalance(uint256 needed, uint256 held);
    error NothingVested(); error ReleaseExceedsVested(uint256 requested, uint256 available); error InvalidSchedule();
    error NotPushSchedule();
}

src/interfaces/SuiteTypes.sol

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

// FeeMath's FeeSchedule as it stands: decaySecs is the uint32 of the suite 4 design (5.1), widened with the hook's
// slot before any ABI or vector that names LaunchParams was frozen (plan file, Departure 2).
import {FeeSchedule} from "../libraries/FeeMath.sol";
import {PricingMode} from "./IBankrLaunchFactory.sol";
import {IBankrLaunchpadRegistry} from "./IBankrLaunchpadRegistry.sol";

// The types the suite 4 settings contract, its resolver, the factory and the stores of a coin's terms share. Every
// struct but PadConfig is all static, so its ABI encoding is a fixed run of words read at fixed offsets.

/// @dev Bankr's cut and the clocks the owner sets; one slot, copied into each coin at launch.
struct ProtocolTerms {
    uint16 bankrFeeBps;
    uint24 bankrMinPips;
    uint16 holdersShareBps;
    uint8 extBankrNum;
    uint8 extBankrDen;
    uint32 ctoNotice;
    uint32 ctoGrace;
    uint32 tokenActivationDivisor;
    uint32 bnkrActivationDivisor;
    uint8 maxPadPayees;
}

/// @dev The numbers the buyback's and the compound's price rule were sized with; one slot, copied into each coin.
struct GuardTerms {
    uint16 refTauSecs;
    uint16 compoundSwapMaxTicks;
    uint16 fillTravelTicks;
    uint16 fillTravelCompoundingTicks;
    uint16 fillStartGapTicks;
    uint24 minRoundTripPips;
    uint16 curveNearStep;
    uint32 maxCompoundUsd; // whole USD, at least 1
}

/// @dev A pad's knob: a launch picks inside [min, max] or takes dflt. One slot.
struct Range {
    uint64 min;
    uint64 max;
    uint64 dflt;
}

/// @dev The owner's outer range of a knob.
struct Limit {
    uint64 min;
    uint64 max;
}

struct QuoteTerms {
    bool allowed;
    PricingMode mode;
    uint8 decimals;
    uint32 maxPriceAge;
    address feed;
    uint128 compoundFloor;
    uint128 compoundCap;
    uint128 quoteActivation;
    bool quotePaid; // this quote's coins pay holders in the quote, on purpose
}

struct PadQuoteTerms {
    bool allowed;
    bool ownAmounts;
    uint128 compoundFloor;
    uint128 compoundCap;
}

struct PresetLimits {
    bool allowed;
    uint32 maxWindowSecs;
    int24 minBrakeTicks;
    uint32 minAnchorTau;
}

struct PresetRecord {
    address deployer;
    bytes32 deployerCodeHash;
    bytes32 creationCodeHash;
    bool selfPayee;
    bool active;
}

struct PadConfig {
    uint8[] knobs; // any subset of the knob table, with its ranges
    Range[] ranges;
    uint256 flags;
    address capController;
    IBankrLaunchpadRegistry.PadTerms terms;
    uint8[] presetIds;
    PresetLimits[] presetLimits;
}

/// @dev LaunchParams.options, ABI-encoded. A clear bit of `set` means the pad's default, and those fields are zero.
struct LaunchOptions {
    uint32 set; // Knobs.OPT_*
    uint16 capBps; // OPT_CAP
    uint32 capSecs;
    uint32 vestCliffSecs; // OPT_VEST_CLOCK
    uint32 vestSecs;
    uint128 compoundFloor; // OPT_COMPOUND_AMOUNTS
    uint128 compoundCap;
    uint32 compoundInterval; // OPT_COMPOUND_CADENCE
    uint16 compoundShareBps;
    uint16 compoundDeviationTicks;
    uint16 bandHalfWidth; // OPT_COMPOUND_BAND
    uint16 bandGrid;
    uint32 buybackInterval; // OPT_BUYBACK_CADENCE
    uint32 buybackRetry;
    uint32 rewardStreamSecs; // OPT_REWARD_STREAM
    uint16 rewardRestartBps;
    uint24 feeCeilingPips; // OPT_FEE_CEILING
    bytes32 expectedTermsHash; // pin; 0 = whatever is in force
    address expectedToken; // pin; 0 = any
}

/// @dev What the hook stores for a pool, forwarded and logged raw. `token` and `startAt` are the factory's; for a
///      preset so are ext, quoteGas, afterGas, codehash, maxBuyPips, maxSellPips, payee, quoteOnly and sunsetSecs.
struct PoolInit {
    address token;
    uint40 startAt;
    bool creatorLp;
    bool decayLp;
    bool buyback;
    FeeSchedule buy;
    FeeSchedule sell;
    uint128 compoundFloor;
    uint128 compoundCap;
    uint32 compoundInterval;
    uint16 compoundShareBps;
    uint16 compoundDeviationTicks;
    uint16 bandHalfWidth;
    uint16 bandGrid;
    uint16 swapCapTicks;
    uint32 buybackInterval;
    uint32 buybackRetry;
    uint16 fillTravelTicks;
    uint16 fillStartGapTicks;
    uint16 refTauSecs;
    address ext; // 0: no extension
    uint24 quoteGas;
    uint24 afterGas;
    uint24 feeCeilingPips;
    uint8 bankrNum;
    uint8 bankrDen;
    bytes32 codehash;
    uint24 maxBuyPips;
    uint24 maxSellPips;
    address payee;
    bool quoteOnly;
    uint32 sunsetSecs;
    bool ownerSwitch;
}

struct CurveRules {
    uint32 minDepthDiv;
    uint32 maxDensity;
    uint24 placeTicks;
    uint16 placeBps;
    uint24 nearTicks;
    uint16 nearStep;
    uint32 dustPpm;
    bool builtIn;
}

/// @dev A coin's resolved terms: stored in the coin's own contracts, hashed and logged once, never changed.
struct CoinTerms {
    uint64 launchpadId;
    address quote;
    bytes32 padTermsHash;
    address hook;
    address holderLeg;
    uint16 legId;
    bool holderConverts;
    uint8 presetId;
    bytes32 presetCodeHash;
    address presetDeployer;
    bytes32 presetDeployerCodeHash;
    bool presetSelfPayee;
    // maxPips u24 | minWindowSecs u32 | maxWindowSecs u32 | minBrakeTicks i24 | minAnchorTau u32 | maxDustFloor u112
    uint256 presetSite;
    uint256 totalSupply;
    uint256 capAmount;
    uint32 capSecs;
    address capController;
    uint32 metadataMaxBytes;
    uint64 startTime;
    uint32 vestCliffSecs;
    uint32 vestSecs;
    uint16 devBuyMaxBps;
    uint8 maxFeeRecipients;
    uint16 holdersBps;
    uint16 autoLpBps;
    uint16 buybackBps;
    uint16 vestBps;
    uint16 vestToHoldersBps;
    uint64 vestToHoldersCliff;
    uint64 vestToHoldersDuration;
    uint256 vestedAmount;
    uint16 bankrFeeBps;
    uint24 bankrMinPips;
    uint16 holdersShareBps;
    bool waiveBnkrPair;
    bool takeover;
    uint32 ctoNotice;
    uint32 ctoGrace;
    uint24 minRoundTripPips;
    uint16 referrerBps;
    PoolInit pool;
    uint24 extMaxPips;
    uint32 rewardStreamSecs;
    uint16 rewardRestartBps;
    uint32 tokenActivationDivisor;
    uint32 bnkrActivationDivisor;
    uint128 quoteActivation;
    CurveRules curve;
}

src/libraries/BucketIds.sol

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

/// Ledger bucket ids (spec v4.1 bucket table). The TypeScript mirror (le4-02 `bucketIds.ts`)
/// hashes the same raw concat via viem's encodePacked.
library BucketIds {
    function creatorId(bytes32 poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(poolId, "creator"));
    }

    /// @dev The coin's holders' half of Bankr's slice (H4), sole beneficiary the chain's BNKR holder leg.
    function holdersId(bytes32 poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(poolId, "holders"));
    }

    /// @dev The decay surplus above the steady rate, registered only when the launch's pad has a decay split (H4).
    function decayId(bytes32 poolId) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(poolId, "decay"));
    }

    /// @dev One bucket per quote currency per chain: Bankr's own half of every pool's slice and its cut of every extension
    ///      fee, sole beneficiary the treasury.
    function bankrId(address quote) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(quote, "bankr"));
    }
}

src/libraries/FeeMath.sol

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

import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";

/// @dev One direction's fee schedule (Launch SDK H3): `startPips` falling linearly to `steadyPips` over `decaySecs` from
///      pool init, bound once at launch. A 0 s decay is flat at the steady rate.
struct FeeSchedule {
    uint24 startPips;
    uint24 steadyPips;
    uint32 decaySecs;
}

/// @dev One direction of a pool as the hook stores it, one slot: the schedule and the pool's compound floor (the same
///      figure in both directions), so the swap's one read of its schedule brings the floor with it.
struct PoolSide {
    uint24 startPips;
    uint24 steadyPips;
    uint32 decaySecs;
    uint128 compoundFloor;
}

/// @dev One swap fee's legs (Launch SDK H4): the coin's holders, Bankr's own half, the referrer, then the remainder's
///      steady part (the creator bucket) and decay surplus (the decay bucket). They sum to the fee exactly.
struct SwapSplit {
    uint256 holders;
    uint256 bankr;
    uint256 referral;
    uint256 steady;
    uint256 decay;
}

/// Per-launch fee schedule, Bankr's slice and the per-swap split (Launch SDK H3/H4), four-shape fee sizing.
library FeeMath {
    /// @dev f(t) = t >= d ? s : a − (a − s)·t / d, the drop rounded down so the fee never undershoots the line.
    ///      `nowTs >= initTimestamp`: the hook refuses a swap before the trading start, and views clamp (HookState).
    function feePipsAt(FeeSchedule memory s, uint256 initTimestamp, uint256 nowTs) internal pure returns (uint24) {
        uint256 elapsed = nowTs - initTimestamp;
        if (elapsed >= s.decaySecs) return s.steadyPips;
        uint256 drop = uint256(s.startPips - s.steadyPips) * elapsed / s.decaySecs;
        // casting to 'uint24' is safe because drop <= startPips - steadyPips
        // forge-lint: disable-next-line(unsafe-typecast)
        return uint24(s.startPips - drop);
    }

    /// @dev feePipsAt on a pool's stored side: the same line, read from the hook's own slot.
    function sideFeeAt(PoolSide memory s, uint256 initTimestamp, uint256 nowTs) internal pure returns (uint24) {
        uint256 elapsed = nowTs - initTimestamp;
        if (elapsed >= s.decaySecs) return s.steadyPips;
        uint256 drop = uint256(s.startPips - s.steadyPips) * elapsed / s.decaySecs;
        // casting to 'uint24' is safe because drop <= startPips - steadyPips
        // forge-lint: disable-next-line(unsafe-typecast)
        return uint24(s.startPips - drop);
    }

    /// @dev Bankr's slice of fee F charged at f pips (D1): max(⌈F·feeBps/1e4⌉, ⌈F·minPips/f⌉), each term rounded up on
    ///      its own. The second is `minPips` of the basis F was sized on. Both numbers are the pool's own, frozen at
    ///      launch (suite 3: 1,000 and 250); the ledger holds them to what the pool's lowest fee can carry.
    function bankrSlice(uint256 fee, uint24 feePips, uint256 feeBps, uint256 minPips)
        internal
        pure
        returns (uint256 b)
    {
        if (fee == 0) return 0;
        b = FullMath.mulDivRoundingUp(fee, feeBps, 10_000);
        uint256 floor_ = FullMath.mulDivRoundingUp(fee, minPips, feePips);
        if (floor_ > b) b = floor_;
    }

    // PoolTerms slot 0 as the ledger stores it: hook 160 | flags 8 | referrerBps 16 | bankrFeeBps 16 | bankrMinPips 24
    // | holdersShareBps 16 | legId 16. BankrFeeLedger.layout.t.sol holds the shifts to the struct.
    uint8 internal constant T_QUOTE_IS_0 = 1;
    uint8 internal constant T_WAIVED = 2;
    uint8 internal constant T_DECAY_SPLIT = 4;
    uint8 internal constant T_TREASURY_CUT = 8;
    uint8 internal constant T_HOLDER_INTAKE = 16;
    uint256 internal constant T_FLAGS_SHIFT = 160;
    uint256 internal constant T_REFERRER_SHIFT = 168;
    uint256 internal constant T_BANKR_FEE_SHIFT = 184;
    uint256 internal constant T_BANKR_MIN_SHIFT = 200;
    uint256 internal constant T_HOLDERS_SHARE_SHIFT = 224;
    uint256 internal constant T_LEG_SHIFT = 240;

    /// @dev Spec §3, fee F at rate f, steady rate s, terms word `w` (PoolTerms slot 0): B = bankrSlice, the holders
    ///      ⌊B·holdersShareBps/1e4⌋, Bankr the rest of B (0 when waived, FD-25), a named referrer ⌊F·referrerBps/1e4⌋,
    ///      the remainder M ⌊M·s/f⌋ steady / the rest decay (decay split, f > s). Rounding favours Bankr; the sum is F.
    function swapSplit(uint256 fee, uint24 f, uint24 s, uint256 w, bool named)
        internal
        pure
        returns (SwapSplit memory x)
    {
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 b = bankrSlice(fee, f, uint16(w >> T_BANKR_FEE_SHIFT), uint24(w >> T_BANKR_MIN_SHIFT));
        // At 5,000 this is suite 3's ⌊B/2⌋. In a fee that splits the product is at most 10,000 times the fee, and a
        // fee is a v4 amount (under 2^127): it cannot overflow there.
        // forge-lint: disable-next-line(unsafe-typecast)
        x.holders = b * uint16(w >> T_HOLDERS_SHARE_SHIFT) / 10_000;
        if (w >> T_FLAGS_SHIFT & T_WAIVED == 0) x.bankr = b - x.holders;
        // forge-lint: disable-next-line(unsafe-typecast)
        if (named) x.referral = FullMath.mulDiv(fee, uint16(w >> T_REFERRER_SHIFT), 10_000);
        uint256 m = fee - x.holders - x.bankr - x.referral;
        x.steady = w >> T_FLAGS_SHIFT & T_DECAY_SPLIT != 0 && f > s ? FullMath.mulDiv(m, s, f) : m;
        x.decay = m - x.steady;
    }

    /// @dev A pad that names the treasury marker: its WAD shares of the steady part and the decay surplus move into Bankr's leg, each
    ///      rounded up, so its claim is never under its share; the rest of each part stays for the other payees. The decay
    ///      cut takes one wei more, at most the whole part (review C finding 3): B rounding up shrinks M by under a wei of
    ///      which K gets only half, and at v2's 29/48 of the surplus that left the treasury up to ~0.1 wei short.
    function treasuryCut(SwapSplit memory x, uint256 steadyWad, uint256 decayWad) internal pure {
        uint256 a = FullMath.mulDivRoundingUp(x.steady, steadyWad, 1e18);
        uint256 b;
        if (decayWad != 0 && x.decay != 0) {
            b = FullMath.mulDivRoundingUp(x.decay, decayWad, 1e18) + 1;
            if (b > x.decay) b = x.decay;
        }
        x.steady -= a;
        x.decay -= b;
        x.bankr += a + b;
    }

    /// @dev Fee on the gross quote leg for the four swap shapes (spec §2), every one rounded up (H13 ECON-1: an exact-in
    ///      sell's too, so Bankr's legs never trail the volume ruling; the hook caps the pair at the output). Exact-out
    ///      shapes are grossed up r / (1 − r − o): the pool amount is the net the trader asked for, and `otherPips` the
    ///      swap's other fee (Bankr's for the extension's, the extension's for Bankr's), so each is sized on the whole
    ///      gross the trader pays, as on the exact-in shapes (H13 AMM-I2).
    function feeFor(uint256 quoteAmount, uint24 feePips, uint24 otherPips, bool exactOut)
        internal
        pure
        returns (uint256)
    {
        if (exactOut) return FullMath.mulDivRoundingUp(quoteAmount, feePips, K.PIPS - feePips - otherPips);
        return FullMath.mulDivRoundingUp(quoteAmount, feePips, K.PIPS);
    }

    /// @dev A swap with no other fee (a pool without an extension). The quote's side no longer changes the rounding.
    function feeFor(uint256 quoteAmount, uint24 feePips, bool exactOut, bool) internal pure returns (uint256) {
        return feeFor(quoteAmount, feePips, 0, exactOut);
    }

    /// @dev Q4-C: Bankr takes num/den of every extension fee, rounded up; the payee the rest. No holders' part (D6).
    ///      Suite 3: 2/7 (28.57 %).
    function extensionBankrCut(uint256 extFee, uint256 num, uint256 den) internal pure returns (uint256) {
        return FullMath.mulDivRoundingUp(extFee, num, den);
    }
}

src/libraries/HookState.sol

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

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {StateLibrary} from "@uniswap/v4-core/src/libraries/StateLibrary.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IBankrLaunchHook, PoolConfig, HookConfig, ExtBinding, SkipReason} from "../interfaces/IBankrLaunchHook.sol";
import {IBankrFeeLedger} from "../interfaces/IBankrFeeLedger.sol";
import {FeeMath, PoolSide} from "./FeeMath.sol";
import {BucketIds} from "./BucketIds.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";

/// @dev The hook's suite pointers, its public immutables.
interface IHookPointers {
    function poolManager() external view returns (IPoolManager);
    function factory() external view returns (address);
    function ledger() external view returns (IBankrFeeLedger);
}

interface IPausable {
    function paused() external view returns (bool);
}

/// @notice BankrLaunchHook's state read through its `extsload`, as v4's StateLibrary reads the PoolManager's. The views
///         left the hook for EIP-170 under solc's legacy pipeline (H18); BankrHookLens serves them, and on-chain readers
///         (RaffleRun, LaunchRegistry) take single fields here. Slots and packing follow the hook's storage layout.
library HookState {
    using StateLibrary for IPoolManager;

    uint256 internal constant POOLS_SLOT = 0;
    uint256 internal constant KEYS_SLOT = 1;
    uint256 internal constant CFG_SLOT = 2;
    // slots 3 and 4 are empty: suite 3 kept WETH and the quote cache there
    uint256 internal constant EXT_SLOT = 5;
    uint256 internal constant SWITCHED_OFF_SLOT = 6;

    function poolConfig(IBankrLaunchHook hook, bytes32 poolId) internal view returns (PoolConfig memory c) {
        bytes32 base = keccak256(abi.encode(poolId, POOLS_SLOT));
        uint256 w = _at(hook, base, 0);
        c.registered = uint8(w) != 0;
        c.tokenIsCurrency0 = uint8(w >> 8) != 0;
        c.initTimestamp = uint40(w >> 16);
        c.startTick = int24(uint24(w >> 56));
        c.token = address(uint160(w >> 80));
        c.hasExtension = uint8(w >> 240) != 0;
        c.decaySplit = uint8(w >> 248) != 0;
        w = _at(hook, base, 1);
        c.refTick = int24(uint24(w));
        c.refTs = uint40(w >> 24);
        c.lastCompoundTs = uint40(w >> 64);
        c.creatorLp = uint8(w >> 104) != 0;
        c.refFrac = uint16(w >> 112);
        c.buybackAt = uint40(w >> 128);
        c.openTick = int24(uint24(w >> 168));
        c.floorTick = int24(uint24(w >> 192));
        c.edgeTick = int24(uint24(w >> 216));
        c.refTauSecs = uint16(w >> 240);
        c.heldQuote = _at(hook, base, 2);
        c.heldToken = _at(hook, base, 3);
        c.buy = _side(_at(hook, base, 4));
        c.sell = _side(_at(hook, base, 5));
        w = _at(hook, base, 6);
        c.works.compoundCap = uint128(w);
        c.works.compoundInterval = uint32(w >> 128);
        c.works.compoundShareBps = uint16(w >> 160);
        c.works.compoundDeviationTicks = uint16(w >> 176);
        c.works.bandHalfWidth = uint16(w >> 192);
        c.works.bandGrid = uint16(w >> 208);
        c.works.swapCapTicks = uint16(w >> 224);
        w = _at(hook, base, 7);
        c.fill.buybackInterval = uint32(w);
        c.fill.buybackRetry = uint32(w >> 32);
        c.fill.fillTravelTicks = uint16(w >> 64);
        c.fill.fillStartGapTicks = uint16(w >> 80);
    }

    /// @dev What a buyback fill reads of a pool, in one call: PoolConfig slots 0, 1, 4 (the buy side) and 7 (the fill's
    ///      terms), then ExtBinding slot 0 (the fee ceiling). The word-taking readers below decode them.
    function fillWords(IBankrLaunchHook hook, bytes32 poolId) internal view returns (bytes32[] memory w) {
        uint256 base = uint256(keccak256(abi.encode(poolId, POOLS_SLOT)));
        w = new bytes32[](5);
        (w[0], w[1], w[2], w[3]) = (bytes32(base), bytes32(base + 1), bytes32(base + 4), bytes32(base + 7));
        w[4] = keccak256(abi.encode(poolId, EXT_SLOT));
        w = hook.extsload(w);
    }

    /// @dev The pool's block-opening reference tick (PoolConfig.refTick), one slot.
    function refTick(IBankrLaunchHook hook, bytes32 poolId) internal view returns (int24) {
        return int24(uint24(_at(hook, keccak256(abi.encode(poolId, POOLS_SLOT)), 1)));
    }

    /// @dev The tick that opened this second's trading (PoolConfig.openTick): the stored one once a swap has folded it,
    ///      else spot, which no swap has moved yet.
    function openTick(IBankrLaunchHook hook, IPoolManager pm, bytes32 poolId) internal view returns (int24 tick) {
        (, tick,,) = pm.getSlot0(PoolId.wrap(poolId));
        return openTickOf(_at(hook, keccak256(abi.encode(poolId, POOLS_SLOT)), 1), tick);
    }

    /// @dev openTick on PoolConfig slot 1 as read, beside the pool's spot tick.
    function openTickOf(uint256 w, int24 spot) internal view returns (int24) {
        return uint40(w >> 24) == uint40(block.timestamp) ? int24(uint24(w >> 168)) : spot;
    }

    /// @dev The fill floor as the pool's next swap will fold it (PoolConfig slot 1, bits 192..215; NS-18 CLOSURES-1): the
    ///      TOKEN-cheapest tick a swap started from, never beyond the liquidity's edge, a tick dearer per second or the
    ///      reference's own weight when that is more. BankrLaunchHook._foldFloor, step for step.
    function fillFloor(IBankrLaunchHook hook, IPoolManager pm, bytes32 poolId, bool t0) internal view returns (int24) {
        (, int24 spot,,) = pm.getSlot0(PoolId.wrap(poolId));
        return fillFloorOf(_at(hook, keccak256(abi.encode(poolId, POOLS_SLOT)), 1), spot, t0);
    }

    /// @dev fillFloor on PoolConfig slot 1 as read, beside the pool's spot tick.
    function fillFloorOf(uint256 w, int24 spot, bool t0) internal view returns (int24) {
        int256 f = int24(uint24(w >> 192));
        uint256 dt = block.timestamp - uint40(w >> 24);
        // forge-lint: disable-next-line(unsafe-typecast)
        if (dt == 0) return int24(f); // folded in this second already: later swaps only lower it
        (int256 e, int256 p) = (int24(uint24(w >> 216)), spot);
        if (!t0) (f, e, p) = (-f, -e, -p); // mirrored: lower is cheaper either way
        if (p < e) p = e;
        if (p > f) {
            // forge-lint: disable-next-line(unsafe-typecast)
            (int256 gap, int256 d) = (p - f, int256(dt));
            int256 rise = gap * d / (d + int256(w >> 240)); // the pool's refTauSecs
            if (rise < d) rise = d;
            if (rise < gap) p = f + rise;
        }
        // between two int24 ticks
        // forge-lint: disable-next-line(unsafe-typecast)
        return int24(t0 ? p : -p);
    }

    /// @dev The TOKEN-cheapest tick any of the pool's locked liquidity reaches (PoolConfig slot 1, bits 216..239): the
    ///      launch tick, or a compound band's edge under it. A price beyond it is one nothing can trade at.
    function liquidityEdge(IBankrLaunchHook hook, bytes32 poolId) internal view returns (int24) {
        return int24(uint24(_at(hook, keccak256(abi.encode(poolId, POOLS_SLOT)), 1) >> 216));
    }

    /// @dev The tick that opened this second's trading as stored, with the liquidity's edge: one slot. For a reader the
    ///      hook calls inside a swap, whose beforeSwap has folded the second (RaffleRun); else use openTick.
    function openAndEdge(IBankrLaunchHook hook, bytes32 poolId) internal view returns (int24 open, int24 edge) {
        uint256 w = _at(hook, keccak256(abi.encode(poolId, POOLS_SLOT)), 1);
        (open, edge) = (int24(uint24(w >> 168)), int24(uint24(w >> 216)));
    }

    /// @dev The pool's launch tick and its trading start (PoolConfig.startTick / initTimestamp), one slot.
    function launchPoint(IBankrLaunchHook hook, bytes32 poolId) internal view returns (int24 tick, uint40 start) {
        uint256 w = _at(hook, keccak256(abi.encode(poolId, POOLS_SLOT)), 0);
        (tick, start) = (int24(uint24(w >> 56)), uint40(w >> 16));
    }

    /// @dev Whether the hook is an auto-LP payee of the pool's creator or decay bucket (PoolConfig.creatorLp /
    ///      decaySplit, set at registration for good): only then does it ever hold a backlog to compound.
    function compounds(IBankrLaunchHook hook, bytes32 poolId) internal view returns (bool) {
        bytes32 base = keccak256(abi.encode(poolId, POOLS_SLOT));
        return uint8(_at(hook, base, 1) >> 104) != 0 || uint8(_at(hook, base, 0) >> 248) != 0;
    }

    /// @dev Whether the pool's own buys ever run: a buyback share (PoolConfig.buybackAt, 1 from registration) or auto-LP.
    function ownBuys(IBankrLaunchHook hook, bytes32 poolId) internal view returns (bool) {
        bytes32 base = keccak256(abi.encode(poolId, POOLS_SLOT));
        uint256 w = _at(hook, base, 1);
        return uint40(w >> 128) != 0 || uint8(w >> 104) != 0 || uint8(_at(hook, base, 0) >> 248) != 0;
    }

    /// @dev The reference as the pool's next swap will see it: the stored EMA, folded with spot (this second's opening tick
    ///      when no swap has run in it yet) exactly as the hook folds it in beforeSwap (keyed on the second, R7-12).
    function blockReference(IBankrLaunchHook hook, IPoolManager pm, bytes32 poolId) internal view returns (int24) {
        (, int24 spot,,) = pm.getSlot0(PoolId.wrap(poolId));
        return blockReferenceOf(_at(hook, keccak256(abi.encode(poolId, POOLS_SLOT)), 1), spot);
    }

    /// @dev blockReference on PoolConfig slot 1 as read, beside the pool's spot tick.
    function blockReferenceOf(uint256 w, int24 spot) internal view returns (int24) {
        int24 ref = int24(uint24(w));
        if (uint40(w >> 24) == uint40(block.timestamp)) return ref;
        int256 dt = int256(block.timestamp - uint40(w >> 24));
        int256 ema = int256(ref) * 65_536 + int256(uint256(uint16(w >> 112))); // refFrac (H13 R2-2)
        ema += (int256(spot) * 65_536 - ema) * dt / (dt + int256(w >> 240)); // the pool's refTauSecs
        // a convex combination of two int24 ticks
        // forge-lint: disable-next-line(unsafe-typecast)
        return int24(ema >> 16);
    }

    function poolKey(IBankrLaunchHook hook, bytes32 poolId) internal view returns (PoolKey memory k) {
        bytes32 base = keccak256(abi.encode(poolId, KEYS_SLOT));
        k.currency0 = Currency.wrap(address(uint160(_at(hook, base, 0))));
        uint256 w = _at(hook, base, 1);
        k.currency1 = Currency.wrap(address(uint160(w)));
        k.fee = uint24(w >> 160);
        k.tickSpacing = int24(uint24(w >> 184));
        k.hooks = IHooks(address(uint160(_at(hook, base, 2))));
    }

    function hookConfig(IBankrLaunchHook hook) internal view returns (HookConfig memory h) {
        h.locker = address(uint160(_at(hook, bytes32(CFG_SLOT), 0)));
    }

    function extensionOf(IBankrLaunchHook hook, bytes32 poolId) internal view returns (ExtBinding memory b) {
        bytes32 base = keccak256(abi.encode(poolId, EXT_SLOT));
        uint256 w = _at(hook, base, 0);
        b.ext = address(uint160(w));
        b.quoteGas = uint24(w >> 160);
        b.afterGas = uint24(w >> 184);
        b.feeCeilingPips = uint24(w >> 208);
        b.bankrNum = uint8(w >> 232);
        b.bankrDen = uint8(w >> 240);
        b.codehash = bytes32(_at(hook, base, 1));
        w = _at(hook, base, 2);
        b.maxBuyPips = uint24(w);
        b.maxSellPips = uint24(w >> 24);
        b.payee = address(uint160(w >> 48));
        b.quoteOnly = uint8(w >> 208) != 0;
        b.sunsetSecs = uint32(w >> 216);
        b.ownerSwitch = uint8(w >> 248) != 0;
    }

    function extensionSwitchedOff(IBankrLaunchHook hook, address ext) internal view returns (bool) {
        return uint8(_at(hook, keccak256(abi.encode(ext, SWITCHED_OFF_SLOT)), 0)) != 0;
    }

    /// @dev The buy schedule's rate at this second (what the hook charges any sender but the factory), whether the pool
    ///      binds an extension and whether the rate is still above its steady one (the decay): two slots.
    function buyFeeNow(IBankrLaunchHook hook, bytes32 poolId)
        internal
        view
        returns (uint24 f, bool hasExtension, bool decaying)
    {
        bytes32 base = keccak256(abi.encode(poolId, POOLS_SLOT));
        return buyFeeOf(_at(hook, base, 0), _at(hook, base, 4));
    }

    /// @dev buyFeeNow on PoolConfig slots 0 and 4 as read.
    function buyFeeOf(uint256 head, uint256 buy) internal view returns (uint24 f, bool hasExtension, bool decaying) {
        hasExtension = uint8(head >> 240) != 0;
        PoolSide memory s = _side(buy);
        f = FeeMath.sideFeeAt(s, _notAfterNow(uint40(head >> 16)), block.timestamp);
        decaying = f > s.steadyPips;
    }

    function currentFeePips(IBankrLaunchHook hook, bytes32 poolId, bool isBuy) internal view returns (uint24) {
        PoolConfig memory c = poolConfig(hook, poolId);
        return FeeMath.sideFeeAt(isBuy ? c.buy : c.sell, _notAfterNow(c.initTimestamp), block.timestamp);
    }

    /// @dev Scheduled start: before the trading start a view reads the schedule's first point (zero seconds elapsed).
    function _notAfterNow(uint256 start) private view returns (uint256) {
        return start > block.timestamp ? block.timestamp : start;
    }

    /// @dev The hook's claimable quote in creatorId (+ decayId with a decay split) plus what earlier executions left held.
    function backlogOf(IBankrLaunchHook hook, bytes32 poolId) internal view returns (uint256 backlog) {
        PoolConfig memory c = poolConfig(hook, poolId);
        IBankrFeeLedger l = IHookPointers(address(hook)).ledger();
        (uint256 a0, uint256 a1) = l.claimable(BucketIds.creatorId(poolId), address(hook));
        backlog = (c.tokenIsCurrency0 ? a1 : a0) + c.heldQuote;
        if (c.decaySplit) {
            (a0, a1) = l.claimable(BucketIds.decayId(poolId), address(hook));
            backlog += c.tokenIsCurrency0 ? a1 : a0;
        }
    }

    /// @dev [floor(ref − half width), ceil(ref + half width)] on the pool's grid around the reference tick, clamped to
    ///      the usable range: the band the hook's next compound places. (0, 0) on a pool with no auto-LP share.
    function straddleBand(IBankrLaunchHook hook, bytes32 poolId) internal view returns (int24 lower, int24 upper) {
        bytes32 base = keccak256(abi.encode(poolId, POOLS_SLOT));
        uint256 w = _at(hook, base, 6);
        if (w == 0) return (0, 0);
        int24 ref = int24(uint24(_at(hook, base, 1)));
        // both at most 8,872 spacings (registerPool), so the products fit int24
        int24 hw = int24(uint24(uint16(w >> 192))) * K.TICK_SPACING;
        int24 grid = int24(uint24(uint16(w >> 208))) * K.TICK_SPACING;
        lower = _floorTo(ref - hw, grid);
        upper = _ceilTo(ref + hw, grid);
        if (lower < K.MIN_USABLE_TICK) lower = K.MIN_USABLE_TICK;
        if (upper > K.MAX_USABLE_TICK) upper = K.MAX_USABLE_TICK;
    }

    /// @dev What the in-swap path would do right now, gate for gate as BankrLaunchHook._maybeCompound runs them: NONE = a
    ///      compound runs, else the reason it is skipped (BELOW_THRESHOLD also on a pool with no auto-LP share).
    function compoundGate(IBankrLaunchHook hook, bytes32 poolId) internal view returns (SkipReason) {
        PoolConfig memory c = poolConfig(hook, poolId);
        if ((!c.creatorLp && !c.decaySplit) || backlogOf(hook, poolId) < c.buy.compoundFloor) {
            return SkipReason.BELOW_THRESHOLD;
        }
        if (IPausable(IHookPointers(address(hook)).factory()).paused()) return SkipReason.PAUSED;
        uint40 last = c.lastCompoundTs; // 0 = never compounded: nothing to space from
        if (last != 0 && block.timestamp < uint256(last) + c.works.compoundInterval) return SkipReason.TOO_SOON;
        // one-sided (H13 AMM-1), against the reference a swap or compound() in this block would fold first
        IPoolManager pm = IHookPointers(address(hook)).poolManager();
        int24 ref = blockReference(hook, pm, poolId);
        (, int24 spot,,) = pm.getSlot0(PoolId.wrap(poolId));
        int24 d = c.tokenIsCurrency0 ? spot - ref : ref - spot;
        // the hook's _over: above the cheaper of the reference and the fill floor
        int24 fl = fillFloor(hook, pm, poolId, c.tokenIsCurrency0);
        int24 over = c.tokenIsCurrency0 ? spot - fl : fl - spot;
        if (over < d) over = d;
        if (over >= int24(uint24(c.works.swapCapTicks)) || -d > int24(uint24(c.works.compoundDeviationTicks))) {
            return SkipReason.PRICE_MOVED;
        }
        return SkipReason.NONE;
    }

    function _at(IBankrLaunchHook hook, bytes32 base, uint256 offset) private view returns (uint256) {
        return uint256(hook.extsload(bytes32(uint256(base) + offset)));
    }

    function _side(uint256 w) private pure returns (PoolSide memory s) {
        s.startPips = uint24(w);
        s.steadyPips = uint24(w >> 24);
        s.decaySecs = uint32(w >> 48);
        s.compoundFloor = uint128(w >> 80);
    }

    // The two below are BankrLaunchHook's own, verbatim.
    function _floorTo(int24 t, int24 g) private pure returns (int24) {
        int24 m = t % g;
        if (m < 0) m += g;
        return t - m;
    }

    function _ceilTo(int24 t, int24 g) private pure returns (int24) {
        int24 fl = _floorTo(t, g);
        return fl == t ? t : fl + g;
    }
}

src/libraries/LaunchConstants.sol

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

/// What the launch suite compiles in (suite 4 design 3.1): units, pool plumbing, labels and the gas budgets sized to
/// the code. Every product figure is a setting of the settings contract, frozen per coin at its launch; suite 3's
/// figures, which this file held, are the defaults a chain's config names (config/<chain>.json, `.settings`).
library LaunchConstants {
    uint24 internal constant PIPS = 1_000_000;
    // The treasury as a pad payee: a marker, never an account. A launch cuts its shares into the quote's bankrId
    // bucket, whose beneficiary is the treasury and moves with it (review B finding 4).
    address internal constant PAD_TREASURY = address(uint160(uint256(keccak256("bankr.launch.pad-payee.treasury"))));
    int24 internal constant TICK_SPACING = 200;
    int24 internal constant MAX_USABLE_TICK = 887_200;
    int24 internal constant MIN_USABLE_TICK = -887_200;
    // At or above this pool tick both sides of any compound band (a spacing or more each way) are worth at least 1 to
    // the hook's arithmetic, so LaunchPool asks the hook for a pool's band only below it (B12 at the start price).
    int24 internal constant COMPOUND_VALUED_TICK = -600_000;
    // A quote's raw supply ceiling (H13 TOKEN-3): a reward leg streaming more than ~1.16e41 wei per second per wei of
    // eligible supply overflows the 1e36-precision accumulator inside every transfer; every listed quote is under 1e29.
    uint256 internal constant MAX_QUOTE_SUPPLY = 1e36;
    // The in-swap compound's gas cap: forwarded whole when the swap has it, else what is left, and a short compound that
    // fails reverts the swap (audit r1 ADM-02). A pool's first compound uses ~476k, ~492k on id 0 (two buckets pulled).
    uint32 internal constant COMPOUND_GAS_STIPEND = 600_000;
    uint32 internal constant SIDE_EFFECT_GAS_TAIL = 20_000; // what afterSwap still needs after an in-swap side effect returns (audit L-4)
    // Decision 3: a buyback pool's fill runs last in an outer swap, at most once per interval, handed exactly the stipend
    // and only with the reserve free past it (the tail, the route's settlement, three reward legs going live), so a fill
    // no estimate carried never starves what the estimate paid for; short, it is skipped. A refused fill retries sooner.
    // D3-T6, audit F-09: a first fill across a tick after a donation, its trigger a sell that pays no fee and the pool's
    // protocol fee on, every access cold: ~388k at worst (a pool with no auto-LP share)
    uint32 internal constant BUYBACK_GAS_STIPEND = 460_000;
    uint32 internal constant BUYBACK_GAS_RESERVE = 320_000;
    uint256 internal constant BUYBACK_GAS_NEED = uint256(BUYBACK_GAS_STIPEND) * 64 / 63 + BUYBACK_GAS_RESERVE;
    // Extension slot (plan "In-swap calls revision"): the fee ceiling each way and the quote's STATICCALL budget. An
    // extension is asked from the first swap and fills only the room under the coin's fee ceiling: nothing while
    // Bankr's decaying fee is at or above it, so a binding above the ceiling could never charge (Launch SDK H3).
    uint24 internal constant EXT_CEILING_PIPS = 100_000;
    // A launch names its two gas budgets in its binding, for life: these are the floors (and a preset's budgets), the
    // _MAX the hard ceilings. Every swap of the pool carries the whole of both, so the ceilings bound every route.
    uint32 internal constant EXT_QUOTE_GAS = 50_000;
    uint32 internal constant EXT_QUOTE_GAS_MAX = 250_000;
    uint32 internal constant EXT_AFTER_GAS_MAX = 1_000_000;
    // The guarded post-swap CALL's floor (G_A, sized for an own-pool buyback), the guard frame's own snapshot / compare
    // overhead around the call (plus 1/63 of what a binding adds over the floor), and the extra per router-pinned route
    // currency. Constants: no setter can loosen the guard.
    uint32 internal constant EXT_AFTER_GAS = 150_000;
    uint32 internal constant EXT_FRAME_GAS = 40_000;
    uint32 internal constant EXT_PIN_GAS = 1_000;
    // Kept free past the tail at an extension pool's last gas check, framed or not, for the PoolManager's tail and the
    // route's settlement after the hook: the heaviest fork-measured settlement (Universal Router, 69,023) with room for a
    // cold Permit2 pull or an unwrap. An extension cannot then take what a wallet's estimate paid it for (audit r3 EXT-2).
    uint32 internal constant EXT_ROUTE_RESERVE = 80_000;
    // Ceiling on the work a quote's answer decides in afterSwap: the extension fee's two legs, cold, with the payee's
    // claims and the treasury bucket going zero to nonzero. The check keeps what a swap did not spend of it free, so a
    // fee charged only on inclusion cannot take what the estimate paid for (audit r4 EXT-1).
    uint32 internal constant EXT_SETTLE_GAS = 75_000;
    // Kept free on top while Bankr's own fee leaves the extension no room under 10 % (the first seconds of a decay), for
    // what the launch second saves (no reference fold, 4,692 cold) and the fee turning on adds outside its measured
    // legs: a second-0 estimate then lands once there is room (r5 ADM-1; test/design/AlwaysOn.t.sol under --isolate).
    uint32 internal constant EXT_ROOM_RESERVE = 6_000;
    // Kept free while the extension has room and charges nothing, for the integer rounding of the slack's 63/64 across
    // the call frames (2 measured either way): an exact-in sell estimated at 0 pips lands once it charges, and one
    // estimated charging lands at 0 pips with about this much more. Other shapes: README, "From the first swap".
    uint32 internal constant EXT_IDLE_RESERVE = 16;
    // Gas a sponsor, router or wallet adds to a swap's simulated limit for EACH Bankr pool on the route (audits r2 ADM-1,
    // r3 ADM-3): a compound, quote or post-swap call can come due before inclusion on any hop, and short of its whole
    // stipend a swap reverts. Each covers its stipends (x 64/63, tail, route and settle reserves) through six frames, and
    // the token's transfer hook with all three reward legs gone live in the same window: measured end to end on id 0, a
    // first compound pulling both buckets with the coin's three legs going live needs +828,273 cold (H13 AMM-2), and a
    // creator holder share's accrue can go from buffer-only to a first join (+55,217): 883,490, 8.0 % under 960,000.
    uint32 internal constant SWAP_GAS_HEADROOM = 960_000;
    // What the extension path spends before its last gas check and no budget or reserve counts: the hook data's
    // parse, the frame's calldata with the longest extData, and per pinned currency its copies. BankrHookLens adds
    // them (six frames, a swap that settles nothing, --isolate: 3,430 for 2,048 bytes, 1,000 a pin; test/ns18 EXT-2).
    uint32 internal constant EXT_PATH_GAS = 10_000;
    uint32 internal constant EXT_PATH_PIN_GAS = 1_200;
    // On top, per extension pool at the floor budgets (499,879; +2,440 per pin). A pool with larger budgets needs
    // BankrHookLens.extSwapGasHeadroom: the same sum with the binding's quoteGas and afterGas.
    uint32 internal constant EXT_SWAP_GAS_HEADROOM = 500_000;
    // Decision 2: what the ledger hands the holder leg's in-swap wake, exactly. Only a sender that asks runs it
    // (HookData.HOLDERS_WAKE), so no other swap's outcome depends on it. Sized ~1.2x a full batch of 8 first-time
    // distributors draining over two hops, cold (~1.64M; round 9 raised it from 1.6M: only a capped batch fitted).
    uint32 internal constant HOLDERS_WAKE_GAS = 2_000_000;
    // The tail: the compound's stipend and tail and the extension frame with its _extNeed at both budget ceilings and 16
    // pins (2,143,084), three reward legs going live (220k), the compound's reads (48k) and the fill last (480k):
    // 2,891,084, 1.7 % under it. _extNeed is kept, not spent: in order the tail has 340,207 to spare (AlwaysOnWakeTail).
    uint32 internal constant HOLDERS_WAKE_TAIL = 2_940_000;
    address internal constant DEAD = 0x000000000000000000000000000000000000dEaD; // TOKEN burns: the locker's launch dust and BankrBuyback's fills; no BNKR ever goes here
    uint160 internal constant HOOK_PERMISSION_MASK = 0x38CC;
    uint24 internal constant DYNAMIC_FEE = 0x800000;
}
Настройки компилятораПоказать
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@uniswap/v4-core/=lib/v4-periphery/lib/v4-core/",
    "v4-core/=lib/v4-periphery/lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "v4-periphery/=lib/v4-periphery/",
    "v4-hooks-public/=lib/v4-hooks-public/",
    "permit2/=lib/permit2/",
    "solady/=lib/solady/",
    "solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "@openzeppelin/=lib/openzeppelin-contracts/",
    "forge-std/=lib/forge-std/src/"
  ]
}

Исходный код и метаданные: Sourcify.

Исходный код принадлежит авторам контракта.