Skip to content
Verified contractPartialMIT

PullPool

Address0xb2d80254af189854bf90d2c338d87236d67d2bf3
Balance

0.581648 ETH

 

Transactions

3,869

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,625,281
Creation transaction
0x613b7b453d…472ce43ee0

src/PullPool.sol

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

import {Ownable} from "solady/auth/Ownable.sol";
import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

import {Config, Bounds} from "./PullPoolTypes.sol";
import {IConfigGuard} from "./interfaces/IConfigGuard.sol";
import {IFWA} from "./interfaces/IFWA.sol";
import {IFWAToken} from "./interfaces/IFWAToken.sol";
import {IFWARewards} from "./interfaces/IFWARewards.sol";
import {IERC721Minimal} from "./interfaces/IERC721Minimal.sol";

/// @title PullPool
/// @notice Pools ticket contributions to make one FWA acquisition per round, settles the allocated
///         position to FWAToken and distributes the
///         proceeds pro rata over the round's tickets. Tickets are a fixed-price denomination of the
///         contribution, not lottery entries: every ticket in a round receives the same share.
///
///         A round is funded, not counted. Tickets sell until the raise covers the live FWA pull price
///         plus the round's headroom; `pull` re-reads the price when called and executes the
///         acquisition only if the raise still covers it. Rounds that never cover, or whose acquisition
///         FWA refunds, pay every ticket back in full.
///
///         A ticket buy names who the tickets belong to, so a contract can fund a round on someone's
///         behalf and this contract pays that person directly. Standing orders are built that way,
///         outside this contract, rather than inside it.
/// @dev Non-upgradeable. No delegatecall. External protocol addresses are immutable. No call in a
///      round's life is discretionary: every crank is permissionless and every bound it applies is the
///      round's own snapshot, so no caller passes a slippage figure. `settle` takes no arguments and
///      no ticket check. The settlement takes FWA's bid as FWAToken and there is no sale, so a
///      floor at all, which `docs/KNOWN-LIMITATIONS.md` item 2 states and bounds.
///
///      `openRound` holds no loop and makes no call to any address but FWA. It is the only writer of
///      `roundCount`, so a revert there would stop every future round permanently; keeping it free of
///      caller-controlled iteration is what makes that unreachable rather than merely bounded.
contract PullPool is Ownable, ReentrancyGuard {
    /* ------------------------------------------------------------------ */
    /*                                TYPES                                */
    /* ------------------------------------------------------------------ */

    /// @notice Round lifecycle. A round only ever moves forward through this enum.
    enum RoundState {
        None,
        Open, // selling tickets until the raise covers the live pull price
        Pulling, // FWA acquisition requested
        Claimable, // FWA allocated a position, awaiting settlement
        Settled, // pots fixed, shares payable
        Refunding // terminal failure, refunds open
    }

    /// @notice How a round ended.
    enum Outcome {
        None,
        Tokens, // position sold to FWAToken and pooled
        BidToEth, // FWA's token route was unavailable, so the bid was taken in ETH instead
        ForcedEth, // the FWA depositor reclaimed the NFT, so the position resolved to ETH
        Refunded // ticket holders were paid back
    }

    /// @notice A run of consecutive ticket indices owned by one buyer. Ticket `i` belongs to the first
    ///         segment whose `endExclusive` exceeds `i`.
    struct Segment {
        address buyer;
        uint32 endExclusive;
    }

    struct Round {
        // --- snapshot, fixed once the round exists ---
        uint96 ticketPrice;
        uint16 feeBps;
        uint16 headroomBps;
        uint16 feeCapBps;
        uint96 crankBountyCap;
        uint96 vrfAllowance;
        uint64 bountyTipWei;
        uint64 stallTimeout;
        uint64 fundingDeadline;
        uint32 ticketsSold;
        uint32 maxTickets;
        uint256 minPoolWeightedValue; // snapshotted at open, so it bounds a value that has had time to move
        // --- ETH accounting, all in wei ---
        uint256 escrow; // round ETH held here and not yet assigned to a pot, fee, or refunds
        uint256 feeOwed; // protocol fee, non-zero only after a successful allocation
        uint256 refundPool; // fixed when the round enters Refunding
        uint256 ethPot; // pro-rata ETH: unspent budget, forced settlements, and sell proceeds
        uint256 tokenPot; // pro-rata FWAToken from settlement
        // --- FWA ---
        uint256 fwaRequestId;
        uint256 acquisitionSpent; // what FWA actually charged; the fee is a share of this
        uint256 bidValue; // the allocated position's bid value in wei, as it stood at allocation
        uint256 listingId;
        uint64 allocatedAt;
        uint64 pullingAt; // when the budget left for FWA; the stall clock runs from here
        RoundState state;
        Outcome outcome;
        bool fwaResolved;
        bool feeClaimed;
        bool nftHeld; // FWA delivered the position's NFT here; redeemable at the bid value
        bool rewardCredited; // the round's share of its reward epoch has been added to `tokenPot`
        uint128 creditTaken; // FWA credit already attributed to this round, against its `priceEscrowed`
        // How much of `tokenPot` came from the emission reward rather than from settlement. Kept as an
        // amount, not derived, because `tokenPot` mixes the two once credited and a holder auditing
        // what the protocol paid out should not have to index events to separate them. `rewardCredited`
        // stays the flag: a legitimate share of zero is not the same as an uncredited round.
        uint128 rewardAmount;
    }

    /* ------------------------------------------------------------------ */
    /*                              CONSTANTS                              */
    /* ------------------------------------------------------------------ */
    uint256 internal constant BPS = Bounds.BPS;

    /*
     * Everything in this block is a hard bound on an owner-settable value in `Config`. They are
     * `constant` and there is no proxy, so a reader gets a guarantee rather than a current setting.
     * A bound that the owner could also move would bound nothing.
     */

    /// @notice Ceiling on the protocol fee. The owner can lower `feeBps` but never raise it past 10%.
    uint16 public constant MAX_FEE_BPS = Bounds.MAX_FEE_BPS;

    /// @notice The protocol's share of every claimed reward epoch, in bps. The remainder is divided
    ///         across this contract's acquisitions in that epoch and paid to ticket holders. Fixed
    ///         rather than owner-settable, and separate from `feeBps`, which is charged on the pull.
    uint16 public constant REWARD_FEE_BPS = 2000; // 20%

    /// @notice Gas allowed to a listing's collection when probing custody, and when FWA's recovery
    ///         reaches that collection. Both calls run on the round's only exit, so what they are
    ///         allowed to spend has to be bounded rather than left at 63/64 of whatever remains.
    ///         Sized well above an ordinary `ownerOf` or `transferFrom` so an unusual but honest
    ///         collection still reads correctly.
    uint256 internal constant OWNER_OF_GAS = 100_000;
    uint256 internal constant RECOVER_GAS = 300_000;

    /// @notice Least a settlement may accept, in bps of the position's bid value. A floor of zero
    ///         would make the permissionless settle an unbounded sale.
    uint16 public constant MAX_HEADROOM_BPS = Bounds.MAX_HEADROOM_BPS; // 500%

    /// @notice Ceiling on how far past its own quote FWA may charge. Bounded far tighter than
    ///         `MAX_HEADROOM_BPS` because this one is a loss and that one is a refund.
    uint16 public constant MAX_FEE_CAP_BPS = Bounds.MAX_FEE_CAP_BPS; // 50%

    /// @notice Ceiling on one crank's reimbursement, whatever the measured gas comes to.
    uint96 public constant MAX_CRANK_BOUNTY = Bounds.MAX_CRANK_BOUNTY;

    /// @notice Ceiling on the per-gas tip a crank may be reimbursed above `block.basefee`.
    uint64 public constant MAX_BOUNTY_TIP = Bounds.MAX_BOUNTY_TIP;

    /// @notice Ceiling on how long a round may sit in `Pulling` before anyone can void it. This one
    ///         bounds how long principal can stay frozen when FWA stops resolving.
    uint64 public constant MAX_STALL_TIMEOUT = Bounds.MAX_STALL_TIMEOUT;

    /// @notice Ceiling on a round's ticket count. Coverage stops sales well before this.
    uint32 public constant MAX_TICKETS = Bounds.MAX_TICKETS;

    /// @notice Cranks a round reserves a bounty for: `pull`, `syncFwaResult`, open `settle`.
    uint256 internal constant BOUNTY_CRANKS = 3;

    /// @notice Gas the reimbursement cannot measure from inside itself: calldata, dispatch, and the
    ///         payout that follows the measurement.
    uint256 internal constant BOUNTY_GAS_OVERHEAD = 40_000;

    /* ------------------------------------------------------------------ */
    /*                             IMMUTABLES                              */
    /* ------------------------------------------------------------------ */

    IFWA public immutable FWA;
    IFWAToken public immutable FWA_TOKEN;
    IFWARewards public immutable FWA_REWARDS;

    /// @notice Stateless `pure` validator for `Config`, reached by staticcall. Not a delegatecall.
    IConfigGuard public immutable CONFIG_GUARD;

    /* ------------------------------------------------------------------ */
    /*                               STORAGE                               */
    /* ------------------------------------------------------------------ */

    /// @notice Protocol fee applied to new rounds, in bps of gross ticket sales. Snapshotted per round.
    uint16 public feeBps;

    /// @notice Blocks `openRound` and `buyTickets`. Never blocks advancing, settling, share payouts,
    ///         or refunds.
    bool public paused;

    /// @notice Permanently blocks new rounds once a successor contract is live.
    bool public deprecated;

    address public feeRecipient;

    /// @notice Terms for new rounds. Changing them never reaches a live round.
    Config public config;

    /// @notice How settlement pots are held and paid. `SellToEth` works without the distributor role.

    uint256 public roundCount;
    mapping(uint256 roundId => Round) internal _rounds;
    mapping(uint256 roundId => Segment[]) internal _segments;
    mapping(uint256 roundId => mapping(address buyer => uint32)) public ticketsOwned;
    /// @notice ETH already paid to a buyer for a round, as an amount rather than a yes/no. A pot can
    ///         still grow after claims open — a late FWA credit tops up a refund, a stuck NFT is
    ///         redeemed into a settled pot — and a boolean would forfeit every claimer's share of it.
    mapping(uint256 roundId => mapping(address buyer => uint256)) public ethPaidTo;

    /// @notice Cursor into `_segments` for the paged permissionless sweeps.
    mapping(uint256 roundId => uint256) internal sweepCursor;
    mapping(uint256 roundId => uint256) internal refundSweepCursor;

    /// @notice FWAToken already paid to a buyer for a round, as an amount rather than a yes/no, and
    ///         tracked separately from `ethPaidTo` so an undeliverable token leg never blocks an ETH
    ///         share. `tokenPot` grows after claims open when `creditRounds` adds the round's emission
    ///         share, and a boolean would forfeit that share for everyone who had already claimed.
    mapping(uint256 roundId => mapping(address buyer => uint256)) public tokenPaidTo;

    /// @notice Every wei this contract is holding for someone. The contract balance may exceed it
    ///         (forced sends); it must never be below it.
    uint256 public accountedEth;

    /// @notice The single round allowed to have ETH in flight at FWA. FWA pushes refunds and pulls
    ///         nothing, so one pointer is enough to attribute every incoming transfer.
    uint256 public ethPendingRound;

    /// @notice FWA credit this contract has withdrawn that belongs to a round other than the one that
    ///         withdrew it. FWA's credit is keyed by address, not by request, so a round voided while
    ///         its acquisition was still live can only be paid from a bucket like this one.
    uint256 public strayCredit;

    /// @notice FWAToken one acquisition in a claimed reward epoch is worth, net of `REWARD_FEE_BPS`.
    ///         One acquisition is one round, so this is what `creditRounds` adds to a round's token pot.
    mapping(uint256 epoch => uint256) public epochShare;

    /// @notice Reward epochs this contract has taken from FWA. Held apart from `epochShare` because a
    ///         share can legitimately be zero: `(received - cut) / units` truncates to nothing when an
    ///         epoch pays fewer wei than this contract has acquisitions in it, so a non-zero share
    ///         cannot serve as the claimed flag without conflating that case with an unclaimed epoch.
    mapping(uint256 epoch => bool) public epochClaimed;

    /* ------------------------------------------------------------------ */
    /*                                EVENTS                               */
    /* ------------------------------------------------------------------ */

    // --- a round's life ---
    /// @notice A round opened. Its terms are the snapshot in `getRound(roundId)`.
    event RoundOpened(uint256 indexed roundId);
    /// @notice Tickets were bought. `beneficiary` owns them and is who the round pays; `payer` sent the
    ///         ETH. They differ when a contract buys on someone's behalf.
    event TicketsPurchased(
        uint256 indexed roundId, address indexed beneficiary, address indexed payer, uint32 quantity, uint256 paid
    );
    event Pulled(uint256 indexed roundId, uint256 fwaRequestId, uint256 spent, address indexed cranker);
    event RoundClaimable(uint256 indexed roundId, uint256 listingId);
    event RoundSettled(uint256 indexed roundId, Outcome outcome, uint256 tokenPot, uint256 ethPot);
    event RoundVoided(uint256 indexed roundId, uint256 refundPool);

    // --- money out ---
    event ShareClaimed(uint256 indexed roundId, address indexed buyer, uint256 tokenAmount, uint256 ethAmount);
    event RefundClaimed(uint256 indexed roundId, address indexed buyer, uint256 amount);
    event FeeClaimed(uint256 indexed roundId, uint256 amount);
    /// @notice The surcharge stream reached the fee recipient. Carries no round: FWA credits it to this
    ///         address per acquisition surcharge, not per round.
    event RewardsClaimed(uint256 tokenAmount, uint256 ethAmount);
    /// @notice A reward epoch was claimed and priced. `received` is gross, `cut` is the protocol's share
    ///         of it, and `units` is how many of this contract's acquisitions divide the remainder.
    event EpochClaimed(uint256 indexed epoch, uint256 received, uint256 cut, uint256 units);
    /// @notice A round's share of its reward epoch was added to its token pot.
    event RoundRewardCredited(uint256 indexed roundId, uint256 indexed epoch, uint256 amount);
    event CrankBountyPaid(uint256 indexed roundId, address indexed cranker, uint256 amount);
    event StuckNftRedeemed(uint256 indexed roundId, address indexed recipient, uint256 paid);

    // --- the operator ---
    /// @notice The settings changed. Carries no payload: encoding the struct into a log cost 704 bytes
    ///         when it was measured. Read `config()` at this block for the new values.
    event ConfigSet();
    event FeeBpsSet(uint16 feeBps);
    event FeeRecipientSet(address indexed feeRecipient);
    event PausedSet(bool paused);
    event Deprecated();

    /* ------------------------------------------------------------------ */
    /*                                ERRORS                               */
    /* ------------------------------------------------------------------ */

    // --- the operator stopped something ---
    error IsPaused(); // temporary
    error IsDeprecated(); // permanent

    // --- the call came at the wrong moment ---
    error WrongState(); // the round is not in a state this call acts on
    error PreviousRoundLive(); // one round at a time
    error FundingClosed(); // past the selling window
    error NotCovered(); // the raise does not yet cover the live pull price
    error AlreadyCovered(); // it already does, so this call would undo a funded round
    error ListingNotReady(); // FWA has not put the listing where this call needs it
    error NothingToClaim();

    // --- the caller passed something the contract will not take ---
    error BadConfig(); // an owner setting outside the constant that bounds it
    error BadQuantity();
    error WrongPayment();
    error DirectEthNotAccepted();

    // --- the world outside is not in a state this contract will act on ---
    error FwaNotPricing(); // FWA cannot quote a pull at all
    error VrfLegTooHigh(); // FWA's randomness leg exceeds the round's snapshotted allowance
    error NotDistributor(); // token mode needs the FWAToken role
    error AlreadyCredited(); // this epoch, or this round's share of it, has already been taken
    error SettlementShortfall();
    error TransferFailed();

    /* ------------------------------------------------------------------ */
    /*                             CONSTRUCTOR                             */
    /* ------------------------------------------------------------------ */

    constructor(
        address fwa,
        address configGuard,
        address fwaToken,
        address fwaRewards,
        address owner_,
        address feeRecipient_,
        uint16 feeBps_,
        Config memory config_
    ) {
        if (
            fwa == address(0) || configGuard == address(0) || fwaToken == address(0) || fwaRewards == address(0)
                || owner_ == address(0)
                || feeRecipient_ == address(0)
        ) revert BadConfig();
        if (feeBps_ > MAX_FEE_BPS) revert BadConfig();

        FWA = IFWA(fwa);
        CONFIG_GUARD = IConfigGuard(configGuard);
        // After assignment: an immutable is not readable before it is written.
        IConfigGuard(configGuard).check(config_);
        FWA_TOKEN = IFWAToken(fwaToken);
        FWA_REWARDS = IFWARewards(fwaRewards);
        feeRecipient = feeRecipient_;
        feeBps = feeBps_;
        config = config_;

        _initializeOwner(owner_);
    }

    /* ------------------------------------------------------------------ */
    /*                                ADMIN                                */
    /* ------------------------------------------------------------------ */

    /// @notice Set the terms for rounds that have not opened yet.
    function setConfig(Config calldata c) external onlyOwner {
        CONFIG_GUARD.check(c);
        config = c;
        emit ConfigSet();
    }

    function setFeeBps(uint16 newFeeBps) external onlyOwner {
        if (newFeeBps > MAX_FEE_BPS) revert BadConfig();
        feeBps = newFeeBps;
        emit FeeBpsSet(newFeeBps);
    }

    function setFeeRecipient(address newFeeRecipient) external onlyOwner {
        if (newFeeRecipient == address(0)) revert BadConfig();
        feeRecipient = newFeeRecipient;
        emit FeeRecipientSet(newFeeRecipient);
    }

    function setPaused(bool newPaused) external onlyOwner {
        paused = newPaused;
        emit PausedSet(newPaused);
    }

    /// @notice Permanent. Blocks new rounds; every claim and refund keeps working.
    function deprecate() external onlyOwner {
        deprecated = true;
        emit Deprecated();
    }

    /* ------------------------------------------------------------------ */
    /*                              OPEN ROUND                             */
    /* ------------------------------------------------------------------ */

    /// @notice Open the next round on the stored config. Permissionless: every term is copied from
    ///         `config`, so the caller supplies nothing. It does fix two values by the block it lands
    ///         in — `fundingDeadline`, and `minPoolWeightedValue` at half FWA's weighted backing, which
    ///         is the floor `pull` passes to `acquire`. An opener choosing a thin block therefore sets
    ///         a lower floor than one choosing a deep block. The floor bounds how far FWA's pool may
    ///         degrade between open and pull; it is not a price the round pays.
    function openRound() external nonReentrant returns (uint256 roundId) {
        return _openRound();
    }

    function _openRound() internal returns (uint256 roundId) {
        if (paused) revert IsPaused();
        if (deprecated) revert IsDeprecated();

        // The previous round only has to have finished selling. One that is still at FWA, or awaiting
        // settlement, does not stop the next one taking tickets: what has to serialise is the pull, and
        // that is enforced in `pull`. A round that is merely selling holds no ETH at FWA, and its
        // ticket money is inside `accountedEth`, so it cannot be confused with a push FWA makes to a
        // round that is.
        uint256 previous = roundCount;
        if (previous != 0 && _rounds[previous].state == RoundState.Open) revert PreviousRoundLive();

        // A round only opens against a pool that can currently price a pull. The fee leg is read
        // rather than the total: the total's VRF component prices off the caller's own tx.gasprice.
        uint256 poolFee = FWA.acquisitionFee();
        if (poolFee == 0) revert FwaNotPricing();
        // Zero disables FWA's drained-pool check, exactly as a zero fee ceiling disables its price
        // check, so the floor this round will be held to has to be a real number at open.
        uint256 poolValue = FWA.weightedBackingTotal();
        if (poolValue < 2) revert FwaNotPricing();

        Config memory c = config;
        roundId = previous + 1;
        roundCount = roundId;

        Round storage r = _rounds[roundId];
        r.ticketPrice = c.ticketPrice;
        r.feeBps = feeBps;
        r.headroomBps = c.headroomBps;
        r.feeCapBps = c.feeCapBps;
        r.maxTickets = c.maxTickets;
        r.crankBountyCap = c.crankBountyCap;
        r.bountyTipWei = c.bountyTipWei;
        r.stallTimeout = c.stallTimeout;
        r.vrfAllowance = c.vrfAllowance;
        r.minPoolWeightedValue = poolValue / 2;
        r.fundingDeadline = uint64(block.timestamp) + c.fundingDuration;
        r.state = RoundState.Open;

        emit RoundOpened(roundId);
    }

    /* ------------------------------------------------------------------ */
    /*                              FUNDING                                */
    /* ------------------------------------------------------------------ */

    /// @notice Buy whole tickets, for yourself or for someone else. Asking for more than the round still
    ///         needs clamps to what is needed and refunds the difference to the payer, so the last buyer
    ///         never overshoots the coverage.
    /// @param beneficiary Who the tickets belong to, and therefore who the round pays and who may settle
    ///        it. Zero means the caller. A contract buying on someone's behalf names them here, so the
    ///        pot and any refund reach them directly and the buying contract never holds either.
    /// @return bought Tickets actually credited, which is below `quantity` when the clamp binds. A caller
    ///         buying out of an escrow it keeps for someone else needs this to debit the right amount.
    function buyTickets(uint256 roundId, uint32 quantity, address beneficiary)
        external
        payable
        nonReentrant
        returns (uint32 bought)
    {
        return _buy(roundId, quantity, beneficiary);
    }

    /// @notice Buy into the round that is currently selling, opening one first if none is. One
    ///         transaction, so a buyer arriving when the last round has moved on is never told to come
    ///         back: `openRound` decides nothing and anybody may call it, so folding it into the buy
    ///         grants nothing that was not already public.
    /// @dev The buyer who opens the round pays that gas themselves. It is not reimbursed, because a
    ///      bounty for it would have to be reserved in every round's coverage target and so charged to
    ///      every round to pay for the occasional one that needed it.
    /// @return roundId The round the tickets went into, new or already selling.
    /// @return bought Tickets actually credited, below `quantity` when the coverage clamp binds.
    function buyIntoCurrentRound(uint32 quantity, address beneficiary)
        external
        payable
        nonReentrant
        returns (uint256 roundId, uint32 bought)
    {
        roundId = roundCount;
        // A round that is still `Open` is the current one even when its funding deadline has passed,
        // because `_openRound` refuses while it is: opening the next one requires voiding this one
        // first, which is a decision this call has no business making on a buyer's behalf. That case
        // reverts `FundingClosed`, and the exit is the permissionless `voidRound`.
        if (roundId == 0 || _rounds[roundId].state != RoundState.Open) roundId = _openRound();
        bought = _buy(roundId, quantity, beneficiary);
    }

    function _buy(uint256 roundId, uint32 quantity, address beneficiary) internal returns (uint32 bought) {
        if (paused) revert IsPaused();
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Open) revert WrongState();
        if (block.timestamp > r.fundingDeadline) revert FundingClosed();
        if (quantity == 0) revert BadQuantity();
        // Tickets credited to the zero address would burn that share of the pot, so this cannot fall
        // through to `_recordTickets`.
        // Tickets credited here would pay a share back into the contract, where `_payOut` has already
        // decremented `accountedEth` for it, turning a holder's share into unattributed stray ETH that
        // the next forced settlement sweeps into a different round.
        if (beneficiary == address(this)) revert BadConfig();
        if (beneficiary == address(0)) beneficiary = msg.sender;

        uint256 needed = ticketsNeeded(roundId);
        if (needed == 0) revert AlreadyCovered();
        if (uint256(quantity) > needed) quantity = uint32(needed);

        uint256 cost = uint256(quantity) * uint256(r.ticketPrice);
        if (msg.value < cost) revert WrongPayment();

        r.escrow += cost;
        accountedEth += cost;
        _recordTickets(roundId, r, beneficiary, quantity);
        emit TicketsPurchased(roundId, beneficiary, msg.sender, quantity, cost);

        // Change goes to whoever paid, which is not necessarily who the tickets belong to.
        uint256 change = msg.value - cost;
        if (change != 0) SafeTransferLib.forceSafeTransferETH(msg.sender, change);
        return quantity;
    }

    /// @dev Append tickets for `buyer`, extending their run when they were the last buyer recorded.
    function _recordTickets(uint256 roundId, Round storage r, address buyer, uint32 quantity) internal {
        uint32 sold = r.ticketsSold;
        uint32 newSold = sold + quantity;
        if (newSold > r.maxTickets) revert BadQuantity();
        r.ticketsSold = newSold;
        ticketsOwned[roundId][buyer] += quantity;

        Segment[] storage segs = _segments[roundId];
        uint256 segCount = segs.length;
        if (segCount != 0 && segs[segCount - 1].buyer == buyer) {
            segs[segCount - 1].endExclusive = newSold;
        } else {
            segs.push(Segment({buyer: buyer, endExclusive: newSold}));
        }
    }

    /// @notice The raise, in wei, this round needs before it can pull at the current FWA price: the
    ///         live quote plus the round's headroom, the crank bounties, and the fee on the whole
    ///         gross, rounded up to a whole ticket.
    function requiredGross(uint256 roundId) public view returns (uint256) {
        Round storage r = _rounds[roundId];
        if (r.state == RoundState.None) revert WrongState();
        // `acquisitionFee()` carries no tx.gasprice term, so the coverage target is the same number
        // for every caller. The randomness leg is a fixed per-round allowance instead.
        uint256 poolFee = FWA.acquisitionFee();
        uint256 target = (poolFee * (BPS + uint256(r.headroomBps))) / BPS + uint256(r.vrfAllowance);
        uint256 reserved = target + BOUNTY_CRANKS * uint256(r.crankBountyCap);
        // `pull` withholds the fee on the whole gross before forming the budget, so the raise has to be
        // the amount that still clears the acquisition after that withholding. Adding the fee on the
        // quote alone leaves a shortfall of `feeBps` of everything else reserved, which a small enough
        // pool fee turns into a round that closes but can never pull. Grossing up is exact.
        //
        // This does not charge holders more. What is actually charged is fixed in `syncFwaResult` as a
        // share of `acquisitionSpent`, the pull itself; the difference `pull` withholds beyond that stays
        // in the round's escrow and reaches holders in the pot.
        uint256 gross = (reserved * BPS) / (BPS - uint256(r.feeBps));
        uint256 price = uint256(r.ticketPrice);
        return ((gross + price - 1) / price) * price;
    }

    /// @notice Tickets still needed at the current FWA price. Zero means the round is covered and can
    ///         advance.
    function ticketsNeeded(uint256 roundId) public view returns (uint256) {
        Round storage r = _rounds[roundId];
        // `openRound` and `pull` both refuse a zero `acquisitionFee()`. Coverage has to refuse it too:
        // the target would otherwise collapse to the reserves alone and an under-funded round would
        // read as covered, which closes ticket sales and the permissionless void at once.
        if (FWA.acquisitionFee() == 0) return type(uint256).max;
        uint256 gross = uint256(r.ticketsSold) * uint256(r.ticketPrice);
        uint256 needed = requiredGross(roundId);
        if (gross >= needed) return 0;
        return (needed - gross) / uint256(r.ticketPrice);
    }

    /* ------------------------------------------------------------------ */
    /*                               ADVANCE                               */
    /* ------------------------------------------------------------------ */

    /// @notice Execute the round's FWA acquisition at the live price. Permissionless and bountied.
    ///         Succeeds exactly when the raise covers the current quote plus reserves; a price move in
    ///         either direction only changes when that is true, never strands the round.
    function pull(uint256 roundId) external nonReentrant {
        uint256 gasStart = gasleft();
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Open) revert WrongState();
        // One round at FWA at a time. `ethPendingRound` is the only attribution an unaccounted transfer
        // from FWA has, so a second acquisition in flight would make a depositor's reclaim payout
        // impossible to assign to the round that earned it.
        if (ethPendingRound != 0) revert PreviousRoundLive();
        // The same coverage test `buyTickets` closes on. Advancing at the bare quote instead would
        // let a holder close the round below the bar it advertises, concentrating the position among
        // the tickets already sold and reverting everyone else's pending purchase.
        if (ticketsNeeded(roundId) != 0) revert NotCovered();

        uint256 gross = uint256(r.ticketsSold) * uint256(r.ticketPrice);
        uint256 feeReserve = (gross * uint256(r.feeBps)) / BPS;
        uint256 bountyReserve = BOUNTY_CRANKS * uint256(r.crankBountyCap);
        if (r.escrow < feeReserve + bountyReserve) revert NotCovered();
        uint256 budget = r.escrow - feeReserve - bountyReserve;

        (uint256 quotedFee, uint256 fwaVrfLeg, uint256 total) = FWA.quoteAcquisitionPrice();
        if (total == 0 || budget < total) revert NotCovered();
        // The randomness leg prices off the caller's own gas price, so it is capped by the round's
        // snapshotted allowance rather than by whatever the cranker chose to pay.
        if (fwaVrfLeg > uint256(r.vrfAllowance)) revert VrfLegTooHigh();
        // The ceiling is the quote plus `feeCapBps`, which is a different number from the raise's
        // `headroomBps` because the two protect against opposite things. Overpayment above what FWA
        // charges is refunded inside `acquire`, so a generous raise costs holders only lockup; a
        // generous ceiling costs them the difference outright. Bounding it by `budget` instead would
        // authorise FWA to consume the whole raise, which is the holders' rebate.
        // FWA reads a zero `maxAcquisitionFee` as "check disabled", so a zero quote would turn the
        // ceiling off rather than set it to zero. `openRound` guards the same value.
        if (quotedFee == 0) revert FwaNotPricing();
        uint256 feeCap = (quotedFee * (BPS + uint256(r.feeCapBps))) / BPS;
        // `feeCapBps` and `headroomBps` are independent settings, so the ceiling can authorise a price
        // the raise was never sized for. FWA would then charge inside the ceiling, revert on the value,
        // and leave a covered round wedged. Clamping to what is actually funded turns that into an
        // ordinary `NotCovered` reopen instead of a stuck round.
        uint256 payable_ = budget > fwaVrfLeg ? budget - fwaVrfLeg : 0;
        if (feeCap > payable_) feeCap = payable_;

        // Effects first: the round is in the pull before any external call is made.
        r.state = RoundState.Pulling;
        ethPendingRound = roundId;

        uint256 balanceBefore = address(this).balance;
        uint256 fwaRequestId = FWA.acquire{value: budget}(feeCap, r.minPoolWeightedValue);
        uint256 spent = balanceBefore - address(this).balance;

        r.fwaRequestId = fwaRequestId;
        r.pullingAt = uint64(block.timestamp);
        r.acquisitionSpent = spent;
        r.escrow -= spent;
        accountedEth -= spent;

        emit Pulled(roundId, fwaRequestId, spent, msg.sender);
        _payBounty(roundId, r, gasStart);
    }

    /// @dev One bounty per crank, from the round's escrow. Skipped silently if the escrow cannot pay,
    ///      so an underfunded bounty can never block the round itself.
    /// @dev Reimburses a crank for the gas it actually burned, capped.
    ///
    ///      Priced off `block.basefee`, not `tx.gasprice`: the caller sets the latter, so pricing a
    ///      refund with it would let a cranker name its own payout up to the cap. `basefee` is the
    ///      block's, and a caller paying it is paying the real cost of the same block.
    ///
    ///      `gasStart` is read at the entry of the calling crank, so the measurement covers that
    ///      function's whole body. What it cannot see, `BOUNTY_GAS_OVERHEAD` covers.
    function _payBounty(uint256 roundId, Round storage r, uint256 gasStart) internal {
        uint256 due = (gasStart - gasleft() + BOUNTY_GAS_OVERHEAD) * (block.basefee + uint256(r.bountyTipWei));
        uint256 cap = uint256(r.crankBountyCap);
        if (due > cap) due = cap;
        if (due == 0 || r.escrow < due) return;
        r.escrow -= due;
        accountedEth -= due;
        emit CrankBountyPaid(roundId, msg.sender, due);
        SafeTransferLib.forceSafeTransferETH(msg.sender, due);
    }

    /* ------------------------------------------------------------------ */
    /*                            FWA RESOLUTION                           */
    /* ------------------------------------------------------------------ */

    /// @notice Read the terminal state of the round's FWA acquisition and record it. Permissionless
    ///         and bountied. A fulfilled acquisition makes the round claimable and accrues the fee; an
    ///         expired or refunded one sends the round to refunds.
    /// @dev FWA settles acquisitions strictly in request order. A request sitting in `Pending`,
    ///      `Ready`, or `TimedOut` has not reached its turn; anyone can move the queue with
    ///      `FWA.processAcquisitions(n)`, which FWA also self-calls at the end of each callback.
    function syncFwaResult(uint256 roundId) external nonReentrant {
        uint256 gasStart = gasleft();
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Pulling) revert WrongState();

        (,,, uint256 listingId, uint8 status) = FWA.acquisitions(r.fwaRequestId);

        if (status == uint8(IFWA.AcquisitionStatus.Fulfilled)) {
            _reconcile(r);
            if (listingId == 0) revert ListingNotReady();
            (, address purchaser,, uint256 backing, uint64 allocatedAt,) = _listing(listingId);
            if (purchaser != address(this)) revert ListingNotReady();

            r.listingId = listingId;
            r.allocatedAt = allocatedAt;
            r.fwaResolved = true;
            // The stuck-NFT price, taken here while the listing is one FWA still reports in full.
            // `redeemStuckNft` is only reachable after this listing has reached `Settled`, and FWA has no
            // reason to maintain `value` past that transition; a zeroed one would hand the token away.
            // Nothing in the funding path is snapshotted with it: coverage reads the price live.
            r.bidValue = (backing * FWA.settlementDiscountBps()) / BPS;

            // On what the pull actually cost. Charging it on the raise would let `headroomBps`,
            // a separate owner setting, multiply the base that `MAX_FEE_BPS` is supposed to bound.
            uint256 fee = (r.acquisitionSpent * uint256(r.feeBps)) / BPS;
            if (fee != 0 && fee <= r.escrow) {
                r.feeOwed = fee;
                r.escrow -= fee;
            }

            r.state = RoundState.Claimable;
            emit RoundClaimable(roundId, listingId);
            _payBounty(roundId, r, gasStart);
        } else if (status == uint8(IFWA.AcquisitionStatus.Expired) || status == uint8(IFWA.AcquisitionStatus.Refunded))
        {
            _reconcile(r);
            // No bounty here: `_enterRefunding` fixes the refund pool from what is left, and a
            // refunded round must return every ticket in full.
            _enterRefunding(roundId, r);
            ethPendingRound = 0;
        } else {
            revert WrongState();
        }
    }

    /* ------------------------------------------------------------------ */
    /*                              SETTLEMENT                             */
    /* ------------------------------------------------------------------ */

    /// @notice Sell the round's allocated position and fix the pots. Permissionless and bountied, from
    ///         the moment the round is `Claimable`. The caller passes nothing and decides nothing.
    ///
    ///         Every number is the contract's own. The settlement takes FWA's bid as FWAToken and
    ///         applied to the position's bid value, which is known exactly, so every caller is held to
    ///         the same floor. On the token path there is no floor, and there does not need to be one:
    ///         a sandwich of it is reachable but not worth running: the buy leg needs a surcharge allowance
    ///         that only accrues after an hour of FWA-wide quiet, and at the pool's depth the attacker
    ///         nets less than the holders lose. The moment the gate opens, `_executeSettlement` stops
    ///         settling to tokens at all and takes the floored ETH path instead.
    ///
    ///         So a round resolves as soon as anyone cranks it, and nobody has a bound to get wrong or a
    ///         window to wait out.
    function settle(uint256 roundId) external nonReentrant {
        uint256 gasStart = gasleft();
        _executeSettlement(roundId, _rounds[roundId], gasStart);
    }

    /// @notice Close a round whose FWA listing left `Allocated` without this contract selling it:
    ///         the depositor reclaimed, or FWA's finalize window lapsed. Permissionless, because
    ///         every branch is decided by FWA's own recorded state.
    /// @dev If FWA delivered the NFT here the round still closes. The NFT is not splittable across
    ///      tickets, so it is parked as `nftHeld` and anyone may buy it at the position's own bid
    ///      value through `redeemStuckNft`, which pays the holders exactly what a sale would have.
    function settleForcedEth(uint256 roundId) external nonReentrant {
        uint256 gasStart = gasleft();
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Claimable) revert WrongState();

        _reconcile(r);

        // The reclaim payout arrives as a push, not a credit, so it sits above the ledger. Only one
        // round can have ETH in flight, so everything unaccounted here belongs to this round.
        uint256 stray = address(this).balance - accountedEth;
        if (stray != 0) {
            r.escrow += stray;
            accountedEth += stray;
        }

        (address collection,, uint256 tokenId,,, uint8 status) = _listing(r.listingId);
        if (status != uint8(IFWA.ListingStatus.Settled)) revert ListingNotReady();

        // Take custody of anything FWA is still holding for us before closing. Both calls reach the
        // listing's collection, which its depositor chose, and this is the round's only exit: `settle`
        // needs the listing `Allocated`, `voidRound` has no `Claimable` branch, and `_closeSettled` is
        // the only writer of `ethPendingRound = 0`. So a revert inside either call would strand this
        // round and, through `ethPendingRound`, stop every future round from pulling, with no owner
        // override. `ownerOf` is required by ERC-721 to throw for a burned token, and `recoverStuckNFT`
        // performs a `transferFrom` on the same contract, so both fail open instead: custody is a
        // best-effort probe, and a collection that misbehaves costs its own round's NFT rather than the
        // protocol's liveness.
        if (FWA.stuckNFTRecipient(r.listingId) == address(this)) {
            // Gas-bounded as well as caught: the recovery reaches the collection's `transferFrom`, and
            // an unbounded `try` forwards 63/64 of what is left, so a collection that simply burns gas
            // starves the rest of this function even though the revert itself is handled.
            try FWA.recoverStuckNFT{gas: RECOVER_GAS}(r.listingId) {} catch {}
        }

        // Bounded on both sides, so a hostile collection cannot halt the round. A probe that can fail
        // is not evidence of absence, which is why `syncNftCustody` can run it again with more gas.
        if (_holdsNft(collection, tokenId, OWNER_OF_GAS)) r.nftHeld = true;

        _closeSettled(roundId, r, Outcome.ForcedEth, gasStart);
    }

    /// @dev The one settlement body. Sells the position for FWAToken, then either holds the pot or
    ///      sells on for ETH per the payout mode, folds the unspent escrow into the ETH pot, and
    ///      closes the round. Under SellToEth the round's own floor binds whatever `minEthOut` says.
    function _executeSettlement(uint256 roundId, Round storage r, uint256 gasStart) internal {
        if (r.state != RoundState.Claimable) revert WrongState();
        _reconcile(r);

        (,,, uint256 backing,, uint8 status) = _listing(r.listingId);
        if (status != uint8(IFWA.ListingStatus.Allocated)) revert ListingNotReady();
        // A zero backing would leave the bid this round is taking unvalued, so refuse it: the same
        // so a holder can read the worst case out of the bytecode, but a zero on either read multiplies
        // that guarantee away and leaves the permissionless sale unbounded. `redeemStuckNft`, `pull` and
        // `openRound` each guard the same hazard on their own FWA read; this one is the sale.
        if (backing == 0) revert ListingNotReady();

        // No mode and no fallback. Taking FWA's bid is an inbound transfer, and the transfer lock
        // passes it whether or not this contract holds the distributor role, so settlement never
        // needed the role: only paying holders does. `_payOut` skips a token leg it cannot deliver
        // and leaves it claimable, so a role that is absent delays a payout instead of stranding a
        // round, and the round still reaches `Settled` and releases `ethPendingRound`.
        //
        // There is no sale, so there is no floor to set and nothing to sandwich on the way out. The
        // buy leg is still unfloored, which `docs/KNOWN-LIMITATIONS.md` item 2 states rather than
        // argues away; what is gone is the path that turned every settlement into sell pressure on
        // the token this pool exists to accumulate.
        r.state = RoundState.Settled;

        // The token route is the one this pool exists for, and it is the one FWA can switch off:
        // `acceptBidAsTokens` reverts `AcceptBidAsTokensDisabled` whenever its owner clears
        // `acceptBidAsTokensEnabled`, which is `internal` on FWA so there is nothing to read first.
        //
        // Without a second route that is the end of the round. `settle` is the only exit from
        // `Claimable`, `voidRound` has no `Claimable` branch, and `settleForcedEth` needs the listing
        // `Settled`, which needs FWA's own `finalizeUnsettled` — and `finalizeWindow` is bounded below
        // by `settlementWindow` and not above, so setting it to `type(uint256).max` makes
        // `allocatedAt + finalizeWindow` overflow and revert for good under FWA's ^0.8.24. The round
        // wedges, `ethPendingRound` stays set, and no later round can ever pull.
        //
        // So fall through to the bid in ETH. Identical economics — `settlementDiscountBps` of the same
        // backing — paid from the depositor's escrow rather than bought off the pool, and FWA exposes
        // no way to disable it. This is not the sale that was removed: nothing here touches the v4
        // pool, so it adds no sell pressure and no pool dependency.
        //
        // The catch is deliberately every revert, not just the disabled one. `acceptBidAsTokensEnabled`
        // is `internal` on FWA with no getter, so the cause cannot be told apart on chain, and the
        // alternative to catching broadly is a round that strands on any token-route failure. A buy
        // that would return zero tokens takes the ETH bid too, which is the same trade at the same
        // price rather than a settlement worth nothing. The cost is that a token-route failure this
        // contract cannot see the reason for ends the round in ETH instead of $FWA, permanently for
        // that round.
        uint256 balanceBefore = FWA_TOKEN.balanceOf(address(this));
        try FWA.acceptBidAsTokens(r.listingId, 1) {
            uint256 received = FWA_TOKEN.balanceOf(address(this)) - balanceBefore;
            if (received == 0) revert SettlementShortfall();
            r.tokenPot = received;
            _closeSettled(roundId, r, Outcome.Tokens, gasStart);
        } catch {
            uint256 ethBefore = address(this).balance;
            FWA.acceptDepositorBid(r.listingId);
            uint256 proceeds = address(this).balance - ethBefore;
            if (proceeds == 0) revert SettlementShortfall();
            r.ethPot += proceeds;
            accountedEth += proceeds;
            _closeSettled(roundId, r, Outcome.BidToEth, gasStart);
        }
    }


    /// @dev Fold the unspent escrow into the ETH pot and close the round. Every settlement path,
    ///      voluntary or forced, ends here.
    /// @dev `gasStart` is the crank's entry reading, or zero for a path that pays no bounty. The bounty
    ///      is paid here rather than at the caller because the measurement has to span the settlement
    ///      body while the escrow it draws from is still intact: the fold below zeroes it.
    function _closeSettled(uint256 roundId, Round storage r, Outcome outcome, uint256 gasStart) internal {
        if (gasStart != 0) _payBounty(roundId, r, gasStart);
        r.state = RoundState.Settled;
        r.outcome = outcome;
        r.ethPot += r.escrow;
        r.escrow = 0;
        ethPendingRound = 0;
        emit RoundSettled(roundId, r.outcome, r.tokenPot, r.ethPot);
    }

    /// @notice Buy a stuck NFT from a settled round at the position's own bid value. The ETH joins
    ///         that round's pot, so its holders receive exactly what a settlement would have paid
    ///         them, and the token leaves a contract that cannot otherwise move it.
    function redeemStuckNft(uint256 roundId, address recipient) external payable nonReentrant {
        Round storage r = _rounds[roundId];
        if (!r.nftHeld) revert NothingToClaim();
        if (recipient == address(0)) revert BadConfig();

        (address collection,, uint256 tokenId,,,) = _listing(r.listingId);
        // The bid value FWA reported at allocation. This function is only ever reachable after the
        // listing reached `Settled`, so pricing off `listings[].value` here prices off a field FWA has
        // no reason to maintain past that transition, and a zeroed one hands the token away for free.
        uint256 price = r.bidValue;
        if (price == 0) revert NothingToClaim();
        if (msg.value != price) revert WrongPayment();

        r.nftHeld = false;
        r.ethPot += price;
        // Rewound for the same reason `creditRounds` rewinds it: a pot that grows after claims opened
        // is only delivered by the paged sweep if the sweep starts again. This is the largest single
        // payout a forced round makes.
        sweepCursor[roundId] = 0;
        accountedEth += price;
        emit StuckNftRedeemed(roundId, recipient, price);

        _transferNft(collection, tokenId, recipient);
    }

    /* ------------------------------------------------------------------ */
    /*                                SHARES                               */
    /* ------------------------------------------------------------------ */

    /// @notice What one buyer's tickets are owed from a settled round.
    function shareOwed(uint256 roundId, address buyer) public view returns (uint256 tokenAmount, uint256 ethAmount) {
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Settled) return (0, 0);
        uint256 tickets = ticketsOwned[roundId][buyer];
        uint256 sold = r.ticketsSold;
        if (tickets == 0 || sold == 0) return (0, 0);
        // Each leg answers for its own ledger. `_payOut` settles them independently, so collapsing
        // both onto the ETH one reports a payable token leg as nothing owed.
        //
        // The token leg mirrors the write path's role check, so this reports what a claim would pay
        // now rather than what the round owes in principle. Without the role `_payOut` skips that leg
        // and returns success, so a caller reconciling against this would book a receipt that never
        // arrived. The latent amount stays derivable from `getRound().tokenPot` and `tokenPaidTo`.
        uint256 tokenOwed = FWA_TOKEN.isDistributor(address(this)) ? (r.tokenPot * tickets) / sold : 0;
        uint256 tokenAlready = tokenPaidTo[roundId][buyer];
        tokenAmount = tokenOwed > tokenAlready ? tokenOwed - tokenAlready : 0;
        uint256 owed = (r.ethPot * tickets) / sold;
        uint256 already = ethPaidTo[roundId][buyer];
        ethAmount = owed > already ? owed - already : 0;
    }

    /// @notice Refund owed to one buyer: their pro-rata share of the refund pool, which is their exact
    ///         contribution whenever the round spent nothing.
    function refundOwed(uint256 roundId, address buyer) public view returns (uint256) {
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Refunding) return 0;
        uint256 tickets = ticketsOwned[roundId][buyer];
        uint256 sold = r.ticketsSold;
        if (tickets == 0 || sold == 0) return 0;
        uint256 owed = (r.refundPool * tickets) / sold;
        uint256 already = ethPaidTo[roundId][buyer];
        return owed > already ? owed - already : 0;
    }

    /// @dev Pay one buyer whatever the round's terminal state owes them: pot shares when settled,
    ///      the refund when refunding. The ETH and token legs carry separate flags, so a token
    ///      transfer this contract cannot make never blocks ETH that never needed it.
    function _payOut(uint256 roundId, Round storage r, address buyer) internal returns (bool paid) {
        bool refunding = r.state == RoundState.Refunding;
        uint256 tickets = ticketsOwned[roundId][buyer];
        if (tickets == 0) return false;
        uint256 sold = r.ticketsSold;

        uint256 owed = ((refunding ? r.refundPool : r.ethPot) * tickets) / sold;
        uint256 already = ethPaidTo[roundId][buyer];
        if (owed > already) {
            uint256 ethAmount = owed - already;
            ethPaidTo[roundId][buyer] = owed;
            paid = true;

            accountedEth -= ethAmount;
            SafeTransferLib.forceSafeTransferETH(buyer, ethAmount);
            if (refunding) emit RefundClaimed(roundId, buyer, ethAmount);
            else emit ShareClaimed(roundId, buyer, 0, ethAmount);
        }

        // The role is checked rather than assumed, so a leg this contract cannot currently pay is
        // skipped and the ETH leg above stands. That covers the role being absent, which is the
        // reachable case. It does not cover the transfer itself failing: a `false` return reverts the
        // whole call, ETH leg included. FWAToken reverts rather than returning false and its lock
        // passes any transfer whose sender is a distributor, which this contract is whenever this
        // branch runs, so the revert is unreachable through it — but the guarantee is the token's,
        // not this contract's.
        if (!refunding && r.tokenPot != 0 && FWA_TOKEN.isDistributor(address(this))) {
            uint256 tokenOwed = (r.tokenPot * tickets) / sold;
            uint256 tokenAlready = tokenPaidTo[roundId][buyer];
            if (tokenOwed > tokenAlready) {
                uint256 tokenAmount = tokenOwed - tokenAlready;
                tokenPaidTo[roundId][buyer] = tokenOwed;
                paid = true;
                if (!FWA_TOKEN.transfer(buyer, tokenAmount)) revert TransferFailed();
                emit ShareClaimed(roundId, buyer, tokenAmount, 0);
            }
        }
    }

    /*
     * `_sweep` and `_terminalRound` serve both terminal states. Naming the flag at the call site
     * keeps `_sweep(roundId, n, REFUNDS)` from reading as `_sweep(roundId, n, true)`.
     */
    bool private constant SHARES = false;
    bool private constant REFUNDS = true;

    /// @dev The round must be in the terminal state its claim path serves.
    function _terminalRound(uint256 roundId, bool refunding) internal view returns (Round storage r) {
        r = _rounds[roundId];
        if (r.state != (refunding ? RoundState.Refunding : RoundState.Settled)) revert WrongState();
    }

    function _sweep(uint256 roundId, uint256 maxSegments, bool refunding) internal {
        Round storage r = _terminalRound(roundId, refunding);
        // The cursor only moves forward, and `_payOut` skips an undeliverable token leg rather than
        // reverting, so sweeping while the role is down would carry the cursor past holders whose
        // tokens were never sent and never come back for them. Refuse instead; `claimShares` still
        // pays anyone who asks for themselves, and the sweep resumes when the role does.
        if (!refunding && r.tokenPot != 0 && !FWA_TOKEN.isDistributor(address(this))) {
            revert NotDistributor();
        }
        mapping(uint256 => uint256) storage cursors = refunding ? refundSweepCursor : sweepCursor;
        Segment[] storage segs = _segments[roundId];

        uint256 cursor = cursors[roundId];
        uint256 end = cursor + maxSegments;
        if (end > segs.length) end = segs.length;
        for (; cursor < end; cursor++) {
            _payOut(roundId, r, segs[cursor].buyer);
        }
        cursors[roundId] = cursor;
    }

    /// @notice Take your refund from one voided or failed round.
    function claimRefund(uint256 roundId) external nonReentrant {
        Round storage r = _terminalRound(roundId, REFUNDS);
        if (!_payOut(roundId, r, msg.sender)) revert NothingToClaim();
    }

    /// @dev Walk a caller's rounds and pay each terminal one.
    function _collect(uint256[] calldata roundIds) internal {
        bool any;
        for (uint256 i = 0; i < roundIds.length; i++) {
            Round storage r = _rounds[roundIds[i]];
            RoundState st = r.state;
            if (st == RoundState.Settled || st == RoundState.Refunding) {
                if (_payOut(roundIds[i], r, msg.sender)) any = true;
            }
        }
        if (!any) revert NothingToClaim();
    }

    /// @notice Take your share of any number of settled rounds. A standing order puts one buyer in
    ///         every round it funded, so many-at-once is the ordinary case, not the rare one; pass a
    ///         single id for a single round.
    function claimShares(uint256[] calldata roundIds) external nonReentrant {
        _collect(roundIds);
    }

    /// @notice Pay out up to `maxSegments` buyers' shares of a settled round. Permissionless; call
    ///         until the cursor reaches the segment count and every buyer is paid.
    function sweepShares(uint256 roundId, uint256 maxSegments) external nonReentrant {
        _sweep(roundId, maxSegments, SHARES);
    }

    /// @notice Pay out up to `maxSegments` buyers' refunds. Permissionless, paged like `sweepShares`.
    function sweepRefunds(uint256 roundId, uint256 maxSegments) external nonReentrant {
        _sweep(roundId, maxSegments, REFUNDS);
    }

    /// @notice Close a round and open refunds. An `Open` round that never covered may be voided
    ///         once its funding deadline passes; a `Pulling` round whose FWA request never reached a
    ///         terminal status may be voided after the round's `stallTimeout`, which is the only exit this
    ///         contract controls if FWA's queue stops moving. The owner may act earlier on an open
    ///         round only. Every ticket is refunded from whatever the round still holds.
    function voidRound(uint256 roundId) external nonReentrant {
        Round storage r = _rounds[roundId];
        if (r.state == RoundState.Pulling) {
            // From when the budget left, not from when ticket sales ended. `pull` has no
            // deadline of its own, so a round advanced late would otherwise arrive with its stall
            // grace already spent and be voidable in the same block.
            if (block.timestamp <= uint256(r.pullingAt) + uint256(r.stallTimeout)) revert FundingClosed();
            // A stall is FWA's status, not the clock. Refunding a request FWA can still fulfil would
            // orphan the position it is about to allocate: the round would be `Refunding`, so neither
            // `syncFwaResult` nor `settleForcedEth` could take custody of it. `Fulfilled` belongs to
            // `syncFwaResult`. `Ready` has an on-time word cached and will be fulfilled when it reaches
            // the head of FWA's queue. `Pending` can still receive an on-time word until its selection
            // deadline lapses. Only `TimedOut`, `Expired` and `Refunded` can no longer become a position.
            (, uint256 requestBlock,,, uint8 acqStatus) = FWA.acquisitions(r.fwaRequestId);
            if (
                acqStatus == uint8(IFWA.AcquisitionStatus.Fulfilled) || acqStatus == uint8(IFWA.AcquisitionStatus.Ready)
                    || (acqStatus == uint8(IFWA.AcquisitionStatus.Pending)
                        && block.number <= requestBlock + FWA.selectionTimeoutBlocks())
            ) revert WrongState();
            _reconcile(r);
            ethPendingRound = 0;
            _enterRefunding(roundId, r);
            return;
        }
        if (r.state != RoundState.Open) revert WrongState();
        if (block.timestamp <= r.fundingDeadline && msg.sender != owner()) revert FundingClosed();
        // Coverage protects a round only until its funding deadline. Before the deadline a covered
        // round belongs to `pull`: killing it is destroying its acquisition, not closing an unfunded
        // one, and that exemption is what the check above enforces by refusing every non-owner caller.
        //
        // The owner is exempt from both this guard and the deadline, so the owner can void a covered
        // round at any moment before `pull` lands. That is a real cancellation right and it is stated
        // rather than implied: it exists because `ticketsNeeded` reads FWA's live price, and an
        // `acquisitionFee()` that reverts would otherwise leave an `Open` round with no exit at all.
        // It cannot take anyone's money — `_enterRefunding` returns the whole escrow — but it can end
        // a funded acquisition.
        //
        // Covered is not the same as pullable, and `pull` can be blocked by conditions coverage never
        // reads: a predecessor still holding `ethPendingRound`, FWA's weighted backing falling under
        // the round's snapshotted floor, FWA charging inside its own ceiling but over the funded
        // budget, a quote that has gone to zero. Each leaves a round that cannot pull, cannot sell more
        // tickets, and — while it stays `Open` — blocks `openRound` for every future round. Enumerating
        // those causes would only hold until FWA grows another, so the rule is the outcome instead.
        //
        // `stallTimeout` past the deadline is the window in which coverage still protects the round.
        // `pull` is permissionless and bountied, so a covered round that anyone can pull is pulled long
        // before this; the window exists so a stranger cannot front-run a live `pull` and destroy a
        // funded acquisition for the price of gas. Past it, the round has demonstrably not pulled and
        // releasing the capital is worth more than the acquisition it is not making. Every ticket is
        // refunded in full from escrow either way.
        if (
            msg.sender != owner() && block.timestamp <= uint256(r.fundingDeadline) + uint256(r.stallTimeout)
                && ticketsNeeded(roundId) == 0
        ) revert AlreadyCovered();
        _enterRefunding(roundId, r);
    }

    function _enterRefunding(uint256 roundId, Round storage r) internal {
        r.state = RoundState.Refunding;
        r.outcome = Outcome.Refunded;
        r.refundPool = r.escrow;
        r.escrow = 0;
        emit RoundVoided(roundId, r.refundPool);
    }

    /* ------------------------------------------------------------------ */
    /*                            FEE AND REWARDS                          */
    /* ------------------------------------------------------------------ */

    /// @notice Send the round's accrued fee to the fee recipient. Anyone may call.
    function claimFee(uint256 roundId) external nonReentrant {
        Round storage r = _rounds[roundId];
        if (r.feeOwed == 0 || r.feeClaimed) revert NothingToClaim();
        r.feeClaimed = true;
        accountedEth -= r.feeOwed;
        emit FeeClaimed(roundId, r.feeOwed);
        SafeTransferLib.forceSafeTransferETH(feeRecipient, r.feeOwed);
    }

    /// @notice Collect this contract's FWA surcharge allowance and route it to the fee recipient, as
    ///         FWAToken or as ETH. Owner-only because it takes a slippage bound.
    ///
    ///         FWA charges a surcharge above its own acquisition fee and commits a share of that back to
    ///         the purchaser as an ETH allowance, which it spends buying FWAToken. The share is
    ///         `tokenShareBps(gap)`: zero at or below `hotGap`, the whole surcharge at `coldGap`, linear
    ///         between, where `gap` is the time since the protocol's last acquisition. FWA zeroes the
    ///         allowance as it pays and is the double-claim guard, so this contract keeps no flag.
    ///
    ///         This stream is retained by the protocol rather than credited to rounds. It is sized by how
    ///         quiet FWA is at the moment of the pull, not by anything a round did, and at the volume FWA
    ///         has run so far it prices in the fifth decimal of an acquisition. The epoch pot, which is
    ///         the reward a round actually earns, goes to holders through `claimEpoch`.
    /// @param minTokensOut Least FWAToken accepted from the surcharge buy. FWA reverts when the allowance
    ///        is zero, so read `tokenBuyAllowance(address(this))` first.
    function claimRewards(uint256 minTokensOut) external onlyOwner nonReentrant {
        uint256 balanceBefore = FWA_TOKEN.balanceOf(address(this));
        FWA_REWARDS.claimAccruedTokens(minTokensOut);
        uint256 received = FWA_TOKEN.balanceOf(address(this)) - balanceBefore;
        if (received == 0) revert NothingToClaim();

        // No sale here either. Reverting without the role costs the owner a retry and nothing else,
        // and the claim is not spent: `received` is a measured delta, so the call is repeatable.
        if (!FWA_TOKEN.isDistributor(address(this))) revert NotDistributor();
        if (!FWA_TOKEN.transfer(feeRecipient, received)) revert TransferFailed();
        emit RewardsClaimed(received, 0);
    }

    /* ------------------------------------------------------------------ */
    /*                       THE EPOCH REWARD, TO HOLDERS                  */
    /* ------------------------------------------------------------------ */

    /// @notice Claim one closed reward epoch, take the protocol's `REWARD_FEE_BPS`, and fix what each of
    ///         this contract's acquisitions in that epoch is worth. Permissionless.
    ///
    ///         FWA allocates a fixed pot to each reward epoch and splits it across every acquisition made
    ///         protocol-wide in that epoch, crediting the purchaser address rather than the request. This
    ///         contract is the purchaser for every round it pulled, so one call collects the whole epoch
    ///         and `epochShare` divides it back down to one acquisition, which is one round.
    ///
    ///         FWA pays a closed epoch only, and only once every acquisition registered in it is
    ///         terminal protocol-wide, so this reverts until then. It records the claim itself, which is
    ///         the double-claim guard; `epochClaimed` is a second one against a change on FWA's side.
    /// @param epoch A reward epoch below `FWA_REWARDS.currentEpoch()`.
    function claimEpoch(uint256 epoch) external nonReentrant {
        if (epochClaimed[epoch]) revert AlreadyCredited();
        // Without the role neither the protocol's cut nor any holder's share can move, so claiming would
        // park the epoch here with no way to pay it out. FWA holds it just as safely until the role
        // returns, and its epoch claim has no expiry.
        if (!FWA_TOKEN.isDistributor(address(this))) revert NotDistributor();

        // The divisor is read from FWA, never supplied by the caller: the epoch can be claimed once, so
        // a caller-sized denominator would let anyone inflate the share of the rounds they hold and
        // leave the rest of this contract's rounds permanently unpayable.
        uint256 units = FWA_REWARDS.userAcquisitionsInEpoch(epoch, address(this));
        if (units == 0) revert NothingToClaim();

        uint256[] memory one = new uint256[](1);
        one[0] = epoch;
        uint256 balanceBefore = FWA_TOKEN.balanceOf(address(this));
        FWA_REWARDS.claimEpochTokens(one);
        uint256 received = FWA_TOKEN.balanceOf(address(this)) - balanceBefore;
        if (received == 0) revert NothingToClaim();

        uint256 cut = (received * REWARD_FEE_BPS) / BPS;
        // Integer division: the remainder of `received - cut` across `units` stays here. It is under one
        // wei of FWAToken per round and is covered by the same balance the token pots are paid from.
        epochClaimed[epoch] = true;
        epochShare[epoch] = (received - cut) / units;
        emit EpochClaimed(epoch, received, cut, units);
        if (cut != 0 && !FWA_TOKEN.transfer(feeRecipient, cut)) revert TransferFailed();
    }

    /// @notice Add each round's share of its reward epoch to that round's token pot. Permissionless,
    ///         pageable, order-independent; call it for any round whose epoch `claimEpoch` has taken.
    ///
    ///         The share lands in `tokenPot`, so it is paid out pro rata by ticket through the same
    ///         `claimShares` and `sweepShares` a holder already uses, and the round's sweep cursor is
    ///         rewound so a sweep that already ran delivers the reward too.
    /// @param roundIds Settled rounds. Each must have a fulfilled acquisition in an epoch `claimEpoch`
    ///        has taken. A round whose epoch paid too little to divide is credited zero and marked, so
    ///        it settles rather than being retried forever.
    function creditRounds(uint256[] calldata roundIds) external nonReentrant {
        for (uint256 i = 0; i < roundIds.length; i++) {
            uint256 roundId = roundIds[i];
            Round storage r = _rounds[roundId];
            // Settled, not merely fulfilled: `_executeSettlement` assigns `tokenPot` rather than adding
            // to it, so crediting a round before it settles would be overwritten and lost.
            if (r.state != RoundState.Settled) revert WrongState();
            // Skipped rather than refused. This crank is permissionless and takes a list, so reverting
            // on an id somebody already credited lets anyone kill a batch by front-running it with a
            // single-element call. A wrong *state* still reverts; only "already done" is a no-op.
            if (r.rewardCredited) continue;

            (, uint64 epoch, uint8 status,) = FWA_REWARDS.acquisitionRewards(r.fwaRequestId);
            if (status != uint8(IFWARewards.AcquisitionRewardStatus.Settled)) revert WrongState();
            if (!epochClaimed[epoch]) revert NothingToClaim();
            uint256 share = epochShare[epoch];

            r.rewardCredited = true;
            r.rewardAmount = uint128(share);
            r.tokenPot += share;
            sweepCursor[roundId] = 0;
            emit RoundRewardCredited(roundId, epoch, share);
        }
    }

    /* ------------------------------------------------------------------ */
    /*                             THE V4 SALE                             */
    /* ------------------------------------------------------------------ */

    /* ------------------------------------------------------------------ */
    /*                                VIEWS                                */
    /* ------------------------------------------------------------------ */

    function getRound(uint256 roundId) external view returns (Round memory) {
        return _rounds[roundId];
    }

    function segmentCount(uint256 roundId) external view returns (uint256) {
        return _segments[roundId].length;
    }

    function segmentAt(uint256 roundId, uint256 i) external view returns (Segment memory) {
        Segment[] storage segs = _segments[roundId];
        if (i >= segs.length) revert BadQuantity();
        return segs[i];
    }

    /* ------------------------------------------------------------------ */
    /*                              INTERNAL                               */
    /* ------------------------------------------------------------------ */

    /// @dev The six listing fields this contract acts on. One decoder for an eleven field return,
    ///         shared by every call site: each separate instance of the decode costs code size, and
    ///         moving it behind a staticcall to a helper costs 65 bytes more than it saves, measured.
    function _listing(uint256 listingId)
        internal
        view
        returns (
            address collection,
            address purchaser,
            uint256 tokenId,
            uint256 backing,
            uint64 allocatedAt,
            uint8 status
        )
    {
        (collection,, purchaser, tokenId,, backing,,,, allocatedAt, status) = FWA.listings(listingId);
    }

    /// @dev Strict ERC721 forward. The buyer has already paid, so a token that does not move must
    ///      take the call down rather than leave them out of pocket.
    function _transferNft(address collection, uint256 tokenId, address to) internal {
        (bool ok,) =
            collection.call(abi.encodeWithSelector(IERC721Minimal.transferFrom.selector, address(this), to, tokenId));
        if (!ok) revert TransferFailed();
        if (IERC721Minimal(collection).ownerOf(tokenId) != to) revert TransferFailed();
    }

    /// @notice Re-run a settled round's NFT custody probe. Permissionless.
    ///
    ///         The probe inside `settleForcedEth` is bounded on gas and on returndata, because it calls
    ///         a contract the listing's depositor chose and an unbounded call there halts the round and,
    ///         through `ethPendingRound`, every round after it. A bound means the probe can be wrong in
    ///         the safe direction: an honest collection whose `ownerOf` costs more than `OWNER_OF_GAS`
    ///         reads as no custody even though this contract holds the token.
    ///
    ///         Without this, that reading is permanent and the NFT is unredeemable, so the round's
    ///         holders lose its whole value to a probe that ran out of gas. This makes the failure
    ///         retryable by anyone, at any later time, with as much gas as the collection needs.
    /// @dev Sets the flag, never clears it. A redeemed NFT has already left, so the probe reads false
    ///      and this reverts rather than reopening a redemption that happened.
    function syncNftCustody(uint256 roundId) external nonReentrant {
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Settled || r.nftHeld) revert WrongState();
        (address collection,, uint256 tokenId,,,) = _listing(r.listingId);
        // All the gas the caller cares to supply. The cap on the settlement path exists because a
        // revert there halts the round and every round after it; a revert here halts nothing, so the
        // only bound this call needs is the one on returndata.
        if (!_holdsNft(collection, tokenId, gasleft())) revert NothingToClaim();
        r.nftHeld = true;
    }

    /// @notice Retry FWA's stuck-NFT recovery for a settled round. Permissionless.
    ///
    ///         `settleForcedEth` attempts the recovery once under `RECOVER_GAS` and swallows a failure,
    ///         because that call reaches a collection the listing's depositor chose and a revert there
    ///         would halt the round and, through `ethPendingRound`, every round after it. So a
    ///         collection that needs more gas than the cap, or that was paused at settlement time,
    ///         leaves the NFT in FWA's custody with this contract still entitled to it.
    ///
    ///         FWA supports the retry: `recoverStuckNFT` clears `stuckNFTRecipient` before transferring
    ///         so a revert restores the entitlement. Nothing here used it until now, so the entitlement
    ///         survived with no way to act on it.
    /// @dev Unbounded gas, deliberately. A revert here halts nothing — the round is already `Settled`
    ///      and `ethPendingRound` is already clear — so the caller may spend whatever the collection
    ///      needs, and a failure costs them their gas and no one else anything.
    function retryNftRecovery(uint256 roundId) external nonReentrant {
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Settled || r.nftHeld) revert WrongState();
        if (FWA.stuckNFTRecipient(r.listingId) != address(this)) revert NothingToClaim();

        FWA.recoverStuckNFT(r.listingId);

        (address collection,, uint256 tokenId,,,) = _listing(r.listingId);
        if (!_holdsNft(collection, tokenId, gasleft())) revert NothingToClaim();
        r.nftHeld = true;
    }

    /// @dev Does this contract hold `tokenId` of `collection`? Bounded on both the gas the collection
    ///      may spend and the returndata copied back, because the collection is chosen by a listing's
    ///      depositor rather than by anyone here.
    ///
    ///      The high-level form cannot do this. A low-level call into `bytes memory` copies the whole of
    ///      `returndatasize()` before any length check runs, and memory expansion is quadratic, so a
    ///      collection that succeeds with an oversized payload costs the caller more gas than a block
    ///      allows. Measured against the unbounded form: a return of 96,000 to 110,000 words made
    ///      `settleForcedEth` impossible for every caller.
    ///
    ///      The returndata bound is what stops the halt and is not optional. The gas bound is the
    ///      caller's choice: `settleForcedEth` caps it because a revert there halts the round and every
    ///      round after it, and `syncNftCustody` does not because a revert there halts nothing.
    ///
    ///      False for a revert, an exhaustion, a short or long return, or an address that is not this
    ///      contract. All of them mean the same thing to a caller: do not claim custody on this reading.
    function _holdsNft(address collection, uint256 tokenId, uint256 gasCap) internal view returns (bool held) {
        address self = address(this);
        assembly ("memory-safe") {
            // Scratch beyond the free memory pointer, which is left where it was: nothing here outlives
            // the call, so the pointer does not move.
            let ptr := mload(0x40)
            mstore(ptr, shl(224, 0x6352211e)) // ownerOf(uint256)
            mstore(add(ptr, 4), tokenId)
            let ok := staticcall(gasCap, collection, ptr, 36, ptr, 32)
            // The address is ABI-encoded right-aligned, so it is the low 160 bits of the word.
            held := and(
                ok,
                and(eq(returndatasize(), 32), eq(and(mload(ptr), 0xffffffffffffffffffffffffffffffffffffffff), self))
            )
        }
    }

    /// @dev Pull any refund credit FWA holds for this contract and attribute it to the round with ETH
    ///      in flight. FWA credits refunds instead of pushing them, so this is the only inflow path.
    function _reconcile(Round storage r) internal {
        // A round voided before it ever pulled has no request. `acquisitions(0)` reads empty on the
        // deployed FWA, so the bound below would already be zero, but that is a property of FWA's id
        // space rather than one this contract enforces. Refusing here does not depend on it.
        if (r.fwaRequestId == 0) return;
        if (FWA.acquisitionRefundCredit(address(this)) == 0) return;
        uint256 balanceBefore = address(this).balance;
        FWA.withdrawAcquisitionRefund();
        uint256 received = address(this).balance - balanceBefore;
        if (received == 0) return;
        // The withdrawal is the whole address-level credit, which may include a voided round's, because
        // FWA keys credit by address rather than by request. Two things bound what this round may take,
        // and both are needed. The status establishes the round is owed anything at all: a round FWA
        // fulfilled is owed nothing and would otherwise absorb a voided round's principal. `creditTaken`
        // establishes how much is left to owe: FWA's status is terminal and `priceEscrowed` stays
        // populated after a refund, so both are permanent, and bounding by `priceEscrowed` alone lets an
        // already-paid round qualify again on every later call. Everything not taken is held as
        // `strayCredit` for the round that paid it.
        (,, uint256 escrowed,, uint8 status) = FWA.acquisitions(r.fwaRequestId);
        uint256 mine;
        if (status == uint8(IFWA.AcquisitionStatus.Expired) || status == uint8(IFWA.AcquisitionStatus.Refunded)) {
            mine = _creditRemaining(r, escrowed);
            if (mine > received) mine = received;
            r.creditTaken += uint128(mine);
        }
        r.escrow += mine;
        accountedEth += received;
        strayCredit += received - mine;
    }

    /// @dev What FWA still owes this round: its escrowed acquisition price less what has already been
    ///      attributed to it across every call that reconciled it.
    function _creditRemaining(Round storage r, uint256 escrowed) internal view returns (uint256) {
        uint256 taken = uint256(r.creditTaken);
        return escrowed > taken ? escrowed - taken : 0;
    }

    /// @notice Pay a voided round the acquisition fee FWA escrowed for it and later credited back.
    ///         Permissionless, and callable as many times as it takes: FWA's credit can arrive after
    ///         the round closed, and `strayCredit` may hold only part of it when the call lands.
    /// @dev The guard is `creditTaken` against the round's own `priceEscrowed`, not a one-shot flag.
    ///      A flag is wrong in both directions here: it lets an already-reconciled round take a second
    ///      full helping out of another round's principal, and it burns on a partial take, stranding
    ///      the rest in `strayCredit`, which has no other drain.
    function reclaimRefund(uint256 roundId) external nonReentrant {
        Round storage r = _rounds[roundId];
        if (r.state != RoundState.Refunding) revert WrongState();
        if (r.fwaRequestId == 0) revert NothingToClaim();

        _reconcile(r);
        uint256 take = r.escrow;
        r.escrow = 0;

        // `_reconcile` has already counted whatever it attributed, so the remainder is what is still
        // owed after it. `take` is not subtracted again: an escrow balance that predates this call is
        // ticket money, not credit, and subtracting it would understate the debt.
        (,, uint256 escrowed,,) = FWA.acquisitions(r.fwaRequestId);
        uint256 short = _creditRemaining(r, escrowed);
        if (short > strayCredit) short = strayCredit;
        if (short != 0) {
            strayCredit -= short;
            r.creditTaken += uint128(short);
            take += short;
        }

        if (take == 0) revert NothingToClaim();
        // The pool grows, and holders are paid by amount rather than by a one-shot flag, so anyone
        // who already claimed can come back for their share of the top-up. The cursor is rewound so
        // the paged sweep delivers it too, rather than resuming past every holder it already paid.
        r.refundPool += take;
        refundSweepCursor[roundId] = 0;
    }

    /* ------------------------------------------------------------------ */
    /*                                HOOKS                                */
    /* ------------------------------------------------------------------ */

    /// @notice Accepts ETH only from FWA (refund pushes and forced settlements) and the PoolManager
    ///         (swap proceeds). Anything else is rejected so stray sends cannot blur the ledger.
    receive() external payable {
        if (msg.sender != address(FWA)) revert DirectEthNotAccepted();
    }

    /// @notice Accepts the allocated NFT if FWA ever pushes one here. The index model never delivers
    ///         it onward; it exists so a safeTransferFrom cannot revert the allocating call.
    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

lib/solady/src/auth/Ownable.sol

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

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /// @dev Cannot double-initialize.
    error AlreadyInitialized();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                           EVENTS                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The owner slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    bytes32 internal constant _OWNER_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
    function _guardInitializeOwner() internal pure virtual returns (bool guard) {}

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                if sload(ownerSlot) {
                    mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                    revert(0x1c, 0x04)
                }
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(_OWNER_SLOT, newOwner)
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, newOwner)
            }
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_OWNER_SLOT)
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         MODIFIERS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}

lib/solady/src/utils/ReentrancyGuard.sol

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

/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unauthorized reentrant call.
    error Reentrancy();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
    /// 9 bytes is large enough to avoid collisions with lower slots,
    /// but not too large to result in excessive bytecode bloat.
    uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      REENTRANCY GUARD                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Guards a function from reentrancy.
    modifier nonReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
            sstore(_REENTRANCY_GUARD_SLOT, address())
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            sstore(_REENTRANCY_GUARD_SLOT, codesize())
        }
    }

    /// @dev Guards a view function from read-only reentrancy.
    modifier nonReadReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
        }
        _;
    }
}

lib/solady/src/utils/SafeTransferLib.sol

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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount :=
                mul( // The arguments of `mul` are evaluated from right to left.
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` does not implement `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented :=
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
            mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

src/PullPoolTypes.sol

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

struct Config {
    uint96 ticketPrice; // wei per ticket
    uint64 fundingDuration; // seconds a round may sell before it is voidable
    uint16 headroomBps; // margin over the live pull price the raise must cover
    uint16 feeCapBps; // margin over the quote that FWA may actually charge inside `acquire`
    uint96 crankBountyCap; // ceiling on one crank's reimbursement, from the round's escrow
    uint96 vrfAllowance; // ETH set aside for FWA's randomness leg, which prices off tx.gasprice
    uint64 bountyTipWei; // per-gas tip allowed above block.basefee when reimbursing a crank
    uint64 stallTimeout; // how long a round may sit in Pulling before anyone can void it
    uint32 maxTickets; // ceiling on a round's ticket count
}

/// @notice The hard bounds on every owner-settable field of `Config`. Shared by the contract that
///         holds the config and the guard that validates it, so there is one source for each number.
library Bounds {
    uint256 internal constant BPS = 10_000;
    /// 1,000 bps of 10,000 is 10%. The ceiling exists so a holder can read the worst case out of the
    /// bytecode instead of trusting an operator, and so a compromised owner key is bounded by it too.
    /// `feeBps` ships at 200, which is 2%, and the owner may move it anywhere at or under this.
    uint16 internal constant MAX_FEE_BPS = 1000;
    /// A buy-then-sell round trip through the FWA/ETH pool keeps 9,800 bps, measured against mainnet
    /// in `test/Fork.t.sol`. The floor is set 800 bps under that so an honest settlement clears it and
    /// the band a manipulated one can operate in is 1,000 bps, not the 5,000 a half-value floor allows.
    /// The measured round trip through the FWA/ETH pool keeps 9,800 bps (`test/Fork.t.sol`), so a floor
    /// above that cannot be cleared by an honest settlement: `settle` would revert for every round
    /// opened on such a config, stranding each in `Claimable` until FWA's finalize window lapses. The
    /// ceiling exists so the owner cannot set a floor that halts settlement while looking conservative.
    /// FWA's randomness leg prices off `tx.gasprice`, and this allowance is both the round's reserve for
    /// it and the ceiling on what a cranker may impose. It enters `requiredGross` additively, so an
    /// unbounded value inflates every raise. Sized well above the 0.010 shipped.
    uint96 internal constant MAX_VRF_ALLOWANCE = 0.5 ether;
    /// The granularity a round is divided into, and the bound on rounding waste. A ticket nobody can
    /// afford is a round nobody can fund.
    uint96 internal constant MAX_TICKET_PRICE = 10 ether;
    uint64 internal constant MAX_FUNDING_DURATION = 30 days;
    uint16 internal constant MAX_HEADROOM_BPS = 50_000;
    uint16 internal constant MAX_FEE_CAP_BPS = 5000;
    uint96 internal constant MAX_CRANK_BOUNTY = 0.01 ether;
    uint64 internal constant MAX_BOUNTY_TIP = 50 gwei;
    uint64 internal constant MAX_STALL_TIMEOUT = 30 days;
    /// This value does two jobs, and the floor is set by the second. It is how long a `Pulling` round
    /// waits before anyone may void it, where correctness is already held by the acquisition-status
    /// check rather than by any clock. It is also the grace a *covered* round keeps past its funding
    /// deadline, and that one is load-bearing: without it a stranger can front-run a live `pull` and
    /// destroy a funded acquisition for the price of gas. An hour is far past the minutes a
    /// permissionless bountied `pull` takes, and far short of trapping capital.
    uint64 internal constant MIN_STALL_TIMEOUT = 1 hours;
    uint32 internal constant MAX_TICKETS = 10_000_000;
    /// The most *observable* buy pressure token mode may be run against: FWA's unspent surcharge
    /// allowances plus FWAToken's own ETH. It caps how far the owner may let those two grow before
    /// settlements fall back to the floored ETH path. It is not a bound on every route to a buy; see
    /// `docs/KNOWN-LIMITATIONS.md` item 2.
}

src/interfaces/IConfigGuard.sol

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

import {Config} from "../PullPoolTypes.sol";

interface IConfigGuard {
    /// @notice Reverts `BadConfig()` unless every field is inside the bound that governs it.
    function check(Config calldata c) external pure;
}

src/interfaces/IERC721Minimal.sol

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

/// @title IERC721Minimal
/// @notice The two ERC721 methods PullPool uses on an allocated FWA listing's collection.
interface IERC721Minimal {
    function ownerOf(uint256 tokenId) external view returns (address);

    function transferFrom(address from, address to, uint256 tokenId) external;
}

src/interfaces/IFWA.sol

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

/// @title IFWA
/// @notice The subset of the deployed FWA core contract (mainnet 0xB276F62DB0ce8CA2Ca5bc522695bE604521eAc1c)
///         that PullPool calls.
/// @dev Every signature here comes from the Etherscan-verified source of that address, compiled with
///      solc 0.8.30. The deployed contract is NOT the code on the main branch of token-works/fwa-relaunch:
///      the live build sequences acquisitions and settles them in request order through a permissionless
///      `processAcquisitions`, returns escrowed fees as pull credits, and keeps token rewards in a separate
///      FWARewards module. docs/LIVE-VS-REPO.md lists every difference that touches this integration.
interface IFWA {
    /// @notice FWA listing lifecycle. Numeric values match the deployed enum.
    /// None 0, Active 1, Allocated 2, Withdrawn 3, Settled 4, Staged 5.
    enum ListingStatus {
        None,
        Active,
        Allocated,
        Withdrawn,
        Settled,
        Staged
    }

    /// @notice FWA acquisition lifecycle. Numeric values match the deployed enum.
    /// @dev Terminal for this integration: Fulfilled, Expired, Refunded. `Pending`, `Ready`, and `TimedOut`
    ///      all still need the request to reach the head of the sequence in `processAcquisitions`.
    enum AcquisitionStatus {
        None,
        Pending, // waiting for an on-time word
        Fulfilled, // a listing was allocated
        Expired, // skipped in sequence past its word deadline; escrowed fee became a pull credit
        Refunded, // empty pool or price drift; escrowed fee became a pull credit
        Ready, // an on-time word is cached and waiting for its turn in the sequence
        TimedOut // a word arrived after the deadline; skipped when it reaches the head
    }

    /* ------------------------------------------------------------------ */
    /*                               QUOTING                               */
    /* ------------------------------------------------------------------ */

    /// @notice Depositor pool fee plus VRF service fee for one acquisition.
    /// @dev The `vrf` leg is derived from `tx.gasprice`, so an off-chain quote must use the gas price it
    ///      intends to send. `acquire` also drains the staging queue before pricing, so the fee read by a
    ///      static call can differ from the fee charged inside the same transaction.
    function quoteAcquisitionPrice() external view returns (uint256 fee, uint256 vrf, uint256 total);

    /// @notice Current depositor pool fee, excluding the VRF service fee.
    function acquisitionFee() external view returns (uint256);

    /// @notice Share of a position's backing paid out when the purchaser takes the bid, in bps.
    function settlementDiscountBps() external view returns (uint256);

    /// @notice Sum of backing across active listings, weighted by selection weight.
    function weightedBackingTotal() external view returns (uint256);

    /// @notice Sum of selection weight across active listings. Zero means no listing can be selected.
    function totalWeight() external view returns (uint256);

    /* ------------------------------------------------------------------ */
    /*                             ACQUISITION                             */
    /* ------------------------------------------------------------------ */

    /// @notice Pay for and request one VRF-selected acquisition. Overpayment above `fee + vrf` is refunded
    ///         to the caller inside this call.
    /// @param maxAcquisitionFee Revert if the pool fee exceeds this. Zero disables the check.
    /// @param minWeightedValue Revert if `weightedBackingTotal` is below this. Zero disables the check.
    function acquire(uint256 maxAcquisitionFee, uint256 minWeightedValue) external payable returns (uint256 requestId);

    /// @notice Settle the ready or expired prefix of the acquisition sequence. Permissionless; the caller
    ///         only picks a gas bound. This is what moves a `Ready` or `TimedOut` request to a terminal
    ///         state, and what expires a `Pending` head once it passes its word deadline.
    function processAcquisitions(uint256 maxCount) external returns (uint256 processed);

    /// @notice Take the caller's accumulated acquisition refund credits. Escrowed fees returned by expiry,
    ///         an empty pool, or price drift arrive as credits, not as a transfer.
    function withdrawAcquisitionRefund() external returns (uint256 amount);

    /// @notice Acquisition refund credit owed to `purchaser`.
    function acquisitionRefundCredit(address purchaser) external view returns (uint256);

    /// @notice Blocks after a request before its word deadline lapses.
    function selectionTimeoutBlocks() external view returns (uint256);

    /// @notice Acquisition record. `priceEscrowed` stays populated after a refund, so it is the exact
    ///         amount credited back to the purchaser.
    function acquisitions(uint256 requestId)
        external
        view
        returns (address purchaser, uint256 requestBlock, uint256 priceEscrowed, uint256 listingId, uint8 status);

    /* ------------------------------------------------------------------ */
    /*                               LISTINGS                              */
    /* ------------------------------------------------------------------ */

    /// @notice Listing record. Field order matches the deployed struct.
    function listings(uint256 listingId)
        external
        view
        returns (
            address collection,
            address depositor,
            address purchaser,
            uint256 tokenId,
            uint256 weight,
            uint256 value,
            uint256 feeShare,
            uint256 feeDebt,
            uint256 slot,
            uint64 allocatedAt,
            uint8 status
        );

    /// @notice Address entitled to pull an NFT whose settlement delivery failed.
    function stuckNFTRecipient(uint256 listingId) external view returns (address);

    /// @notice Seconds the purchaser holds an exclusive settlement right after allocation.
    function settlementWindow() external view returns (uint256);

    /// @notice Seconds after allocation before anyone may finalize an unsettled listing.
    function finalizeWindow() external view returns (uint256);

    /// @notice The FWAToken address FWA settles in. Zero until the token is wired up.
    function token() external view returns (address);

    /* ------------------------------------------------------------------ */
    /*                       PURCHASER SETTLEMENT                          */
    /* ------------------------------------------------------------------ */

    /// @notice Purchaser takes the NFT. Backing returns to the depositor. Strict: reverts if the ERC721
    ///         transfer to the purchaser fails.
    function keepNFT(uint256 listingId) external;

    /// @notice Purchaser accepts the depositor bid and receives it as FWAToken bought from the pool.
    /// @param minOut Slippage guard on the FWAToken received.
    function acceptBidAsTokens(uint256 listingId, uint256 minOut) external returns (uint256 tokenOut);

    /// @notice Purchaser sells the position back for ETH: receives `settlementDiscountBps` of the
    ///         backing, and the NFT returns to the depositor. Same economics as `acceptBidAsTokens`,
    ///         paid from the depositor's escrow rather than bought off the pool.
    /// @dev No enable flag. FWA's own comment: "Available the whole time the listing is allocated."
    ///      That is why this is the fallback: `acceptBidAsTokens` can be switched off by FWA's owner
    ///      (`acceptBidAsTokensEnabled`), and this cannot.
    function acceptDepositorBid(uint256 listingId) external;

    /// @notice Pull an NFT whose settlement delivery failed. Caller must be the recorded stuck recipient.
    function recoverStuckNFT(uint256 listingId) external;
}

src/interfaces/IFWARewards.sol

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

/// @title IFWARewards
/// @notice The subset of FWA's rewards module (mainnet 0x6a1a1C0CfB3D3C538e13D36d608a5bcaa992fc78) this
///         contract calls.
/// @dev Purchaser emissions are pooled per epoch, not paid per acquisition. FWA allocates a fixed amount
///      to each reward epoch (`purchaserDailyPot`, 10,000,000 FWAToken per day over `EMISSION_DAYS`) and
///      splits it across every acquisition made in that epoch. FWA records the acquisition against the
///      purchaser address when it registers it, and the purchaser claims its share per epoch, once the
///      epoch has closed.
///
///      `claimAccruedTokens` is a second, separate purchaser stream. FWA charges a surcharge on top of
///      each acquisition fee and commits a share of it back to the purchaser as an ETH allowance, spent
///      buying FWAToken. The share is `tokenShareBps(gap)`, ramping from zero at `hotGap` (60s) to the
///      whole surcharge at `coldGap` (3600s), where `gap` is the time since the protocol's last
///      acquisition. So it pays nothing while FWA is busy and the full surcharge after an hour of quiet.
///      Its parameter is a slippage bound on FWA's buy, not an acquisition id.
interface IFWARewards {
    /// @notice Terminal status of one acquisition's reward record.
    enum AcquisitionRewardStatus {
        None,
        Pending,
        Settled,
        Refunded
    }

    /// @notice Claim this address's share of each listed epoch's purchaser pot. Reverts
    ///         `EpochNotClosed()` for an epoch still running, `EpochStillPending()` while any
    ///         acquisition registered in it is not yet terminal protocol-wide, and reverts on a second
    ///         claim of an epoch already claimed, which makes FWA's own record the double-claim guard.
    /// @return The FWAToken transferred to the caller.
    function claimEpochTokens(uint256[] calldata epochs) external returns (uint256);

    /// @notice One acquisition's reward record: the purchaser FWA credited, the epoch it was registered
    ///         in, its terminal status, and the surcharge slice committed to it. The epoch is stamped at
    ///         registration, so it is the epoch of the pull rather than of the fulfilment.
    function acquisitionRewards(uint256 requestId)
        external
        view
        returns (address purchaser, uint64 epoch, uint8 status, uint256 tokenSlice);

    /// @notice The reward epoch in progress. Epochs are one day.
    function currentEpoch() external view returns (uint256);

    /// @notice Acquisitions `who` made in `epoch`: the numerator of their share of that epoch's pot.
    function userAcquisitionsInEpoch(uint256 epoch, address who) external view returns (uint256);

    /// @notice Spend the caller's accrued surcharge allowance buying FWAToken and send it to them.
    ///         Reverts `NoTokenReward()` when the allowance is zero.
    /// @param minOut Least FWAToken accepted from that buy.
    function claimAccruedTokens(uint256 minOut) external returns (uint256);

    /// @notice The caller's unspent surcharge allowance, in wei.
    function tokenBuyAllowance(address who) external view returns (uint256);

    /// @notice Every unspent surcharge allowance, in wei. This is the ETH FWA is holding to spend buying
    ///         FWAToken on demand, so it is the ceiling on a buy anyone can route through
    ///         `claimAccruedTokens` — the leg a sandwich of an unfloored token settlement needs.
    function tokenBuyAllowanceTotal() external view returns (uint256);
}

src/interfaces/IFWAToken.sol

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

/// @title IFWAToken
/// @notice The subset of the deployed FWAToken (mainnet 0xa0Df17B5aC76ABaBA36E1450E2cbCd18A620C845)
///         that PullPool calls.
/// @dev FWAToken locks transfers. A transfer succeeds only when the sender or the receiver is a
///      distributor, is the token owner, or is the Uniswap v4 PoolManager under a hook-granted transient
///      allowance. PullPool needs `isDistributor[PullPool] == true` for both legs of a settlement:
///      FWA to PullPool, and PullPool to the winner's recipient.
interface IFWAToken {
    function balanceOf(address account) external view returns (uint256);

    function transfer(address to, uint256 amount) external returns (bool);

    /// @notice Whether `account` may move FWAToken while transfers are locked.
    function isDistributor(address account) external view returns (bool);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/",
    "@chainlink/=lib/chainlink-brownie-contracts/contracts/src/v0.8/",
    "chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.