Skip to content
Verified contractExactMIT

LedgerCto

Address0x41b2c9dea6fc0e588620be61fb513ef300b45bef
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,597
Creation transaction
0x53cdc211e3…07010a2b7e

32 files

src/libraries/LedgerCto.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {IBankrFeeLedger} from "../interfaces/IBankrFeeLedger.sol";
import {BucketIds} from "./BucketIds.sol";
import {LedgerOps, Bucket} from "./LedgerOps.sol";

/// @title LedgerCto
/// @notice The ledger's community takeover (spec §9), linked and delegatecalled so its bytes are not the ledger's
///         (design/fee-recipients). It runs on the ledger's storage as the ledger: msg.sender is the ledger's caller.
library LedgerCto {
    uint8 internal constant QUEUE = 0;
    uint8 internal constant CANCEL = 1;
    uint8 internal constant EXECUTE = 2;

    /// @dev What the ledger hands over by value: the step, its arguments, the appointment and its two immutables.
    struct Call {
        uint8 op;
        bytes32 creatorId;
        address to; // QUEUE: the new recipient
        address authority;
        uint32 epoch;
        address poolManager;
        address factory;
    }

    function run(
        mapping(bytes32 => Bucket) storage buckets,
        mapping(bytes32 => mapping(address => IBankrFeeLedger.Beneficiary)) storage bens,
        mapping(address => mapping(Currency => uint256)) storage balances,
        mapping(bytes32 => IBankrFeeLedger.PendingCto) storage pending,
        Call memory c
    ) external {
        if (c.op == CANCEL) return _cancel(pending, c);
        if (msg.sender != c.authority) revert IBankrFeeLedger.NotCtoAuthority();
        Bucket storage b = buckets[c.creatorId];
        // Keyed by the launch's creatorId only: its decayId creator parts move with it.
        bytes32 d = BucketIds.decayId(b.poolId);
        if (c.op == QUEUE) {
            if (!b.cto) revert IBankrFeeLedger.NotCtoEligible();
            _checkRecipient(buckets, bens, c, d, c.to);
            // The coin's own notice and grace, frozen in its bucket at launch: 32 bits each, so neither sum overflows.
            uint64 executeAfter = uint64(block.timestamp) + b.ctoNotice;
            pending[c.creatorId] = IBankrFeeLedger.PendingCto(c.to, executeAfter, c.epoch);
            emit IBankrFeeLedger.CtoQueued(c.creatorId, c.to, executeAfter, executeAfter + b.ctoGrace);
            return;
        }
        address to = _due(pending, c, b.ctoGrace);
        // the recipient may have become a beneficiary during the notice
        _checkRecipient(buckets, bens, c, d, to);
        delete pending[c.creatorId];
        // Settle only: no call leaves the ledger, so no recipient's code or token can stop or price a takeover, and
        // its cost is the entry count alone (LedgerCold caps both buckets). Each old holder withdraws as ever.
        _takeOver(b, bens[c.creatorId], balances, c.creatorId, to);
        _takeOver(buckets[d], bens[d], balances, d, to);
    }

    /// @dev The authority or the owner, never the creator; the owner's lever also clears what a revoked authority queued.
    function _cancel(mapping(bytes32 => IBankrFeeLedger.PendingCto) storage pending, Call memory c) private {
        if (msg.sender != c.authority && msg.sender != Ownable(c.factory).owner()) {
            revert IBankrFeeLedger.NotCtoAuthority();
        }
        if (pending[c.creatorId].executeAfter == 0) revert IBankrFeeLedger.NoPendingCto();
        delete pending[c.creatorId];
        emit IBankrFeeLedger.CtoCancelled(c.creatorId, msg.sender);
    }

    function _due(mapping(bytes32 => IBankrFeeLedger.PendingCto) storage pending, Call memory c, uint256 grace)
        private
        view
        returns (address)
    {
        IBankrFeeLedger.PendingCto memory p = pending[c.creatorId];
        if (p.executeAfter == 0) revert IBankrFeeLedger.NoPendingCto();
        // queued under an earlier appointment: dead, whatever the clock says
        if (p.epoch != c.epoch) revert IBankrFeeLedger.CtoAuthorityRotated();
        if (block.timestamp < p.executeAfter) revert IBankrFeeLedger.CtoTimelockActive();
        // a notice left unexecuted goes stale: the authority queues again, with a fresh notice
        if (block.timestamp > p.executeAfter + grace) revert IBankrFeeLedger.CtoExpired();
        return p.newRecipient;
    }

    /// @dev Only where a share moves: a recipient holding another kind of share there (a pad payee's, the holders')
    ///      would merge into, or be overwritten by, the creators'.
    function _checkRecipient(
        mapping(bytes32 => Bucket) storage buckets,
        mapping(bytes32 => mapping(address => IBankrFeeLedger.Beneficiary)) storage bens,
        Call memory c,
        bytes32 d,
        address to
    ) private view {
        Bucket storage b = buckets[c.creatorId];
        Bucket storage decay = buckets[d];
        if (
            to == address(0) || LedgerOps.isSentinel(to) || _holdsBeside(b, bens[c.creatorId][to])
                || _holdsBeside(decay, bens[d][to]) || LedgerOps.strands(b, c.creatorId, to, c.poolManager, c.factory)
                || (decay.creators != 0 && LedgerOps.strands(decay, d, to, c.poolManager, c.factory))
        ) revert IBankrFeeLedger.InvalidCtoRecipient();
    }

    /// @dev Holding a creator part alone is no bar (a fee recipient that moved its entry to the queued recipient would
    ///      otherwise block the takeover of every other part): that entry is taken over with the rest.
    function _holdsBeside(Bucket storage b, IBankrFeeLedger.Beneficiary storage e) private view returns (bool) {
        return b.creators != 0 && e.shares != e.creatorShare;
    }

    /// @dev Every entry's creator part moves to the one new recipient; whatever else a merged entry held (a pad payee's
    ///      share) stays. Each old holder is settled into its own balance first. No call leaves the ledger here, and
    ///      `_checkRecipient` proved the recipient holds nothing but a creator part, which the loop removes.
    function _takeOver(
        Bucket storage b,
        mapping(address => IBankrFeeLedger.Beneficiary) storage bens,
        mapping(address => mapping(Currency => uint256)) storage balances,
        bytes32 bucketId,
        address to
    ) private {
        if (b.creators == 0) return; // no creator part: nothing moves, nothing is logged (NS-18 LEDGER-4, accepted)
        uint256 moved;
        for (uint256 i = b.beneficiaries.length; i != 0; --i) {
            address from = b.beneficiaries[i - 1];
            uint256 part = bens[from].creatorShare;
            if (part == 0) continue;
            _strip(b, bens[from], balances, bucketId, from, i - 1);
            moved += part;
            emit IBankrFeeLedger.CtoExecuted(bucketId, from, to, part);
        }
        // creator parts sum to at most WAD
        // forge-lint: disable-next-line(unsafe-typecast)
        bens[to] = IBankrFeeLedger.Beneficiary(uint128(moved), uint64(moved), b.cumulated0, b.cumulated1);
        b.beneficiaries.push(to);
        b.creators = 1;
    }

    function _strip(
        Bucket storage b,
        IBankrFeeLedger.Beneficiary storage old,
        mapping(address => mapping(Currency => uint256)) storage balances,
        bytes32 bucketId,
        address from,
        uint256 at
    ) private {
        LedgerOps.settle(b, old, balances, bucketId, from);
        uint128 part = old.creatorShare;
        if (old.shares == part) {
            delete old.shares;
            delete old.creatorShare;
            delete old.lastCumulatedFees0;
            delete old.lastCumulatedFees1;
            b.beneficiaries[at] = b.beneficiaries[b.beneficiaries.length - 1];
            b.beneficiaries.pop();
        } else {
            (old.shares, old.creatorShare) = (old.shares - part, 0);
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/v4-periphery/lib/v4-core/src/libraries/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/Lock.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type Currency is address;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type PoolId is bytes32;

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

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

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

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

using PoolIdLibrary for PoolKey global;

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

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

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

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

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

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

src/interfaces/IBankrFeeLedger.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/interfaces/IBankrLaunchFactory.sol

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

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


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


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

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

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

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

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

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

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

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

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

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

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

src/interfaces/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/IHolderRewards.sol

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

/// @notice What a BankrLaunchToken calls on its distributor before every balance change, with the PRE-transfer balances,
///         so the distributor never calls back into the token (or anything else) from inside a transfer (spec §6, D16).
interface IHolderHook {
    function onTransfer(address from, address to, uint256 value, uint256 fromBalance, uint256 toBalance) external;
}

/// @notice The chain's BNKR as its holder leg (BnkrHolderLeg, H17) names it; 0 until BNKR is set there.
interface IBnkrSource {
    function bnkr() external view returns (address);
    function minPile(address quote) external view returns (uint96);
    function pending(bytes32 poolId) external view returns (uint256);
    function poke(bytes32 poolId) external;
}

/// @notice Hold-to-earn distributor of one launch (spec §6): holders earn by holding, pro rata to their wallet balance, on
///         three legs that share one eligible supply: the launch token (vest-to-holders, donations), the pool's quote (the
///         creator's holder share, accrued in every swap; Bankr's 5 % where it is paid in quote) and BNKR. No owner, no
///         staking, no keeper (decision 1).
interface IHolderRewardsDistributor is IHolderHook {
    /// @dev `amount`: what the notify added to the leg's stream (its floored rate's remainder is carried, not counted).
    event RewardsNotified(uint8 indexed leg, uint256 amount, uint256 rewardRate, uint256 periodFinish);
    event RewardClaimed(address indexed account, address indexed operator, uint256[3] amounts);
    event RewardExcluded(address indexed account, uint256[3] forfeited);
    event FeesPulled(uint256 amount);
    event VestPushed(uint256 amount);
    event BnkrLegEnabled(address indexed bnkr);

    error NotToken();
    error NotSelf();
    error ExcludedAccount();
    error NothingToClaim();
    error PayoutRefused(); // every owed leg's asset refused its payout (H13 TOKEN-4); the rewards stay claimable
    /// @dev claimFor or claimPastBnkr for an account whose ledger claim policy (Q9) refuses the caller.
    error ClaimerNotAllowed();
    error BadLeg();
    error ZeroAddress();
    /// @dev accrue from anyone but the fee ledger.
    error NotLedger();
    /// @dev onLegPush from anyone but the chain's holder leg.
    error NotHolderLeg();
    /// @dev openVest from anyone but the factory.
    error NotFactory();
    /// @dev openVest on a launch without a vest-to-holders slice, or a second time.
    error VestOpen();
    /// @dev A capped call could not be handed its whole cap (a lazy pull, reconcile's BNKR leg, a full claim's payout),
    ///      or a claimForMany element started under MIN_GAS_PER_CLAIM or ran out of gas.
    error InsufficientGas();
    /// @dev A hard bound of the design's section 2, by number. At construction: 7, a stream of 0 seconds or an
    ///      activation divisor under 10,000 (TOKEN) or 10,000,000 (BNKR); 4, a restart share outside 1 to 10,000 bps;
    ///      21, a QUOTE floor past 112 bits. In openVest: 5, a vest stream ending past the 40-bit clocks.
    error HardBound(uint8 bound);

    /// @notice The fee ledger only, inside every swap that credits this coin's creator holder share (decision 1):
    ///         storage only. `bufferOnly` for a nested swap, which only buffers.
    function accrue(uint256 h, bool bufferOnly) external;
    /// @notice The holder leg only, after each push (decisions 1-2 seam): a forward's `quoteIn` joins the QUOTE buffer; 0
    ///         streams the BNKR it pushed. Storage and capped reads only; a no-op inside this distributor's own call.
    function onLegPush(uint256 quoteIn) external;
    /// @notice The factory only, once, at a launch with a vest-to-holders slice: the TOKEN leg's stream from the cliff.
    function openVest(uint256 total, uint64 cliff, uint64 duration) external;
    /// @notice Permissionless backstop: pulls the creator's holder share from the ledger, then streams each leg's surplus
    ///         (QUOTE with its buffer; TOKEN once the vest stream has ended; BNKR). Never reverts for a missing feature
    ///         (I12). Needs 1,030,873 gas left at its BNKR leg or reverts InsufficientGas.
    function reconcile() external returns (uint256 pulled, uint256[3] memory notified);
    /// @notice QUOTE taken in and not streaming yet: under the activation floor, under one wei a second while a period
    ///         is open, or the remainder a fold's floored rate left.
    function pendingQuote() external view returns (uint256);
    /// @notice Every leg: pulls the creator's holder share from the ledger first when the QUOTE balance cannot pay it,
    ///         and releases the vest from the escrow when the TOKEN balance cannot.
    /// @notice Pays every leg first; then, with the gas the payouts left (POKE_GAS and its gate), pokes the holder leg for
    ///         this coin's pile when it is due (decision 2's claim retry). Reverts NothingToClaim only when it neither
    ///         paid nor poked.
    function claim() external returns (uint256[3] memory amounts);
    /// @notice One leg only, its asset handed all the gas: the escape hatch for an asset whose honest transfer needs
    ///         more than the 1,000,000 a full claim hands each payout. An asset that refuses reverts PayoutRefused
    ///         here; claim() pays the other legs and keeps it.
    function claimLeg(uint8 leg) external returns (uint256 amount);
    /// @notice Pays `account`, never the caller, under the ledger's one claim policy (Q9, mayClaimFor): anyone while
    ///         the account is open (the default), else only the account or a claim operator it named there.
    function claimFor(address account) external returns (uint256[3] memory amounts);
    /// @notice claimFor for each account, skipping any the policy refuses the caller.
    function claimForMany(address[] calldata accounts) external returns (uint256 paid);
    function claimForAuthorized(address account) external returns (uint256[3] memory amounts);
    /// @notice One-way: the caller stops earning and forfeits what it accrued to everyone else (a contract that can
    ///         never claim, such as another launch's distributor holding this token as its quote).
    function excludeSelf() external;

    function token() external view returns (address);
    function quote() external view returns (address);
    function bnkr() external view returns (address);
    function poolId() external view returns (bytes32);
    function escrow() external view returns (address);
    function hasHolderVest() external view returns (bool);
    function eligibleSupply() external view returns (uint256);
    function rewardExcluded(address account) external view returns (bool);
    function assetOf(uint8 leg) external view returns (address);
    function earned(uint8 leg, address account) external view returns (uint256);
    function surplus(uint8 leg) external view returns (uint256);
    /// @notice What a leg's first notify must reach before it goes live (review C finding 7).
    function activationFloor(uint8 leg) external view returns (uint256);
    function rewardsOwed(uint8 leg) external view returns (uint256);
    function remainingStream(uint8 leg) external view returns (uint256);
    function streamOf(uint8 leg)
        external
        view
        returns (
            bool streams,
            uint256 periodFinish,
            uint256 rewardRate,
            uint256 rewardPerTokenStored,
            uint256 rewardsAllocated,
            uint256 rewardsClaimed
        );
    function rewardsOf(uint8 leg, address account) external view returns (uint256 settled, uint256 paidCheckpoint);
}

/// @notice Deploys one HolderRewardsDistributor for a token the factory is about to create at `token`, before the token
///         (its constructor binds the distributor as its reward hook), and records it by pool and by token.
interface IHolderRewardsDeployer {
    /// @dev Factory only; CREATE2 with salt bytes32(uint256(uint160(token))). `escrow` is the launch's predicted vesting
    ///      escrow, excluded from rewards whether or not anything vests; `holderVest` says it holds a vest-to-holders
    ///      schedule for the distributor to push. `holderLeg` and `terms` are the coin's for life (see launchingTerms).
    function deploy(
        address token,
        bytes32 poolId,
        address quote,
        address escrow,
        bool holderVest,
        address holderLeg,
        uint256 terms
    ) external returns (address distributor);
    /// @notice The terms word of the distributor being constructed right now (transient, so `predict` ignores it):
    ///         streamSecs | restartBps << 32 | tokenDivisor << 48 | bnkrDivisor << 80 | quoteActivation << 112.
    function launchingTerms() external view returns (uint256);
    /// @notice Its holder leg, handed over the same way.
    function launchingLeg() external view returns (address);
    function predict(address token, bytes32 poolId, address quote, address escrow, bool holderVest)
        external
        view
        returns (address);
    function distributorOf(bytes32 poolId) external view returns (address);
    function distributorOfToken(address token) external view returns (address);
}

src/libraries/BucketIds.sol

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

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

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

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

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

src/libraries/FeeMath.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/libraries/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;
}

src/libraries/LedgerOps.sol

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

import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {TransientStateLibrary} from "@uniswap/v4-core/src/libraries/TransientStateLibrary.sol";
import {IBankrFeeLedger} from "../interfaces/IBankrFeeLedger.sol";
import {IBankrLaunchFactory} from "../interfaces/IBankrLaunchFactory.sol";
import {IHolderRewardsDeployer} from "../interfaces/IHolderRewards.sol";
import {BucketIds} from "./BucketIds.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";

/// @dev The ledger's bucket record, at file level so the ledger and its linked takeover library share one layout.
struct Bucket {
    address hook; // pool buckets: key.hooks, the sole crediter; currency buckets: 0 (any allowlisted hook)
    bool exists;
    bool locked; // beneficiaries can never move (a launch's holders bucket)
    bool cto; // a launch's creatorId whose pad had takeover on: its creator entries can be taken over (spec §9)
    uint8 creators; // entries holding a creator part (a fee recipient's own)
    // The takeover's public notice and how long past it an execute stays open, frozen at launch. 32 bits each, so the
    // uint64 clock sums in LedgerCto cannot overflow. The slot is full.
    uint32 ctoNotice;
    uint32 ctoGrace;
    bytes32 poolId;
    Currency currency0;
    Currency currency1;
    uint256 cumulated0;
    uint256 cumulated1;
    address[] beneficiaries;
}

/// @title LedgerOps
/// @notice The ledger's accounting and payout steps as internal functions over its storage, so BankrFeeLedger and the
///         linked LedgerCto library run one implementation each (design/fee-recipients: the takeover left the ledger).
library LedgerOps {
    uint256 internal constant WAD = 1e18;
    address internal constant FEES_TO_HOLDERS = 0x968b0c1e896FB1DdB2042957Fc0614c67AB7FFc2;
    uint8 internal constant SIDE0 = 1;
    uint8 internal constant SIDE1 = 2;
    uint8 internal constant BOTH = 3;
    uint256 internal constant PAYOUT_GAS = 1_000_000;
    /// @dev The call's own cost on top of PAYOUT_GAS (cold PoolManager, memory), so the check proves the callee gets it
    ///      all.
    uint256 internal constant PAYOUT_TAIL = 10_000;
    /// @dev Gas a factory isSuite read is handed (it calls the account's poolId()): the account's own code burns no
    ///      more, of a keeper's push or of the takeover that names it (NS-18 I8). Out of it reads as not suite.
    uint256 internal constant SUITE_CHECK_GAS = 100_000;
    // BankrFeeLedger's storage slots, for the linked libraries that run on it without a pointer handed in (LedgerCold,
    // and `isLeg` below). test/unit/BankrFeeLedger.layout.t.sol holds them to the compiler's layout.
    uint256 internal constant IS_HOOK_SLOT = 0;
    uint256 internal constant BUCKETS_SLOT = 1;
    uint256 internal constant BENEFICIARIES_SLOT = 2;
    uint256 internal constant TERMS_SLOT = 6;
    uint256 internal constant QUOTE_OF_SLOT = 7;
    uint256 internal constant LEG_ID_OF_SLOT = 14;

    /// @dev The accounting half of every release and settle: advances the masked sides' checkpoints and returns what they
    ///      owed. A side never credited is skipped: its checkpoint is 0 too, since a checkpoint never exceeds the total.
    function accrue(Bucket storage b, IBankrFeeLedger.Beneficiary storage ben, uint256 shares, uint8 sides)
        internal
        returns (uint256 owed0, uint256 owed1)
    {
        if (sides & SIDE0 != 0) {
            uint256 cum = b.cumulated0;
            if (cum != 0) {
                owed0 = FullMath.mulDiv(cum - ben.lastCumulatedFees0, shares, WAD);
                ben.lastCumulatedFees0 = cum;
            }
        }
        if (sides & SIDE1 != 0) {
            uint256 cum = b.cumulated1;
            if (cum != 0) {
                owed1 = FullMath.mulDiv(cum - ben.lastCumulatedFees1, shares, WAD);
                ben.lastCumulatedFees1 = cum;
            }
        }
    }

    /// @dev Accounting only, with the same floor and checkpoint as a release. A nonzero share implies the bucket
    ///      exists.
    function settle(
        Bucket storage b,
        IBankrFeeLedger.Beneficiary storage ben,
        mapping(address => mapping(Currency => uint256)) storage balances,
        bytes32 bucketId,
        address who
    ) internal returns (uint256 owed0, uint256 owed1) {
        uint256 shares = ben.shares;
        if (shares == 0) return (0, 0);
        (owed0, owed1) = accrue(b, ben, shares, BOTH);
        if (owed0 != 0) balances[who][b.currency0] += owed0;
        if (owed1 != 0) balances[who][b.currency1] += owed1;
        if (owed0 | owed1 != 0) emit IBankrFeeLedger.Settled(bucketId, who, owed0, owed1);
    }

    /// @dev Balance first, then the payout of `amount` of it. A refused payout rolled back its own frame only, never
    ///      the debit here, so the restore is what keeps a withheld amount: a balance again, never ERC-6909 claims
    ///      (an issuer's freeze holds).
    function pay(
        mapping(address => mapping(Currency => uint256)) storage balances,
        mapping(Currency => uint256) storage outstanding,
        address pm,
        address who,
        Currency c,
        uint256 amount
    ) internal {
        if (amount == 0) return;
        balances[who][c] -= amount;
        outstanding[c] -= amount;
        // Handed exactly PAYOUT_GAS: a caller that cannot hand all of it reverts, so a short gas limit never passes
        // for a refusal.
        if (gasleft() < PAYOUT_GAS * 64 / 63 + PAYOUT_TAIL) revert IBankrFeeLedger.InsufficientGas();
        if (unlockPay(pm, c, amount, who, PAYOUT_GAS)) {
            emit IBankrFeeLedger.Withdraw(who, c, amount);
        } else {
            // Called inside someone's own unlock, the payout's unlock was refused, not the token: fail loudly.
            if (TransientStateLibrary.isUnlocked(IPoolManager(pm))) revert IPoolManager.AlreadyUnlocked();
            balances[who][c] += amount;
            outstanding[c] += amount;
            emit IBankrFeeLedger.Withheld(who, c, amount);
        }
    }

    /// @dev One burn + take under a fresh unlock with `g` gas, copying none of its return data (a bomb costs nothing).
    function unlockPay(address pm, Currency c, uint256 amount, address to, uint256 g) internal returns (bool ok) {
        bytes memory data =
            abi.encodeCall(IPoolManager.unlock, (abi.encode(c, Currency.wrap(address(0)), amount, uint256(0), to)));
        assembly ("memory-safe") {
            ok := call(g, pm, 0, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Where a share could never be collected (H13 ECON-I2, GOV-L1, R2-5): the bucket's own currencies (the coin's
    ///      TOKEN, its quote), the PoolManager, this ledger and any protocol contract (the factory's isSuite: every suite
    ///      contract and generation, every launch's token, escrow and distributor, preset instances, the markers), read
    ///      from the factory leniently (a factory without the view refuses nothing more). The one protocol contract that
    ///      collects a bucket is the pool's own holder distributor, which pulls its creatorId. Any leg strands (isLeg).
    function strands(Bucket storage b, bytes32 bucketId, address to, address pm, address factory)
        internal
        view
        returns (bool)
    {
        if (
            to == address(this) || to == pm || to == Currency.unwrap(b.currency0) || to == Currency.unwrap(b.currency1)
                || isLeg(to)
        ) return true;
        (bool ok, bytes memory r) =
            factory.staticcall{gas: SUITE_CHECK_GAS}(abi.encodeWithSelector(IBankrLaunchFactory.isSuite.selector, to));
        if (!ok || r.length != 32 || !abi.decode(r, (bool))) return false;
        return bucketId != BucketIds.creatorId(b.poolId)
            || IHolderRewardsDeployer(IBankrLaunchFactory(factory).holderRewardsDeployer()).distributorOf(b.poolId) != to;
    }

    /// @dev Whether the factory ever registered `a` as a holder leg (BankrFeeLedger.legIdOf, written once and never
    ///      cleared). Runs on the ledger's storage, in the ledger or in a library it delegatecalls.
    function isLeg(address a) internal view returns (bool leg) {
        uint256 slot = LEG_ID_OF_SLOT;
        assembly ("memory-safe") {
            mstore(0x00, and(a, 0xffffffffffffffffffffffffffffffffffffffff))
            mstore(0x20, slot)
            leg := iszero(iszero(and(sload(keccak256(0x00, 0x40)), 0xffff)))
        }
    }

    /// @dev pools.fun's FEES_TO_HOLDERS sentinel range (16 addresses) and the treasury marker (a launch cuts it into
    ///      bankrId; nothing can claim as it, review D 6) are routing markers, never payees: not as a bucket's
    ///      beneficiary, a beneficiary's move or a takeover's recipient.
    function isSentinel(address a) internal pure returns (bool) {
        return a == K.PAD_TREASURY
            || (uint160(a) >= uint160(FEES_TO_HOLDERS) && uint160(a) <= uint160(FEES_TO_HOLDERS) + 15);
    }
}
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.