Skip to content
Verified contractExactMIT

LaunchRegistry

Address0x93d8ec767b641d7ca6fef1544a1911fa24f4fb86
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

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

43 files

src/libraries/LaunchRegistry.sol

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

import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {Currency} from "@uniswap/v4-core/src/types/Currency.sol";
import {
    IBankrLaunchFactory,
    LaunchParams,
    FeeRecipient,
    LaunchEconomics as Economics
} from "../interfaces/IBankrLaunchFactory.sol";
import {IBankrFeeLedger} from "../interfaces/IBankrFeeLedger.sol";
import {IBankrLaunchHook, ExtBinding} from "../interfaces/IBankrLaunchHook.sol";
import {CoinTerms} from "../interfaces/SuiteTypes.sol";
import {IBankrLaunchpadRegistry} from "../interfaces/IBankrLaunchpadRegistry.sol";
import {IBankrPresetDeployer} from "../interfaces/IBankrPreset.sol";
import {BucketIds} from "./BucketIds.sol";
import {FeeMath} from "./FeeMath.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";
import {LaunchEconomics as EconomicsCheck} from "./LaunchEconomics.sol";

/// @dev The hook's periphery getters, read by selector: a hook generation without one is simply not matched.
interface IHookPeriphery {
    function guardLens() external view returns (address);
    function claimsRedeemer() external view returns (address);
    function hookLens() external view returns (address);
}

/// @dev The pointers a hook generation and the factory must share (the hook's immutables, the factory's getters),
///      and what a generation's periphery answers as the contract it is named as.
interface ISuitePointers {
    function poolManager() external view returns (address);
    function ledger() external view returns (address);
    function factory() external view returns (address);
    function hook() external view returns (address);
}

/// @dev What a holder leg and its references answer for wireLeg, read by selector.
interface ILegPointers {
    function ledger() external view returns (address);
    function distributorDeployer() external view returns (address);
    function references() external view returns (address);
    function isReferenced(address asset) external view returns (bool);
    function TWAP_WINDOW() external view returns (uint32);
}

/// @notice External (delegatecalled) library holding the factory's suite record (its hook generations, and what
///         isSuite never asks again) and a launch's registration: its record with its launchpad, its payee checks,
///         a preset's checked deploy, the hook's pool record, the ledger's buckets and split terms, and the freeze of
///         the coin's terms. Every number comes from the settings contract's resolve (`terms`); nothing here reads
///         a setting. Split out of BankrLaunchFactory for EIP-170. It runs in the factory's context: events carry
///         the factory's address, and the ledger, hooks and preset deployers see the factory as msg.sender.
library LaunchRegistry {
    using PoolIdLibrary for PoolKey;

    /// @dev The hook generations and isSuite's record, written when a generation or a leg is wired or an instance
    ///      bound and never asked again (R7-05): every hook generation with its claims redeemer and lenses, every
    ///      holder leg with its references, every preset deployer a launch used and each instance bound.
    struct Suite {
        address[] hooks; // every hook generation wired, oldest first; a launch registers on the newest
        mapping(address => bool) suite;
        // the code of each generation's claims redeemer and guard lens, recorded with it: _checkPayees refuses copies
        mapping(bytes32 => bool) suiteCode;
    }

    /// @dev One launch's registration, in memory: every boundary below takes this, never a longer argument list.
    struct Reg {
        PoolKey key;
        address token;
        address hook;
        Payees w;
        Shares s;
        address inst; // this launch's preset instance, 0 without one
    }

    // Word offsets into resolve's result, abi.encode(CoinTerms, bytes32 resolvedHash, address expectedToken,
    // PadTerms): CoinTerms is all static, 91 words, its PoolInit at word 40 (test/unit/LaunchTermsOffsets.t.sol).
    uint256 internal constant W_PRESET_ID = 7;
    uint256 internal constant W_PRESET_DEPLOYER = 9;
    uint256 internal constant W_PRESET_SELF = 11;
    uint256 internal constant W_PRESET_SITE = 12;
    uint256 internal constant W_POOL = 40;
    uint256 internal constant W_RESOLVED_HASH = 91;
    uint256 internal constant TERMS_BYTES = 91 * 32;

    // ── wiring: hook generations and holder legs ─────────────────────────────

    /// @dev A new generation joins the list and takes every launch from now on. Nothing is pushed to it: a pool is
    ///      handed its own terms at its launch and keeps them.
    function wireHook(Suite storage q, address hook) external {
        // An account answers nothing: refused by name, before any call to it.
        if (hook.code.length == 0) revert IBankrLaunchFactory.InvalidHook();
        // A generation on another ledger or PoolManager would take launches whose first trade reverts, their LP locked
        // for good (audit r6 OPS-2). Under delegatecall this is the factory, so it answers its own getters.
        ISuitePointers h = ISuitePointers(hook);
        ISuitePointers f = ISuitePointers(address(this));
        address pm = f.poolManager();
        if (h.factory() != address(this) || h.ledger() != f.ledger() || h.poolManager() != pm) {
            revert IBankrLaunchFactory.InvalidHook();
        }
        q.hooks.push(hook);
        q.suite[hook] = true;
        _recordPeriphery(q, hook, IHookPeriphery.claimsRedeemer.selector, ISuitePointers.poolManager.selector, pm);
        _recordPeriphery(q, hook, IHookPeriphery.guardLens.selector, ISuitePointers.poolManager.selector, pm);
        _recordPeriphery(q, hook, IHookPeriphery.hookLens.selector, ISuitePointers.hook.selector, hook);
    }

    /// @dev Read once, here, leniently (a generation without the getter names nothing): a generation that later
    ///      names other addresses can no longer reach isSuite (R7-05). The record makes an address a puller on the
    ///      ledger for good, so what is named joins it only if the generation built it itself (`_builtBy`) and it
    ///      answers as that contract does (`probe` with `answer`): a generation's word never reaches a live payee,
    ///      whatever the payee answers. A redeemer's or guard lens's code is refused as a payee.
    function _recordPeriphery(Suite storage q, address hook, bytes4 getter, bytes4 probe, address answer) private {
        (bool ok, bytes memory r) = hook.staticcall(abi.encodeWithSelector(getter));
        if (!ok || r.length != 32) return;
        // an address word: dirty high bits only name another account, which the checks below refuse
        // forge-lint: disable-next-line(unsafe-typecast)
        address a = address(uint160(uint256(bytes32(r))));
        if (a == address(0)) return; // names none
        if (!_builtBy(hook, a) || _word(a, abi.encodeWithSelector(probe)) != uint160(answer)) {
            revert IBankrLaunchFactory.InvalidHook();
        }
        q.suite[a] = true;
        if (probe != ISuitePointers.hook.selector) q.suiteCode[a.codehash] = true;
    }

    /// @dev Whether `a` is one of `hook`'s first three CREATE addresses (nonces 1 to 3), where its constructor
    ///      builds its guard lens, claims redeemer and hook lens: rlp([hook, nonce]) is 0xd6, 0x94, the address and
    ///      the nonce's own byte. No contract that existed before the generation can sit at one.
    function _builtBy(address hook, address a) private pure returns (bool) {
        for (uint256 n = 1; n < 4; ++n) {
            // forge-lint: disable-next-line(unsafe-typecast)
            bytes32 h = keccak256(abi.encodePacked(bytes2(0xd694), hook, uint8(n)));
            // forge-lint: disable-next-line(unsafe-typecast)
            if (a == address(uint160(uint256(h)))) return true;
        }
        return false;
    }

    /// @dev A leg generation: only one built on this factory's ledger and distributor deployer (on another, its
    ///      coins' holders could never be paid). Its references join isSuite's record only if they answer as an
    ///      oracle themselves (no asset 0, a TWAP window), so a leg's word never makes a live payee a puller.
    function wireLeg(Suite storage q, address leg) external {
        IBankrLaunchFactory f = IBankrLaunchFactory(address(this));
        address l = f.ledger();
        address refs = address(uint160(_word(leg, abi.encodeCall(ILegPointers.references, ()))));
        if (
            _word(leg, abi.encodeCall(ILegPointers.ledger, ())) != uint160(l)
                || _word(leg, abi.encodeCall(ILegPointers.distributorDeployer, ())) != uint160(f.holderRewardsDeployer())
                || _word(refs, abi.encodeCall(ILegPointers.TWAP_WINDOW, ())) == 0
                || _word(refs, abi.encodeCall(ILegPointers.isReferenced, (address(0)))) != 0
        ) revert IBankrLaunchFactory.InvalidHolderLeg();
        q.suite[leg] = true;
        q.suite[refs] = true;
        emit IBankrLaunchFactory.HolderLegSet(leg, IBankrFeeLedger(l).addLeg(leg));
    }

    /// @dev One word of a view's answer, read leniently: 0 when `target` does not answer with exactly a word.
    function _word(address target, bytes memory call) private view returns (uint256 w) {
        (bool ok, bytes memory r) = target.staticcall(call);
        // casting to 'bytes32' is safe because r is exactly one word
        // forge-lint: disable-next-line(unsafe-typecast)
        if (ok && r.length == 32) w = uint256(bytes32(r));
    }

    // ── payees ───────────────────────────────────────────────────────────────

    /// @dev Payees isSuite cannot see that could never spend what they are paid (audit r3 F-1): a copy of any guard lens
    ///      or claims redeemer a generation named when wired (its code, recorded then: R7-05), this launch's own preset
    ///      instance (r4 F-1; every earlier one is isSuite's record, so no deployer is asked) unless it is a Raffle Run
    ///      paying itself, and, as extension payee, the launch's own distributor (it cannot burn claims).
    function _checkPayees(
        Suite storage q,
        address inst,
        bool ownPayee,
        Payees memory w,
        address[] memory pads,
        FeeRecipient[] memory r
    ) internal view {
        if (w.extPayee != address(0) && w.extPayee == w.distributor) {
            revert IBankrLaunchFactory.InvalidExtensionPayee();
        }
        // a recipient is never address(0), so an absent instance matches none
        for (uint256 j; j < r.length; ++j) {
            if (r[j].recipient == inst || _isSuiteCode(q, r[j].recipient)) revert IBankrLaunchFactory.InvalidFeeRecipient();
        }
        if (inst != address(0)) {
            if (w.extPayee == inst && !ownPayee) revert IBankrLaunchFactory.InvalidExtensionPayee();
            for (uint256 j; j < pads.length; ++j) {
                if (pads[j] == inst) revert IBankrLaunchFactory.LaunchpadPayeeRejected();
            }
        }
        if (_isSuiteCode(q, w.extPayee)) revert IBankrLaunchFactory.InvalidExtensionPayee();
        for (uint256 j; j < pads.length; ++j) {
            if (_isSuiteCode(q, pads[j])) revert IBankrLaunchFactory.LaunchpadPayeeRejected();
        }
    }

    /// @dev A pad payee is checked as the factory checks a fee recipient (H13 R2-5): never the token, the escrow or any
    ///      protocol contract (isSuite: the BNKR holder leg included on every pad, every launch's token, escrow and
    ///      distributor, every hook generation's periphery, every preset instance). Id 0's treasury marker is the one
    ///      marker a pad pays: the ledger routes it to the treasury.
    function _checkPadPayees(address[] memory payees, address token, address escrow) internal view {
        IBankrLaunchFactory f = IBankrLaunchFactory(address(this));
        for (uint256 i; i < payees.length; ++i) {
            address a = payees[i];
            if (a == token || a == escrow || (a != K.PAD_TREASURY && f.isSuite(a))) {
                revert IBankrLaunchFactory.LaunchpadPayeeRejected();
            }
        }
    }

    /// @dev A hook generation and the preset deployer are suite by address (isSuite, run on every payee before this).
    function _isSuiteCode(Suite storage q, address a) internal view returns (bool) {
        return a.code.length != 0 && q.suiteCode[a.codehash];
    }

    /// @dev The launch's own payees as the factory resolved them; the pad's come from the launchpad registry.
    struct Payees {
        address feeRecipient;
        address vestingRecipient;
        address distributor; // the launch's hold-to-earn distributor (every launch)
        address extPayee; // 0 = no extension
        address escrow; // the launch's escrow clone, predicted (code only when something vests)
        address buyback; // the chain's BankrBuyback, the creator side's buyback payee
    }

    /// @dev A launch's two remainder buckets (spec §3): creatorId, and decayId when the pad has a decay split. The treasury
    ///      payee (K.PAD_TREASURY) is cut to bankrId in the ledger (`treasuryWad`, `treasuryDecayWad`).
    struct Shares {
        address[] who;
        uint256[] sh;
        address[] decayWho;
        uint256[] decaySh;
        bool creatorLp; // the hook is an auto-LP payee of creatorId, so it pulls it (review B finding 2)
        bool decayLp; // the hook is an auto-LP payee of decayId, so it pulls it (review finding 4)
        uint256 treasuryWad;
        uint256 treasuryDecayWad;
        // Each entry's creator part (a fee recipient's own, before any merge with a pad payee): the ledger's label,
        // and what a takeover moves (spec §9). `r` is the launch's fee recipients, resolved and checked.
        uint256[] cw;
        uint256[] decayCw;
        FeeRecipient[] r;
    }


    // ── a launch's registration ──────────────────────────────────────────────

    /// @dev Registers the pool on the newest hook and in the ledger from resolve's result (`terms`) and the launch's
    ///      own encoding (`launch` = launch()'s calldata): the pad's record, the words only the factory knows, the
    ///      payee checks, the hook's pool record, the buckets and split terms. Returns the hash of the coin's terms
    ///      as its contracts now hold them, logged here (this library works on its own copy of `terms`).
    function registerPool(Suite storage q, bytes calldata launch, bytes memory terms, Reg memory r)
        external
        returns (bytes32)
    {
        LaunchParams memory p = abi.decode(launch, (LaunchParams));
        _record(p, r, EconomicsCheck.termsHash(launch, r.w.feeRecipient, r.w.vestingRecipient, r.w.extPayee, msg.value));
        _fill(q, terms, p, r);
        _register(q, terms, p, r);
        return _freeze(terms, r, p.startTime);
    }

    /// @dev The launch's record with its pad, every launch, id 0 included (D10): signature, nonce, pause, vanity.
    function _record(LaunchParams memory p, Reg memory r, bytes32 paramsHash) private {
        IBankrLaunchpadRegistry(IBankrLaunchFactory(address(this)).launchpadRegistry())
            .recordLaunch(p.launchpadId, msg.sender, r.token, paramsHash, p.authorization);
    }

    function _word(bytes memory terms, uint256 i) private pure returns (uint256 w) {
        assembly ("memory-safe") {
            w := mload(add(terms, add(0x20, mul(i, 0x20))))
        }
    }

    function _setWord(bytes memory terms, uint256 i, uint256 w) private pure {
        assembly ("memory-safe") {
            mstore(add(terms, add(0x20, mul(i, 0x20))), w)
        }
    }

    /// @dev The words the resolver cannot know, written before the pool's record is decoded: always the token and
    ///      the trading start (this second, or the scheduled one, which the resolver held inside the pad's wait and
    ///      40 bits); for a preset the whole binding as its deployer returned it.
    function _fill(Suite storage q, bytes memory terms, LaunchParams memory p, Reg memory r) private {
        _setWord(terms, W_POOL, uint160(r.token));
        _setWord(terms, W_POOL + 1, p.startTime > block.timestamp ? p.startTime : block.timestamp);
        uint256 id = _word(terms, W_PRESET_ID);
        if (id == 0) return;
        // a uint8 field of the record
        // forge-lint: disable-next-line(unsafe-typecast)
        ExtBinding memory b = _preset(q, terms, p, r, uint8(id));
        r.inst = b.ext;
        _setWord(terms, W_POOL + 24, uint160(b.ext));
        _setWord(terms, W_POOL + 25, b.quoteGas);
        _setWord(terms, W_POOL + 26, b.afterGas);
        _setWord(terms, W_POOL + 30, uint256(b.codehash));
        _setWord(terms, W_POOL + 31, b.maxBuyPips);
        _setWord(terms, W_POOL + 32, b.maxSellPips);
        _setWord(terms, W_POOL + 33, uint160(b.payee));
        _setWord(terms, W_POOL + 34, b.quoteOnly ? 1 : 0);
        _setWord(terms, W_POOL + 35, b.sunsetSecs);
    }

    /// @dev A preset's instance from the record's deployer, pinned to its predict, its presetOf and the launch's
    ///      payee (audit r1 ADM-07); it and its deployer join isSuite's record for good (R7-05).
    function _preset(Suite storage q, bytes memory terms, LaunchParams memory p, Reg memory r, uint8 id)
        private
        returns (ExtBinding memory b)
    {
        IBankrPresetDeployer pd = IBankrPresetDeployer(address(uint160(_word(terms, W_PRESET_DEPLOYER))));
        b = _deployPreset(pd, id, p.extension.params, r, _word(terms, W_PRESET_SITE));
        if (pd.presetOf(b.ext) != id || b.payee != (_word(terms, W_PRESET_SELF) != 0 ? b.ext : r.w.extPayee)) {
            revert IBankrLaunchFactory.PresetBindingMismatch();
        }
        q.suite[b.ext] = true;
        q.suite[address(pd)] = true;
        // Public before the launch but code only now, so the vesting code guard could not see it; payees are
        // checked against it afterwards (_checkPayees). An instance can never call release (audit r4 F-1).
        if (b.ext == p.vestingRecipient) revert IBankrLaunchFactory.InvalidVestingRecipient();
        for (uint256 i; i < p.extraAllocations.length; ++i) {
            if (b.ext == p.extraAllocations[i].recipient) revert IBankrLaunchFactory.InvalidVestingRecipient();
        }
    }

    /// @dev Apart from _preset for its stack. The instance must be new code: a deployer naming a live contract (a
    ///      payee's Safe) is refused. The limits word is constructor data, so predict and deploy take the same one.
    function _deployPreset(IBankrPresetDeployer pd, uint8 id, bytes memory params, Reg memory r, uint256 site)
        private
        returns (ExtBinding memory b)
    {
        bool t0 = Currency.unwrap(r.key.currency0) == r.token;
        address ext = pd.predict(id, params, r.key, t0, site);
        if (ext.code.length != 0) revert IBankrLaunchFactory.PresetBindingMismatch();
        b = pd.deploy(id, params, r.w.extPayee, r.key, t0, site);
        if (b.ext != ext) revert IBankrLaunchFactory.PresetBindingMismatch();
    }

    /// @dev The one decode of the result, after the filled words are in: the pad's payees and every payee's check
    ///      against code that could never spend (audit r3 F-1), the hook's record, the buckets and split terms.
    function _register(Suite storage q, bytes memory terms, LaunchParams memory p, Reg memory r) private {
        (CoinTerms memory t,,, IBankrLaunchpadRegistry.PadTerms memory pad) =
            abi.decode(terms, (CoinTerms, bytes32, address, IBankrLaunchpadRegistry.PadTerms));
        _checkPadPayees(pad.payees, r.token, r.w.escrow);
        r.s = _shares(pad, r.w, _feeRecipients(p, r.w, r.token), r.hook, p.econ);
        // the record's two auto-LP bits are the resolver's reading of this same split, its hook the one registered
        if (r.s.creatorLp != t.pool.creatorLp || r.s.decayLp != t.pool.decayLp || t.hook != r.hook) {
            revert IBankrLaunchFactory.TermsMismatch();
        }
        IBankrLaunchHook(r.hook).registerPool(r.key, t.pool);
        _checkPayees(q, r.inst, t.presetSelfPayee, r.w, pad.payees, r.s.r);
        _registerBuckets(t, r, pad.decay.on);
    }

    /// @dev The hash over CoinTerms' words as they now stand, and their log: those same words, raw. A scheduled
    ///      start is announced beside it.
    function _freeze(bytes memory terms, Reg memory r, uint64 startTime) private returns (bytes32 termsHash) {
        bytes32 id = PoolId.unwrap(r.key.toId());
        if (startTime > block.timestamp) emit IBankrLaunchFactory.TradingScheduled(r.token, id, startTime);
        bytes32 resolved;
        uint256 len = terms.length;
        assembly ("memory-safe") {
            termsHash := keccak256(add(terms, 0x20), TERMS_BYTES)
            resolved := mload(add(terms, add(0x20, mul(W_RESOLVED_HASH, 0x20))))
            mstore(terms, TERMS_BYTES)
        }
        emit IBankrLaunchFactory.CoinTermsFrozen(r.token, id, termsHash, resolved, terms);
        assembly ("memory-safe") {
            mstore(terms, len)
        }
    }

    /// @dev The quote's bankrId bucket (from its first launch), creatorId, decayId with a decay split, the holders'
    ///      locked bucket (the coin's own leg's) and the pool's split terms as the coin's record names them. decayId
    ///      is registered before the terms: the ledger holds a takeover coin's decay bucket to its limit there.
    function _registerBuckets(CoinTerms memory t, Reg memory r, bool decayOn) private {
        IBankrLaunchFactory f = IBankrLaunchFactory(address(this));
        IBankrFeeLedger l = IBankrFeeLedger(f.ledger());
        _registerSoleCurrencyBucket(address(l), BucketIds.bankrId(t.quote), t.quote, f.treasury());
        bytes32 id = PoolId.unwrap(r.key.toId());
        // The takeover word: the flag as resolved, with the owner's notice and grace on every coin.
        _splitBuckets((t.takeover ? 1 : 0) | uint256(t.ctoNotice) << 8 | uint256(t.ctoGrace) << 40, l, id, r, decayOn);
        l.registerSoleBucket(BucketIds.holdersId(id), r.key, t.holderLeg, true);
        IBankrFeeLedger.PoolTerms memory pt = _poolTerms(t, r);
        if (decayOn) pt.flags |= FeeMath.T_DECAY_SPLIT;
        l.registerPoolTerms(
            id,
            r.key,
            pt,
            t.pool.buy.steadyPips < t.pool.sell.steadyPips ? t.pool.buy.steadyPips : t.pool.sell.steadyPips
        );
    }

    /// @dev The pool's split terms: Bankr's cut, its floor, the holders' share and the leg id from the coin's
    ///      record, the distributor's creatorId share for the in-swap accrue (decision 1), and the key's flag.
    function _poolTerms(CoinTerms memory t, Reg memory r) private pure returns (IBankrFeeLedger.PoolTerms memory pt) {
        Shares memory s = r.s;
        (pt.hook, pt.referrerBps, pt.legId) = (r.hook, t.referrerBps, t.legId);
        (pt.bankrFeeBps, pt.bankrMinPips, pt.holdersShareBps) = (t.bankrFeeBps, t.bankrMinPips, t.holdersShareBps);
        // Both under WAD (the resolver's payee bound), so the casts cannot truncate.
        // forge-lint: disable-next-line(unsafe-typecast)
        (pt.treasuryWad, pt.treasuryDecayWad) = (uint64(s.treasuryWad), uint64(s.treasuryDecayWad));
        if (s.treasuryWad != 0 || s.treasuryDecayWad != 0) pt.flags = FeeMath.T_TREASURY_CUT;
        for (uint256 i; i < s.who.length; ++i) {
            // at most WAD: the cast cannot truncate
            // forge-lint: disable-next-line(unsafe-typecast)
            if (s.who[i] == r.w.distributor) pt.holderWad = uint64(s.sh[i]);
        }
        if (pt.holderWad != 0) (pt.distributor, pt.flags) = (r.w.distributor, pt.flags | FeeMath.T_HOLDER_INTAKE);
        if (t.waiveBnkrPair) pt.flags |= FeeMath.T_WAIVED;
        if (Currency.unwrap(r.key.currency1) == r.token) pt.flags |= FeeMath.T_QUOTE_IS_0;
    }

    /// @dev Apart from _registerBuckets for its stack. `cto` is the ledger's takeover word (IBankrFeeLedger
    ///      .registerBucket): creatorId carries it, and its decayId's creator parts move with it (F4, D21).
    function _splitBuckets(uint256 cto, IBankrFeeLedger l, bytes32 id, Reg memory r, bool decayOn) private {
        Shares memory s = r.s;
        l.registerBucket(BucketIds.creatorId(id), r.key, s.who, s.sh, s.cw, cto);
        if (decayOn) l.registerBucket(BucketIds.decayId(id), r.key, s.decayWho, s.decaySh, s.decayCw, 0);
    }

    /// @dev creatorId over the remainder (spec §3): each pad payee its WAD share, then of the rest C the coin's holders
    ///      C·holdersBps (rounded down) and auto-LP C·autoLpBps (rounded to nearest, so neither LP nor creator moves more
    ///      than 1e-18 of the remainder on Bankr's preset), the creator the rest. decayId the same way over the decay
    ///      surplus: each payee its decay share, auto-LP decayAutoLpBps of the rest, the creator what is left. Zero
    ///      shares omitted, duplicates merged (D26).
    function _shares(
        IBankrLaunchpadRegistry.PadTerms memory pad,
        Payees memory w,
        FeeRecipient[] memory r,
        address hook,
        Economics memory e
    ) internal pure returns (Shares memory s) {
        (s.treasuryWad, s.treasuryDecayWad) = _cutTreasury(pad, K.PAD_TREASURY);
        s.r = r;
        (s.who, s.sh, s.cw) = _creatorShares(pad, w, r, hook, e);
        for (uint256 i; i < s.who.length && !s.creatorLp; ++i) {
            s.creatorLp = s.who[i] == hook;
        }
        if (pad.decay.on) {
            (s.decayWho, s.decaySh, s.decayCw, s.decayLp) = _decayShares(pad, r, hook);
        }
    }

    /// @dev A treasury payee leaves the buckets: the ledger cuts its shares to bankrId (`t`, `td`), its entries become 0
    ///      (which _put omits), and the other payees' shares become shares of what the cut leaves, rounded up (on Bankr's
    ///      pad they are Bankr's own). Shares only, in place: the payee list stays whole for the payee checks.
    function _cutTreasury(IBankrLaunchpadRegistry.PadTerms memory pad, address treasury)
        private
        pure
        returns (uint256 t, uint256 td)
    {
        uint256 n = pad.payees.length;
        bool on = pad.decay.on;
        for (uint256 i; i < n; ++i) {
            if (pad.payees[i] != treasury) continue; // payees are distinct (registry), so one entry at most
            (t, pad.steadySharesWad[i]) = (pad.steadySharesWad[i], 0);
            if (on) (td, pad.decay.sharesWad[i]) = (pad.decay.sharesWad[i], 0);
        }
        if (t == 0 && td == 0) return (0, 0);
        for (uint256 i; i < n; ++i) {
            pad.steadySharesWad[i] = _rescale(pad.steadySharesWad[i], t);
            if (on) pad.decay.sharesWad[i] = _rescale(pad.decay.sharesWad[i], td);
        }
    }

    /// @dev ⌈share / (1 − cut)⌉ in WAD; both are at most 0.95e18, so the product cannot overflow.
    function _rescale(uint256 share, uint256 cut) private pure returns (uint256) {
        return (share * 1e18 + (1e18 - cut) - 1) / (1e18 - cut);
    }

    function _creatorShares(
        IBankrLaunchpadRegistry.PadTerms memory pad,
        Payees memory w,
        FeeRecipient[] memory r,
        address hook,
        Economics memory e
    ) private pure returns (address[] memory who, uint256[] memory sh, uint256[] memory cw) {
        (who, sh, cw) = _arrays(pad.payees.length + 3 + r.length);
        (uint256 k, uint256 c) = _payeeShares(who, sh, pad.payees, pad.steadySharesWad);
        uint256 x = c * e.holdersBps / 10_000; // holders, rounded down
        k = _put(who, sh, k, w.distributor, x);
        uint256 mine = c - x;
        x = (c * e.autoLpBps + 5_000) / 10_000; // auto-LP, to nearest
        k = _put(who, sh, k, hook, x);
        mine -= x;
        x = c * e.buybackBps / 10_000; // buyback, rounded down
        k = _put(who, sh, k, w.buyback, x);
        mine -= x; // the creator's own, before any merge
        k = _putCreators(who, sh, cw, k, r, mine);
        _trim(who, sh, cw, k);
    }

    function _decayShares(IBankrLaunchpadRegistry.PadTerms memory pad, FeeRecipient[] memory r, address hook)
        private
        pure
        returns (address[] memory who, uint256[] memory sh, uint256[] memory cw, bool hookPaid)
    {
        (who, sh, cw) = _arrays(pad.payees.length + 1 + r.length);
        (uint256 k, uint256 c) = _payeeShares(who, sh, pad.payees, pad.decay.sharesWad);
        uint256 lp = (c * pad.decay.autoLpBps + 5_000) / 10_000;
        k = _put(who, sh, k, hook, lp);
        k = _putCreators(who, sh, cw, k, r, c - lp);
        _trim(who, sh, cw, k);
        hookPaid = lp != 0;
    }

    function _arrays(uint256 n) private pure returns (address[] memory, uint256[] memory, uint256[] memory) {
        return (new address[](n), new uint256[](n), new uint256[](n));
    }

    /// @dev The creator's own `mine` over the launch's fee recipients by bps: each after the first rounded down, the
    ///      first the rest (never 0 while `mine` is not), so the bucket still sums to WAD. A recipient that is also a pad
    ///      payee merges into one entry; `cw` keeps its creator part apart.
    function _putCreators(
        address[] memory who,
        uint256[] memory sh,
        uint256[] memory cw,
        uint256 k,
        FeeRecipient[] memory r,
        uint256 mine
    ) private pure returns (uint256) {
        uint256 first = mine;
        for (uint256 i = 1; i < r.length; ++i) {
            first -= mine * r[i].shareBps / 10_000;
        }
        for (uint256 i; i < r.length; ++i) {
            uint256 x = i == 0 ? first : mine * r[i].shareBps / 10_000;
            if (x == 0) continue;
            k = _put(who, sh, k, r[i].recipient, x);
            for (uint256 j; j < k; ++j) {
                if (who[j] == r[i].recipient) cw[j] = x; // recipients are distinct: set once
            }
        }
        return k;
    }

    /// @dev A launch's fee recipients, resolved (none: the primary alone, the launcher) and checked by LaunchEconomics
    ///      (the bounds, the split, each recipient as the factory checks the primary, and the contract-recipient rule).
    function _feeRecipients(LaunchParams memory p, Payees memory w, address token)
        private
        view
        returns (FeeRecipient[] memory r)
    {
        r = p.feeRecipients;
        // With several recipients no position stands in for an extension's payee: it is named or the launch reverts.
        if (r.length > 1 && w.extPayee != address(0) && p.extension.payee == address(0)) {
            revert IBankrLaunchFactory.ExtensionPayeeUnnamed();
        }
        if (r.length == 0) {
            r = new FeeRecipient[](1);
            r[0] = FeeRecipient(w.feeRecipient, 10_000);
        }
        EconomicsCheck.checkFeeRecipients(r, token, w.escrow, w.distributor, p.allowOpenCodeFeeRecipients);
    }

    /// @dev The pad payees' entries; returns the count and what they leave of WAD.
    function _payeeShares(address[] memory who, uint256[] memory sh, address[] memory payees, uint256[] memory shares)
        private
        pure
        returns (uint256 k, uint256 rest)
    {
        rest = 1e18;
        for (uint256 i; i < payees.length; ++i) {
            k = _put(who, sh, k, payees[i], shares[i]);
            rest -= shares[i];
        }
    }

    function _trim(address[] memory who, uint256[] memory sh, uint256[] memory cw, uint256 n) private pure {
        assembly ("memory-safe") {
            mstore(who, n)
            mstore(sh, n)
            mstore(cw, n)
        }
    }

    function _put(address[] memory who, uint256[] memory sh, uint256 n, address a, uint256 share)
        private
        pure
        returns (uint256)
    {
        if (share == 0) return n;
        for (uint256 i; i < n; ++i) {
            if (who[i] == a) {
                sh[i] += share;
                return n;
            }
        }
        who[n] = a;
        sh[n] = share;
        return n + 1;
    }

    // ── buckets (Interfaces block bucket table) ──────────────────────────────

    /// @dev A quote's chain-wide bankrId bucket (Bankr's own half of every pool's slice and its extension cuts), sole
    ///      beneficiary the treasury of its first launch. Idempotent: an existing bucket keeps its beneficiary.
    function _registerSoleCurrencyBucket(address ledger, bytes32 b, address quote, address beneficiary) internal {
        (,,, bool exists) = IBankrFeeLedger(ledger).bucketOf(b);
        if (exists) return;
        address[] memory who = new address[](1);
        who[0] = beneficiary;
        uint256[] memory sh = new uint256[](1);
        sh[0] = 1e18;
        IBankrFeeLedger(ledger).registerCurrencyBucket(b, Currency.wrap(quote), who, sh);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

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

pragma solidity >=0.4.16;

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

lib/openzeppelin-contracts/contracts/interfaces/IERC20Metadata.sol

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

pragma solidity >=0.6.2;

import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

lib/openzeppelin-contracts/contracts/proxy/Clones.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (proxy/Clones.sol)

pragma solidity ^0.8.20;

import {Create2} from "../utils/Create2.sol";
import {Errors} from "../utils/Errors.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 */
library Clones {
    error CloneArgumentsTooLong();

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function clone(address implementation) internal returns (address instance) {
        return clone(implementation, 0);
    }

    /**
     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
     * to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function clone(address implementation, uint256 value) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(value, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple times will revert, since
     * the clones cannot be deployed twice at the same address.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        return cloneDeterministic(implementation, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
     * a `value` parameter to send native currency to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(232, shl(96, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(120, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(value, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
     * access the arguments within the implementation, use {fetchCloneArgs}.
     *
     * This function uses the create opcode, which should never revert.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {
        return cloneWithImmutableArgs(implementation, args, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`
     * parameter to send native currency to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneWithImmutableArgs(
        address implementation,
        bytes memory args,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        assembly ("memory-safe") {
            instance := create(value, add(bytecode, 0x20), mload(bytecode))
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
     * immutable arguments. These are provided through `args` and cannot be changed after deployment. To
     * access the arguments within the implementation, use {fetchCloneArgs}.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same
     * `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice
     * at the same address.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     */
    function cloneDeterministicWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],
     * but with a `value` parameter to send native currency to the new contract.
     *
     * WARNING: This function does not check if `implementation` has code. A clone that points to an address
     * without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
     * have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministicWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        return Create2.deploy(value, salt, bytecode);
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
     */
    function predictDeterministicAddressWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
        return Create2.computeAddress(salt, keccak256(bytecode), deployer);
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
     */
    function predictDeterministicAddressWithImmutableArgs(
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));
    }

    /**
     * @dev Get the immutable args attached to a clone.
     *
     * - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this
     *   function will return an empty array.
     * - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or
     *   `cloneDeterministicWithImmutableArgs`, this function will return the args array used at
     *   creation.
     * - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This
     *   function should only be used to check addresses that are known to be clones.
     */
    function fetchCloneArgs(address instance) internal view returns (bytes memory) {
        bytes memory result = new bytes(instance.code.length - 0x2d); // revert if length is too short
        assembly ("memory-safe") {
            extcodecopy(instance, add(result, 0x20), 0x2d, mload(result))
        }
        return result;
    }

    /**
     * @dev Helper that prepares the initcode of the proxy with immutable args.
     *
     * An assembly variant of this function requires copying the `args` array, which can be efficiently done using
     * `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using
     * abi.encodePacked is more expensive but also more portable and easier to review.
     *
     * NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.
     * With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.
     */
    function _cloneCodeWithImmutableArgs(
        address implementation,
        bytes memory args
    ) private pure returns (bytes memory) {
        if (args.length > 0x5fd3) revert CloneArgumentsTooLong();
        return
            abi.encodePacked(
                hex"61",
                uint16(args.length + 0x2d),
                hex"3d81600a3d39f3363d3d373d3d3d363d73",
                implementation,
                hex"5af43d82803e903d91602b57fd5bf3",
                args
            );
    }
}

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

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /// @dev Attempts to fetch the token decimals. A return value of false indicates that the attempt failed in some way.
    function tryGetDecimals(IERC20 token) internal view returns (bool success, uint8 decimals) {
        bytes4 selector = IERC20Metadata.decimals.selector;
        assembly ("memory-safe") {
            mstore(0x00, selector)
            success := staticcall(gas(), token, 0x00, 4, 0x00, 0x20)
            success := and(and(success, gt(returndatasize(), 0x1f)), lt(mload(0x00), 0x100))
            decimals := mul(success, mload(0x00))
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, relaxing the requirement on the return value: the
     * return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, relaxing the requirement on the return
     * value: the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, relaxing the requirement on the return value:
     * the return value is optional (but if data is returned, it must not be false).
     *
     * @param token The token targeted by the call.
     * @param spender The spender of the tokens
     * @param value The amount of token to approve
     * @param bubble Behavior switch if the approve call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

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

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

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        assembly ("memory-safe") {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        if (addr == address(0)) {
            if (LowLevelCall.returnDataSize() == 0) {
                revert Errors.FailedDeployment();
            } else {
                LowLevelCall.bubbleRevert();
            }
        }
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        assembly ("memory-safe") {
            let ptr := mload(0x40) // Get free memory pointer

            // |                     | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |---------------------|---------------------------------------------------------------------------|
            // | bytecodeHash        |                                                        CCCCCCCCCCCCC...CC |
            // | salt                |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer            | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF                |            FF                                                             |
            // |---------------------|---------------------------------------------------------------------------|
            // | memory              | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 0x55) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := and(keccak256(start, 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            let fmp := mload(0x40)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type Currency is address;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

type PoolId is bytes32;

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

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

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

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

using PoolIdLibrary for PoolKey global;

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

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

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

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

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

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

src/interfaces/IBankrFeeLedger.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/interfaces/IBankrHookExtension.sol

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

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

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

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

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

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

src/interfaces/IBankrLaunchFactory.sol

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

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


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


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

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

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

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

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

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

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

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

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

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

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

src/interfaces/IBankrLaunchHook.sol

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

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

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

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

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

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

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

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

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

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

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

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

src/interfaces/IBankrLaunchpadRegistry.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/interfaces/IBankrPreset.sol

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

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

/// @dev Where a preset instance runs and the limits it is built under, handed to every preset constructor by
///      BankrPresetDeployer: the launch's pool before it is registered, which currency is TOKEN, and the launch's
///      frozen limits word (CoinTerms.presetSite) field by field, so the limits are part of the instance address.
struct PresetSite {
    IPoolManager poolManager;
    PoolKey key;
    bool tokenIsCurrency0;
    uint24 maxPips; // the most a preset may declare on either side
    uint32 minWindowSecs; // a window is longer than this: the launch's own longer fee decay
    uint32 maxWindowSecs;
    int24 minBrakeTicks;
    uint32 minAnchorTau;
    uint112 maxDustFloor; // Raffle Run: the most minBuyback may be (B14)
}

/// @notice A Bankr preset extension. Every one is constructed as `(PresetSite, bytes params)`, checks `params` against
///         its bounds in that constructor (Presets) and keeps them as immutables; its declared maxima, quote-only flag
///         and sunset become the pool's binding.
interface IBankrPreset is IBankrHookExtension {
    function presetId() external view returns (uint8);
    function maxBuyPips() external view returns (uint24);
    function maxSellPips() external view returns (uint24);
    /// @notice True when its post-swap call does nothing: the pool binds it quote-only and the hook never calls it.
    function quoteOnly() external view returns (bool);
    /// @notice Seconds after launch from which its quote is 0 for good (0 = never): the hook stops asking it then.
    function sunsetSecs() external view returns (uint32);
    /// @notice The limits word the instance was built under, as `deploy` was handed it (Presets.word's layout).
    function presetSite() external view returns (uint256);
}

/// @notice The factory's preset instantiator: CREATE2s one preset instance per launch (salt = the pool id) inside the
///         launch transaction and returns the binding the factory writes into the coin's record.
interface IBankrPresetDeployer {
    /// @dev Factory only. `payee` is the launch's effective extension payee; a Raffle Run instance is its own payee.
    ///      `site` is the launch's limits word, which the instance's constructor holds its parameters to.
    function deploy(
        uint8 preset,
        bytes calldata params,
        address payee,
        PoolKey calldata key,
        bool tokenIsCurrency0,
        uint256 site
    ) external returns (ExtBinding memory binding);
    /// @notice The instance address `deploy` would create for these arguments: `site` is constructor data.
    function predict(uint8 preset, bytes calldata params, PoolKey calldata key, bool tokenIsCurrency0, uint256 site)
        external
        view
        returns (address);
    /// @notice keccak256 of the creation code `preset` deploys, which a preset record and its allowlist key name.
    function creationCodeHash(uint8 preset) external view returns (bytes32);
    /// @notice The preset id of an instance this deployer created; 0 for any other address.
    function presetOf(address ext) external view returns (uint8);
    function factory() external view returns (address);
    function poolManager() external view returns (IPoolManager);

    event PresetDeployed(
        bytes32 indexed poolId, uint8 indexed preset, address indexed ext, address payee, bytes params
    );

    error NotFactory();
    error UnknownPreset(uint8 preset);
}

src/interfaces/ICreatorVestingEscrow.sol

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

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

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

src/interfaces/IHolderRewards.sol

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

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

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

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

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

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

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

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

src/interfaces/SuiteTypes.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

src/libraries/BucketIds.sol

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

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

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

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

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

src/libraries/FeeMath.sol

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {
    IBankrLaunchFactory,
    LaunchParams,
    FeeRecipient,
    LaunchEconomics as Economics
} from "../interfaces/IBankrLaunchFactory.sol";
import {ICreatorVestingEscrow, VestingAllocation} from "../interfaces/ICreatorVestingEscrow.sol";
import {IHolderRewardsDistributor} from "../interfaces/IHolderRewards.sol";
import {IBankrFeeLedger} from "../interfaces/IBankrFeeLedger.sol";
import {FeeSchedule} from "./FeeMath.sol";
import {LaunchConstants as K} from "./LaunchConstants.sol";
import {LaunchpadAuth} from "./LaunchpadAuth.sol";

/// @notice A launch's economics as an external library the factory and LaunchRegistry reach by delegatecall (spec §13;
///         EIP-170 under the legacy pipeline, H18): the guards on a launch's recipients and allocations that need
///         isSuite, the hash a pad's signer signs, and the vesting escrow's setup. Every number of a launch is the
///         settings contract's to check (LaunchResolver).
library LaunchEconomics {
    using SafeERC20 for IERC20;

    /// @dev The builder allocations' guards (B20), before anything is deployed (audit I-10): a recipient that could
    ///      never release, no amount, or a push schedule, which is only ever the factory's own (vest-to-holders). Any
    ///      cliff and duration is a schedule: an allocation may unlock at once. The sum is the resolver's.
    function checkAllocations(VestingAllocation[] calldata list) external view {
        IBankrLaunchFactory f = IBankrLaunchFactory(address(this));
        for (uint256 i; i < list.length; ++i) {
            VestingAllocation calldata a = list[i];
            if (f.isSuite(a.recipient) || a.recipient == address(0) || a.amount == 0 || a.push) {
                revert IBankrLaunchFactory.InvalidVestingRecipient();
            }
        }
    }

    /// @dev A launch's fee recipients, already resolved (none named: the launcher alone; how many is the pad's knob,
    ///      held by the resolver): distinct, each share above 0, summing to 10,000 bps (B4). Each as the factory checks the primary: never the token,
    ///      the escrow, the distributor or a protocol contract. Code that is not an EIP-7702 account must have restricted
    ///      its claims on the ledger: an open contract can be settled around its own accounting (RSEC-1).
    function checkFeeRecipients(
        FeeRecipient[] memory r,
        address token,
        address escrow,
        address distributor,
        bool allowOpen
    ) external view {
        IBankrLaunchFactory f = IBankrLaunchFactory(address(this));
        IBankrFeeLedger l = IBankrFeeLedger(f.ledger());
        uint256 sum;
        for (uint256 i; i < r.length; ++i) {
            address a = r[i].recipient;
            if (a == address(0) || r[i].shareBps == 0) revert IBankrLaunchFactory.InvalidFeeRecipients();
            for (uint256 j; j < i; ++j) {
                if (r[j].recipient == a) revert IBankrLaunchFactory.InvalidFeeRecipients();
            }
            if (a == token || a == escrow || a == distributor || f.isSuite(a)) {
                revert IBankrLaunchFactory.InvalidFeeRecipient();
            }
            if (!allowOpen && _isContract(a) && !l.claimRestricted(a)) {
                revert IBankrLaunchFactory.OpenContractFeeRecipient(a);
            }
            sum += r[i].shareBps;
        }
        if (sum != 10_000) revert IBankrLaunchFactory.InvalidFeeRecipients();
    }

    /// @dev Code that is not an EIP-7702 delegation: exactly 23 bytes, 0xef0100 and an address. Any other code counts,
    ///      0xEF-prefixed or not (Arbitrum Stylus programs start 0xEFF000 and run).
    function _isContract(address a) private view returns (bool c) {
        assembly ("memory-safe") {
            let n := extcodesize(a)
            if n {
                c := 1
                if eq(n, 23) {
                    mstore(0x00, 0)
                    extcodecopy(a, 0x00, 0x00, 0x03)
                    c := iszero(eq(shr(232, mload(0x00)), 0xef0100))
                }
            }
        }
    }

    /// @dev What a signer signs over (LaunchRegistry's launch terms): `launch` = launch()'s own encoding, the payees as
    ///      the factory resolved them. Here, not in LaunchRegistry, for its bytecode room (the CI size gate).
    function termsHash(bytes calldata launch, address fee, address vest, address ext, uint256 nativeDevBuy)
        external
        pure
        returns (bytes32)
    {
        return LaunchpadAuth.termsHash(abi.decode(launch, (LaunchParams)), fee, vest, ext, nativeDevBuy);
    }

    /// @notice What a signer signs for a launch (`launch` = the call's encoding, LaunchParams first): the fee recipient
    ///         and vesting recipient default to the launcher, an extension's payee to the fee recipient, as in launch().
    function hashLaunchTerms(bytes calldata launch, address launcher, uint256 nativeDevBuy)
        external
        pure
        returns (bytes32)
    {
        LaunchParams memory p = abi.decode(launch, (LaunchParams));
        address fee = p.feeRecipients.length == 0 ? launcher : p.feeRecipients[0].recipient;
        address vest = p.vestingRecipient == address(0) ? launcher : p.vestingRecipient;
        bool none = p.extension.id == 0 && p.extension.ext == address(0);
        address ext = none ? address(0) : p.extension.payee == address(0) ? fee : p.extension.payee;
        return LaunchpadAuth.termsHash(p, fee, vest, ext, nativeDevBuy);
    }

    /// @dev The factory's launch, when something vests: every schedule of the launch (creator vest, vest-to-holders and
    ///      builder allocations) lives in one clone of `impl` at `escrow`, deterministic in (launcher, salt); the token is
    ///      moved first because initialize() checks the escrow's balance. `launch` is launch()'s own argument encoding.
    ///      A vest-to-holders slice then opens the distributor's TOKEN stream, with the escrow's total, cliff and length.
    ///      `vested` carries the creator's own clock above the amount: cliff from bit 128, length from bit 160.
    function escrowVested(
        bytes calldata launch,
        address impl,
        address escrow,
        address token,
        address vestingRecipient,
        address distributor,
        uint256 supply,
        uint256 vested
    ) external {
        LaunchParams memory p = abi.decode(launch, (LaunchParams));
        address esc = Clones.cloneDeterministic(impl, keccak256(abi.encodePacked(msg.sender, p.salt)));
        if (esc != escrow) revert IBankrLaunchFactory.TokenSaltTaken();
        uint16 toHolders = p.econ.vestToHoldersBps;
        VestingAllocation[] memory v = new VestingAllocation[](
            p.extraAllocations.length + (p.vestBps > 0 ? 1 : 0) + (toHolders > 0 ? 1 : 0)
        );
        uint256 i;
        if (p.vestBps > 0) {
            v[i++] = VestingAllocation(
                vestingRecipient, supply * p.vestBps / 10_000, uint32(vested >> 128), uint32(vested >> 160), false
            );
        }
        if (toHolders > 0) {
            v[i++] = VestingAllocation(
                distributor,
                supply * toHolders / 10_000,
                p.econ.vestToHoldersCliff,
                p.econ.vestToHoldersDuration,
                true
            );
        }
        for (uint256 j; j < p.extraAllocations.length; ++j) {
            v[i++] = p.extraAllocations[j];
        }
        IERC20(token).safeTransfer(esc, uint128(vested));
        ICreatorVestingEscrow(esc).initialize(token, v, p.startTime);
        // decision 1: the TOKEN leg streams the slice on the escrow's own clock from the cliff, so nothing pushes it
        if (toHolders > 0) {
            // scheduled start: the stream's own clock is now-based, so both ends move out by the wait to the start
            uint64 wait = p.startTime > block.timestamp ? p.startTime - uint64(block.timestamp) : 0;
            IHolderRewardsDistributor(distributor).openVest(
                supply * toHolders / 10_000, p.econ.vestToHoldersCliff + wait, p.econ.vestToHoldersDuration + wait
            );
        }
    }
}

src/libraries/LaunchpadAuth.sol

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

import {LaunchParams, FeeRecipient} from "../interfaces/IBankrLaunchFactory.sol";

/// @notice EIP-712 hashing for a launchpad operator's (or, while the factory is gated, Bankr's) one-use
///         LaunchAuthorization (white-label launchpads, D1/D2). Pure hashing only; the registry supplies the domain and
///         verifies the signature.
library LaunchpadAuth {
    bytes32 internal constant LAUNCH_AUTHORIZATION_TYPEHASH = keccak256(
        "LaunchAuthorization(uint64 launchpadId,address launcher,bytes32 paramsHash,bytes32 nonce,uint256 deadline)"
    );

    /// @dev The `paramsHash` an authorization signs: keccak256(abi.encode(p)) over every launch term, with the launcher's
    ///      timing and signatures blanked (deadline, devBuyMinOut, authorization, priceAttestation), the payees as the
    ///      factory resolves them (an empty fee-recipient list written out as the launcher alone, `feeRecipient` at
    ///      10,000 bps, so one launch has one hash; a named list is signed whole, order and shares), a native dev buy
    ///      folded into devBuyAmountIn and the extension cleared when none is named. A signed launch cannot change its supply, vest, allocations, cap exclusions, dev buy or extension
    ///      (audit r1 ADM-01).
    function termsHash(
        LaunchParams memory p,
        address feeRecipient,
        address vestingRecipient,
        address extPayee,
        uint256 nativeDevBuy
    ) internal pure returns (bytes32) {
        p.deadline = 0;
        p.devBuyMinOut = 0;
        delete p.authorization;
        delete p.priceAttestation;
        if (p.feeRecipients.length == 0) {
            p.feeRecipients = new FeeRecipient[](1);
            p.feeRecipients[0] = FeeRecipient(feeRecipient, 10_000);
        }
        p.vestingRecipient = vestingRecipient;
        p.devBuyAmountIn += nativeDevBuy;
        if (p.extension.id == 0 && p.extension.ext == address(0)) delete p.extension;
        else p.extension.payee = extPayee;
        return keccak256(abi.encode(p));
    }

    function structHash(uint64 launchpadId, address launcher, bytes32 pHash, bytes32 nonce, uint256 deadline)
        internal
        pure
        returns (bytes32)
    {
        return keccak256(abi.encode(LAUNCH_AUTHORIZATION_TYPEHASH, launchpadId, launcher, pHash, nonce, deadline));
    }
}
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.