Skip to content
Verified contractExactMIT

BankrLaunchSettings

Address0x7fd2bd17387e3da342db0952ba0b2f250114fda2
Balance

0 ETH

 

Transactions

3

 

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,624
Creation transaction
0x43d30b5702…2edb656fcc

45 files

src/BankrLaunchSettings.sol

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

import {IBankrLaunchSettings} from "./interfaces/IBankrLaunchSettings.sol";
import {IBankrLaunchpadRegistry} from "./interfaces/IBankrLaunchpadRegistry.sol";
import {LaunchParams, LaunchExtension, PriceAttestation} from "./interfaces/IBankrLaunchFactory.sol";
import {
    CoinTerms,
    GuardTerms,
    Limit,
    PadConfig,
    PadQuoteTerms,
    PresetLimits,
    PresetRecord,
    ProtocolTerms,
    QuoteTerms,
    Range
} from "./interfaces/SuiteTypes.sol";
import {Knobs} from "./libraries/Knobs.sol";
import {LaunchConstants as K} from "./libraries/LaunchConstants.sol";
import {LaunchPricing} from "./libraries/LaunchPricing.sol";
import {LaunchResolver} from "./libraries/LaunchResolver.sol";
import {SettingsCold} from "./libraries/SettingsCold.sol";
import {SettingsRead, SettingsStore, TEMPLATE} from "./libraries/SettingsStore.sol";

/// @title BankrLaunchSettings
/// @notice Every setting of the launch suite (IBankrLaunchSettings). Storage and views live here; every setter's body
///         is SettingsCold's, which checks the caller, and the launch check is LaunchResolver's and LaunchPricing's.
///         No Ownable: the owner is the factory's, read live, and a pad's operator is the pad registry's. It makes
///         no call that changes another contract's state.
contract BankrLaunchSettings is IBankrLaunchSettings {
    using SettingsRead for SettingsStore;

    address public immutable factory;
    address public immutable registry;
    SettingsStore internal s; // slot 0: SettingsCold reads it there

    /// @dev Emits one event per value, so an indexer rebuilds every setting from this contract's logs alone.
    constructor(address factory_, address registry_, SettingsInit memory i) {
        (factory, registry) = (factory_, registry_);
        SettingsCold.init(i);
    }

    // ── setters: SettingsCold's, on this storage ─────────────────────────────

    function setProtocolTerms(ProtocolTerms calldata) external {
        _cold(SettingsCold.setProtocolTerms.selector);
    }

    function setGuardTerms(GuardTerms calldata) external {
        _cold(SettingsCold.setGuardTerms.selector);
    }

    function setBnkrPairWaiver(uint64, bool) external {
        _cold(SettingsCold.setBnkrPairWaiver.selector);
    }

    function setLimits(uint8[] calldata, Limit[] calldata) external {
        _cold(SettingsCold.setLimits.selector);
    }

    function setTemplate(uint8[] calldata, Range[] calldata, uint256, address) external {
        _cold(SettingsCold.setTemplate.selector);
    }

    function setTemplatePresetLimits(uint8, PresetLimits calldata) external {
        _cold(SettingsCold.setTemplatePresetLimits.selector);
    }

    function setAllowedFlags(uint256) external {
        _cold(SettingsCold.setAllowedFlags.selector);
    }

    function setQuote(address, QuoteTerms calldata) external {
        _cold(SettingsCold.setQuote.selector);
    }

    function removeQuote(address) external {
        _cold(SettingsCold.removeQuote.selector);
    }

    function setPriceSigner(address) external {
        _cold(SettingsCold.setPriceSigner.selector);
    }

    function setSequencerUptimeFeed(address, uint32) external {
        _cold(SettingsCold.setSequencerUptimeFeed.selector);
    }

    function setPreset(uint8, PresetRecord calldata) external {
        _cold(SettingsCold.setPreset.selector);
    }

    function setExtensionAllowed(bytes32, bool) external {
        _cold(SettingsCold.setExtensionAllowed.selector);
    }

    function configure(uint64, PadConfig calldata) external {
        _cold(SettingsCold.configure.selector);
    }

    function setKnobs(uint64, uint8[] calldata, Range[] calldata) external {
        _cold(SettingsCold.setKnobs.selector);
    }

    function setFlags(uint64, uint256) external {
        _cold(SettingsCold.setFlags.selector);
    }

    function setPayees(uint64, IBankrLaunchpadRegistry.PadTerms calldata) external {
        _cold(SettingsCold.setPayees.selector);
    }

    function setCapController(uint64, address) external {
        _cold(SettingsCold.setCapController.selector);
    }

    function setQuoteTerms(uint64, address, PadQuoteTerms calldata) external {
        _cold(SettingsCold.setQuoteTerms.selector);
    }

    function setCurveAllowed(uint64, uint256, bool) external {
        _cold(SettingsCold.setCurveAllowed.selector);
    }

    function setPresetLimits(uint64, uint8, PresetLimits calldata) external {
        _cold(SettingsCold.setPresetLimits.selector);
    }

    function initPad(uint64, IBankrLaunchpadRegistry.PadTerms calldata) external {
        _cold(SettingsCold.initPad.selector);
    }

    /// @dev Ends this call inside SettingsCold, on this storage: the same calldata under the library's selector (a
    ///      library names a struct argument by its type, so the two differ), its return or revert passed on.
    function _cold(bytes4 sel) private {
        address lib = address(SettingsCold);
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            calldatacopy(add(m, 4), 4, sub(calldatasize(), 4))
            let ok := delegatecall(gas(), lib, m, calldatasize(), 0x00, 0x00)
            returndatacopy(m, 0x00, returndatasize())
            if iszero(ok) { revert(m, returndatasize()) }
            return(m, returndatasize())
        }
    }

    // ── the launch: LaunchResolver's and LaunchPricing's, on this storage ─────

    function resolve(address, uint256, LaunchParams calldata)
        external
        view
        returns (CoinTerms memory, bytes32, address, IBankrLaunchpadRegistry.PadTerms memory)
    {
        _answer(_view(address(LaunchResolver), LaunchResolver.resolve.selector));
    }

    function startTickBounds(uint64, address, uint256, PriceAttestation calldata) external view returns (int24, int24) {
        _answer(_view(address(LaunchPricing), LaunchPricing.padStartTickBounds.selector));
    }

    /// @dev Under delegatecall the library's domain is this contract's.
    function hashPriceAttestation(address, uint256, uint64, uint64) external view returns (bytes32) {
        _answer(_view(address(LaunchPricing), msg.sig));
    }

    /// @dev `_cold` for a view. The libraries' entry points write nothing, so the delegatecall is a view in fact,
    ///      which the compiler cannot see: the call is made through a pointer typed as one.
    function _view(address lib, bytes4 sel) private view returns (bool) {
        function(address, bytes4) internal returns (bool) fn = _forward;
        function(address, bytes4) internal view returns (bool) viewFn;
        assembly ("memory-safe") {
            viewFn := fn
        }
        return viewFn(lib, sel);
    }

    function _forward(address lib, bytes4 sel) private returns (bool ok) {
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, sel)
            calldatacopy(add(m, 4), 4, sub(calldatasize(), 4))
            ok := delegatecall(gas(), lib, m, calldatasize(), 0x00, 0x00)
        }
    }

    /// @dev Ends the call with what the library answered, its revert included.
    function _answer(bool ok) private pure {
        assembly ("memory-safe") {
            let m := mload(0x40)
            returndatacopy(m, 0x00, returndatasize())
            if iszero(ok) { revert(m, returndatasize()) }
            return(m, returndatasize())
        }
    }

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

    function protocolTerms() external view returns (ProtocolTerms memory) {
        return s.protocol;
    }

    function guardTerms() external view returns (GuardTerms memory) {
        return s.guards;
    }

    function bnkrPairWaiver(uint64 padId) external view returns (bool) {
        return s.waiver[padId];
    }

    function hardBounds(uint8 knob) external pure returns (uint64, uint64) {
        return Knobs.hardBounds(knob);
    }

    function limitOf(uint8 knob) public view returns (Limit memory l) {
        (l.min, l.max) = s.limit(knob);
    }

    function limits() external view returns (Limit[] memory l) {
        l = new Limit[](Knobs.COUNT);
        for (uint8 k; k < Knobs.COUNT; ++k) {
            l[k] = limitOf(k);
        }
    }

    function template() external view returns (Range[] memory knobs, uint256 flags, address capController) {
        knobs = _knobs(TEMPLATE);
        (flags, capController) = (s.flags[TEMPLATE], s.capController[TEMPLATE]);
    }

    function templatePresetLimits(uint8 presetId) external view returns (PresetLimits memory) {
        return s.presetLimits[TEMPLATE][presetId];
    }

    function allowedFlags() external view returns (uint256) {
        return s.allowedFlags;
    }

    function padConfig(uint64 id) external view returns (PadConfig memory c) {
        c.ranges = _knobs(id);
        c.knobs = new uint8[](Knobs.COUNT);
        for (uint8 k; k < Knobs.COUNT; ++k) {
            c.knobs[k] = k;
        }
        (c.flags, c.capController, c.terms) = (s.flags[id], s.capController[id], s.payees[id]);
        uint256 top = s.presetTop;
        c.presetIds = new uint8[](top);
        c.presetLimits = new PresetLimits[](top);
        for (uint256 p; p < top; ++p) {
            // p < presetTop, a uint8
            // forge-lint: disable-next-line(unsafe-typecast)
            (c.presetIds[p], c.presetLimits[p]) = (uint8(p + 1), s.presetLimits[id][p + 1]);
        }
    }

    function _knobs(uint64 id) internal view returns (Range[] memory r) {
        r = new Range[](Knobs.COUNT);
        for (uint8 k; k < Knobs.COUNT; ++k) {
            r[k] = s.knobs[id][k];
        }
    }

    function knobOf(uint64 id, uint8 knob) external view returns (Range memory) {
        return s.knobs[id][knob];
    }

    function flagsOf(uint64 id) external view returns (uint256) {
        return s.flags[id];
    }

    function payeesOf(uint64 id) external view returns (IBankrLaunchpadRegistry.PadTerms memory) {
        return s.payees[id];
    }

    function capControllerOf(uint64 id) external view returns (address) {
        return s.capController[id];
    }

    function padQuoteTerms(uint64 id, address quote) external view returns (PadQuoteTerms memory) {
        return s.padQuotes[id][quote];
    }

    function isQuoteAllowed(uint64 id, address quote) external view returns (bool) {
        return s.padQuoteCount[id] == 0 || s.padQuotes[id][quote].allowed;
    }

    function isCurveAllowed(uint64 id, uint256 key) external view returns (bool) {
        return s.curveFlip[id][key] != (key < 3);
    }

    function presetLimitsOf(uint64 id, uint8 presetId) external view returns (PresetLimits memory) {
        return s.presetLimits[id][presetId];
    }

    function presetOf(uint8 presetId) external view returns (PresetRecord memory) {
        return s.presets[presetId];
    }

    /// @dev A preset's key names its code, not only its id. Custom code keeps suite 3's key: sha256 for a budget key,
    ///      so no contract's code hash (keccak256) can equal one; a call budget of 0 is quote-only.
    function extensionKey(LaunchExtension calldata e) external view returns (bytes32) {
        if (e.id != 0) return keccak256(abi.encodePacked("preset", e.id, s.presets[e.id].creationCodeHash));
        if (e.ext == address(0)) return bytes32(0);
        if ((e.quoteGas | e.afterGas) == 0) return e.codehash;
        return sha256(
            abi.encode(
                e.codehash,
                e.quoteGas == 0 ? K.EXT_QUOTE_GAS : e.quoteGas,
                e.afterGas == 0 && !e.quoteOnly ? K.EXT_AFTER_GAS : e.afterGas
            )
        );
    }

    function quoteTerms(address quote) external view returns (QuoteTerms memory) {
        return s.quotes[quote];
    }

    function quoteList() external view returns (address[] memory) {
        return s.quoteList;
    }

    function namedAs(address a) external view returns (uint256) {
        return s.named[a];
    }

    function extensionAllowed(bytes32 key) external view returns (bool) {
        return s.extAllowed[key];
    }

    function pricingConfig() external view returns (address, address, uint32) {
        return (s.priceSigner, s.sequencerFeed, s.sequencerGrace);
    }
}

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/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

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

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

pragma solidity ^0.8.24;

import {Math} from "./math/Math.sol";

/**
 * @dev Bytes operations.
 */
library Bytes {
    /**
     * @dev Forward search for `s` in `buffer`
     * * If `s` is present in the buffer, returns the index of the first instance
     * * If `s` is not present in the buffer, returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
     */
    function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
        return indexOf(buffer, s, 0);
    }

    /**
     * @dev Forward search for `s` in `buffer` starting at position `pos`
     * * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
     * * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
     */
    function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
        uint256 length = buffer.length;
        for (uint256 i = pos; i < length; ++i) {
            if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
                return i;
            }
        }
        return type(uint256).max;
    }

    /**
     * @dev Backward search for `s` in `buffer`
     * * If `s` is present in the buffer, returns the index of the last instance
     * * If `s` is not present in the buffer, returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
     */
    function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
        return lastIndexOf(buffer, s, type(uint256).max);
    }

    /**
     * @dev Backward search for `s` in `buffer` starting at position `pos`
     * * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
     * * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
     */
    function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
        unchecked {
            uint256 length = buffer.length;
            for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
                if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
                    return i - 1;
                }
            }
            return type(uint256).max;
        }
    }

    /**
     * @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
     * memory.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
        return slice(buffer, start, buffer.length);
    }

    /**
     * @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
     * memory. The `end` argument is truncated to the length of the `buffer`.
     *
     * NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
     */
    function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
        // sanitize
        end = Math.min(end, buffer.length);
        start = Math.min(start, end);

        // allocate and copy
        bytes memory result = new bytes(end - start);
        assembly ("memory-safe") {
            mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
        }

        return result;
    }

    /**
     * @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer,
     * and shrinks the buffer length accordingly, effectively overriding the content of buffer with buffer[start:].
     *
     * NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
     */
    function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
        return splice(buffer, start, buffer.length);
    }

    /**
     * @dev Moves the content of `buffer`, from `start` (included) to `end` (excluded) to the start of that buffer,
     * and shrinks the buffer length accordingly, effectively overriding the content of buffer with buffer[start:end].
     * The `end` argument is truncated to the length of the `buffer`.
     *
     * NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
     */
    function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
        // sanitize
        end = Math.min(end, buffer.length);
        start = Math.min(start, end);

        // move and resize
        assembly ("memory-safe") {
            mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
            mstore(buffer, sub(end, start))
        }

        return buffer;
    }

    /**
     * @dev Replaces bytes in `buffer` starting at `pos` with all bytes from `replacement`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`).
     * If `pos >= buffer.length`, no replacement occurs and the buffer is returned unchanged.
     *
     * NOTE: This function modifies the provided buffer in place.
     */
    function replace(bytes memory buffer, uint256 pos, bytes memory replacement) internal pure returns (bytes memory) {
        return replace(buffer, pos, replacement, 0, replacement.length);
    }

    /**
     * @dev Replaces bytes in `buffer` starting at `pos` with bytes from `replacement` starting at `offset`.
     * Copies at most `length` bytes from `replacement` to `buffer`.
     *
     * Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`, `offset` is
     * clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
     * buffer.length - pos))`. If `pos >= buffer.length` or `offset >= replacement.length`, no replacement occurs
     * and the buffer is returned unchanged.
     *
     * NOTE: This function modifies the provided buffer in place.
     */
    function replace(
        bytes memory buffer,
        uint256 pos,
        bytes memory replacement,
        uint256 offset,
        uint256 length
    ) internal pure returns (bytes memory) {
        // sanitize
        pos = Math.min(pos, buffer.length);
        offset = Math.min(offset, replacement.length);
        length = Math.min(length, Math.min(replacement.length - offset, buffer.length - pos));

        // replace
        assembly ("memory-safe") {
            mcopy(add(add(buffer, 0x20), pos), add(add(replacement, 0x20), offset), length)
        }

        return buffer;
    }

    /**
     * @dev Concatenate an array of bytes into a single bytes object.
     *
     * For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)
     * `abi.encodePacked`.
     *
     * NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be
     * significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.
     */
    function concat(bytes[] memory buffers) internal pure returns (bytes memory) {
        uint256 length = 0;
        for (uint256 i = 0; i < buffers.length; ++i) {
            length += buffers[i].length;
        }

        bytes memory result = new bytes(length);

        uint256 offset = 0x20;
        for (uint256 i = 0; i < buffers.length; ++i) {
            bytes memory input = buffers[i];
            assembly ("memory-safe") {
                mcopy(add(result, offset), add(input, 0x20), mload(input))
            }
            unchecked {
                offset += input.length;
            }
        }

        return result;
    }

    /**
     * @dev Split each byte in `input` into two nibbles (4 bits each)
     *
     * Example: hex"01234567" → hex"0001020304050607"
     */
    function toNibbles(bytes memory input) internal pure returns (bytes memory output) {
        assembly ("memory-safe") {
            let length := mload(input)
            output := mload(0x40)
            mstore(0x40, add(add(output, 0x20), mul(length, 2)))
            mstore(output, mul(length, 2))
            for {
                let i := 0
            } lt(i, length) {
                i := add(i, 0x10)
            } {
                let chunk := shr(128, mload(add(add(input, 0x20), i)))
                chunk := and(
                    0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff,
                    or(shl(64, chunk), chunk)
                )
                chunk := and(
                    0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff,
                    or(shl(32, chunk), chunk)
                )
                chunk := and(
                    0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff,
                    or(shl(16, chunk), chunk)
                )
                chunk := and(
                    0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff,
                    or(shl(8, chunk), chunk)
                )
                chunk := and(
                    0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f,
                    or(shl(4, chunk), chunk)
                )
                mstore(add(add(output, 0x20), mul(i, 2)), chunk)
            }
        }
    }

    /**
     * @dev Returns true if the two byte buffers are equal.
     */
    function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
        return a.length == b.length && keccak256(a) == keccak256(b);
    }

    /**
     * @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
     * Inspired by https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
     */
    function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
        value = // swap bytes
            ((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
            ((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
        value = // swap 2-byte long pairs
            ((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
            ((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
        value = // swap 4-byte long pairs
            ((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
            ((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
        value = // swap 8-byte long pairs
            ((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
            ((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
        return (value >> 128) | (value << 128); // swap 16-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 128-bit values.
    function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
        value = // swap bytes
            ((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
        value = // swap 2-byte long pairs
            ((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
        value = // swap 4-byte long pairs
            ((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
        return (value >> 64) | (value << 64); // swap 8-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 64-bit values.
    function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
        value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
        value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
        return (value >> 32) | (value << 32); // swap 4-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 32-bit values.
    function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
        value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
        return (value >> 16) | (value << 16); // swap 2-byte long pairs
    }

    /// @dev Same as {reverseBytes32} but optimized for 16-bit values.
    function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
        return (value >> 8) | (value << 8);
    }

    /**
     * @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
     * if the buffer is all zeros.
     */
    function clz(bytes memory buffer) internal pure returns (uint256) {
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
            if (chunk != bytes32(0)) {
                return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
            }
        }
        return 8 * buffer.length;
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(add(buffer, 0x20), offset))
        }
    }
}

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/openzeppelin-contracts/contracts/utils/Panic.sol

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

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

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

pragma solidity ^0.8.24;

import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";

/**
 * @dev String operations.
 */
library Strings {
    using SafeCast for *;

    bytes16 private constant HEX_DIGITS = "0123456789abcdef";
    uint8 private constant ADDRESS_LENGTH = 20;
    uint256 private constant SPECIAL_CHARS_LOOKUP =
        0xffffffff | // first 32 bits corresponding to the control characters (U+0000 to U+001F)
            (1 << 0x22) | // double quote
            (1 << 0x5c); // backslash

    /**
     * @dev The `value` string doesn't fit in the specified `length`.
     */
    error StringsInsufficientHexLength(uint256 value, uint256 length);

    /**
     * @dev The string being parsed contains characters that are not in scope of the given base.
     */
    error StringsInvalidChar();

    /**
     * @dev The string being parsed is not a properly formatted address.
     */
    error StringsInvalidAddressFormat();

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            assembly ("memory-safe") {
                ptr := add(add(buffer, 0x20), length)
            }
            while (true) {
                ptr--;
                assembly ("memory-safe") {
                    mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toStringSigned(int256 value) internal pure returns (string memory) {
        return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        uint256 localValue = value;
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = HEX_DIGITS[localValue & 0xf];
            localValue >>= 4;
        }
        if (localValue != 0) {
            revert StringsInsufficientHexLength(value, length);
        }
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
     * representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
     * representation, according to EIP-55.
     */
    function toChecksumHexString(address addr) internal pure returns (string memory) {
        bytes memory buffer = bytes(toHexString(addr));

        // hash the hex part of buffer (skip length + 2 bytes, length 40)
        uint256 hashValue;
        assembly ("memory-safe") {
            hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
        }

        for (uint256 i = 41; i > 1; --i) {
            // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
            if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
                // case shift by xoring with 0x20
                buffer[i] ^= 0x20;
            }
            hashValue >>= 4;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
     */
    function toHexString(bytes memory input) internal pure returns (string memory) {
        unchecked {
            bytes memory buffer = new bytes(2 * input.length + 2);
            buffer[0] = "0";
            buffer[1] = "x";
            for (uint256 i = 0; i < input.length; ++i) {
                uint8 v = uint8(input[i]);
                buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
                buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
            }
            return string(buffer);
        }
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return Bytes.equal(bytes(a), bytes(b));
    }

    /**
     * @dev Parse a decimal string and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input) internal pure returns (uint256) {
        return parseUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[0-9]*`
     * - The result must fit into an `uint256` type
     */
    function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        uint256 result = 0;
        for (uint256 i = begin; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 9) return (false, 0);
            result *= 10;
            result += chr;
        }
        return (true, result);
    }

    /**
     * @dev Parse a decimal string and returns the value as a `int256`.
     *
     * Requirements:
     * - The string must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input) internal pure returns (int256) {
        return parseInt(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `[-+]?[0-9]*`
     * - The result must fit in an `int256` type.
     */
    function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
        (bool success, int256 value) = tryParseInt(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
     * the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
        return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
    }

    uint256 private constant ABS_MIN_INT256 = 2 ** 255;

    /**
     * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
     * character or if the result does not fit in a `int256`.
     *
     * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
     */
    function tryParseInt(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, int256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseIntUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseIntUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, int256 value) {
        bytes memory buffer = bytes(input);

        // Check presence of a negative sign.
        bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        bool positiveSign = sign == bytes1("+");
        bool negativeSign = sign == bytes1("-");
        uint256 offset = (positiveSign || negativeSign).toUint();

        (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);

        if (absSuccess && absValue < ABS_MIN_INT256) {
            return (true, negativeSign ? -int256(absValue) : int256(absValue));
        } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
            return (true, type(int256).min);
        } else return (false, 0);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input) internal pure returns (uint256) {
        return parseHexUint(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
     * - The result must fit in an `uint256` type.
     */
    function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
        (bool success, uint256 value) = tryParseHexUint(input, begin, end);
        if (!success) revert StringsInvalidChar();
        return value;
    }

    /**
     * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
        return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
     * invalid character.
     *
     * NOTE: This function will revert if the result does not fit in a `uint256`.
     */
    function tryParseHexUint(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, uint256 value) {
        if (end > bytes(input).length || begin > end) return (false, 0);
        return _tryParseHexUintUncheckedBounds(input, begin, end);
    }

    /**
     * @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
     * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
     */
    function _tryParseHexUintUncheckedBounds(
        string memory input,
        uint256 begin,
        uint256 end
    ) private pure returns (bool success, uint256 value) {
        bytes memory buffer = bytes(input);

        // skip 0x prefix if present
        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 offset = hasPrefix.toUint() * 2;

        uint256 result = 0;
        for (uint256 i = begin + offset; i < end; ++i) {
            uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (chr > 15) return (false, 0);
            result *= 16;
            unchecked {
                // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
                // This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
                result += chr;
            }
        }
        return (true, result);
    }

    /**
     * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
     *
     * Requirements:
     * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input) internal pure returns (address) {
        return parseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
     * `end` (excluded).
     *
     * Requirements:
     * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
     */
    function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
        (bool success, address value) = tryParseAddress(input, begin, end);
        if (!success) revert StringsInvalidAddressFormat();
        return value;
    }

    /**
     * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
     * formatted address. See {parseAddress-string} requirements.
     */
    function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
        return tryParseAddress(input, 0, bytes(input).length);
    }

    /**
     * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
     * formatted address. See {parseAddress-string-uint256-uint256} requirements.
     */
    function tryParseAddress(
        string memory input,
        uint256 begin,
        uint256 end
    ) internal pure returns (bool success, address value) {
        if (end > bytes(input).length || begin > end) return (false, address(0));

        bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
        uint256 expectedLength = 40 + hasPrefix.toUint() * 2;

        // check that input is the correct length
        if (end - begin == expectedLength) {
            // length guarantees that this does not overflow, and value is at most type(uint160).max
            (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
            return (s, address(uint160(v)));
        } else {
            return (false, address(0));
        }
    }

    function _tryParseChr(bytes1 chr) private pure returns (uint8) {
        uint8 value = uint8(chr);

        // Try to parse `chr`:
        // - Case 1: [0-9]
        // - Case 2: [a-f]
        // - Case 3: [A-F]
        // - otherwise not supported
        unchecked {
            if (value > 47 && value < 58) value -= 48;
            else if (value > 96 && value < 103) value -= 87;
            else if (value > 64 && value < 71) value -= 55;
            else return type(uint8).max;
        }

        return value;
    }

    /**
     * @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
     *
     * WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
     *
     * NOTE: This function escapes backslashes (including those in \uXXXX sequences) and the characters in ranges
     * defined in section 2.5 of RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). All control characters in U+0000
     * to U+001F are escaped (\b, \t, \n, \f, \r use short form; others use \u00XX). ECMAScript's `JSON.parse` does
     * recover escaped unicode characters that are not in this range, but other tooling may provide different results.
     */
    function escapeJSON(string memory input) internal pure returns (string memory) {
        bytes memory buffer = bytes(input);

        // Put output at the FMP. Memory will be reserved later when we figure out the actual length of the escaped
        // string. All write are done using _unsafeWriteBytesOffset, which avoid the (expensive) length checks for
        // each character written.
        bytes memory output;
        assembly ("memory-safe") {
            output := mload(0x40)
        }
        uint256 outputLength = 0;

        for (uint256 i = 0; i < buffer.length; ++i) {
            uint8 char = uint8(bytes1(_unsafeReadBytesOffset(buffer, i)));
            if (((SPECIAL_CHARS_LOOKUP & (1 << char)) != 0)) {
                _unsafeWriteBytesOffset(output, outputLength++, "\\");
                if (char == 0x08) _unsafeWriteBytesOffset(output, outputLength++, "b");
                else if (char == 0x09) _unsafeWriteBytesOffset(output, outputLength++, "t");
                else if (char == 0x0a) _unsafeWriteBytesOffset(output, outputLength++, "n");
                else if (char == 0x0c) _unsafeWriteBytesOffset(output, outputLength++, "f");
                else if (char == 0x0d) _unsafeWriteBytesOffset(output, outputLength++, "r");
                else if (char == 0x5c) _unsafeWriteBytesOffset(output, outputLength++, "\\");
                else if (char == 0x22) {
                    // solhint-disable-next-line quotes
                    _unsafeWriteBytesOffset(output, outputLength++, '"');
                } else {
                    // U+0000 to U+001F without short form: output \u00XX
                    _unsafeWriteBytesOffset(output, outputLength++, "u");
                    _unsafeWriteBytesOffset(output, outputLength++, "0");
                    _unsafeWriteBytesOffset(output, outputLength++, "0");
                    _unsafeWriteBytesOffset(output, outputLength++, HEX_DIGITS[char >> 4]);
                    _unsafeWriteBytesOffset(output, outputLength++, HEX_DIGITS[char & 0x0f]);
                }
            } else {
                _unsafeWriteBytesOffset(output, outputLength++, bytes1(char));
            }
        }
        // write the actual length and reserve memory
        assembly ("memory-safe") {
            mstore(output, outputLength)
            mstore(0x40, add(output, add(outputLength, 0x20)))
        }

        return string(output);
    }

    /**
     * @dev Reads a bytes32 from a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            value := mload(add(add(buffer, 0x20), offset))
        }
    }

    /**
     * @dev Write a bytes1 to a bytes array without bounds checking.
     *
     * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
     * assembly block as such would prevent some optimizations.
     */
    function _unsafeWriteBytesOffset(bytes memory buffer, uint256 offset, bytes1 value) private pure {
        // This is not memory safe in the general case, but all calls to this private function are within bounds.
        assembly ("memory-safe") {
            mstore8(add(add(buffer, 0x20), offset), shr(248, value))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.7.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.20;

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS
    }

    /**
     * @dev The signature is invalid.
     */
    error ECDSAInvalidSignature();

    /**
     * @dev The signature has an invalid length.
     */
    error ECDSAInvalidSignatureLength(uint256 length);

    /**
     * @dev The signature has an S value that is in the upper half order.
     */
    error ECDSAInvalidSignatureS(bytes32 s);

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
     * return address(0) without also returning an error description. Errors are documented using an enum (error type)
     * and a bytes32 providing additional information about the error.
     *
     * If no error is returned, then the address can be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
     * invalidation or nonces for replay protection.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     *
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     */
    function tryRecover(
        bytes32 hash,
        bytes memory signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            assembly ("memory-safe") {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Variant of {tryRecover} that takes a signature in calldata
     */
    function tryRecoverCalldata(
        bytes32 hash,
        bytes calldata signature
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, calldata slices would work here, but are
            // significantly more expensive (length check) than using calldataload in assembly.
            assembly ("memory-safe") {
                r := calldataload(signature.offset)
                s := calldataload(add(signature.offset, 0x20))
                v := byte(0, calldataload(add(signature.offset, 0x40)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * NOTE: This function only supports 65-byte signatures. ERC-2098 short signatures are rejected. This restriction
     * is DEPRECATED and will be removed in v6.0. Developers SHOULD NOT use signatures as unique identifiers; use hash
     * invalidation or nonces for replay protection.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, signature);
        _throwError(err, errorArg);
        return recovered;
    }

    /**
     * @dev Variant of {recover} that takes a signature in calldata
     */
    function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
        (address recovered, RecoverError err, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
        _throwError(err, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        unchecked {
            bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
            // We do not check for an overflow here since the shift operation results in 0 or 1.
            uint8 v = uint8((uint256(vs) >> 255) + 27);
            return tryRecover(hash, v, r, s);
        }
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r` and `vs` short-signature fields separately.
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, r, vs);
        _throwError(err, errorArg);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS, s);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature, bytes32(0));
        }

        return (signer, RecoverError.NoError, bytes32(0));
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError err, bytes32 errorArg) = tryRecover(hash, v, r, s);
        _throwError(err, errorArg);
        return recovered;
    }

    /**
     * @dev Parse a signature into its `v`, `r` and `s` components. Supports 65-byte and 64-byte (ERC-2098)
     * formats. Returns (0,0,0) for invalid signatures.
     *
     * For 64-byte signatures, `v` is automatically normalized to 27 or 28.
     * For 65-byte signatures, `v` is returned as-is and MUST already be 27 or 28 for use with ecrecover.
     *
     * Consider validating the result before use, or use {tryRecover}/{recover} which perform full validation.
     */
    function parse(bytes memory signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        assembly ("memory-safe") {
            // Check the signature length
            switch mload(signature)
            // - case 65: r,s,v signature (standard)
            case 65 {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
            case 64 {
                let vs := mload(add(signature, 0x40))
                r := mload(add(signature, 0x20))
                s := and(vs, shr(1, not(0)))
                v := add(shr(255, vs), 27)
            }
            default {
                r := 0
                s := 0
                v := 0
            }
        }
    }

    /**
     * @dev Variant of {parse} that takes a signature in calldata
     */
    function parseCalldata(bytes calldata signature) internal pure returns (uint8 v, bytes32 r, bytes32 s) {
        assembly ("memory-safe") {
            // Check the signature length
            switch signature.length
            // - case 65: r,s,v signature (standard)
            case 65 {
                r := calldataload(signature.offset)
                s := calldataload(add(signature.offset, 0x20))
                v := byte(0, calldataload(add(signature.offset, 0x40)))
            }
            // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098)
            case 64 {
                let vs := calldataload(add(signature.offset, 0x20))
                r := calldataload(signature.offset)
                s := and(vs, shr(1, not(0)))
                v := add(shr(255, vs), 27)
            }
            default {
                r := 0
                s := 0
                v := 0
            }
        }
    }

    /**
     * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
     */
    function _throwError(RecoverError err, bytes32 errorArg) private pure {
        if (err == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (err == RecoverError.InvalidSignature) {
            revert ECDSAInvalidSignature();
        } else if (err == RecoverError.InvalidSignatureLength) {
            revert ECDSAInvalidSignatureLength(uint256(errorArg));
        } else if (err == RecoverError.InvalidSignatureS) {
            revert ECDSAInvalidSignatureS(errorArg);
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/cryptography/MessageHashUtils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/cryptography/MessageHashUtils.sol)

pragma solidity ^0.8.24;

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

/**
 * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
 *
 * The library provides methods for generating a hash of a message that conforms to the
 * https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
 * specifications.
 */
library MessageHashUtils {
    error ERC5267ExtensionsNotSupported();

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing a bytes32 `messageHash` with
     * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
     * keccak256, although any bytes32 value can be safely used because the final digest will
     * be re-hashed.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
            mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
            digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x45` (`personal_sign` messages).
     *
     * The digest is calculated by prefixing an arbitrary `message` with
     * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
     * hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
     *
     * See {ECDSA-recover}.
     */
    function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
        return
            keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
    }

    /**
     * @dev Returns the keccak256 digest of an ERC-191 signed data with version
     * `0x00` (data with intended validator).
     *
     * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
     * `validator` address. Then hashing the result.
     *
     * See {ECDSA-recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked(hex"19_00", validator, data));
    }

    /**
     * @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
     */
    function toDataWithIntendedValidatorHash(
        address validator,
        bytes32 messageHash
    ) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            mstore(0x00, hex"19_00")
            mstore(0x02, shl(96, validator))
            mstore(0x16, messageHash)
            digest := keccak256(0x00, 0x36)
        }
    }

    /**
     * @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
     *
     * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
     * `\x19\x01` and hashing the result. It corresponds to the hash signed by the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
     *
     * See {ECDSA-recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, hex"19_01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            digest := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns the EIP-712 domain separator constructed from an `eip712Domain`. See {IERC5267-eip712Domain}
     *
     * This function dynamically constructs the domain separator based on which fields are present in the
     * `fields` parameter. It contains flags that indicate which domain fields are present:
     *
     * * Bit 0 (0x01): name
     * * Bit 1 (0x02): version
     * * Bit 2 (0x04): chainId
     * * Bit 3 (0x08): verifyingContract
     * * Bit 4 (0x10): salt
     *
     * Arguments that correspond to fields which are not present in `fields` are ignored. For example, if `fields` is
     * `0x0f` (`0b01111`), then the `salt` parameter is ignored.
     */
    function toDomainSeparator(
        bytes1 fields,
        string memory name,
        string memory version,
        uint256 chainId,
        address verifyingContract,
        bytes32 salt
    ) internal pure returns (bytes32 hash) {
        return
            toDomainSeparator(
                fields,
                keccak256(bytes(name)),
                keccak256(bytes(version)),
                chainId,
                verifyingContract,
                salt
            );
    }

    /// @dev Variant of {toDomainSeparator-bytes1-string-string-uint256-address-bytes32} that uses hashed name and version.
    function toDomainSeparator(
        bytes1 fields,
        bytes32 nameHash,
        bytes32 versionHash,
        uint256 chainId,
        address verifyingContract,
        bytes32 salt
    ) internal pure returns (bytes32 hash) {
        bytes32 domainTypeHash = toDomainTypeHash(fields);

        assembly ("memory-safe") {
            // align fields to the right for easy processing
            fields := shr(248, fields)

            // FMP used as scratch space
            let fmp := mload(0x40)
            mstore(fmp, domainTypeHash)

            let ptr := add(fmp, 0x20)
            if and(fields, 0x01) {
                mstore(ptr, nameHash)
                ptr := add(ptr, 0x20)
            }
            if and(fields, 0x02) {
                mstore(ptr, versionHash)
                ptr := add(ptr, 0x20)
            }
            if and(fields, 0x04) {
                mstore(ptr, chainId)
                ptr := add(ptr, 0x20)
            }
            if and(fields, 0x08) {
                mstore(ptr, verifyingContract)
                ptr := add(ptr, 0x20)
            }
            if and(fields, 0x10) {
                mstore(ptr, salt)
                ptr := add(ptr, 0x20)
            }

            hash := keccak256(fmp, sub(ptr, fmp))
        }
    }

    /// @dev Builds an EIP-712 domain type hash depending on the `fields` provided, following https://eips.ethereum.org/EIPS/eip-5267[ERC-5267]
    function toDomainTypeHash(bytes1 fields) internal pure returns (bytes32 hash) {
        if (fields & 0x20 == 0x20) revert ERC5267ExtensionsNotSupported();

        assembly ("memory-safe") {
            // align fields to the right for easy processing
            fields := shr(248, fields)

            // FMP used as scratch space
            let fmp := mload(0x40)
            mstore(fmp, "EIP712Domain(")

            let ptr := add(fmp, 0x0d)
            // name field
            if and(fields, 0x01) {
                mstore(ptr, "string name,")
                ptr := add(ptr, 0x0c)
            }
            // version field
            if and(fields, 0x02) {
                mstore(ptr, "string version,")
                ptr := add(ptr, 0x0f)
            }
            // chainId field
            if and(fields, 0x04) {
                mstore(ptr, "uint256 chainId,")
                ptr := add(ptr, 0x10)
            }
            // verifyingContract field
            if and(fields, 0x08) {
                mstore(ptr, "address verifyingContract,")
                ptr := add(ptr, 0x1a)
            }
            // salt field
            if and(fields, 0x10) {
                mstore(ptr, "bytes32 salt,")
                ptr := add(ptr, 0x0d)
            }
            // if any field is enabled, remove the trailing comma
            ptr := sub(ptr, iszero(iszero(and(fields, 0x1f))))
            // add the closing brace
            mstore8(ptr, 0x29) // add closing brace
            ptr := add(ptr, 1)

            hash := keccak256(fmp, sub(ptr, fmp))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

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

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the 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.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.sol.eta.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
        }
    }

    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
            // Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
            // taking advantage of the most significant (or "sign" bit) in two's complement representation.
            // This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
            // the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
            int256 mask = n >> 255;

            // A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
            return uint256((n + mask) ^ mask);
        }
    }
}

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/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/libraries/BitMath.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            uint256 price = uint256(sqrtPriceX96) << 32;

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

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

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

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

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

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

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

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

lib/v4-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;
}

lib/v4-periphery/src/libraries/LiquidityAmounts.sol

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

import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {FixedPoint96} from "@uniswap/v4-core/src/libraries/FixedPoint96.sol";
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";

/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
    using SafeCast for uint256;

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount0 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount0(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount0)
        internal
        pure
        returns (uint128 liquidity)
    {
        unchecked {
            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
            uint256 intermediate = FullMath.mulDiv(sqrtPriceAX96, sqrtPriceBX96, FixedPoint96.Q96);
            return FullMath.mulDiv(amount0, intermediate, sqrtPriceBX96 - sqrtPriceAX96).toUint128();
        }
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, uint256 amount1)
        internal
        pure
        returns (uint128 liquidity)
    {
        unchecked {
            if (sqrtPriceAX96 > sqrtPriceBX96) (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
            return FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtPriceBX96 - sqrtPriceAX96).toUint128();
        }
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtPriceX96 A sqrt price representing the current pool prices
    /// @param sqrtPriceAX96 A sqrt price representing the first tick boundary
    /// @param sqrtPriceBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount of token0 being sent in
    /// @param amount1 The amount of token1 being sent in
    /// @return liquidity The maximum amount of liquidity received
    function getLiquidityForAmounts(
        uint160 sqrtPriceX96,
        uint160 sqrtPriceAX96,
        uint160 sqrtPriceBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtPriceAX96 > sqrtPriceBX96) {
            (sqrtPriceAX96, sqrtPriceBX96) = (sqrtPriceBX96, sqrtPriceAX96);
        }

        if (sqrtPriceX96 <= sqrtPriceAX96) {
            liquidity = getLiquidityForAmount0(sqrtPriceAX96, sqrtPriceBX96, amount0);
        } else if (sqrtPriceX96 < sqrtPriceBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtPriceX96, sqrtPriceBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(sqrtPriceAX96, sqrtPriceBX96, amount1);
        }
    }
}

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

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

import {IBankrLaunchpadRegistry} from "./IBankrLaunchpadRegistry.sol";
import {LaunchParams, LaunchExtension, PriceAttestation} from "./IBankrLaunchFactory.sol";
import {
    CoinTerms,
    GuardTerms,
    Limit,
    PadConfig,
    PadQuoteTerms,
    PresetLimits,
    PresetRecord,
    ProtocolTerms,
    QuoteTerms,
    Range
} from "./SuiteTypes.sol";

/// @notice Every setting of the launch suite: the owner's protocol terms, price guards, limits and template, each
///         pad's knobs and flags, the quote table, the preset records and the extension allowlist. Every setter is
///         instant and reaches future launches only: a coin carries its own copy of its terms from its launch, and
///         no contract on a live coin's path reads this one. The owner is the factory's, read live.
interface IBankrLaunchSettings {
    /// @dev The constructor's argument: one limit and one template row per knob, in knob order. Preset ids are 1..4.
    struct SettingsInit {
        ProtocolTerms protocol;
        GuardTerms guards;
        Limit[] limits;
        Range[] templateKnobs;
        uint256 templateFlags;
        address templateCapController;
        PresetLimits[4] templatePresetLimits;
        PresetRecord[4] presets;
        PadConfig bankrPad; // pad 0 starts as the template; this is where it differs
        bytes32[] allowedKeys;
    }

    // ── owner (the factory's owner) ──────────────────────────────────────────

    /// @notice Bankr's cut and the takeover clock. Reverts unless the cut fits inside a fee the limits admit, inside
    ///         the template's whole fee range and inside pad 0's.
    function setProtocolTerms(ProtocolTerms calldata t) external;
    function setGuardTerms(GuardTerms calldata g) external;
    /// @notice `padId` = max uint64 sets what a new pad starts with.
    function setBnkrPairWaiver(uint64 padId, bool waived) external;
    /// @notice The outer range of each named knob. A pad row set before is clamped at launch, never rewritten.
    function setLimits(uint8[] calldata knobs, Limit[] calldata limits) external;
    /// @notice What a pad registered from now on starts with. Takeover is never part of it: only a pad switches
    ///         takeover on, for itself.
    function setTemplate(uint8[] calldata knobs, Range[] calldata ranges, uint256 flags, address capController) external;
    function setTemplatePresetLimits(uint8 presetId, PresetLimits calldata l) external;
    function setAllowedFlags(uint256 flags) external;
    /// @notice Lists, updates or re-prices a quote. Mode NONE takes no launches.
    function setQuote(address quote, QuoteTerms calldata t) external;
    function removeQuote(address quote) external;
    function setPriceSigner(address signer) external;
    /// @notice `feed` 0: no sequencer gate.
    function setSequencerUptimeFeed(address feed, uint32 graceSecs) external;
    /// @notice Which code a preset id deploys. Reverts unless the record names the deployer's code hash and the
    ///         deployer answers `creationCodeHash(presetId)` with the record's. An all-zero record clears the id.
    function setPreset(uint8 presetId, PresetRecord calldata r) external;
    function setExtensionAllowed(bytes32 key, bool allowed) external;

    // ── a pad's operator (id 0: the owner) ───────────────────────────────────

    /// @notice Knobs, flags, cap controller, payees and preset limits in one call, checked together at the end.
    function configure(uint64 id, PadConfig calldata c) external;
    function setKnobs(uint64 id, uint8[] calldata knobs, Range[] calldata ranges) external;
    function setFlags(uint64 id, uint256 flags) external;
    function setPayees(uint64 id, IBankrLaunchpadRegistry.PadTerms calldata terms) external;
    /// @notice Who may end the wallet cap early on this pad's future coins; zero: nobody.
    function setCapController(uint64 id, address controller) external;
    function setQuoteTerms(uint64 id, address quote, PadQuoteTerms calldata t) external;
    /// @notice A built-in curve (keys 0..2) is allowed until refused; any other key is refused until allowed.
    function setCurveAllowed(uint64 id, uint256 key, bool allowed) external;
    function setPresetLimits(uint64 id, uint8 presetId, PresetLimits calldata l) external;

    /// @notice The pad registry, from `register()`: copies the template into the pad's own rows and emits each value
    ///         as the pad event a setter would emit.
    function initPad(uint64 id, IBankrLaunchpadRegistry.PadTerms calldata terms) external;

    // ── the launch ───────────────────────────────────────────────────────────

    /// @notice The factory at launch; anyone as a preview. `resolvedHash` is what `expectedTermsHash` is compared with.
    function resolve(address launcher, uint256 nativeDevBuy, LaunchParams calldata p)
        external
        view
        returns (
            CoinTerms memory terms,
            bytes32 resolvedHash,
            address expectedToken,
            IBankrLaunchpadRegistry.PadTerms memory pad
        );
    /// @dev The pad's FDV window as ticks for a listed quote. An unlisted quote has no window: the usable range comes
    ///      back, which is not a range of starts that launch (the curve's own placement refuses most of it).
    function startTickBounds(uint64 id, address quote, uint256 totalSupply, PriceAttestation calldata a)
        external
        view
        returns (int24 lowest, int24 highest);
    /// @notice EIP-712 digest under the domain ("Bankr Launch Pricing", "1", chainId, this contract).
    function hashPriceAttestation(address quote, uint256 priceUsdE18, uint64 observedAt, uint64 expiresAt)
        external
        view
        returns (bytes32 digest);

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

    function protocolTerms() external view returns (ProtocolTerms memory);
    function guardTerms() external view returns (GuardTerms memory);
    function bnkrPairWaiver(uint64 padId) external view returns (bool);
    function hardBounds(uint8 knob) external pure returns (uint64 lo, uint64 hi);
    function limitOf(uint8 knob) external view returns (Limit memory);
    function limits() external view returns (Limit[] memory);
    function template() external view returns (Range[] memory knobs, uint256 flags, address capController);
    function templatePresetLimits(uint8 presetId) external view returns (PresetLimits memory);
    function allowedFlags() external view returns (uint256);
    /// @notice Every knob and every preset id that has had a record, in one call.
    function padConfig(uint64 id) external view returns (PadConfig memory);
    function knobOf(uint64 id, uint8 knob) external view returns (Range memory);
    function flagsOf(uint64 id) external view returns (uint256);
    function payeesOf(uint64 id) external view returns (IBankrLaunchpadRegistry.PadTerms memory);
    function capControllerOf(uint64 id) external view returns (address);
    function padQuoteTerms(uint64 id, address quote) external view returns (PadQuoteTerms memory);
    /// @notice By the pad's own list alone: a pad that allows no quote by name takes every quote.
    function isQuoteAllowed(uint64 id, address quote) external view returns (bool);
    function isCurveAllowed(uint64 id, uint256 key) external view returns (bool);
    function presetLimitsOf(uint64 id, uint8 presetId) external view returns (PresetLimits memory);
    function presetOf(uint8 presetId) external view returns (PresetRecord memory);
    /// @notice The allowlist key of a launch's extension: a preset by id and creation-code hash; custom code by its
    ///         code hash at the floor gas budgets, else sha256 over the hash and the budgets; 0 for none.
    function extensionKey(LaunchExtension calldata e) external view returns (bytes32);
    function quoteTerms(address quote) external view returns (QuoteTerms memory);
    function quoteList() external view returns (address[] memory);
    /// @notice What the owner has ever named `a` as, kept for good through a removal or a new record: bit 0 a
    ///         listed quote, bit 1 a preset's deployer. The factory's isSuite and setTreasury read it.
    function namedAs(address a) external view returns (uint256 kinds);
    function extensionAllowed(bytes32 key) external view returns (bool);
    function pricingConfig()
        external
        view
        returns (address priceSigner, address sequencerUptimeFeed, uint32 sequencerGrace);
    function factory() external view returns (address);
    function registry() external view returns (address);

    // Every setter emits the whole new value, and the constructor and initPad emit the same events, so the state is
    // the fold of the logs from the deploy block. A pad event carries the pad id first.
    event ProtocolTermsSet(ProtocolTerms terms);
    event GuardTermsSet(GuardTerms terms);
    event BnkrPairWaiverSet(uint64 indexed padId, bool waived);
    event LimitSet(uint8 indexed knob, uint64 min, uint64 max);
    event TemplateKnobSet(uint8 indexed knob, uint64 min, uint64 max, uint64 dflt);
    event TemplateFlagsSet(uint256 flags, address capController);
    event TemplatePresetLimitsSet(uint8 indexed presetId, PresetLimits limits);
    event AllowedFlagsSet(uint256 flags);
    event QuoteSet(address indexed quote, QuoteTerms terms);
    event QuoteRemoved(address indexed quote);
    event PriceSignerSet(address signer);
    event SequencerUptimeFeedSet(address feed, uint32 graceSecs);
    event PresetSet(uint8 indexed presetId, PresetRecord record);
    event ExtensionAllowedSet(bytes32 indexed key, bool allowed);
    event PadKnobSet(uint64 indexed padId, uint8 indexed knob, uint64 min, uint64 max, uint64 dflt);
    event PadFlagsSet(uint64 indexed padId, uint256 flags);
    event PadPayeesSet(uint64 indexed padId, IBankrLaunchpadRegistry.PadTerms terms);
    event PadCapControllerSet(uint64 indexed padId, address controller);
    event PadQuoteSet(uint64 indexed padId, address indexed quote, PadQuoteTerms terms);
    event PadCurveSet(uint64 indexed padId, uint256 key, bool allowed);
    event PadPresetLimitsSet(uint64 indexed padId, uint8 indexed presetId, PresetLimits limits);

    error NotOwner();
    error NotOperator();
    error NotRegistry();
    error UnknownLaunchpad();
    error UnknownKnob(uint8 knob);
    error LengthMismatch();
    error KnobOutOfRange(uint8 knob); // a setter: outside the owner's limit or the hard range, or not min <= dflt <= max
    error OutsideLaunchpadRange(uint8 knob, uint64 min, uint64 max); // a launch's value; carries the range in force
    error FlagNotAllowed(uint256 flag); // a flag the owner does not allow, or takeover in the template
    error NotAllowedByLaunchpad(uint256 flag); // a launch using a feature its pad switched off
    error InvalidProtocolTerms();
    error InvalidGuardTerms();
    error InvalidOptions();
    error InvalidPayees();
    error BankrPadIsPreset(); // pad 0's fee knobs (K0 to K3) and payees move only together, through configure
    error HardBound(uint8 bound); // design section 2, by number, where no named error exists
    error BankrCutDoesNotFit(); // B2: a setter or a launch
    error AutoLpNeedsCompoundTerms(); // B12
    error QuoteAmountsOutOfRange(); // B21: a setter or a launch
    error QuoteHasNoRoute(address quote); // B22
    error PresetOff(uint8 presetId);
    error PresetCodeChanged(); // a record that does not match its deployer's code, at the setter or at a launch
    error TermsChanged(bytes32 actual);
    // unchanged from the factory and the pad registry, which lose them
    error QuoteNotAllowed();
    error QuoteNotAllowedByLaunchpad();
    error CurveNotAllowedByLaunchpad();
    error ExtensionNotAllowlisted();
    error OperatorShareAboveLauncherBound();
    error OperatorPayeesMismatch();
    error InvalidFeeSchedule();
    error InvalidSplits();
    error BuybackFeeTooLow();
    error InvalidVestToHolders();
    error VestBpsTooHigh();
    error StartTooFar();
    error StartPassed();
    error InvalidPricing();
    error StartPriceUnavailable();
    error InvalidPriceAttestation();
    error StartTickOutOfBounds(int24 lowest, int24 highest);
}

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

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

/// @notice A holder leg's price references (H13 R2-1): exactly one per asset, fixed at construction from the chain's
///         config with the oracle's own numbers, with no owner and no setter. A conversion hop is guarded against
///         the pair these two references make, whatever venue its route names. A leg names its oracle for life.
interface IBankrReferenceOracle {
    /// @dev An oracle's numbers, fixed at construction (suite 4): the TWAP's window (at least a second, B19), how far
    ///      spot may sit from its mean, the share of a floor reserve one window may spend, the sequencer's grace.
    struct OracleTerms {
        uint32 twapWindow;
        uint24 spotGuardTicks;
        uint16 depthCapBps;
        uint32 sequencerGrace;
    }

    /// @dev One asset's reference: its Chainlink USD feed (`feed`, an answer no older than `maxAge`), or the TWAP of
    ///      one canonical v3 pool (`pool`) pairing it with an asset that has a feed, refused while the window's
    ///      harmonic-mean liquidity is below `minLiquidity`, spot is off its mean, or the sequencer is down.
    struct Reference {
        address asset;
        address feed;
        uint32 maxAge;
        address pool;
        uint128 minLiquidity;
    }

    event ReferenceSet(address indexed asset, address feed, uint32 maxAge, address pool, uint128 minLiquidity);

    error InvalidReference(); // at construction: a duplicate, both or neither source, a feed age of 0, a floor on the
    // wrong kind of row, a pool the canonical v3 factory does not know, or a TWAP whose other token has no feed
    error InvalidTerms(); // at construction: a TWAP window of 0, or a depth cap of 0 beside a TWAP reference
    error NoReference(); // an asset the oracle was not built with
    error ReferenceUnavailable(); // a stale or broken feed, a down sequencer, a TWAP the pool cannot answer, too thin,
    // or whose pool's spot is more than SPOT_GUARD_TICKS from the window's mean (H13 R3-2)

    function TWAP_WINDOW() external view returns (uint32);
    function SPOT_GUARD_TICKS() external view returns (uint24);
    function DEPTH_CAP_BPS() external view returns (uint16);
    function SEQUENCER_GRACE() external view returns (uint32);
    function v3Factory() external view returns (address);
    function sequencerUptimeFeed() external view returns (address);
    function assets() external view returns (address[] memory);
    function referenceOf(address asset) external view returns (Reference memory);
    function isReferenced(address asset) external view returns (bool);
    /// @notice The pair's reference price as a v4 / v3 sqrtPriceX96: token1 per token0 of the sorted pair (a, b), in raw
    ///         units. Reverts NoReference or ReferenceUnavailable.
    function sqrtPriceX96(address a, address b) external view returns (uint160);
    /// @notice The most of `x` (raw units) one conversion into `y` may spend (H13 R3-3): DEPTH_CAP_BPS of the virtual
    ///         reserve each TWAP reference of the pair would hold at its floor, valued in `x`; type(uint256).max when both
    ///         are feeds. Reverts as sqrtPriceX96.
    function maxNotional(address x, address y) external view returns (uint256);
    /// @notice Every row but `skip`'s, hashed in construction order (the stored fields, derived ones included): what
    ///         a deploy check compares between two oracles.
    function referencesHash(address skip) external view returns (bytes32);
}

src/interfaces/IBnkrHolderLeg.sol

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

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

/// @notice A BNKR holder leg (Launch SDK H17), one generation: the locked payee of the holdersId bucket of every coin
///         launched while the factory named it. Keeperless for every quote it was built with a floor for: it converts
///         due piles to BNKR inside on-chain bounds, or forwards them in quote. Anyone may pull, poke, convert and
///         forward.
interface IBnkrHolderLeg {
    enum PayoutMode {
        BNKR,
        QUOTE
    }

    /// @dev One conversion hop out of the previous hop's token (the quote for the first) into `tokenOut`: a pool-direct
    ///      Uniswap-v3-shaped pool of the chain's canonical v3 factory (`v3Pool`), or a hookless v4 pool at most 1 % fee
    ///      (`v4Key`, when `v3Pool` is 0). A route names venues only: every hop is guarded by its two assets' references
    ///      in the leg's `references` (H13 R2-1).
    struct Hop {
        address tokenOut;
        address v3Pool;
        PoolKey v4Key;
    }

    /// @dev A leg's numbers, fixed at construction (suite 4, B19) but `maxImpactBps`, which only falls: one word.
    struct LegTerms {
        uint32 minConvertInterval;
        uint32 staleAfter;
        uint24 maxRouteFeePips;
        uint16 referenceGuardSqrtBps;
        uint16 fillSlackBps;
        uint16 maxImpactBps;
    }

    /// @dev One constructor route: `quote`'s 1 or 2 hops to the leg's BNKR and the pile a pool needs to join its line.
    ///      No hops: a floor and a wake only, for a quote the leg pays in quote (a chain without BNKR, a coin paired
    ///      with BNKR, a quote with no route); its piles then forward in their own pool's swap, as suite 3's did.
    struct RouteInit {
        address quote;
        uint96 pileFloor;
        Hop[] hops;
    }

    event Pulled(bytes32 indexed poolId, address indexed quote, uint256 amount);
    event Converted(address indexed quote, uint256 quoteIn, uint256 bnkrOut, uint256 pools);
    event Credited(bytes32 indexed poolId, uint256 quoteIn, uint256 bnkrOut);
    event Forwarded(bytes32 indexed poolId, address indexed quote, uint256 amount);
    event LegTermsSet(LegTerms terms);
    /// @dev From the constructor for each of its routes (no hops: a floor only), and with no hops from clearRoute.
    event RouteSet(address indexed quote, Hop[] hops);
    /// @dev A constructor floor, or type(uint96).max on the first use of a quote the leg was built without.
    event FloorSet(address indexed quote, uint96 floor);
    event Batched(bytes32 indexed poolId, address indexed quote, bool joined);
    event MaxImpactSet(uint16 bps);
    event UnattributedRescued(address indexed asset, address indexed to, uint256 amount);

    error ZeroAddress();
    error NotOwner(); // the factory's owner, read live: a leg has no owner of its own
    error NotLedger();
    error NotSelf();
    error InsufficientGas(); // a push could not hand its distributor's onLegPush all of PUSH_NOTIFY_GAS
    error OuterSettleOpen(); // inside an unlock whose caller has synced a currency and not settled it
    error DeltaOpen(); // the wake left a PoolManager delta open (never: its every hop settles)
    error NotPoolManager();
    error UnexpectedCallback();
    error UnknownPool();
    error WrongMode(); // convert needs payout mode BNKR, a BNKR set, and a quote other than BNKR
    error TooSoon(); // the quote's window has less than a floor pile of its depth cap left
    error NothingToConvert(); // nothing offered, or less than the quote's floor (a dust offer never spends a window)
    error NoRoute();
    error RouteNotToBnkr();
    error NothingFilled();
    error PartialFill(); // a hop after the first did not fill whole
    error NoRoom(); // spot is already at the price bound's edge
    error ReferenceDeviation(); // spot more than 2 % from the hop's reference
    error BelowReference(); // a hop, or a two-hop route end to end, paid more than FILL_SLACK_BPS + maxImpactBps under
    // its reference (H13 R2-1, R3-2)
    error ReferenceUnavailable(); // the references' (IBankrReferenceOracle): a stale or broken feed, a TWAP too thin
    /// @dev At construction: not the canonical factory's v3 pool, a v4 pool with a hook or above the leg's fee
    ///      ceiling, a pair mismatch, over 2 hops, a second row for one quote, or a floor of 0 or type(uint96).max.
    error InvalidRoute();
    error ReferenceRequired(); // a hop between assets that are not both in the leg's references
    error InvalidImpact();
    /// @dev At construction (B19): impact plus fill slack at 100 % or more, an impact of 0, a reference guard at
    ///      100 % or more, or a conversion interval shorter than the references' TWAP window.
    error InvalidTerms();
    /// @dev At construction: no code, no answer to balanceOf or decimals, a raw totalSupply above MAX_QUOTE_SUPPLY, or
    ///      a coin of this suite.
    error InvalidBnkr();
    error NothingToRescue();
    error NoDistributor();

    function pull(bytes32[] calldata pools) external returns (uint256 total);
    /// @notice Anyone: the first MAX_BATCH pools of the quote's line, up to what its window has left of the depth cap.
    function convert(address quote) external returns (uint256 quoteIn, uint256 bnkrOut);
    function forward(bytes32[] calldata pools) external returns (uint256 forwarded);
    /// @notice The ledger's in-swap wake (BankrFeeLedger._wakeHolders), under its capped and swallowed call only.
    function onPile(bytes32 poolId) external;
    /// @notice Anyone (a holder's claim, the SDK's convert action): the pool's pile staged, forwarded or converted.
    function poke(bytes32 poolId) external;
    /// @notice Anyone: hands a quote's constructor floor to the ledger's wake (NoRoute for a quote built without).
    function armWake(address quote) external;
    /// @notice Anyone: repeats the leg's own excludeSelf() on the quote's holder distributor, if it has one (lenient).
    function excludeFrom(address quote) external;
    /// @notice The factory owner, instant: fills get tighter (never to 0, never up).
    function lowerMaxImpactBps(uint16 bps) external;
    /// @notice The factory owner, instant: the quote's piles then reach holders in quote after STALE_AFTER.
    function clearRoute(address quote) external;

    function bnkr() external view returns (address);
    function payoutMode() external view returns (PayoutMode);
    function legTerms() external view returns (LegTerms memory);
    /// @notice Every constructor row with its floor (no hops: cleared, or paidInQuote): a leg read without its logs.
    function routes() external view returns (RouteInit[] memory);
    /// @notice Payout mode BNKR, a BNKR named, not that BNKR, and a constructor route that has not been cleared.
    function converts(address quote) external view returns (bool);
    /// @notice Built with a floor and no route: `quote`'s piles reach holders in quote at once, in its pools' swaps.
    function paidInQuote(address quote) external view returns (bool);
    function maxImpactBps() external view returns (uint16);
    /// @notice A quote's constructor floor; type(uint96).max once a quote built without one is first staged; else 0.
    function minPile(address quote) external view returns (uint96);
    function batchOf(address quote) external view returns (bytes32[] memory);
    function pending(bytes32 poolId) external view returns (uint256);
    function pendingSince(bytes32 poolId) external view returns (uint64);
    function poolQuote(bytes32 poolId) external view returns (address);
    /// @notice When `quote` last converted through any leg, as this leg's interval reads the ledger's window (0: never).
    function lastConvertAt(address quote) external view returns (uint64);
    function ledgered(address asset) external view returns (uint256);
    function routeOf(address quote) external view returns (Hop[] memory);
    function v3Factory() external view returns (address);
    function references() external view returns (IBankrReferenceOracle);
}

src/interfaces/IChainlinkAggregatorV3.sol

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

/// @dev The Chainlink Data Feed surface the start-price bound reads: a quote's USD feed, and the L2 sequencer-uptime
///      feed (answer 0 = up, 1 = down; startedAt = when the current status began). Same shape as v2's PairRegistry.
interface IChainlinkAggregatorV3 {
    function decimals() external view returns (uint8);

    function description() external view returns (string memory);

    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

src/interfaces/ICreatorVestingEscrow.sol

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

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

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

src/interfaces/SuiteTypes.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/libraries/CurveTable.sol

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

import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {FullMath} from "@uniswap/v4-core/src/libraries/FullMath.sol";
import {IBankrLaunchFactory} from "../interfaces/IBankrLaunchFactory.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";
import {RunnerCurve} from "./RunnerCurve.sol";
import {CurveRules} from "../interfaces/SuiteTypes.sol";

/// @notice A launch's own bands, carried in LaunchParams.curveId (any value above RunnerCurve's ids): up to MAX_ROWS 32-bit
///         rows from the word's top bits, each (width in 200-tick spacings << 16) | share of the sale in bps, contiguous
///         outward from the start tick; the last has width 0 and runs to the usable edge. A bad table reverts here,
///         against the rules its coin's terms froze (CurveRules); a built-in curve meets `checkBuiltIn` instead.
library CurveTable {
    uint256 internal constant MAX_ROWS = 8;
    // Half of v4's Pool.tickSpacingToMaxLiquidityPerTick(200) = type(uint128).max / 8,874: the rest is the compounds'.
    uint256 internal constant MAX_TICK_LIQUIDITY = type(uint128).max / 8_874 / 2;
    // A built-in curve's two bounds (B9, B10): the most any tick held (94 % of v4's ceiling) and, rounded up to a whole
    // ppm, the most of the sale left unplaced (4.47 ppm) over every aligned start tick suite 3 took, -560,000 to
    // 200,000, at the default supply on the three curves in both token orders (test/unit/BuiltInCurveSweep.t.sol).
    uint256 internal constant BUILTIN_TICK_LIQUIDITY = 36_050_941_454_790_270_779_975_733_334_698_189;
    uint256 internal constant BUILTIN_DUST_PPM = 5;
    uint256 internal constant Q96 = 1 << 96;

    /// @dev The loop's running state, in memory for the legacy pipeline's stack.
    struct Walk {
        uint256 left; // of the sale
        int256 edge; // the next band's near tick
        uint256 under; // the liquidity of the band before
        uint256 thin; // the thinnest band so far
        uint256 placed; // TOKEN sold by PLACE_TICKS past the start
        uint256 flat; // the whole sale as one band from the start tick to the usable edge
        int256 start;
        int256 far; // the usable edge the bands run towards
        int256 placeTick;
        uint256 sale;
        bool t0;
        bool ownBuys;
        CurveRules r; // the coin's own, from its terms
    }

    function bands(int24 startTick, bool t0, uint256 sale, uint256 table, bool ownBuys, CurveRules memory r)
        internal
        pure
        returns (RunnerCurve.Band[] memory b)
    {
        uint256 n;
        uint256 sum;
        for (; n < MAX_ROWS; ++n) {
            uint256 row = uint32(table >> (224 - 32 * n));
            if (row == 0) break;
            sum += uint16(row);
        }
        if (n == 0 || sum != 10_000 || (n < MAX_ROWS && table << (32 * n) != 0)) {
            revert IBankrLaunchFactory.InvalidCurve();
        }
        b = new RunnerCurve.Band[](n);
        Walk memory s;
        (s.left, s.sale, s.thin) = (sale, sale, type(uint256).max);
        (s.edge, s.start, s.t0, s.ownBuys, s.r) = (startTick, startTick, t0, ownBuys, r);
        s.far = t0 ? int256(K.MAX_USABLE_TICK) : int256(K.MIN_USABLE_TICK);
        // Rule E, no parked supply: placeBps of the sale is sold by placeTicks past the start (0 bps: the rule is off).
        s.placeTick = t0 ? s.start + int256(uint256(r.placeTicks)) : s.start - int256(uint256(r.placeTicks));
        if (t0 ? s.placeTick > s.far : s.placeTick < s.far) s.placeTick = s.far;
        s.flat = _liq(s, s.start, s.far, sale);
        for (uint256 i; i < n; ++i) {
            b[i] = _row(s, uint32(table >> (224 - 32 * i)), i, i + 1 == n);
        }
        if (s.placed * 10_000 < sale * r.placeBps) revert IBankrLaunchFactory.CurvePlacement();
    }

    /// @dev A built-in curve's bands against what every curve meets, on the launch's real numbers: inside the usable
    ///      range, liquidity above 0 in each band (B8), and no tick past the figure the sweep measured (B9).
    function checkBuiltIn(RunnerCurve.Band[] memory b, bool t0) internal pure {
        Walk memory s;
        s.t0 = t0;
        for (uint256 i; i < b.length; ++i) {
            (int256 lo, int256 hi) = (b[i].lower, b[i].upper);
            if (lo >= hi || lo < K.MIN_USABLE_TICK || hi > K.MAX_USABLE_TICK) {
                revert IBankrLaunchFactory.InvalidCurve();
            }
            uint256 liq = t0 ? _liq(s, lo, hi, b[i].amount) : _liq(s, hi, lo, b[i].amount);
            if (liq == 0) revert IBankrLaunchFactory.CurveTooThin(i);
            if (s.under + liq > BUILTIN_TICK_LIQUIDITY) revert IBankrLaunchFactory.CurveLiquidity(i);
            s.under = liq;
        }
    }

    /// @dev The part of a table's check that needs no pool: its rows, their sum, the tail and the usable range, with the
    ///      start tick in the token-as-currency0 frame. Run before anything is deployed (LaunchPricing.checkStart),
    ///      so a malformed table fails early and by name; `bands` checks it again with everything else.
    function checkFormat(uint256 table, int24 tick) internal pure {
        uint256 n;
        uint256 sum;
        int256 edge = tick;
        for (; n < MAX_ROWS; ++n) {
            uint256 row = uint32(table >> (224 - 32 * n));
            if (row == 0) break;
            sum += uint16(row);
            edge += int256(row >> 16) * K.TICK_SPACING;
            bool last = n + 1 == MAX_ROWS || uint32(table >> (192 - 32 * n)) == 0;
            if (uint16(row) == 0 || ((row >> 16) == 0) != last) revert IBankrLaunchFactory.InvalidCurve();
        }
        if (n == 0 || sum != 10_000 || edge >= K.MAX_USABLE_TICK || (n < MAX_ROWS && table << (32 * n) != 0)) {
            revert IBankrLaunchFactory.InvalidCurve();
        }
    }

    /// @dev One row's band: ⌊sale·bps / 1e4⌋ (the last the rest), `width` spacings outward from the band before it, and
    ///      every check on it: C no ramp, F half of v4's per-tick ceiling (B9), D no wall, G the step (B17).
    function _row(Walk memory s, uint256 row, uint256 i, bool last)
        private
        pure
        returns (RunnerCurve.Band memory band)
    {
        if (uint16(row) == 0 || ((row >> 16) == 0) != last) {
            revert IBankrLaunchFactory.InvalidCurve();
        }
        band.amount = last ? s.left : s.sale * uint16(row) / 10_000;
        s.left -= band.amount;
        int256 next = s.far;
        if (!last) {
            int256 w = int256(row >> 16) * K.TICK_SPACING;
            next = s.t0 ? s.edge + w : s.edge - w;
            if (next >= K.MAX_USABLE_TICK || next <= K.MIN_USABLE_TICK) revert IBankrLaunchFactory.InvalidCurve();
        }
        // both inside the usable range
        // forge-lint: disable-next-line(unsafe-typecast)
        (band.lower, band.upper) = s.t0 ? (int24(s.edge), int24(next)) : (int24(next), int24(s.edge));
        uint256 liq = _liq(s, s.edge, next, band.amount);
        if (liq == 0 || liq * s.r.minDepthDiv < s.flat) revert IBankrLaunchFactory.CurveTooThin(i);
        if (s.under + liq > MAX_TICK_LIQUIDITY) revert IBankrLaunchFactory.CurveLiquidity(i);
        if (liq > s.r.maxDensity * _liq(s, s.edge, s.far, s.sale)) revert IBankrLaunchFactory.CurveTooDense(i);
        // A pool whose own buys run: what a held pump takes from them grows with the thin liquidity under a rise. A
        // band that begins within the pool's own band half width holds at most the owner's step times the thinnest
        // band under it; one that begins further out, no more than the band under it.
        if (s.ownBuys && i != 0) {
            int256 off = s.t0 ? s.edge - s.start : s.start - s.edge;
            if (liq > (off <= int256(uint256(s.r.nearTicks)) ? s.thin * s.r.nearStep : s.under)) {
                revert IBankrLaunchFactory.CurveStep(i);
            }
        }
        if (liq < s.thin) s.thin = liq;
        s.placed += _placed(s, next, band.amount);
        (s.under, s.edge) = (liq, next);
    }

    /// @dev One-sided liquidity of `amount` TOKEN between two ticks, as LiquidityAmounts floors it but with no 128-bit
    ///      cast, so a table past v4's cap reverts by name.
    function _liq(Walk memory s, int256 near, int256 far, uint256 amount) private pure returns (uint256) {
        // forge-lint: disable-next-line(unsafe-typecast)
        (uint256 a, uint256 c) = (TickMath.getSqrtPriceAtTick(int24(near)), TickMath.getSqrtPriceAtTick(int24(far)));
        return s.t0 ? FullMath.mulDiv(amount, FullMath.mulDiv(a, c, Q96), c - a) : FullMath.mulDiv(amount, Q96, a - c);
    }

    /// @dev How much of a band's TOKEN is sold once the price reaches the placement tick.
    function _placed(Walk memory s, int256 next, uint256 amount) private pure returns (uint256) {
        int256 p = s.placeTick;
        if (s.t0 ? s.edge >= p : s.edge <= p) return 0;
        if (s.t0 ? next <= p : next >= p) return amount;
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 a = TickMath.getSqrtPriceAtTick(int24(s.edge));
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 c = TickMath.getSqrtPriceAtTick(int24(next));
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 m = TickMath.getSqrtPriceAtTick(int24(p));
        return
            s.t0 ? FullMath.mulDiv(amount, FullMath.mulDiv(m - a, c, m), c - a) : FullMath.mulDiv(amount, a - m, a - c);
    }
}

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

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

/// @title Knobs
/// @notice The numbered settings of suite 4: a pad's knobs (each a min, max and default inside the owner's limit),
///         a pad's flag bits and a launch's option bits. The ids are ABI: core, the SDK and the founder script read
///         them from abi/knobs.json, so an id is never renumbered or reused.
library Knobs {
    error UnknownKnob(uint8 knob);

    // ── knobs: id, then unit ─────────────────────────────────────────────────
    uint8 internal constant STEADY_PIPS = 0; // pips, both directions
    uint8 internal constant START_PIPS = 1; // pips
    uint8 internal constant DECAY_SECS = 2; // seconds
    uint8 internal constant REFERRER_BPS = 3; // bps of the fee
    uint8 internal constant HOLDERS_BPS = 4; // bps of the creator side
    uint8 internal constant AUTO_LP_BPS = 5; // bps of the creator side
    uint8 internal constant BUYBACK_BPS = 6; // bps of the creator side
    uint8 internal constant VEST_BPS = 7; // bps of supply: min on the creator's own, max on creator + allocations
    uint8 internal constant VEST_TO_HOLDERS_BPS = 8; // bps of supply (max)
    uint8 internal constant VESTED_TOTAL_BPS = 9; // bps of supply, all three together (max)
    uint8 internal constant VEST_TO_HOLDERS_SECS = 10; // seconds
    uint8 internal constant VEST_CLIFF_SECS = 11; // seconds
    uint8 internal constant VEST_SECS = 12; // seconds
    uint8 internal constant SUPPLY = 13; // whole tokens
    uint8 internal constant CAP_BPS = 14; // bps of supply
    uint8 internal constant CAP_SECS = 15; // seconds
    uint8 internal constant DEV_BUY_MAX_BPS = 16; // bps of supply (max)
    uint8 internal constant START_DELAY_SECS = 17; // seconds (max)
    uint8 internal constant START_FDV_USD = 18; // whole USD; the default is the default start
    uint8 internal constant METADATA_BYTES = 19; // bytes (max)
    uint8 internal constant FEE_RECIPIENTS = 20; // count (max)
    uint8 internal constant COMPOUND_INTERVAL_SECS = 21; // seconds
    uint8 internal constant COMPOUND_SHARE_BPS = 22; // bps of the backlog; 0 = no share cap
    uint8 internal constant COMPOUND_DEVIATION_TICKS = 23; // ticks
    uint8 internal constant BAND_HALF_WIDTH = 24; // tick spacings
    uint8 internal constant BAND_GRID = 25; // tick spacings
    uint8 internal constant BUYBACK_INTERVAL_SECS = 26; // seconds
    uint8 internal constant BUYBACK_RETRY_SECS = 27; // seconds
    uint8 internal constant REWARD_STREAM_SECS = 28; // seconds
    uint8 internal constant FEE_CEILING_PIPS = 29; // pips: base fee + extension fee
    uint8 internal constant EXT_MAX_PIPS = 30; // pips (max an extension may declare)
    uint8 internal constant CURVE_MIN_DEPTH_DIV = 31; // divisor (rule C)
    uint8 internal constant CURVE_MAX_DENSITY = 32; // factor (rule D)
    uint8 internal constant CURVE_PLACE_TICKS = 33; // ticks (rule E)
    uint8 internal constant CURVE_PLACE_BPS = 34; // bps (rule E); 0 = rule off
    uint8 internal constant CURVE_DUST_PPM = 35; // ppm of the sale (rule H)
    uint8 internal constant PAD_SHARE_BPS = 36; // bps of the remainder a pad's payees take (owner limit only)
    uint8 internal constant REWARD_RESTART_BPS = 37; // bps of what is streaming
    uint8 internal constant COUNT = 38;

    // ── a pad's flags ────────────────────────────────────────────────────────
    uint256 internal constant F_DEV_BUY = 1 << 0;
    uint256 internal constant F_ALLOCATIONS = 1 << 1;
    uint256 internal constant F_CAP_EXCLUSIONS = 1 << 2;
    uint256 internal constant F_METADATA_ADMIN = 1 << 3;
    uint256 internal constant F_TAKEOVER = 1 << 4;
    uint256 internal constant F_UNLISTED_QUOTES = 1 << 5;
    uint256 internal constant F_EXT_PRESETS = 1 << 6;
    uint256 internal constant F_EXT_QUOTE_ONLY = 1 << 7;
    uint256 internal constant F_EXT_CALLS_OUT = 1 << 8;
    uint256 internal constant F_EXT_OWNER_SWITCH = 1 << 9;
    uint256 internal constant F_LAUNCH_COMPOUND_AMOUNTS = 1 << 10;
    uint256 internal constant F_ALL = (1 << 11) - 1;

    // ── LaunchOptions.set ────────────────────────────────────────────────────
    uint32 internal constant OPT_CAP = 1 << 0;
    uint32 internal constant OPT_VEST_CLOCK = 1 << 1;
    uint32 internal constant OPT_COMPOUND_AMOUNTS = 1 << 2;
    uint32 internal constant OPT_COMPOUND_CADENCE = 1 << 3;
    uint32 internal constant OPT_COMPOUND_BAND = 1 << 4;
    uint32 internal constant OPT_BUYBACK_CADENCE = 1 << 5;
    uint32 internal constant OPT_REWARD_STREAM = 1 << 6;
    uint32 internal constant OPT_FEE_CEILING = 1 << 7;
    uint32 internal constant OPT_ALL = (1 << 8) - 1;

    // ── hard ranges ──────────────────────────────────────────────────────────
    uint64 internal constant MAX_PIPS = 999_999; // a fee below 100 %
    uint64 internal constant MAX_VEST_BPS = 9_999; // a pool is never empty
    uint64 internal constant MAX_SUPPLY = 1e18; // whole tokens: 1e36 raw, the reward accumulator's bound
    uint64 internal constant MAX_BAND_SPACINGS = 8_872; // the usable tick range in 200-tick spacings
    uint64 internal constant MAX_BAND_TICKS = 1_774_400;
    uint64 internal constant MAX_EXT_PIPS = 0xFFFFFE; // 0xFFFFFF is an extension's refusal value
    // The fee decay, the compound interval, the buyback interval and its retry: a share waits behind each, and past
    // a year a mistyped one would hold it for the coin's life (as B14's anchor and B19's stale period).
    uint64 internal constant MAX_CLOCK = 31_536_000; // 365 days

    /// @dev One nibble per knob, knob 0 lowest: its row in `hardBounds`.
    uint256 private constant CLASS = 0xd0c0b44a24ef9980f736303053331110000e22;

    /// @notice The compiled range of a knob: only what arithmetic and a working pool need (design section 2). The
    ///         owner's limit sits inside it and a pad's range inside that.
    function hardBounds(uint8 knob) internal pure returns (uint64 lo, uint64 hi) {
        if (knob >= COUNT) revert UnknownKnob(knob);
        uint256 c = (CLASS >> (uint256(knob) * 4)) & 0xf;
        if (c == 0) return (0, 10_000);
        if (c == 1) return (0, MAX_VEST_BPS);
        if (c == 2) return (0, MAX_PIPS);
        if (c == 3) return (0, type(uint32).max);
        if (c == 4) return (1, type(uint32).max);
        if (c == 5) return (1, MAX_SUPPLY);
        if (c == 6) return (0, type(uint64).max);
        if (c == 7) return (1, 255);
        if (c == 8) return (1, MAX_BAND_TICKS);
        if (c == 9) return (1, MAX_BAND_SPACINGS);
        if (c == 10) return (0, MAX_EXT_PIPS);
        if (c == 11) return (0, MAX_BAND_TICKS);
        if (c == 12) return (0, 1_000_000);
        if (c == 13) return (1, 10_000);
        if (c == 14) return (0, MAX_CLOCK);
        return (1, MAX_CLOCK);
    }
}

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

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

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {TickMath} from "@uniswap/v4-core/src/libraries/TickMath.sol";
import {PricingMode, PriceAttestation} from "../interfaces/IBankrLaunchFactory.sol";
import {IBankrLaunchSettings as S} from "../interfaces/IBankrLaunchSettings.sol";
import {IChainlinkAggregatorV3} from "../interfaces/IChainlinkAggregatorV3.sol";
import {QuoteTerms, Range} from "../interfaces/SuiteTypes.sol";
import {Knobs} from "./Knobs.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";
import {RunnerCurve} from "./RunnerCurve.sol";
import {CurveTable} from "./CurveTable.sol";
import {SettingsRead, SettingsStore} from "./SettingsStore.sol";

/// @notice A launch's start-price bound (security finding 9) over the settings contract's store, delegatecalled by
///         it and by LaunchResolver: each quote's USD price source, the pad's FDV window and the signed price,
///         whose EIP-712 domain names the settings contract. The factory reads none of it: resolve does.
library LaunchPricing {
    using SettingsRead for SettingsStore;

    bytes32 internal constant PRICE_ATTESTATION_TYPEHASH =
        keccak256("PriceAttestation(address quote,uint256 priceUsdE18,uint64 observedAt,uint64 expiresAt)");
    bytes32 internal constant DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    /// @dev Under delegatecall `address(this)` is the settings contract: the domain is ("Bankr Launch Pricing", "1",
    ///      chainId, settings).
    function hashPriceAttestation(address quote, uint256 priceUsdE18, uint64 observedAt, uint64 expiresAt)
        public
        view
        returns (bytes32)
    {
        bytes32 domain = keccak256(
            abi.encode(DOMAIN_TYPEHASH, keccak256("Bankr Launch Pricing"), keccak256("1"), block.chainid, address(this))
        );
        return MessageHashUtils.toTypedDataHash(
            domain, keccak256(abi.encode(PRICE_ATTESTATION_TYPEHASH, quote, priceUsdE18, observedAt, expiresAt))
        );
    }

    /// @dev v2 PairRegistry._usdPriceTick on the launch's own supply: quote raw per token raw = fdv x 10^(18 + dec) /
    ///      (priceUsdE18 x supply), as the tick at or below it. Clamped to the v4 range; X128 above 2^64 keeps 256 bits.
    function _fdvTick(uint64 fdvUsd, uint8 dec, uint256 px, uint256 supply) internal pure returns (int24) {
        if (px > type(uint256).max / supply) return TickMath.MIN_TICK;
        uint256 num = uint256(fdvUsd) * 10 ** (18 + uint256(dec)); // <= 1e9 x 1e36
        uint256 den = px * supply;
        uint256 whole = num / den;
        uint256 sqrtP;
        if (whole < 1 << 64) sqrtP = Math.sqrt(Math.mulDiv(num, 1 << 192, den));
        else if (whole < 1 << 128) sqrtP = Math.sqrt(Math.mulDiv(num, 1 << 128, den)) << 32;
        else return TickMath.MAX_TICK;
        if (sqrtP < TickMath.MIN_SQRT_PRICE) return TickMath.MIN_TICK;
        if (sqrtP >= TickMath.MAX_SQRT_PRICE) return TickMath.MAX_TICK;
        // below MAX_SQRT_PRICE < 2^160
        // forge-lint: disable-next-line(unsafe-typecast)
        return TickMath.getTickAtSqrtPrice(uint160(sqrtP));
    }

    /// @dev The feed's USD answer scaled to 1e18; (false, 0) on a stale, non-positive, incomplete or unreadable round.
    function _feedUsdE18(address feed, uint32 maxAge) internal view returns (bool, uint256) {
        if (feed.code.length == 0) return (false, 0);
        try IChainlinkAggregatorV3(feed).latestRoundData() returns (
            uint80 roundId, int256 answer, uint256, uint256 updatedAt, uint80 answeredInRound
        ) {
            if (
                answer <= 0 || updatedAt == 0 || updatedAt > block.timestamp || answeredInRound < roundId
                    || block.timestamp - updatedAt > maxAge
            ) return (false, 0);
            try IChainlinkAggregatorV3(feed).decimals() returns (uint8 d) {
                // answer > 0 above
                // forge-lint: disable-next-line(unsafe-typecast)
                uint256 v = uint256(answer);
                if (d > 18 || v > type(uint256).max / 10 ** (18 - uint256(d))) return (false, 0);
                return (true, v * 10 ** (18 - uint256(d)));
            } catch {
                return (false, 0);
            }
        } catch {
            return (false, 0);
        }
    }

    /// @dev Read once when the pricing is set; above 18 the FDV numerator could overflow.
    function _decimals(address quote) internal view returns (uint8 d) {
        if (quote.code.length == 0) revert S.InvalidPricing();
        d = IERC20Metadata(quote).decimals();
        if (d > 18) revert S.InvalidPricing();
    }

    // ── the launch's start ───────────────────────────────────────────────────

    /// @dev What LaunchResolver hands over of a launch: `amounts` is the coin's compound cap in the high 128 bits (0:
    ///      the pool compounds nothing) and its QUOTE activation floor in the low, in quote units (B21).
    struct Start {
        uint64 id;
        address quote;
        uint256 supply;
        int24 tick;
        uint64 startTime;
        uint256 curveId;
        uint256 amounts;
    }

    /// @dev A launch's start: its own table's form, a scheduled start inside the pad's wait, and on a listed quote
    ///      the tick inside the pad's FDV window and the coin's quote amounts inside B21's two dollar edges, all
    ///      at one price. An unlisted quote has no USD price, so neither bound: its launcher prices it, and the
    ///      curve's own placement (LaunchPool, B9 and B10) is what refuses a start it cannot hold.
    function checkStart(Start memory c, PriceAttestation calldata a) external view {
        SettingsStore storage s = _settings();
        if (c.curveId > RunnerCurve.CURVE_THIN_TOPSIDE) CurveTable.checkFormat(c.curveId, c.tick);
        if (c.startTime != 0) {
            if (c.startTime <= block.timestamp) revert S.StartPassed();
            if (c.startTime - block.timestamp > s.range(c.id, Knobs.START_DELAY_SECS).max) revert S.StartTooFar();
        }
        QuoteTerms memory q = s.quotes[c.quote];
        if (!q.allowed) return;
        uint256 px = _price(s, c.quote, q, a);
        (int24 lo, int24 hi) = _window(s, c.id, q.decimals, px, c.supply);
        if (c.tick < lo || c.tick > hi) revert S.StartTickOutOfBounds(lo, hi);
        // B21: a coin freezes these for life, so a decimals slip is refused at the price the launch already reads.
        // Up: over the owner's ceiling. Down: a cap worth under one whole dollar (cap x px < one) places dust each
        // compound, and the backlog behind it never drains.
        uint256 one = 10 ** (18 + uint256(q.decimals));
        uint256 cap = c.amounts >> 128;
        uint256 most = uint128(c.amounts);
        if (cap != 0) {
            if (cap > most) most = cap;
            // one is at least 1e18 and cap is not 0
            unchecked {
                if (px <= (one - 1) / cap) revert S.QuoteAmountsOutOfRange();
            }
        }
        if (Math.mulDiv(most, px, one) > s.guards.maxCompoundUsd) revert S.QuoteAmountsOutOfRange();
    }

    /// @dev The settings contract's startTickBounds: [tick at the pad's lowest FDV, tick at its highest] for the
    ///      supply at the quote's price now (0: the pad's default supply). An unlisted quote: the usable range.
    function padStartTickBounds(uint64 id, address quote, uint256 totalSupply, PriceAttestation calldata a)
        external
        view
        returns (int24 lowest, int24 highest)
    {
        SettingsStore storage s = _settings();
        if (!s.inited[id]) revert S.UnknownLaunchpad();
        QuoteTerms memory q = s.quotes[quote];
        if (!q.allowed) return (K.MIN_USABLE_TICK, K.MAX_USABLE_TICK);
        if (totalSupply == 0) totalSupply = uint256(s.range(id, Knobs.SUPPLY).dflt) * 1e18;
        return _window(s, id, q.decimals, _price(s, quote, q, a), totalSupply);
    }

    function _settings() private pure returns (SettingsStore storage s) {
        assembly ("memory-safe") {
            s.slot := 0
        }
    }

    function _window(SettingsStore storage s, uint64 id, uint8 dec, uint256 px, uint256 supply)
        private
        view
        returns (int24, int24)
    {
        Range memory r = s.range(id, Knobs.START_FDV_USD);
        return (_fdvTick(r.min, dec, px, supply), _fdvTick(r.max, dec, px, supply));
    }

    /// @dev A quote's USD price from the owner's row: a feed behind the sequencer gate with the owner's grace, or the
    ///      launch's own attestation, whose domain names the settings contract. Fail-closed: no price, no launch.
    function _price(SettingsStore storage s, address quote, QuoteTerms memory q, PriceAttestation calldata a)
        private
        view
        returns (uint256 px)
    {
        if (q.mode == PricingMode.CHAINLINK) {
            bool ok;
            if (_sequencerUpFor(s.sequencerFeed, s.sequencerGrace)) (ok, px) = _feedUsdE18(q.feed, q.maxPriceAge);
            if (!ok) revert S.StartPriceUnavailable();
            return px;
        }
        address signer = s.priceSigner;
        if (q.mode != PricingMode.SIGNED || signer == address(0)) revert S.StartPriceUnavailable();
        px = a.priceUsdE18;
        if (
            px == 0 || a.observedAt > block.timestamp || a.expiresAt < block.timestamp
                || block.timestamp - a.observedAt > q.maxPriceAge
        ) revert S.InvalidPriceAttestation();
        (address rec, ECDSA.RecoverError err,) =
            ECDSA.tryRecoverCalldata(hashPriceAttestation(quote, px, a.observedAt, a.expiresAt), a.signature);
        if (err != ECDSA.RecoverError.NoError || rec != signer) revert S.InvalidPriceAttestation();
    }

    /// @dev Chainlink L2 convention: answer 0 = up, startedAt = when that status began, held to the owner's grace.
    ///      Any anomaly reads as down.
    function _sequencerUpFor(address feed, uint256 grace) private view returns (bool) {
        if (feed == address(0)) return true;
        if (feed.code.length == 0) return false;
        try IChainlinkAggregatorV3(feed).latestRoundData() returns (
            uint80, int256 answer, uint256 startedAt, uint256, uint80
        ) {
            return answer == 0 && startedAt != 0 && startedAt <= block.timestamp
                && block.timestamp - startedAt > grace;
        } catch {
            return false;
        }
    }
}

src/libraries/LaunchResolver.sol

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

import {
    IBankrLaunchFactory,
    LaunchParams,
    LaunchExtension,
    LaunchEconomics as Economics
} from "../interfaces/IBankrLaunchFactory.sol";
import {IBankrLaunchpadRegistry} from "../interfaces/IBankrLaunchpadRegistry.sol";
import {IBankrLaunchSettings as S} from "../interfaces/IBankrLaunchSettings.sol";
import {IBnkrHolderLeg} from "../interfaces/IBnkrHolderLeg.sol";
import {VestingAllocation} from "../interfaces/ICreatorVestingEscrow.sol";
import {
    CoinTerms,
    GuardTerms,
    LaunchOptions,
    PadQuoteTerms,
    PresetLimits,
    PresetRecord,
    ProtocolTerms,
    QuoteTerms,
    Range
} from "../interfaces/SuiteTypes.sol";
import {FeeSchedule} from "./FeeMath.sol";
import {Knobs} from "./Knobs.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";
import {LaunchPricing} from "./LaunchPricing.sol";
import {RunnerCurve} from "./RunnerCurve.sol";
import {SettingsRead, SettingsStore} from "./SettingsStore.sol";

/// @dev The factory as the resolver reads it: the wiring a launch landing now would get.
interface IResolverWiring {
    function hook() external view returns (address);
    function holderLeg() external view returns (address);
    function ledger() external view returns (address);
}

interface IResolverLegs {
    function legIdOf(address leg) external view returns (uint16);
}

interface IResolverLeg {
    function bnkr() external view returns (address);
    function payoutMode() external view returns (IBnkrHolderLeg.PayoutMode);
    function converts(address quote) external view returns (bool);
}

/// @title LaunchResolver
/// @notice The settings contract's launch check, delegatecalled on its storage: a launch's values picked inside its
///         pad's ranges and the owner's limits, the hard bounds held on the coin's own numbers whoever chose them,
///         and the result as one all-static record with its hash. A view: it cannot change a coin that exists.
library LaunchResolver {
    using SettingsRead for SettingsStore;

    uint256 private constant WAD = 1e18;
    uint256 private constant ALWAYS = 1 << 31; // _pick's bit for a value LaunchParams itself carries
    uint256 private constant CTO_MAX_ENTRIES = 64; // B18: a takeover settles every recipient in one transaction
    uint256 private constant BUYBACK_MAX_FEE_PIPS = 999_899; // B1: a fill is sized with 1,000,000 - fee - 100
    address private constant TREASURY = address(uint160(uint256(keccak256("bankr.launch.pad-payee.treasury"))));
    uint256 private constant ANY_CURVE = type(uint256).max;

    /// @dev One scratch struct for every intermediate, so no step takes more than three arguments.
    struct Ctx {
        uint64 id;
        address launcher;
        uint256 flags; // the pad's, inside what the owner allows now
        uint256 set; // LaunchOptions.set | ALWAYS
        uint256 kept; // WAD: what the pad's payees and the referrer leave of the remainder (B12, B15)
        uint256 steadySum; // buy steady + sell steady
        bool lp; // the pool compounds: an auto-LP share on the creator side or in the decay split
        GuardTerms g;
        LaunchOptions o;
    }

    /// @dev IBankrLaunchSettings.resolve: the contract forwards its own calldata here. The launch's options ride in
    ///      LaunchParams.options: empty, or abi.encode(LaunchOptions).
    function resolve(address launcher, uint256 nativeDevBuy, LaunchParams calldata p)
        external
        view
        returns (CoinTerms memory t, bytes32 hash, address expectedToken, IBankrLaunchpadRegistry.PadTerms memory pad)
    {
        LaunchOptions memory o = _options(p.options);
        (t, pad) = _resolve(launcher, nativeDevBuy, p, o);
        (hash, expectedToken) = _pin(t, o);
    }

    function _resolve(address launcher, uint256 nativeDevBuy, LaunchParams calldata p, LaunchOptions memory o)
        private
        view
        returns (CoinTerms memory t, IBankrLaunchpadRegistry.PadTerms memory pad)
    {
        SettingsStore storage s = _s();
        Ctx memory x;
        (x.id, x.launcher, x.o, x.set) = (p.launchpadId, launcher, o, o.set | ALWAYS);
        if (!s.inited[x.id]) revert S.UnknownLaunchpad();
        // a pad's stored flags are not rewritten when the owner narrows what pads may switch on
        (x.flags, x.g) = (s.flags[x.id] & s.allowedFlags, s.guards);
        (t.launchpadId, t.quote, t.startTime) = (x.id, p.quote, p.startTime);
        _owner(t, x);
        _wiring(t, x);
        _supplyAndVest(p, t, x);
        _capAndSwitches(p, t, x);
        if ((p.devBuyAmountIn | nativeDevBuy) != 0) _flag(x, Knobs.F_DEV_BUY);
        _fees(p.econ, t, x);
        pad = _payees(p, t, x);
        _works(t, x);
        _stream(t, x);
        _extension(p, t, x);
        _start(p, t, x);
        _curve(p.curveId, t, x);
    }

    /// @dev The hash a launch may pin: the record as resolved, before the factory fills in what only it can know.
    function _pin(CoinTerms memory t, LaunchOptions memory o) private pure returns (bytes32 hash, address token) {
        hash = keccak256(abi.encode(t));
        if (o.expectedTermsHash != bytes32(0) && o.expectedTermsHash != hash) revert S.TermsChanged(hash);
        token = o.expectedToken;
    }

    function _s() private pure returns (SettingsStore storage s) {
        assembly ("memory-safe") {
            s.slot := 0
        }
    }

    // ── options, picks and flags ─────────────────────────────────────────────

    /// @dev One launch, one encoding: empty, or exactly the struct with a set bit or a pin, and a clear bit's fields
    ///      zero (they mean the pad's default).
    function _options(bytes calldata raw) private pure returns (LaunchOptions memory o) {
        if (raw.length == 0) return o;
        if (raw.length != 19 * 32) revert S.InvalidOptions();
        o = abi.decode(raw, (LaunchOptions));
        uint256 set = o.set;
        if (
            set & ~uint256(Knobs.OPT_ALL) != 0
                || (set == 0 && o.expectedTermsHash == bytes32(0) && o.expectedToken == address(0))
                || (set & Knobs.OPT_CAP == 0 && (o.capBps | o.capSecs) != 0)
                || (set & Knobs.OPT_VEST_CLOCK == 0 && (o.vestCliffSecs | o.vestSecs) != 0)
                || (set & Knobs.OPT_COMPOUND_AMOUNTS == 0 && (o.compoundFloor | o.compoundCap) != 0)
                || (set & Knobs.OPT_COMPOUND_CADENCE == 0
                    && (o.compoundInterval | o.compoundShareBps | o.compoundDeviationTicks) != 0)
                || (set & Knobs.OPT_COMPOUND_BAND == 0 && (o.bandHalfWidth | o.bandGrid) != 0)
                || (set & Knobs.OPT_BUYBACK_CADENCE == 0 && (o.buybackInterval | o.buybackRetry) != 0)
                || (set & Knobs.OPT_REWARD_STREAM == 0 && (o.rewardStreamSecs | o.rewardRestartBps) != 0)
                || (set & Knobs.OPT_FEE_CEILING == 0 && o.feeCeilingPips != 0)
        ) revert S.InvalidOptions();
    }

    function _range(Ctx memory x, uint8 knob) private view returns (Range memory) {
        return _s().range(x.id, knob);
    }

    /// @dev A value the launch chooses: inside the pad's range where it names one (`bit` set), else the default.
    function _pick(Ctx memory x, uint8 knob, uint256 bit, uint256 v) private view returns (uint256) {
        Range memory r = _range(x, knob);
        if (x.set & bit == 0) return r.dflt;
        if (v < r.min || v > r.max) revert S.OutsideLaunchpadRange(knob, r.min, r.max);
        return v;
    }

    /// @dev A knob that is only a ceiling: the launch's count or size under it. Returns the ceiling.
    function _under(Ctx memory x, uint8 knob, uint256 v) private view returns (uint256) {
        Range memory r = _range(x, knob);
        if (v > r.max) revert S.OutsideLaunchpadRange(knob, r.min, r.max);
        return r.max;
    }

    function _flag(Ctx memory x, uint256 flag) private pure {
        if (x.flags & flag == 0) revert S.NotAllowedByLaunchpad(flag);
    }

    /// @dev Terms of a feature the launch leaves off are not the launch's to name: its record would not hold them.
    function _unset(Ctx memory x, uint256 bits) private pure {
        if (x.set & bits != 0) revert S.InvalidOptions();
    }

    // ── steps ────────────────────────────────────────────────────────────────

    /// @dev Bankr's cut and the takeover clock, copied from the owner's slot: no pad or launch value is an input.
    function _owner(CoinTerms memory t, Ctx memory x) private view {
        ProtocolTerms memory o = _s().protocol;
        (t.bankrFeeBps, t.bankrMinPips, t.holdersShareBps) = (o.bankrFeeBps, o.bankrMinPips, o.holdersShareBps);
        (t.takeover, t.ctoNotice, t.ctoGrace) = (x.flags & Knobs.F_TAKEOVER != 0, o.ctoNotice, o.ctoGrace);
        (t.tokenActivationDivisor, t.bnkrActivationDivisor) = (o.tokenActivationDivisor, o.bnkrActivationDivisor);
        (t.minRoundTripPips, t.pool.refTauSecs) = (x.g.minRoundTripPips, x.g.refTauSecs);
    }

    /// @dev The quote, and the hook and leg in force: the one hash then pins the owner's instant setHook and
    ///      setHolderLeg. B6: a quote's raw supply stays inside what the reward accumulator can carry. B22: a
    ///      listed quote's coins are never fixed to quote payouts by the order of two owner calls.
    function _wiring(CoinTerms memory t, Ctx memory x) private view {
        SettingsStore storage s = _s();
        address quote = t.quote;
        QuoteTerms storage q = s.quotes[quote];
        bool listed = q.allowed;
        if (!listed) {
            _flag(x, Knobs.F_UNLISTED_QUOTES);
            if (quote.code.length == 0) revert S.QuoteNotAllowed();
        }
        if (s.padQuoteCount[x.id] != 0 && !s.padQuotes[x.id][quote].allowed) revert S.QuoteNotAllowedByLaunchpad();
        {
            (bool ok, bytes memory r) = quote.staticcall{gas: 50_000}(abi.encodeWithSignature("totalSupply()"));
            if (ok && r.length >= 32 && abi.decode(r, (uint256)) > K.MAX_QUOTE_SUPPLY) revert S.HardBound(6);
        }
        // what the distributor stores: a floor of 0, an unlisted quote's included, is one raw unit there
        t.quoteActivation = q.quoteActivation == 0 ? 1 : q.quoteActivation;
        IResolverWiring f = IResolverWiring(S(address(this)).factory());
        address leg = f.holderLeg();
        (t.hook, t.holderLeg, t.legId) = (f.hook(), leg, IResolverLegs(f.ledger()).legIdOf(leg));
        address bnkr = IResolverLeg(leg).bnkr();
        t.holderConverts = IResolverLeg(leg).converts(quote);
        if (
            listed && !t.holderConverts && !q.quotePaid && quote != bnkr
                && IResolverLeg(leg).payoutMode() == IBnkrHolderLeg.PayoutMode.BNKR
        ) revert S.QuoteHasNoRoute(quote);
        t.waiveBnkrPair = bnkr != address(0) && quote == bnkr && s.waiver[x.id];
    }

    /// @dev Supply in raw units inside the pad's range of whole tokens (B6; 0 takes the default), then what vests:
    ///      the creator's own inside the pad's floor, it and the builder allocations under the pad's ceiling, the
    ///      holders' slice, and all three short of the supply (B8).
    function _supplyAndVest(LaunchParams calldata p, CoinTerms memory t, Ctx memory x) private view {
        uint256 supply = p.totalSupply;
        {
            Range memory r = _range(x, Knobs.SUPPLY);
            if (supply == 0) supply = uint256(r.dflt) * WAD;
            else if (supply < uint256(r.min) * WAD || supply > uint256(r.max) * WAD) {
                revert S.OutsideLaunchpadRange(Knobs.SUPPLY, r.min, r.max);
            }
        }
        uint256 own = p.vestBps;
        uint256 toHolders = p.econ.vestToHoldersBps;
        uint256 vested = supply * (own + toHolders) / 10_000;
        {
            uint256 alloc;
            if (p.extraAllocations.length != 0) {
                _flag(x, Knobs.F_ALLOCATIONS);
                alloc = _allocated(p.extraAllocations);
            }
            // allocations in bps of supply, rounded up, as suite 3 counts them against the pad's ceiling
            Range memory r = _range(x, Knobs.VEST_BPS);
            if (own < r.min || own + (alloc * 10_000 + supply - 1) / supply > r.max) {
                revert S.OutsideLaunchpadRange(Knobs.VEST_BPS, r.min, r.max);
            }
            vested += alloc;
        }
        (uint64 cliff, uint64 dur) = (p.econ.vestToHoldersCliff, p.econ.vestToHoldersDuration);
        if (toHolders == 0) {
            if ((cliff | dur) != 0) revert S.InvalidVestToHolders();
        } else {
            _pick(x, Knobs.VEST_TO_HOLDERS_BPS, ALWAYS, toHolders);
            _pick(x, Knobs.VEST_TO_HOLDERS_SECS, ALWAYS, dur);
            if (cliff > dur) revert S.InvalidVestToHolders();
        }
        // B8: an empty pool cannot open
        if (vested >= supply) revert S.VestBpsTooHigh();
        {
            Range memory all = _range(x, Knobs.VESTED_TOTAL_BPS);
            if (vested * 10_000 > supply * all.max) {
                revert S.OutsideLaunchpadRange(Knobs.VESTED_TOTAL_BPS, all.min, all.max);
            }
        }
        (t.totalSupply, t.vestedAmount) = (supply, vested);
        // each within 9,999 by the knobs' hard ranges
        // forge-lint: disable-next-line(unsafe-typecast)
        (t.vestBps, t.vestToHoldersBps) = (uint16(own), uint16(toHolders));
        (t.vestToHoldersCliff, t.vestToHoldersDuration) = (cliff, dur);
        if (own == 0) return _unset(x, Knobs.OPT_VEST_CLOCK);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.vestCliffSecs = uint32(_pick(x, Knobs.VEST_CLIFF_SECS, Knobs.OPT_VEST_CLOCK, x.o.vestCliffSecs));
        // forge-lint: disable-next-line(unsafe-typecast)
        t.vestSecs = uint32(_pick(x, Knobs.VEST_SECS, Knobs.OPT_VEST_CLOCK, x.o.vestSecs));
    }

    function _allocated(VestingAllocation[] calldata list) private pure returns (uint256 sum) {
        for (uint256 i; i < list.length; ++i) {
            sum += list[i].amount;
        }
    }

    /// @dev The wallet cap (B11), what the token is deployed with, and the launch's own switches against its
    ///      pad's flags.
    function _capAndSwitches(LaunchParams calldata p, CoinTerms memory t, Ctx memory x) private view {
        // the length is the switch: with no cap the pad's size knob is not read, so it cannot refuse the launch
        uint256 secs = _pick(x, Knobs.CAP_SECS, Knobs.OPT_CAP, x.o.capSecs);
        if (secs != 0) {
            t.capAmount = t.totalSupply * _pick(x, Knobs.CAP_BPS, Knobs.OPT_CAP, x.o.capBps) / 10_000;
        }
        // B11: one encoding of "off", and a cap of zero tokens would block every buy
        if (secs == 0 ? x.o.capBps != 0 : t.capAmount == 0) revert S.HardBound(11);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.capSecs = uint32(secs);
        t.capController = _s().capController[x.id];
        // forge-lint: disable-next-line(unsafe-typecast)
        t.metadataMaxBytes = uint32(_under(x, Knobs.METADATA_BYTES, bytes(p.metadataUri).length));
        // forge-lint: disable-next-line(unsafe-typecast)
        t.devBuyMaxBps = uint16(_under(x, Knobs.DEV_BUY_MAX_BPS, 0));
        if (p.metadataAdmin != address(0)) _flag(x, Knobs.F_METADATA_ADMIN);
        if (p.capExclusions.length != 0) _flag(x, Knobs.F_CAP_EXCLUSIONS);
        // none named: the launcher alone
        uint256 n = p.feeRecipients.length;
        uint256 most = _under(x, Knobs.FEE_RECIPIENTS, n);
        if (t.takeover && most > CTO_MAX_ENTRIES) {
            // B18
            if (n > CTO_MAX_ENTRIES) revert S.HardBound(18);
            most = CTO_MAX_ENTRIES;
        }
        // forge-lint: disable-next-line(unsafe-typecast)
        t.maxFeeRecipients = uint8(most);
    }

    /// @dev B1, B2 and B4 on the launch's own schedules and shares. Founder ruling: a fee that cannot carry
    ///      Bankr's cut is refused here, whoever set the cut, the range or the fee.
    function _fees(Economics calldata e, CoinTerms memory t, Ctx memory x) private view {
        _schedule(x, e.buy);
        _schedule(x, e.sell);
        (t.pool.buy, t.pool.sell) = (e.buy, e.sell);
        uint256 lower = e.buy.steadyPips < e.sell.steadyPips ? e.buy.steadyPips : e.sell.steadyPips;
        x.steadySum = uint256(e.buy.steadyPips) + e.sell.steadyPips;
        uint256 referrer = _pick(x, Knobs.REFERRER_BPS, ALWAYS, e.referrerBps);
        // B2: otherwise the per-swap split underflows and the pool stops trading with its liquidity locked
        if (t.bankrFeeBps + referrer > 10_000 || uint256(t.bankrMinPips) * 10_000 > lower * (10_000 - referrer)) {
            revert S.BankrCutDoesNotFit();
        }
        // forge-lint: disable-next-line(unsafe-typecast)
        t.referrerBps = uint16(referrer);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.holdersBps = uint16(_pick(x, Knobs.HOLDERS_BPS, ALWAYS, e.holdersBps));
        // forge-lint: disable-next-line(unsafe-typecast)
        t.autoLpBps = uint16(_pick(x, Knobs.AUTO_LP_BPS, ALWAYS, e.autoLpBps));
        // forge-lint: disable-next-line(unsafe-typecast)
        t.buybackBps = uint16(_pick(x, Knobs.BUYBACK_BPS, ALWAYS, e.buybackBps));
        if (uint256(t.holdersBps) + t.autoLpBps + t.buybackBps > 10_000) revert S.InvalidSplits();
        t.pool.buyback = t.buybackBps != 0;
        // B1: from 999,900 up the buyback's money, which has no other exit, could never be spent
        if (t.pool.buyback && e.buy.steadyPips > BUYBACK_MAX_FEE_PIPS) revert S.HardBound(1);
    }

    /// @dev One encoding per schedule (B1). The opening fee's knob is read only when there is one: a pad pins an
    ///      opening fee through its decay range, which B1 ties to it.
    function _schedule(Ctx memory x, FeeSchedule calldata f) private view {
        _pick(x, Knobs.STEADY_PIPS, ALWAYS, f.steadyPips);
        if (f.startPips != f.steadyPips) _pick(x, Knobs.START_PIPS, ALWAYS, f.startPips);
        _pick(x, Knobs.DECAY_SECS, ALWAYS, f.decaySecs);
        if (f.startPips < f.steadyPips || (f.decaySecs == 0) != (f.startPips == f.steadyPips)) {
            revert S.InvalidFeeSchedule();
        }
    }

    /// @dev The pad's payees as the launcher expects them, inside the owner's count and share limits as they stand
    ///      now; what they and the referrer leave of the remainder; and whether the hook is paid an auto-LP share,
    ///      worked out as the bucket split works it out (the treasury's cut first, the rest rescaled).
    function _payees(LaunchParams calldata p, CoinTerms memory t, Ctx memory x)
        private
        view
        returns (IBankrLaunchpadRegistry.PadTerms memory pad)
    {
        SettingsStore storage s = _s();
        pad = s.payees[x.id];
        t.padTermsHash = keccak256(abi.encode(pad));
        if (p.operatorPayeesHash != bytes32(0) && p.operatorPayeesHash != t.padTermsHash) {
            revert S.OperatorPayeesMismatch();
        }
        (uint256 steady, uint256 rest) = _split(pad.payees, pad.steadySharesWad);
        (uint256 decay, uint256 decayRest) = pad.decay.on ? _split(pad.payees, pad.decay.sharesWad) : (0, 0);
        uint256 most = steady > decay ? steady : decay;
        (, uint256 limit) = s.limit(Knobs.PAD_SHARE_BPS);
        if (pad.payees.length > s.protocol.maxPadPayees || most > limit * 1e14) revert S.InvalidPayees();
        if (most > uint256(p.maxOperatorShareBps) * 1e14) revert S.OperatorShareAboveLauncherBound();
        steady += uint256(t.referrerBps) * 1e14;
        x.kept = steady < WAD ? WAD - steady : 0;
        t.pool.creatorLp = (rest * t.autoLpBps + 5_000) / 10_000 != 0;
        t.pool.decayLp = (decayRest * pad.decay.autoLpBps + 5_000) / 10_000 != 0;
        // B12: the decay bucket is paid only while a fee decays; what is under the floor then, with no creator-side
        // share to lift it, would never leave
        if (t.pool.decayLp && !t.pool.creatorLp && (t.pool.buy.decaySecs | t.pool.sell.decaySecs) != 0) {
            revert S.HardBound(12);
        }
        x.lp = t.pool.creatorLp || t.pool.decayLp;
        _entries(p.feeRecipients.length, pad, t);
    }

    /// @dev B18 on what the ledger counts, a bucket's entries: the fee recipients (the launcher alone when none is
    ///      named), each pad payee with a share, and the distributor, the hook and the buyback where the launch
    ///      pays them. An upper bound (a recipient that is also a payee counts twice), never under the ledger's own.
    function _entries(uint256 n, IBankrLaunchpadRegistry.PadTerms memory pad, CoinTerms memory t) private pure {
        if (n == 0) n = 1;
        uint256 creator = n + (t.holdersBps != 0 ? 1 : 0) + (t.pool.creatorLp ? 1 : 0) + (t.buybackBps != 0 ? 1 : 0);
        uint256 decay = n + (t.pool.decayLp ? 1 : 0);
        for (uint256 i; i < pad.payees.length; ++i) {
            if (pad.payees[i] == TREASURY) continue;
            if (pad.steadySharesWad[i] != 0) ++creator;
            if (pad.decay.on && pad.decay.sharesWad[i] != 0) ++decay;
        }
        if (!pad.decay.on) decay = 0;
        uint256 most = t.takeover ? CTO_MAX_ENTRIES : 255;
        if (creator > most || decay > most) revert S.HardBound(18);
    }

    /// @dev One share list: its sum, and what it leaves of the remainder once the treasury marker's share is cut to
    ///      Bankr's bucket and the others are rescaled over what that cut leaves, rounded up (B4: the cut is under
    ///      the whole, and the parts fit it).
    function _split(address[] memory payees, uint256[] memory shares) private pure returns (uint256 sum, uint256 rest) {
        uint256 cut;
        for (uint256 i; i < shares.length; ++i) {
            sum += shares[i];
            if (payees[i] == TREASURY) cut = shares[i];
        }
        if (cut >= WAD) revert S.InvalidPayees();
        rest = WAD;
        for (uint256 i; i < shares.length; ++i) {
            if (payees[i] == TREASURY) continue;
            uint256 part = (shares[i] * WAD + (WAD - cut) - 1) / (WAD - cut);
            if (part > rest) revert S.InvalidPayees();
            rest -= part;
        }
    }

    /// @dev The pool's own compound and buyback terms (B12, B15, B16). A knob of a feature the launch leaves off
    ///      is not read, so a minimum never refuses a launch that does not use it.
    function _works(CoinTerms memory t, Ctx memory x) private view {
        if (x.lp) {
            _amounts(t, x);
            // forge-lint: disable-next-line(unsafe-typecast)
            t.pool.compoundInterval =
                uint32(_pick(x, Knobs.COMPOUND_INTERVAL_SECS, Knobs.OPT_COMPOUND_CADENCE, x.o.compoundInterval));
            // forge-lint: disable-next-line(unsafe-typecast)
            t.pool.compoundShareBps =
                uint16(_pick(x, Knobs.COMPOUND_SHARE_BPS, Knobs.OPT_COMPOUND_CADENCE, x.o.compoundShareBps));
            uint256 dev =
                _pick(x, Knobs.COMPOUND_DEVIATION_TICKS, Knobs.OPT_COMPOUND_CADENCE, x.o.compoundDeviationTicks);
            uint256 half = _pick(x, Knobs.BAND_HALF_WIDTH, Knobs.OPT_COMPOUND_BAND, x.o.bandHalfWidth);
            // forge-lint: disable-next-line(unsafe-typecast)
            t.pool.bandGrid = uint16(_pick(x, Knobs.BAND_GRID, Knobs.OPT_COMPOUND_BAND, x.o.bandGrid));
            // the compound's own buy may push the price by half of what a trader really pays, at most the owner's cap
            uint256 cap = x.steadySum * x.kept / 200e18;
            if (cap > x.g.compoundSwapMaxTicks) cap = x.g.compoundSwapMaxTicks;
            // B12: a gate wider than the band, or a round trip under 200 pips kept, and no compound ever runs
            if (dev > half * uint24(K.TICK_SPACING) || dev > type(uint16).max || cap == 0) revert S.HardBound(12);
            // forge-lint: disable-next-line(unsafe-typecast)
            (t.pool.compoundDeviationTicks, t.pool.bandHalfWidth) = (uint16(dev), uint16(half));
            // forge-lint: disable-next-line(unsafe-typecast)
            t.pool.swapCapTicks = uint16(cap);
        } else {
            _unset(x, Knobs.OPT_COMPOUND_AMOUNTS | Knobs.OPT_COMPOUND_CADENCE | Knobs.OPT_COMPOUND_BAND);
        }
        if (!t.pool.buyback) return _unset(x, Knobs.OPT_BUYBACK_CADENCE);
        // B15: a buy, trigger, sell around a fill must lose, or the coin's buyback budget is drained
        if (x.steadySum * x.kept < uint256(x.g.minRoundTripPips) * WAD) revert S.BuybackFeeTooLow();
        // forge-lint: disable-next-line(unsafe-typecast)
        t.pool.buybackInterval =
            uint32(_pick(x, Knobs.BUYBACK_INTERVAL_SECS, Knobs.OPT_BUYBACK_CADENCE, x.o.buybackInterval));
        // forge-lint: disable-next-line(unsafe-typecast)
        t.pool.buybackRetry = uint32(_pick(x, Knobs.BUYBACK_RETRY_SECS, Knobs.OPT_BUYBACK_CADENCE, x.o.buybackRetry));
        (t.pool.fillTravelTicks, t.pool.fillStartGapTicks) =
        (x.lp ? x.g.fillTravelCompoundingTicks : x.g.fillTravelTicks, x.g.fillStartGapTicks);
        // B16: a fill with no travel can never run, and the buyback's share has no other exit
        if (t.pool.fillTravelTicks == 0) revert S.HardBound(16);
    }

    /// @dev The launch's own floor and cap (flag 10), else the pad's for this quote, else the owner's row.
    function _amounts(CoinTerms memory t, Ctx memory x) private view {
        SettingsStore storage s = _s();
        uint256 floor_;
        uint256 cap;
        if (x.set & Knobs.OPT_COMPOUND_AMOUNTS != 0) {
            _flag(x, Knobs.F_LAUNCH_COMPOUND_AMOUNTS);
            (floor_, cap) = (x.o.compoundFloor, x.o.compoundCap);
        } else {
            PadQuoteTerms storage own = s.padQuotes[x.id][t.quote];
            QuoteTerms storage q = s.quotes[t.quote];
            (floor_, cap) = own.ownAmounts ? (own.compoundFloor, own.compoundCap) : (q.compoundFloor, q.compoundCap);
        }
        // B12: with no floor, a cap under it or a cap of one raw unit (which no band's two sides can share), every
        // compound reverts or never opens and the share strands
        if (floor_ == 0 || floor_ > cap || cap < 2) revert S.AutoLpNeedsCompoundTerms();
        // forge-lint: disable-next-line(unsafe-typecast)
        (t.pool.compoundFloor, t.pool.compoundCap) = (uint128(floor_), uint128(cap));
    }

    /// @dev The holders' stream (K28, K37) and B5: every clock of the launch fits the 40 bits the hook and the
    ///      distributor keep.
    function _stream(CoinTerms memory t, Ctx memory x) private view {
        // forge-lint: disable-next-line(unsafe-typecast)
        t.rewardStreamSecs = uint32(_pick(x, Knobs.REWARD_STREAM_SECS, Knobs.OPT_REWARD_STREAM, x.o.rewardStreamSecs));
        // forge-lint: disable-next-line(unsafe-typecast)
        t.rewardRestartBps = uint16(_pick(x, Knobs.REWARD_RESTART_BPS, Knobs.OPT_REWARD_STREAM, x.o.rewardRestartBps));
        uint256 start = t.startTime == 0 ? block.timestamp : t.startTime;
        if (
            start + t.vestToHoldersCliff + t.vestToHoldersDuration + t.rewardStreamSecs >= 1 << 40
                || start + t.capSecs >= 1 << 40
        ) revert S.HardBound(5);
    }

    /// @dev The extension's kind against the pad's flags, its allowlist key, and the binding's frozen ceiling and
    ///      cut. Founder ruling: an extension that can charge a fee launches only with the owner's stop granted for
    ///      that coin. With no extension the binding stays empty: the hook stores none.
    function _extension(LaunchParams calldata p, CoinTerms memory t, Ctx memory x) private view {
        LaunchExtension calldata e = p.extension;
        if (e.id == 0 && e.ext == address(0)) return _unset(x, Knobs.OPT_FEE_CEILING);
        SettingsStore storage s = _s();
        (t.pool.bankrNum, t.pool.bankrDen) = (s.protocol.extBankrNum, s.protocol.extBankrDen);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.pool.feeCeilingPips = uint24(_pick(x, Knobs.FEE_CEILING_PIPS, Knobs.OPT_FEE_CEILING, x.o.feeCeilingPips));
        // B1: the buyback's public fill sizes with the pool's ceiling on an extension pool
        if (t.pool.buyback && t.pool.feeCeilingPips > BUYBACK_MAX_FEE_PIPS) revert S.HardBound(1);
        t.pool.ownerSwitch = x.flags & Knobs.F_EXT_OWNER_SWITCH != 0;
        bytes32 key;
        // a preset's maxima are known only once its instance exists, so every preset counts as charging
        bool charges = true;
        if (e.id != 0) {
            _flag(x, Knobs.F_EXT_PRESETS);
            key = _preset(e, t, x);
        } else {
            _flag(x, e.quoteOnly ? Knobs.F_EXT_QUOTE_ONLY : Knobs.F_EXT_CALLS_OUT);
            key = _custom(p, e, t, x);
            charges = (e.maxBuyPips | e.maxSellPips) != 0;
        }
        if (charges) _flag(x, Knobs.F_EXT_OWNER_SWITCH);
        if (!s.extAllowed[key]) revert S.ExtensionNotAllowlisted();
    }

    /// @dev The launcher's own code as the hook will admit it (B13), with its budgets filled in and its payee
    ///      resolved as the factory resolves it. One encoding per term: a floor budget is never spelled out.
    function _custom(LaunchParams calldata p, LaunchExtension calldata e, CoinTerms memory t, Ctx memory x)
        private
        view
        returns (bytes32 key)
    {
        (uint24 qg, uint24 ag) = (e.quoteGas, e.afterGas);
        if (e.params.length != 0 || qg == K.EXT_QUOTE_GAS || ag == K.EXT_AFTER_GAS) {
            revert IBankrLaunchFactory.AmbiguousExtension();
        }
        // forge-lint: disable-next-line(unsafe-typecast)
        if (qg == 0) qg = uint24(K.EXT_QUOTE_GAS);
        // forge-lint: disable-next-line(unsafe-typecast)
        if (ag == 0 && !e.quoteOnly) ag = uint24(K.EXT_AFTER_GAS);
        // sha256 for a budget key, so no contract's code hash (keccak256) can equal one
        key = (e.quoteGas | e.afterGas) == 0 ? e.codehash : sha256(abi.encode(e.codehash, uint32(qg), uint32(ag)));
        t.pool.payee = _payee(p, x);
        if (
            !_admitted(e.ext, e.codehash) || t.pool.payee == address(0) || qg < K.EXT_QUOTE_GAS
                || qg > K.EXT_QUOTE_GAS_MAX
                || (e.quoteOnly ? ag != 0 : ag < K.EXT_AFTER_GAS || ag > K.EXT_AFTER_GAS_MAX)
        ) revert S.HardBound(13);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.extMaxPips =
            uint24(_under(x, Knobs.EXT_MAX_PIPS, e.maxBuyPips > e.maxSellPips ? e.maxBuyPips : e.maxSellPips));
        (t.pool.ext, t.pool.quoteGas, t.pool.afterGas, t.pool.codehash) = (e.ext, qg, ag, e.codehash);
        (t.pool.maxBuyPips, t.pool.maxSellPips) = (e.maxBuyPips, e.maxSellPips);
        (t.pool.quoteOnly, t.pool.sunsetSecs) = (e.quoteOnly, e.sunsetSecs);
    }

    /// @dev Real code at the pinned hash that does not start 0xEF: suite 3's admission rule, before the hook's own.
    function _admitted(address ext, bytes32 codehash) private view returns (bool ok) {
        uint256 first;
        assembly ("memory-safe") {
            mstore(0x00, 0)
            extcodecopy(ext, 0x00, 0x00, 0x01)
            first := byte(0, mload(0x00))
        }
        return ext.code.length != 0 && first != 0xEF && ext.codehash == codehash;
    }

    /// @dev An extension's payee as the factory resolves it: named, else the one fee recipient. With several
    ///      recipients no position stands in for it.
    function _payee(LaunchParams calldata p, Ctx memory x) private pure returns (address payee) {
        payee = p.extension.payee;
        if (payee != address(0)) return payee;
        if (p.feeRecipients.length > 1) revert IBankrLaunchFactory.ExtensionPayeeUnnamed();
        return p.feeRecipients.length == 0 ? x.launcher : p.feeRecipients[0].recipient;
    }

    /// @dev A preset names code, not only an id: the record's deployer and both code hashes ride in the terms, so a
    ///      deployer swapped under the same creation-code hash moves the hash a launch pinned. Its binding is the
    ///      factory's to fill; here, the word its constructor is handed (B14).
    function _preset(LaunchExtension calldata e, CoinTerms memory t, Ctx memory x) private view returns (bytes32) {
        SettingsStore storage s = _s();
        if (
            e.ext != address(0) || e.quoteOnly
                || (e.maxBuyPips | e.maxSellPips | e.sunsetSecs | e.quoteGas | e.afterGas) != 0
        ) revert IBankrLaunchFactory.AmbiguousExtension();
        PresetRecord memory r = s.presets[e.id];
        PresetLimits memory l = s.presetLimits[x.id][e.id];
        if (!r.active || !l.allowed) revert S.PresetOff(e.id);
        if (r.deployer.codehash != r.deployerCodeHash || (e.codehash != bytes32(0) && e.codehash != r.creationCodeHash))
        {
            revert S.PresetCodeChanged();
        }
        (t.presetId, t.presetCodeHash, t.presetDeployer) = (e.id, r.creationCodeHash, r.deployer);
        (t.presetDeployerCodeHash, t.presetSelfPayee) = (r.deployerCodeHash, r.selfPayee);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.extMaxPips = uint24(_under(x, Knobs.EXT_MAX_PIPS, 0));
        uint256 decay = t.pool.buy.decaySecs > t.pool.sell.decaySecs ? t.pool.buy.decaySecs : t.pool.sell.decaySecs;
        // Raffle Run's dust floor: a floor no pool reaches leaves its fees in the instance for good
        uint256 dust = s.quotes[t.quote].compoundFloor;
        if (dust < 1_000) dust = 1_000;
        if (dust > type(uint112).max) dust = type(uint112).max;
        // maxPips u24 | minWindowSecs u32 | maxWindowSecs u32 | minBrakeTicks i24 | minAnchorTau u32 | maxDustFloor u112
        t.presetSite = uint256(t.extMaxPips) | decay << 24 | uint256(l.maxWindowSecs) << 56
            | uint256(uint24(l.minBrakeTicks)) << 88 | uint256(l.minAnchorTau) << 112 | dust << 144;
        return keccak256(abi.encodePacked("preset", e.id, r.creationCodeHash));
    }

    /// @dev The start, in LaunchPricing: the table's form, the scheduled start, and on a listed quote the tick inside
    ///      the pad's FDV window and the coin's quote amounts inside B21 at that one price.
    function _start(LaunchParams calldata p, CoinTerms memory t, Ctx memory x) private view {
        uint256 amounts = uint256(t.pool.compoundCap) << 128 | t.quoteActivation;
        LaunchPricing.checkStart(
            LaunchPricing.Start(x.id, t.quote, t.totalSupply, p.expectedStartTick, t.startTime, p.curveId, amounts),
            p.priceAttestation
        );
    }

    /// @dev The curve against the pad's list: a built-in it left on, a table it lists, or any table when it leaves
    ///      them open. A launch's own table takes the pad's rules; a built-in is exempt, as in suite 3.
    function _curve(uint256 key, CoinTerms memory t, Ctx memory x) private view {
        if (!_curveOn(x, key) && (key < 3 || !_curveOn(x, ANY_CURVE))) revert S.CurveNotAllowedByLaunchpad();
        if (key <= RunnerCurve.CURVE_THIN_TOPSIDE) {
            t.curve.builtIn = true;
            return;
        }
        // forge-lint: disable-next-line(unsafe-typecast)
        t.curve.minDepthDiv = uint32(_range(x, Knobs.CURVE_MIN_DEPTH_DIV).dflt);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.curve.maxDensity = uint32(_range(x, Knobs.CURVE_MAX_DENSITY).dflt);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.curve.placeTicks = uint24(_range(x, Knobs.CURVE_PLACE_TICKS).dflt);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.curve.placeBps = uint16(_range(x, Knobs.CURVE_PLACE_BPS).dflt);
        // forge-lint: disable-next-line(unsafe-typecast)
        t.curve.dustPpm = uint32(_range(x, Knobs.CURVE_DUST_PPM).dflt);
        // B17: only where the pool may buy its own token (auto-LP, a buyback share, an extension the hook calls after
        // a swap; a preset's budget is known only once it is built), inside its compound half width (the pad's
        // default with none). LaunchPool asks the hook whether such buys run.
        if (!x.lp && !t.pool.buyback && t.pool.afterGas == 0 && t.presetId == 0) return;
        uint256 half = x.lp ? t.pool.bandHalfWidth : _range(x, Knobs.BAND_HALF_WIDTH).dflt;
        // forge-lint: disable-next-line(unsafe-typecast)
        (t.curve.nearStep, t.curve.nearTicks) = (x.g.curveNearStep, uint24(half * uint24(K.TICK_SPACING)));
    }

    function _curveOn(Ctx memory x, uint256 key) private view returns (bool) {
        return _s().curveFlip[x.id][key] != (key < 3);
    }
}

src/libraries/RunnerCurve.sol

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

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

/// @notice The launch curves (spec §10, H10) as constant tables of (width in ticks, share of the sale in bps) rows from
///         the pool's own start tick outward, at most MAX_BANDS contiguous bands, the last running to the usable edge.
///         A marketcap boundary `mc` of a curve starting at `start` sits 200·⌊log_1.0001(mc / start) / 200⌋ ticks from
///         the start tick (its exact tick floored to the 200 spacing), which gives runner_v1's 6,800 ($20K) and
///         6,800 + 110,000 ($1.2B) from $10K, and the degen pocket's 20,600 ($2.5K to $20K).
library RunnerCurve {
    uint8 internal constant CURVE_RUNNER_V1 = 0;
    uint8 internal constant CURVE_RUNNER_V1_DEGEN = 1; // runner_v1 with the pocket's start moved down to $2.5K
    uint8 internal constant CURVE_THIN_TOPSIDE = 2;
    uint256 internal constant MAX_BANDS = 8;
    // runner_v1 (dopplerLaunchConfig.ts runner_v1): $10K-$20K pocket, $20K-$1.2B backbone, the tail above
    int24 internal constant POCKET_TICKS = 6_800;
    int24 internal constant DEGEN_POCKET_TICKS = 20_600;
    int24 internal constant BACKBONE_TICKS = 110_000;
    uint16 internal constant POCKET_BPS = 300;
    uint16 internal constant BACKBONE_BPS = 9_500;
    uint16 internal constant TAIL_BPS = 200;

    struct Band {
        int24 lower;
        int24 upper;
        uint256 amount;
    }

    error UnknownCurve();

    /// @dev Curve 2 is Doppler's thin_topside_v3 with the v33 topside bump (DOPPLER_TOPSIDE_BUMP_CURVES.thin_topside_v3,
    ///      live with dopplerCurveTopsideBumpEnabled), eight rows as it stands: $10K-20K 3 %, -40K 35.65 %, -56K 4 %,
    ///      -120K 38.65 %, -480K 10 %, -12M 3 %, -1.2B 4.5 %, above 1.2 %; its boundaries sit at 6,800, 13,800, 17,200,
    ///      24,800, 38,600, 70,800 and 116,800 ticks.
    function table(uint8 curveId) internal pure returns (int24[] memory w, uint16[] memory bps) {
        if (curveId == CURVE_THIN_TOPSIDE) {
            w = new int24[](8);
            bps = new uint16[](8);
            w[0] = 6_800;
            bps[0] = 300;
            w[1] = 7_000;
            bps[1] = 3_565;
            w[2] = 3_400;
            bps[2] = 400;
            w[3] = 7_600;
            bps[3] = 3_865;
            w[4] = 13_800;
            bps[4] = 1_000;
            w[5] = 32_200;
            bps[5] = 300;
            w[6] = 46_000;
            bps[6] = 450;
            bps[7] = 120;
        } else if (curveId == CURVE_RUNNER_V1 || curveId == CURVE_RUNNER_V1_DEGEN) {
            w = new int24[](3);
            bps = new uint16[](3);
            w[0] = curveId == CURVE_RUNNER_V1 ? POCKET_TICKS : DEGEN_POCKET_TICKS;
            bps[0] = POCKET_BPS;
            w[1] = BACKBONE_TICKS;
            bps[1] = BACKBONE_BPS;
            bps[2] = TAIL_BPS;
        } else {
            revert UnknownCurve();
        }
    }

    /// @dev The curve's bands outward from the start tick: above spot when the token is currency0, mirrored below it when
    ///      it is currency1. Each band takes ⌊supply·bps / 1e4⌋ and the last the rest, so they sum to `supply` exactly.
    function bands(int24 startTick, bool tokenIsCurrency0, uint256 supply, uint8 curveId)
        internal
        pure
        returns (Band[] memory b)
    {
        (int24[] memory w, uint16[] memory bps) = table(curveId);
        uint256 n = w.length;
        b = new Band[](n);
        uint256 left = supply;
        int24 edge = startTick;
        for (uint256 i; i < n; ++i) {
            bool last = i + 1 == n;
            uint256 amount = last ? left : supply * bps[i] / 10_000;
            left -= amount;
            if (tokenIsCurrency0) {
                int24 next = last ? K.MAX_USABLE_TICK : edge + w[i];
                b[i] = Band(edge, next, amount);
                edge = next;
            } else {
                int24 next = last ? K.MIN_USABLE_TICK : edge - w[i];
                b[i] = Band(next, edge, amount);
                edge = next;
            }
        }
    }

    /// @dev One-sided liquidity for a band: the token is the only asset the launch positions hold.
    function liquidityFor(Band memory b, bool tokenIsCurrency0) internal pure returns (uint128) {
        uint160 lo = TickMath.getSqrtPriceAtTick(b.lower);
        uint160 hi = TickMath.getSqrtPriceAtTick(b.upper);
        return tokenIsCurrency0
            ? LiquidityAmounts.getLiquidityForAmount0(lo, hi, b.amount)
            : LiquidityAmounts.getLiquidityForAmount1(lo, hi, b.amount);
    }
}

src/libraries/SettingsCold.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {PricingMode} from "../interfaces/IBankrLaunchFactory.sol";
import {IBankrLaunchSettings as S} from "../interfaces/IBankrLaunchSettings.sol";
import {IBankrLaunchpadRegistry} from "../interfaces/IBankrLaunchpadRegistry.sol";
import {IChainlinkAggregatorV3} from "../interfaces/IChainlinkAggregatorV3.sol";
import {
    GuardTerms,
    Limit,
    PadConfig,
    PadQuoteTerms,
    PresetLimits,
    PresetRecord,
    ProtocolTerms,
    QuoteTerms,
    Range
} from "../interfaces/SuiteTypes.sol";
import {Knobs} from "./Knobs.sol";
import {LaunchPricing} from "./LaunchPricing.sol";
import {NAMED_PRESET_DEPLOYER, NAMED_QUOTE, SettingsRead, SettingsStore, TEMPLATE} from "./SettingsStore.sol";

interface IPadOperators {
    function operatorOf(uint64 id) external view returns (address);
}

interface IPresetCode {
    function creationCodeHash(uint8 id) external view returns (bytes32);
    function factory() external view returns (address);
}

/// @title SettingsCold
/// @notice Every setter of the settings contract, linked and delegatecalled so their bytes are not the contract's
///         (EIP-170). The contract forwards its own calldata: this code checks the caller and runs on the contract's
///         storage at slot 0. Nothing here is reachable from a live coin: a setter changes what the next launch gets.
library SettingsCold {
    using SettingsRead for SettingsStore;

    uint256 private constant CTO_MAX_ENTRIES = 64; // B18: a takeover settles every recipient in one transaction
    uint256 private constant MIN_ANCHOR_TAU = 21_600; // B14: Raffle Run's audited anchor is a floor
    uint256 private constant MAX_ANCHOR_TAU = 31_536_000; // B14: a floor over Raffle Run's own top admits no launch

    /// @dev The constructor's whole work. It runs with no code at the settings address yet, so nothing here asks the
    ///      contract for its factory or registry. Pad 0 starts as the template, then takes its own configuration.
    function init(S.SettingsInit memory i) external {
        SettingsStore storage s = _s();
        _storeProtocol(i.protocol);
        _setGuardTerms(i.guards);
        if (i.limits.length != Knobs.COUNT || i.templateKnobs.length != Knobs.COUNT) revert S.LengthMismatch();
        for (uint8 k; k < Knobs.COUNT; ++k) {
            _setLimit(k, i.limits[k]);
        }
        _setAllowedFlags(Knobs.F_ALL);
        for (uint8 k; k < Knobs.COUNT; ++k) {
            _setKnob(TEMPLATE, k, i.templateKnobs[k]);
        }
        _setTemplateFlags(i.templateFlags, i.templateCapController);
        _setWaiver(TEMPLATE, true);
        s.presetTop = 4;
        for (uint8 p = 1; p <= 4; ++p) {
            _setPreset(p, i.presets[p - 1]);
            _setPresetLimits(TEMPLATE, p, i.templatePresetLimits[p - 1]);
        }
        for (uint256 n; n < i.allowedKeys.length; ++n) {
            _setExtensionAllowed(i.allowedKeys[n], true);
        }
        s.inited[0] = true;
        _copyTemplate(0);
        _configure(0, i.bankrPad);
        _setWaiver(0, false);
        _checkCut();
    }

    function _s() private pure returns (SettingsStore storage s) {
        assembly ("memory-safe") {
            s.slot := 0
        }
    }

    function _onlyOwner() private view {
        if (msg.sender != Ownable(S(address(this)).factory()).owner()) revert S.NotOwner();
    }

    /// @dev A pad's operator; pad 0's is the owner. The template's id is no pad, so no operator reaches its rows.
    function _onlyOperator(uint64 id) private view {
        if (!_s().inited[id]) revert S.UnknownLaunchpad();
        if (id == 0) return _onlyOwner();
        if (msg.sender != IPadOperators(S(address(this)).registry()).operatorOf(id)) revert S.NotOperator();
    }

    // ── owner ────────────────────────────────────────────────────────────────

    function setProtocolTerms(ProtocolTerms calldata t) external {
        _onlyOwner();
        _storeProtocol(t);
        _checkCut();
    }

    function setGuardTerms(GuardTerms calldata g) external {
        _onlyOwner();
        _setGuardTerms(g);
    }

    function setBnkrPairWaiver(uint64 padId, bool waived) external {
        _onlyOwner();
        if (padId != TEMPLATE && !_s().inited[padId]) revert S.UnknownLaunchpad();
        _setWaiver(padId, waived);
    }

    function setLimits(uint8[] calldata knobs, Limit[] calldata limits_) external {
        _onlyOwner();
        if (knobs.length != limits_.length) revert S.LengthMismatch();
        for (uint256 i; i < knobs.length; ++i) {
            _setLimit(knobs[i], limits_[i]);
        }
        _checkCut();
    }

    function setTemplate(uint8[] calldata knobs, Range[] calldata ranges, uint256 flags, address capController)
        external
    {
        _onlyOwner();
        _setKnobs(TEMPLATE, knobs, ranges);
        _setTemplateFlags(flags, capController);
        _checkPad(TEMPLATE);
    }

    function setTemplatePresetLimits(uint8 presetId, PresetLimits calldata l) external {
        _onlyOwner();
        _setPresetLimits(TEMPLATE, presetId, l);
    }

    function setAllowedFlags(uint256 flags) external {
        _onlyOwner();
        _setAllowedFlags(flags);
    }

    /// @dev List, update or re-price in one call, at once: each coin carries its own copy of these numbers. A row is
    ///      a listed quote; `removeQuote` unlists.
    function setQuote(address quote, QuoteTerms calldata t) external {
        _onlyOwner();
        SettingsStore storage s = _s();
        if (!t.allowed) revert S.QuoteNotAllowed();
        // B21: a coin freezes these for life, and the reward buffer is a uint112
        if (
            t.quoteActivation >= 1 << 112
                || (t.compoundFloor != 0 && (t.quoteActivation > t.compoundFloor || t.compoundFloor > t.compoundCap))
        ) revert S.QuoteAmountsOutOfRange();
        if (t.mode != PricingMode.NONE) _checkPricing(quote, t);
        if (!s.quotes[quote].allowed) s.quoteList.push(quote);
        s.quotes[quote] = t;
        s.named[quote] |= NAMED_QUOTE; // for good: a removed quote still has live pools
        emit S.QuoteSet(quote, t);
    }

    function removeQuote(address quote) external {
        _onlyOwner();
        SettingsStore storage s = _s();
        if (!s.quotes[quote].allowed) revert S.QuoteNotAllowed();
        uint256 n = s.quoteList.length;
        for (uint256 i; i < n; ++i) {
            if (s.quoteList[i] == quote) {
                s.quoteList[i] = s.quoteList[n - 1];
                s.quoteList.pop();
                break;
            }
        }
        delete s.quotes[quote];
        emit S.QuoteRemoved(quote);
    }

    function setPriceSigner(address signer) external {
        _onlyOwner();
        _s().priceSigner = signer;
        emit S.PriceSignerSet(signer);
    }

    /// @dev Probed as suite 3 does: a feed that does not answer 0 or 1 with a sane startedAt is no sequencer feed.
    function setSequencerUptimeFeed(address feed, uint32 graceSecs) external {
        _onlyOwner();
        SettingsStore storage s = _s();
        if (feed != address(0)) {
            if (feed.code.length == 0) revert S.InvalidPricing();
            (, int256 answer, uint256 startedAt,,) = IChainlinkAggregatorV3(feed).latestRoundData();
            if ((answer != 0 && answer != 1) || startedAt == 0 || startedAt > block.timestamp) {
                revert S.InvalidPricing();
            }
        }
        (s.sequencerFeed, s.sequencerGrace) = (feed, graceSecs);
        emit S.SequencerUptimeFeedSet(feed, graceSecs);
    }

    /// @dev The record makes a deployer suite code for good, so only one built for this factory, with no code for
    ///      id 0, is taken: a contract that answers every call with one word (a live payee's fallback) never is.
    function setPreset(uint8 presetId, PresetRecord calldata r) external {
        _onlyOwner();
        address d = r.deployer;
        if (
            d != address(0)
                && (_word(d, IPresetCode.factory.selector) != uint160(S(address(this)).factory())
                    || _word(d, IPresetCode.creationCodeHash.selector) != 0)
        ) revert S.PresetCodeChanged();
        _setPreset(presetId, r);
    }

    /// @dev One word of `target`'s answer to `sel` with a zero argument, read leniently: 0 when it does not answer
    ///      with exactly a word.
    function _word(address target, bytes4 sel) private view returns (uint256 w) {
        (bool ok, bytes memory ret) = target.staticcall(abi.encodeWithSelector(sel, uint256(0)));
        // forge-lint: disable-next-line(unsafe-typecast)
        if (ok && ret.length == 32) w = uint256(bytes32(ret));
    }

    function setExtensionAllowed(bytes32 key, bool allowed) external {
        _onlyOwner();
        _setExtensionAllowed(key, allowed);
    }

    // ── a pad's operator ─────────────────────────────────────────────────────

    function configure(uint64 id, PadConfig calldata c) external {
        _onlyOperator(id);
        _configure(id, c);
    }

    function setKnobs(uint64 id, uint8[] calldata knobs, Range[] calldata ranges) external {
        _onlyOperator(id);
        _setKnobs(id, knobs, ranges);
        _checkPad(id);
    }

    function setFlags(uint64 id, uint256 flags) external {
        _onlyOperator(id);
        _setFlags(id, flags);
        _checkPad(id);
    }

    function setPayees(uint64 id, IBankrLaunchpadRegistry.PadTerms calldata terms) external {
        _onlyOperator(id);
        if (id == 0) revert S.BankrPadIsPreset();
        _setPayees(id, terms);
    }

    function setCapController(uint64 id, address controller) external {
        _onlyOperator(id);
        _setCapController(id, controller);
    }

    /// @dev `allowed` puts the quote on the pad's own list (a pad with an empty list takes every quote); `ownAmounts`
    ///      gives its coins on that quote the pad's compound floor and cap in place of the owner's row.
    function setQuoteTerms(uint64 id, address quote, PadQuoteTerms calldata t) external {
        _onlyOperator(id);
        SettingsStore storage s = _s();
        if (t.ownAmounts ? t.compoundFloor > t.compoundCap : (t.compoundFloor | t.compoundCap) != 0) {
            revert S.QuoteAmountsOutOfRange();
        }
        if (t.ownAmounts) {
            // B21 where the quote is priced: a listed quote whose feed answers now
            QuoteTerms storage q = s.quotes[quote];
            if (q.mode == PricingMode.CHAINLINK) {
                (bool ok, uint256 px) = LaunchPricing._feedUsdE18(q.feed, q.maxPriceAge);
                if (ok) _checkUsd(t.compoundCap, px, q.decimals);
            }
        }
        bool was = s.padQuotes[id][quote].allowed;
        if (t.allowed != was) s.padQuoteCount[id] = t.allowed ? s.padQuoteCount[id] + 1 : s.padQuoteCount[id] - 1;
        s.padQuotes[id][quote] = t;
        emit S.PadQuoteSet(id, quote, t);
    }

    function setCurveAllowed(uint64 id, uint256 key, bool allowed) external {
        _onlyOperator(id);
        _s().curveFlip[id][key] = allowed != (key < 3);
        emit S.PadCurveSet(id, key, allowed);
    }

    function setPresetLimits(uint64 id, uint8 presetId, PresetLimits calldata l) external {
        _onlyOperator(id);
        _setPresetLimits(id, presetId, l);
    }

    /// @dev The registry, from register(): the template copied into the pad's own rows, each logged, so a pad's
    ///      state is the fold of the events that carry its id and a later setTemplate never moves it. Takeover is
    ///      masked out whatever the template holds: only the pad's own operator switches it on (founder ruling).
    function initPad(uint64 id, IBankrLaunchpadRegistry.PadTerms calldata terms) external {
        SettingsStore storage s = _s();
        if (msg.sender != S(address(this)).registry()) revert S.NotRegistry();
        if (id == TEMPLATE || s.inited[id]) revert S.UnknownLaunchpad();
        s.inited[id] = true;
        _copyTemplate(id);
        _writeFlags(id, s.flags[TEMPLATE] & s.allowedFlags & ~Knobs.F_TAKEOVER);
        _setCapController(id, s.capController[TEMPLATE]);
        _setPayees(id, terms);
        _setWaiver(id, s.waiver[TEMPLATE]);
    }

    // ── internals ────────────────────────────────────────────────────────────

    function _storeProtocol(ProtocolTerms memory t) private {
        // B4 (shares of a whole), B7 (the audited floors: divisors, the takeover notice), B18 (payees fit a launch)
        if (
            t.bankrFeeBps > 10_000 || t.holdersShareBps > 10_000 || t.extBankrDen == 0 || t.extBankrNum > t.extBankrDen
                || t.ctoNotice < 3_600 || t.ctoGrace == 0 || t.tokenActivationDivisor < 10_000
                || t.bnkrActivationDivisor < 10_000_000 || t.maxPadPayees > 16
        ) revert S.InvalidProtocolTerms();
        _s().protocol = t;
        emit S.ProtocolTermsSet(t);
    }

    /// @dev B2: Bankr's slice beside the referrer's, and its floor inside what the referrer leaves of the fee.
    function _fits(ProtocolTerms memory t, uint256 steadyPips, uint256 referrerBps) private pure returns (bool) {
        return uint256(t.bankrFeeBps) + referrerBps <= 10_000
            && uint256(t.bankrMinPips) * 10_000 <= steadyPips * (10_000 - referrerBps);
    }

    function _fitsRow(ProtocolTerms memory t, uint64 id) private view returns (bool) {
        SettingsStore storage s = _s();
        return _fits(t, s.knobs[id][Knobs.STEADY_PIPS].min, s.knobs[id][Knobs.REFERRER_BPS].max);
    }

    /// @dev Founder ruling: a cut that does not fit the fee is refused when it is set. The owner's side: the cut fits
    ///      somewhere inside the limits, and inside the whole fee range of the two rows the owner holds, the
    ///      template and pad 0. Another pad's row is held by `_checkPad` when it is set and by the launch check.
    function _checkCut() private view {
        SettingsStore storage s = _s();
        ProtocolTerms memory t = s.protocol;
        (, uint64 steadyMax) = s.limit(Knobs.STEADY_PIPS);
        (uint64 referrerMin,) = s.limit(Knobs.REFERRER_BPS);
        if (!_fits(t, steadyMax, referrerMin) || !_fitsRow(t, TEMPLATE) || !_fitsRow(t, 0)) {
            revert S.BankrCutDoesNotFit();
        }
    }

    /// @dev What a pad's row must hold as a whole, after any change to its knobs or flags: every fee it admits
    ///      carries Bankr's cut (its lowest fee beside its highest referrer rate), and a pad whose coins can be taken
    ///      over names no more fee recipients than a takeover settles (B18).
    function _checkPad(uint64 id) private view {
        SettingsStore storage s = _s();
        if (!_fitsRow(s.protocol, id)) revert S.BankrCutDoesNotFit();
        if (s.flags[id] & Knobs.F_TAKEOVER != 0 && s.knobs[id][Knobs.FEE_RECIPIENTS].max > CTO_MAX_ENTRIES) {
            revert S.KnobOutOfRange(Knobs.FEE_RECIPIENTS);
        }
    }

    function _setGuardTerms(GuardTerms memory g) private {
        // B16: travel and the fee it is measured against move together; B17 and the audited figures are floors
        if (
            g.refTauSecs < 1_800 || g.compoundSwapMaxTicks == 0 || uint256(g.fillTravelTicks) * 100 > g.minRoundTripPips
                || (uint256(g.fillTravelCompoundingTicks) + g.compoundSwapMaxTicks) * 100 > g.minRoundTripPips
                || g.curveNearStep == 0 || g.curveNearStep > 13 || g.maxCompoundUsd == 0
        ) revert S.InvalidGuardTerms();
        _s().guards = g;
        emit S.GuardTermsSet(g);
    }

    function _setWaiver(uint64 padId, bool waived) private {
        _s().waiver[padId] = waived;
        emit S.BnkrPairWaiverSet(padId, waived);
    }

    function _setAllowedFlags(uint256 flags) private {
        if (flags & ~Knobs.F_ALL != 0) revert S.FlagNotAllowed(flags & ~Knobs.F_ALL);
        _s().allowedFlags = flags;
        emit S.AllowedFlagsSet(flags);
    }

    function _setExtensionAllowed(bytes32 key, bool allowed) private {
        _s().extAllowed[key] = allowed;
        emit S.ExtensionAllowedSet(key, allowed);
    }

    function _setLimit(uint8 knob, Limit memory l) private {
        SettingsStore storage s = _s();
        (uint64 lo, uint64 hi) = Knobs.hardBounds(knob);
        if (l.min < lo || l.max > hi || l.min > l.max) revert S.KnobOutOfRange(knob);
        // a limit at the hard range needs no read at launch
        if (l.min == lo && l.max == hi) s.limitBitmap &= ~(uint256(1) << knob);
        else s.limitBitmap |= uint256(1) << knob;
        s.limits[knob] = l;
        emit S.LimitSet(knob, l.min, l.max);
    }

    function _setKnobs(uint64 id, uint8[] calldata knobs, Range[] calldata ranges) private {
        if (knobs.length != ranges.length) revert S.LengthMismatch();
        for (uint256 i; i < knobs.length; ++i) {
            // pad 0's payee shares are sized for its fee: K0 to K3 and the payees move in one configure, so no
            // launch lands between them (review C finding 2)
            uint8 knob = knobs[i];
            if (id == 0 && knob <= Knobs.REFERRER_BPS) revert S.BankrPadIsPreset();
            _setKnob(id, knob, ranges[i]);
        }
    }

    /// @dev hard.lo <= limit.min <= min <= dflt <= max <= limit.max <= hard.hi
    function _setKnob(uint64 id, uint8 knob, Range memory r) private {
        (uint64 lo, uint64 hi) = _s().limit(knob);
        if (r.min < lo || r.max > hi || r.min > r.dflt || r.dflt > r.max) revert S.KnobOutOfRange(knob);
        _writeKnob(id, knob, r);
    }

    function _writeKnob(uint64 id, uint8 knob, Range memory r) private {
        _s().knobs[id][knob] = r;
        if (id == TEMPLATE) emit S.TemplateKnobSet(knob, r.min, r.max, r.dflt);
        else emit S.PadKnobSet(id, knob, r.min, r.max, r.dflt);
    }

    function _setTemplateFlags(uint256 flags, address capController) private {
        SettingsStore storage s = _s();
        uint256 refused = flags & (~s.allowedFlags | Knobs.F_TAKEOVER);
        if (refused != 0) revert S.FlagNotAllowed(refused);
        (s.flags[TEMPLATE], s.capController[TEMPLATE]) = (flags, capController);
        emit S.TemplateFlagsSet(flags, capController);
    }

    function _setFlags(uint64 id, uint256 flags) private {
        uint256 refused = flags & ~_s().allowedFlags;
        if (refused != 0) revert S.FlagNotAllowed(refused);
        _writeFlags(id, flags);
    }

    function _writeFlags(uint64 id, uint256 flags) private {
        _s().flags[id] = flags;
        emit S.PadFlagsSet(id, flags);
    }

    /// @dev 0 to maxPadPayees distinct payees; steady and decay shares each summing to at most the owner's limit on
    ///      a pad's share (K36, never above the whole remainder); the decay split off is one encoding.
    function _setPayees(uint64 id, IBankrLaunchpadRegistry.PadTerms memory t) private {
        SettingsStore storage s = _s();
        uint256 n = t.payees.length;
        (, uint256 most) = s.limit(Knobs.PAD_SHARE_BPS);
        most *= 1e14;
        bool bad = n > s.protocol.maxPadPayees || t.steadySharesWad.length != n || _sum(t.steadySharesWad) > most
            || (t.decay.on
                    ? t.decay.sharesWad.length != n || _sum(t.decay.sharesWad) > most || t.decay.autoLpBps > 10_000
                    : t.decay.sharesWad.length != 0 || t.decay.autoLpBps != 0);
        for (uint256 i; i < n && !bad; ++i) {
            bad = t.payees[i] == address(0);
            for (uint256 j; j < i && !bad; ++j) {
                bad = t.payees[j] == t.payees[i];
            }
        }
        if (bad) revert S.InvalidPayees();
        s.payees[id] = t;
        emit S.PadPayeesSet(id, t);
    }

    /// @dev Saturates on a share above the whole, so the caller's comparison refuses it and the sum cannot wrap.
    function _sum(uint256[] memory a) private pure returns (uint256 total) {
        for (uint256 i; i < a.length; ++i) {
            if (a[i] > 1e18) return type(uint256).max;
            total += a[i];
        }
    }

    function _setCapController(uint64 id, address controller) private {
        _s().capController[id] = controller;
        emit S.PadCapControllerSet(id, controller);
    }

    function _setPresetLimits(uint64 id, uint8 presetId, PresetLimits memory l) private {
        if (presetId == 0 || presetId > _s().presetTop) revert S.PresetOff(presetId);
        if (l.allowed && (l.minAnchorTau < MIN_ANCHOR_TAU || l.minAnchorTau > MAX_ANCHOR_TAU)) revert S.HardBound(14);
        _writePresetLimits(id, presetId, l);
    }

    function _writePresetLimits(uint64 id, uint8 presetId, PresetLimits memory l) private {
        _s().presetLimits[id][presetId] = l;
        if (id == TEMPLATE) emit S.TemplatePresetLimitsSet(presetId, l);
        else emit S.PadPresetLimitsSet(id, presetId, l);
    }

    /// @dev A mistake check, not a trust boundary: the launch check compares the deployer's code with the record
    ///      again. A record with no deployer is the cleared id and carries nothing. Ids are taken in order, so the
    ///      rows a new pad copies grow one preset at a time.
    function _setPreset(uint8 presetId, PresetRecord memory r) private {
        SettingsStore storage s = _s();
        if (presetId == 0 || presetId > uint256(s.presetTop) + 1) revert S.PresetOff(presetId);
        address d = r.deployer;
        if (d == address(0)) {
            if (r.active || r.selfPayee || (r.deployerCodeHash | r.creationCodeHash) != 0) {
                revert S.PresetCodeChanged();
            }
        } else {
            if (d.code.length == 0 || d.codehash != r.deployerCodeHash) revert S.PresetCodeChanged();
            try IPresetCode(d).creationCodeHash(presetId) returns (bytes32 h) {
                if (h == bytes32(0) || h != r.creationCodeHash) revert S.PresetCodeChanged();
            } catch {
                revert S.PresetCodeChanged();
            }
            // for good, from this call: suite code no launch may pay, used by a launch yet or not (r3 F-1, H13 R2-5)
            s.named[d] |= NAMED_PRESET_DEPLOYER;
        }
        if (presetId > s.presetTop) s.presetTop = presetId;
        s.presets[presetId] = r;
        emit S.PresetSet(presetId, r);
    }

    function _configure(uint64 id, PadConfig memory c) private {
        if (c.knobs.length != c.ranges.length || c.presetIds.length != c.presetLimits.length) {
            revert S.LengthMismatch();
        }
        for (uint256 i; i < c.knobs.length; ++i) {
            _setKnob(id, c.knobs[i], c.ranges[i]);
        }
        _setFlags(id, c.flags);
        _setCapController(id, c.capController);
        _setPayees(id, c.terms);
        for (uint256 i; i < c.presetIds.length; ++i) {
            _setPresetLimits(id, c.presetIds[i], c.presetLimits[i]);
        }
        _checkPad(id);
    }

    function _copyTemplate(uint64 id) private {
        SettingsStore storage s = _s();
        for (uint8 k; k < Knobs.COUNT; ++k) {
            _writeKnob(id, k, s.knobs[TEMPLATE][k]);
        }
        uint256 top = s.presetTop;
        for (uint256 p = 1; p <= top; ++p) {
            // p <= presetTop, a uint8
            // forge-lint: disable-next-line(unsafe-typecast)
            _writePresetLimits(id, uint8(p), s.presetLimits[TEMPLATE][p]);
        }
    }

    /// @dev A priced row answers when it is set (B7: an age of 0 never answers; decimals above 18 overflow the FDV
    ///      numerator), and on a feed its amounts are worth at most the owner's guard (B21).
    function _checkPricing(address quote, QuoteTerms calldata t) private view {
        if (t.maxPriceAge == 0 || t.decimals != LaunchPricing._decimals(quote)) revert S.InvalidPricing();
        if (t.mode == PricingMode.SIGNED) {
            if (t.feed != address(0)) revert S.InvalidPricing();
            return;
        }
        (bool ok, uint256 px) = LaunchPricing._feedUsdE18(t.feed, t.maxPriceAge);
        if (!ok) revert S.InvalidPricing();
        try IChainlinkAggregatorV3(t.feed).description() returns (string memory d) {
            if (bytes(d).length == 0) revert S.InvalidPricing();
        } catch {
            revert S.InvalidPricing();
        }
        _checkUsd(t.compoundCap > t.quoteActivation ? t.compoundCap : t.quoteActivation, px, t.decimals);
    }

    /// @dev `amount` of a quote with `dec` decimals at `px` (USD per whole token, 1e18) against the owner's ceiling.
    function _checkUsd(uint256 amount, uint256 px, uint256 dec) private view {
        if (Math.mulDiv(amount, px, 10 ** (18 + dec)) > _s().guards.maxCompoundUsd) revert S.QuoteAmountsOutOfRange();
    }
}

src/libraries/SettingsStore.sol

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

import {IBankrLaunchpadRegistry} from "../interfaces/IBankrLaunchpadRegistry.sol";
import {
    GuardTerms,
    Limit,
    PadQuoteTerms,
    PresetLimits,
    PresetRecord,
    ProtocolTerms,
    QuoteTerms,
    Range
} from "../interfaces/SuiteTypes.sol";
import {Knobs} from "./Knobs.sol";

/// @dev The settings contract's whole storage, at slot 0: its linked libraries run on it by delegatecall.
struct SettingsStore {
    ProtocolTerms protocol;
    GuardTerms guards;
    uint256 limitBitmap; // bit k: knob k's limit differs from its hard range, so a reader loads the row only then
    uint256 allowedFlags;
    address priceSigner;
    address sequencerFeed;
    uint32 sequencerGrace;
    uint8 presetTop; // preset ids 1..presetTop have had a record: what a new pad copies and padConfig lists
    mapping(uint256 => Limit) limits;
    // keyed by pad id; TEMPLATE is the row a new pad copies
    mapping(uint64 => mapping(uint256 => Range)) knobs;
    mapping(uint64 => uint256) flags;
    mapping(uint64 => bool) inited;
    mapping(uint64 => bool) waiver;
    mapping(uint64 => address) capController;
    mapping(uint64 => IBankrLaunchpadRegistry.PadTerms) payees;
    mapping(uint64 => mapping(address => PadQuoteTerms)) padQuotes;
    mapping(uint64 => uint256) padQuoteCount; // 0: the pad takes every quote
    // true where a pad's key departs from its default: a built-in curve (0..2) is allowed, anything else refused
    mapping(uint64 => mapping(uint256 => bool)) curveFlip;
    mapping(uint64 => mapping(uint256 => PresetLimits)) presetLimits;
    mapping(uint256 => PresetRecord) presets;
    mapping(bytes32 => bool) extAllowed;
    mapping(address => QuoteTerms) quotes;
    address[] quoteList;
    // What the owner has ever named an address as (NAMED_*), kept through a removal or a new record: the factory
    // takes neither kind as its treasury, and a preset's deployer is suite code no launch may pay.
    mapping(address => uint256) named;
}

uint256 constant NAMED_QUOTE = 1;
uint256 constant NAMED_PRESET_DEPLOYER = 2;

/// @dev The pad id of the template: no pad can hold it, and the owner's waiver default is set under it.
uint64 constant TEMPLATE = type(uint64).max;

library SettingsRead {
    /// @dev A knob's outer range: the owner's row where the bitmap marks one, else the compiled hard range.
    function limit(SettingsStore storage s, uint8 knob) internal view returns (uint64 lo, uint64 hi) {
        if (s.limitBitmap >> knob & 1 == 0) return Knobs.hardBounds(knob);
        Limit storage l = s.limits[knob];
        return (l.min, l.max);
    }

    /// @dev A pad's knob as a launch meets it: the overlap of the pad's range and the owner's limit, or the nearest
    ///      edge of the limit when the owner has since moved it past the pad's row, the default clamped inside.
    function range(SettingsStore storage s, uint64 id, uint8 knob) internal view returns (Range memory r) {
        r = s.knobs[id][knob];
        if (s.limitBitmap >> knob & 1 == 0) return r;
        Limit memory l = s.limits[knob];
        if (r.min < l.min) r.min = l.min;
        if (r.min > l.max) r.min = l.max;
        if (r.max > l.max) r.max = l.max;
        if (r.max < l.min) r.max = l.min;
        if (r.dflt < r.min) r.dflt = r.min;
        if (r.dflt > r.max) r.dflt = r.max;
    }
}
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.