Skip to content
Verified contractExactMIT

BankrGuardLens

Address0x296a78f57c93f1258ccf48c56dfc35879a54bd2c
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,452,616
Creation transaction
0x1669448499…f1b3f6b6ed

28 files

src/BankrGuardLens.sol

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

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {CurrencyDelta} from "@uniswap/v4-core/src/libraries/CurrencyDelta.sol";
import {CurrencyReserves} from "@uniswap/v4-core/src/libraries/CurrencyReserves.sol";
import {NonzeroDeltaCount} from "@uniswap/v4-core/src/libraries/NonzeroDeltaCount.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {EXT_REFUSE} from "./interfaces/IBankrHookExtension.sol";
import {IBankrLaunchHook} from "./interfaces/IBankrLaunchHook.sol";
import {LaunchConstants as K} from "./libraries/LaunchConstants.sol";

/// @title BankrGuardLens — the guard frame's open-delta reads (plan I4) and the quote's probe, split out of
///        BankrLaunchHook for EIP-170. The hook creates it, STATICCALLs it around an extension's post-swap call
///        (reverting the frame if the two digests differ) and runs every quote through it. No owner, no storage.
contract BankrGuardLens {
    using CurrencyLibrary for Currency;

    IPoolManager public immutable poolManager;

    constructor(IPoolManager pm) {
        poolManager = pm;
    }

    /// @notice Digest of [delta count, synced currency, its reserves (only while one is synced), `sender`'s and the
    ///         caller's deltas on c0 / c1, `sender`'s on each pinned currency] and the PoolManager's balance of the
    ///         synced currency (a raw transfer into it credits the next settle). Named deltas catch hidden debt. Only c0
    ///         or c1 is ever asked for a balance: another synced currency is code the router picked (audit r5 EXT-1).
    function state(address sender, Currency c0, Currency c1, address[] calldata pins) external view returns (bytes32) {
        return _digest(sender, c0, c1, pins, false);
    }

    /// @notice The frame's first read: `state`, refusing (ForeignCurrencySynced) while a currency other than c0 / c1 is
    ///         synced. The call then never runs with one, and one synced by the call shows as a moved currency slot.
    function stateBefore(address sender, Currency c0, Currency c1, address[] calldata pins)
        external
        view
        returns (bytes32)
    {
        return _digest(sender, c0, c1, pins, true);
    }

    function _digest(address sender, Currency c0, Currency c1, address[] calldata pins, bool before)
        internal
        view
        returns (bytes32)
    {
        bytes32[] memory slots = new bytes32[](7 + pins.length);
        slots[0] = NonzeroDeltaCount.NONZERO_DELTA_COUNT_SLOT;
        slots[1] = CurrencyReserves.CURRENCY_SLOT;
        slots[2] = CurrencyReserves.RESERVES_OF_SLOT;
        slots[3] = CurrencyDelta._computeSlot(sender, c0);
        slots[4] = CurrencyDelta._computeSlot(sender, c1);
        slots[5] = CurrencyDelta._computeSlot(msg.sender, c0);
        slots[6] = CurrencyDelta._computeSlot(msg.sender, c1);
        for (uint256 i; i < pins.length; ++i) {
            slots[7 + i] = CurrencyDelta._computeSlot(sender, Currency.wrap(pins[i]));
        }
        bytes32[] memory v = poolManager.exttload(slots);
        Currency synced = Currency.wrap(address(uint160(uint256(v[1]))));
        uint256 bal;
        if (synced.isAddressZero()) v[2] = 0;
        else if (synced == c0 || synced == c1) bal = synced.balanceOf(address(poolManager));
        else if (before) revert IBankrLaunchHook.ForeignCurrencySynced();
        return keccak256(abi.encode(v, bal));
    }

    /// @notice The quote's probe (input: one word, the extension below bit 160 and its gas budget above, then the quote's
    ///         calldata). It always reverts with
    ///         (answer, gas spent), so nothing the quote warmed (EIP-2929) outlives it (audit r4 EXT-1); a failed or short
    ///         answer is 0, no fee (spec §11, D8: only an explicit EXT_REFUSE refuses a buy), and with less than the whole
    ///         budget to forward it reverts empty.
    fallback() external {
        assembly ("memory-safe") {
            if lt(calldatasize(), 0x20) { revert(0, 0) }
            let n := sub(calldatasize(), 0x20)
            let ptr := mload(0x40)
            calldatacopy(ptr, 0x20, n)
            let w := calldataload(0)
            let g := shr(160, w)
            if lt(gas(), add(div(mul(g, 64), 63), 1000)) { revert(0, 0) }
            let spent := gas()
            let ok := staticcall(g, and(w, 0xffffffffffffffffffffffffffffffffffffffff), ptr, n, 0x00, 0x20)
            spent := sub(spent, gas())
            let q := mload(0x00)
            if iszero(and(ok, gt(returndatasize(), 0x1f))) { q := 0 }
            mstore(0x00, q)
            mstore(0x20, spent)
            revert(0x00, 0x40)
        }
    }
}

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/CurrencyDelta.sol

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

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

/// @title a library to store callers' currency deltas in transient storage
/// @dev this library implements the equivalent of a mapping, as transient storage can only be accessed in assembly
library CurrencyDelta {
    /// @notice calculates which storage slot a delta should be stored in for a given account and currency
    function _computeSlot(address target, Currency currency) internal pure returns (bytes32 hashSlot) {
        assembly ("memory-safe") {
            mstore(0, and(target, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(32, and(currency, 0xffffffffffffffffffffffffffffffffffffffff))
            hashSlot := keccak256(0, 64)
        }
    }

    function getDelta(Currency currency, address target) internal view returns (int256 delta) {
        bytes32 hashSlot = _computeSlot(target, currency);
        assembly ("memory-safe") {
            delta := tload(hashSlot)
        }
    }

    /// @notice applies a new currency delta for a given account and currency
    /// @return previous The prior value
    /// @return next The modified result
    function applyDelta(Currency currency, address target, int128 delta)
        internal
        returns (int256 previous, int256 next)
    {
        bytes32 hashSlot = _computeSlot(target, currency);

        assembly ("memory-safe") {
            previous := tload(hashSlot)
        }
        next = previous + delta;
        assembly ("memory-safe") {
            tstore(hashSlot, next)
        }
    }
}

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

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

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

library CurrencyReserves {
    using CustomRevert for bytes4;

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

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

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

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

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

lib/v4-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/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/NonzeroDeltaCount.sol

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

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

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

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

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

lib/v4-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/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/IBankrHookExtension.sol

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

import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";

/// @dev What `quote` returns to refuse a BUY (plan Q31-B): the buy reverts. On a sell it is ignored and the extension
///      charges nothing, so holders can always sell. Any other value is a fee in pips, clamped by the hook.
uint24 constant EXT_REFUSE = type(uint24).max;

/// @dev Everything an extension learns about a swap. `sender` is the router (msg.sender of PoolManager.swap), never the
///      trader; `amountSpecified` keeps v4's sign (negative = exact in); `bankrFeePips` is Bankr's own fee on this swap.
///      `sqrtPriceX96` is the pool's price before this swap (in `afterSwap` too), so a reaction can bound itself by what
///      the triggering swap moved (audit r1 EXT-2). It need not be a price anything traded at: spot can sit beyond the
///      pool's liquidity, moved there for nothing, so a bound kept across swaps must not be this value alone (NS-18 EXT-1).
struct SwapCtx {
    address sender;
    bytes32 poolId;
    bool isBuy; // quote in, TOKEN out
    int256 amountSpecified;
    uint24 bankrFeePips;
    uint32 secsSinceLaunch; // since the trading start: a scheduled launch's start, not its launch transaction
    uint160 sqrtPriceX96;
}

/// @notice A launch's optional extension on the Bankr hook (plan "In-swap calls revision"). DYOR: bound once at launch
///         by address + codehash, with declared maxima the hook clamps to (at most 10 % each way, and never more than
///         the room Bankr's own fee leaves under 10 %) and with its two gas budgets, fixed for the pool's life.
interface IBankrHookExtension {
    /// @notice STATICCALLed in beforeSwap with the binding's `quoteGas` (50,000 unless the launch named more, at most
    ///         250,000), from the pool's first swap on: it can read anything but write nothing. `extData` is the
    ///         router's hookData after the Bankr prefix (HookData), chosen by the trader. EXT_REFUSE refuses a buy (a sell
    ///         is charged 0); a revert, out-of-gas or a return shorter than 32 bytes charges 0 and refuses nothing (spec
    ///         §11), so an allowlisted quote must answer every extData: a trader could otherwise pick one that dodges it.
    ///         While Bankr's own fee is at or above 10 % (a launch's decay) a fee it asks for is clamped to 0, a refusal
    ///         still refuses; never called on the factory's dev buy or from the binding's `sunsetSecs` on. `extData` is at
    ///         most 2,048 bytes (HookData.MAX_EXT_DATA).
    function quote(SwapCtx calldata ctx, bytes calldata extData) external view returns (uint24 extraPips);

    /// @notice CALLed after Bankr's legs are settled, with exactly the binding's `afterGas` (150,000 unless the launch
    ///         named more, at most 1,000,000) and no value, from the pool's first swap on, in a guard frame that undoes it
    ///         all if the PoolManager's open deltas moved; the trade lands whatever it does. Its own pool it trades only by
    ///         calling PoolManager.swap itself (audit r2 EXT-2). `delta` is the pool's swap delta before the hook's fees;
    ///         `extFee` is what this swap minted to the payee (0 while there is no room). Never on a `quoteOnly` binding; a sell's
    ///         trader may skip it (HookData flag 1), a buyer cannot (audit r4 EXT-2, r5 EXT-1 / EXT-2). README "Post-swap
    ///         call".
    function afterSwap(SwapCtx calldata ctx, BalanceDelta delta, uint256 extFee, bytes calldata extData) external;
}

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/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/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;
}
Compiler settingsShow
{
  "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/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.