Skip to content
Verified contractPartialMIT

StandardPoolBuyback

Address0x85faf92967705dc45535ebca74d6333f6bcbfee7
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 1 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,335,984
Creation transaction
0x35c80fe91c…cb87aee499

src/poolsV2/StandardPoolBuyback.sol

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

import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {StandardPool} from "./StandardPool.sol";

interface IPoolBuybackFactory {
    function fwaToken() external view returns (address);
}

interface IPoolFeeBuyback {
    function token() external view returns (address);
}

/// @notice Standard-pool implementation that sends its entire ETH purchase markup to FWAV2Buyback.
/// @dev Install through the existing factory's setImplementation while pool creation is disabled.
/// Only subsequently created clones use this implementation. The existing factory, service, token
/// launcher and fee router retain their addresses and their separate launch-tax and surplus routes.
contract StandardPoolBuyback is StandardPool {
    address payable public immutable feeBuyback;

    constructor(address factory_, address service_, address payable feeBuyback_) StandardPool(factory_, service_) {
        if (
            feeBuyback_.code.length == 0
                || IPoolFeeBuyback(feeBuyback_).token() != IPoolBuybackFactory(factory_).fwaToken()
        ) revert InvalidConfig();
        feeBuyback = feeBuyback_;
    }

    /// @notice Fund the existing FWA buyback with all accrued ETH purchase fees, with or without a pool token.
    /// @dev Buyback execution and main-pool purchaser rewards remain in their existing contracts.
    /// A failed ETH transfer reverts the accrual reset, keeping the complete amount available for retry.
    function payoutProtocolFees() external override nonReentrant returns (uint256 amount) {
        amount = accruedProtocolFees;
        if (amount == 0) revert NoProtocolFees();
        accruedProtocolFees = 0;
        SafeTransferLib.safeTransferETH(feeBuyback, amount);
        emit ProtocolFeesPaidOut(feeBuyback, amount);
    }
}

lib/chainlink-evm/contracts/src/v0.8/vrf/interfaces/IVRFCoordinatorV2Plus.sol

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

import {VRFV2PlusClient} from "../libraries/VRFV2PlusClient.sol";
import {IVRFSubscriptionV2Plus} from "./IVRFSubscriptionV2Plus.sol";

// Interface that enables consumers of VRFCoordinatorV2Plus to be future-proof for upgrades
// This interface is supported by subsequent versions of VRFCoordinatorV2Plus
interface IVRFCoordinatorV2Plus is IVRFSubscriptionV2Plus {
  /**
   * @notice Request a set of random words.
   * @param req - a struct containing following fields for randomness request:
   * keyHash - Corresponds to a particular oracle job which uses
   * that key for generating the VRF proof. Different keyHash's have different gas price
   * ceilings, so you can select a specific one to bound your maximum per request cost.
   * subId  - The ID of the VRF subscription. Must be funded
   * with the minimum subscription balance required for the selected keyHash.
   * requestConfirmations - How many blocks you'd like the
   * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS
   * for why you may want to request more. The acceptable range is
   * [minimumRequestBlockConfirmations, 200].
   * callbackGasLimit - How much gas you'd like to receive in your
   * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords
   * may be slightly less than this amount because of gas used calling the function
   * (argument decoding etc.), so you may need to request slightly more than you expect
   * to have inside fulfillRandomWords. The acceptable range is
   * [0, maxGasLimit]
   * numWords - The number of uint256 random values you'd like to receive
   * in your fulfillRandomWords callback. Note these numbers are expanded in a
   * secure way by the VRFCoordinator from a single random value supplied by the oracle.
   * extraArgs - abi-encoded extra args
   * @return requestId - A unique identifier of the request. Can be used to match
   * a request to a response in fulfillRandomWords.
   */
  function requestRandomWords(
    VRFV2PlusClient.RandomWordsRequest calldata req
  ) external returns (uint256 requestId);
}

lib/chainlink-evm/contracts/src/v0.8/vrf/interfaces/IVRFSubscriptionV2Plus.sol

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

/// @notice The IVRFSubscriptionV2Plus interface defines the subscription
/// @notice related methods implemented by the V2Plus coordinator.
interface IVRFSubscriptionV2Plus {
  /**
   * @notice Add a consumer to a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - New consumer which can use the subscription
   */
  function addConsumer(
    uint256 subId,
    address consumer
  ) external;

  /**
   * @notice Remove a consumer from a VRF subscription.
   * @param subId - ID of the subscription
   * @param consumer - Consumer to remove from the subscription
   */
  function removeConsumer(
    uint256 subId,
    address consumer
  ) external;

  /**
   * @notice Cancel a subscription
   * @param subId - ID of the subscription
   * @param to - Where to send the remaining LINK to
   */
  function cancelSubscription(
    uint256 subId,
    address to
  ) external;

  /**
   * @notice Accept subscription owner transfer.
   * @param subId - ID of the subscription
   * @dev will revert if original owner of subId has
   * not requested that msg.sender become the new owner.
   */
  function acceptSubscriptionOwnerTransfer(
    uint256 subId
  ) external;

  /**
   * @notice Request subscription owner transfer.
   * @param subId - ID of the subscription
   * @param newOwner - proposed new owner of the subscription
   */
  function requestSubscriptionOwnerTransfer(
    uint256 subId,
    address newOwner
  ) external;

  /**
   * @notice Create a VRF subscription.
   * @return subId - A unique subscription id.
   * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer.
   * @dev Note to fund the subscription with LINK, use transferAndCall. For example
   * @dev  LINKTOKEN.transferAndCall(
   * @dev    address(COORDINATOR),
   * @dev    amount,
   * @dev    abi.encode(subId));
   * @dev Note to fund the subscription with Native, use fundSubscriptionWithNative. Be sure
   * @dev  to send Native with the call, for example:
   * @dev COORDINATOR.fundSubscriptionWithNative{value: amount}(subId);
   */
  function createSubscription() external returns (uint256 subId);

  /**
   * @notice Get a VRF subscription.
   * @param subId - ID of the subscription
   * @return balance - LINK balance of the subscription in juels.
   * @return nativeBalance - native balance of the subscription in wei.
   * @return reqCount - Requests count of subscription.
   * @return owner - owner of the subscription.
   * @return consumers - list of consumer address which are able to use this subscription.
   */
  function getSubscription(
    uint256 subId
  )
    external
    view
    returns (uint96 balance, uint96 nativeBalance, uint64 reqCount, address owner, address[] memory consumers);

  /*
   * @notice Check to see if there exists a request commitment consumers
   * for all consumers and keyhashes for a given sub.
   * @param subId - ID of the subscription
   * @return true if there exists at least one unfulfilled request for the subscription, false
   * otherwise.
   */
  function pendingRequestExists(
    uint256 subId
  ) external view returns (bool);

  /**
   * @notice Paginate through all active VRF subscriptions.
   * @param startIndex index of the subscription to start from
   * @param maxCount maximum number of subscriptions to return, 0 to return all
   * @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one
   * @dev should consider keeping the blockheight constant to ensure a holistic picture of the contract state
   */
  function getActiveSubscriptionIds(
    uint256 startIndex,
    uint256 maxCount
  ) external view returns (uint256[] memory);

  /**
   * @notice Fund a subscription with native.
   * @param subId - ID of the subscription
   * @notice This method expects msg.value to be greater than or equal to 0.
   */
  function fundSubscriptionWithNative(
    uint256 subId
  ) external payable;
}

lib/chainlink-evm/contracts/src/v0.8/vrf/libraries/VRFV2PlusClient.sol

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

// End consumer library.
library VRFV2PlusClient {
  // extraArgs will evolve to support new features
  bytes4 public constant EXTRA_ARGS_V1_TAG = bytes4(keccak256("VRF ExtraArgsV1"));

  struct ExtraArgsV1 {
    bool nativePayment;
  }

  struct RandomWordsRequest {
    bytes32 keyHash;
    uint256 subId;
    uint16 requestConfirmations;
    uint32 callbackGasLimit;
    uint32 numWords;
    bytes extraArgs;
  }

  function _argsToBytes(
    ExtraArgsV1 memory extraArgs
  ) internal pure returns (bytes memory bts) {
    return abi.encodeWithSelector(EXTRA_ARGS_V1_TAG, extraArgs);
  }
}

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/tokens/ERC721.sol

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

/// @notice Simple ERC721 implementation with storage hitchhiking.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/tokens/ERC721.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC721.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/token/ERC721/ERC721.sol)
///
/// @dev Note:
/// - The ERC721 standard allows for self-approvals.
///   For performance, this implementation WILL NOT revert for such actions.
///   Please add any checks with overrides if desired.
/// - For performance, methods are made payable where permitted by the ERC721 standard.
/// - The `safeTransfer` functions use the identity precompile (0x4)
///   to copy memory internally.
///
/// If you are overriding:
/// - NEVER violate the ERC721 invariant:
///   the balance of an owner MUST always be equal to their number of ownership slots.
///   The transfer functions do not have an underflow guard for user token balances.
/// - Make sure all variables written to storage are properly cleaned
///   (e.g. the bool value for `isApprovedForAll` MUST be either 1 or 0 under the hood).
/// - Check that the overridden function is actually used in the function you want to
///   change the behavior of. Much of the code has been manually inlined for performance.
abstract contract ERC721 {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev An account can hold up to 4294967295 tokens.
    uint256 internal constant _MAX_ACCOUNT_BALANCE = 0xffffffff;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Only the token owner or an approved account can manage the token.
    error NotOwnerNorApproved();

    /// @dev The token does not exist.
    error TokenDoesNotExist();

    /// @dev The token already exists.
    error TokenAlreadyExists();

    /// @dev Cannot query the balance for the zero address.
    error BalanceQueryForZeroAddress();

    /// @dev Cannot mint or transfer to the zero address.
    error TransferToZeroAddress();

    /// @dev The token must be owned by `from`.
    error TransferFromIncorrectOwner();

    /// @dev The recipient's balance has overflowed.
    error AccountBalanceOverflow();

    /// @dev Cannot safely transfer to a contract that does not implement
    /// the ERC721Receiver interface.
    error TransferToNonERC721ReceiverImplementer();

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

    /// @dev Emitted when token `id` is transferred from `from` to `to`.
    event Transfer(address indexed from, address indexed to, uint256 indexed id);

    /// @dev Emitted when `owner` enables `account` to manage the `id` token.
    event Approval(address indexed owner, address indexed account, uint256 indexed id);

    /// @dev Emitted when `owner` enables or disables `operator` to manage all of their tokens.
    event ApprovalForAll(address indexed owner, address indexed operator, bool isApproved);

    /// @dev `keccak256(bytes("Transfer(address,address,uint256)"))`.
    uint256 private constant _TRANSFER_EVENT_SIGNATURE =
        0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;

    /// @dev `keccak256(bytes("Approval(address,address,uint256)"))`.
    uint256 private constant _APPROVAL_EVENT_SIGNATURE =
        0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925;

    /// @dev `keccak256(bytes("ApprovalForAll(address,address,bool)"))`.
    uint256 private constant _APPROVAL_FOR_ALL_EVENT_SIGNATURE =
        0x17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31;

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

    /// @dev The ownership data slot of `id` is given by:
    /// ```
    ///     mstore(0x00, id)
    ///     mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
    ///     let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
    /// ```
    /// Bits Layout:
    /// - [0..159]   `addr`
    /// - [160..255] `extraData`
    ///
    /// The approved address slot is given by: `add(1, ownershipSlot)`.
    ///
    /// See: https://notes.ethereum.org/%40vbuterin/verkle_tree_eip
    ///
    /// The balance slot of `owner` is given by:
    /// ```
    ///     mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
    ///     mstore(0x00, owner)
    ///     let balanceSlot := keccak256(0x0c, 0x1c)
    /// ```
    /// Bits Layout:
    /// - [0..31]   `balance`
    /// - [32..255] `aux`
    ///
    /// The `operator` approval slot of `owner` is given by:
    /// ```
    ///     mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
    ///     mstore(0x00, owner)
    ///     let operatorApprovalSlot := keccak256(0x0c, 0x30)
    /// ```
    uint256 private constant _ERC721_MASTER_SLOT_SEED = 0x7d8825530a5a2e7a << 192;

    /// @dev Pre-shifted and pre-masked constant.
    uint256 private constant _ERC721_MASTER_SLOT_SEED_MASKED = 0x0a5a2e7a00000000;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC721 METADATA                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the token collection name.
    function name() public view virtual returns (string memory);

    /// @dev Returns the token collection symbol.
    function symbol() public view virtual returns (string memory);

    /// @dev Returns the Uniform Resource Identifier (URI) for token `id`.
    function tokenURI(uint256 id) public view virtual returns (string memory);

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

    /// @dev Returns the owner of token `id`.
    ///
    /// Requirements:
    /// - Token `id` must exist.
    function ownerOf(uint256 id) public view virtual returns (address result) {
        result = _ownerOf(id);
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(result) {
                mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns the number of tokens owned by `owner`.
    ///
    /// Requirements:
    /// - `owner` must not be the zero address.
    function balanceOf(address owner) public view virtual returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            // Revert if the `owner` is the zero address.
            if iszero(owner) {
                mstore(0x00, 0x8f4eb604) // `BalanceQueryForZeroAddress()`.
                revert(0x1c, 0x04)
            }
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            mstore(0x00, owner)
            result := and(sload(keccak256(0x0c, 0x1c)), _MAX_ACCOUNT_BALANCE)
        }
    }

    /// @dev Returns the account approved to manage token `id`.
    ///
    /// Requirements:
    /// - Token `id` must exist.
    function getApproved(uint256 id) public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            if iszero(shl(96, sload(ownershipSlot))) {
                mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
                revert(0x1c, 0x04)
            }
            result := sload(add(1, ownershipSlot))
        }
    }

    /// @dev Sets `account` as the approved account to manage token `id`.
    ///
    /// Requirements:
    /// - Token `id` must exist.
    /// - The caller must be the owner of the token,
    ///   or an approved operator for the token owner.
    ///
    /// Emits an {Approval} event.
    function approve(address account, uint256 id) public payable virtual {
        _approve(msg.sender, account, id);
    }

    /// @dev Returns whether `operator` is approved to manage the tokens of `owner`.
    function isApprovedForAll(address owner, address operator)
        public
        view
        virtual
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x1c, operator)
            mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
            mstore(0x00, owner)
            result := sload(keccak256(0x0c, 0x30))
        }
    }

    /// @dev Sets whether `operator` is approved to manage the tokens of the caller.
    ///
    /// Emits an {ApprovalForAll} event.
    function setApprovalForAll(address operator, bool isApproved) public virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Convert to 0 or 1.
            isApproved := iszero(iszero(isApproved))
            // Update the `isApproved` for (`msg.sender`, `operator`).
            mstore(0x1c, operator)
            mstore(0x08, _ERC721_MASTER_SLOT_SEED_MASKED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x30), isApproved)
            // Emit the {ApprovalForAll} event.
            mstore(0x00, isApproved)
            // forgefmt: disable-next-item
            log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, caller(), shr(96, shl(96, operator)))
        }
    }

    /// @dev Transfers token `id` from `from` to `to`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must exist.
    /// - `from` must be the owner of the token.
    /// - `to` cannot be the zero address.
    /// - The caller must be the owner of the token, or be approved to manage the token.
    ///
    /// Emits a {Transfer} event.
    function transferFrom(address from, address to, uint256 id) public payable virtual {
        _beforeTokenTransfer(from, to, id);
        /// @solidity memory-safe-assembly
        assembly {
            // Clear the upper 96 bits.
            let bitmaskAddress := shr(96, not(0))
            from := and(bitmaskAddress, from)
            to := and(bitmaskAddress, to)
            // Load the ownership data.
            mstore(0x00, id)
            mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, caller()))
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            let ownershipPacked := sload(ownershipSlot)
            let owner := and(bitmaskAddress, ownershipPacked)
            // Revert if the token does not exist, or if `from` is not the owner.
            if iszero(mul(owner, eq(owner, from))) {
                // `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
                mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
                revert(0x1c, 0x04)
            }
            // Load, check, and update the token approval.
            {
                mstore(0x00, from)
                let approvedAddress := sload(add(1, ownershipSlot))
                // Revert if the caller is not the owner, nor approved.
                if iszero(or(eq(caller(), from), eq(caller(), approvedAddress))) {
                    if iszero(sload(keccak256(0x0c, 0x30))) {
                        mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
                        revert(0x1c, 0x04)
                    }
                }
                // Delete the approved address if any.
                if approvedAddress { sstore(add(1, ownershipSlot), 0) }
            }
            // Update with the new owner.
            sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
            // Decrement the balance of `from`.
            {
                let fromBalanceSlot := keccak256(0x0c, 0x1c)
                sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
            }
            // Increment the balance of `to`.
            {
                mstore(0x00, to)
                let toBalanceSlot := keccak256(0x0c, 0x1c)
                let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
                // Revert if `to` is the zero address, or if the account balance overflows.
                if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
                    // `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
                    mstore(shl(2, iszero(to)), 0xea553b3401336cea)
                    revert(0x1c, 0x04)
                }
                sstore(toBalanceSlot, toBalanceSlotPacked)
            }
            // Emit the {Transfer} event.
            log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
        }
        _afterTokenTransfer(from, to, id);
    }

    /// @dev Equivalent to `safeTransferFrom(from, to, id, "")`.
    function safeTransferFrom(address from, address to, uint256 id) public payable virtual {
        transferFrom(from, to, id);
        if (_hasCode(to)) _checkOnERC721Received(from, to, id, "");
    }

    /// @dev Transfers token `id` from `from` to `to`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must exist.
    /// - `from` must be the owner of the token.
    /// - `to` cannot be the zero address.
    /// - The caller must be the owner of the token, or be approved to manage the token.
    /// - If `to` refers to a smart contract, it must implement
    ///   {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
    ///
    /// Emits a {Transfer} event.
    function safeTransferFrom(address from, address to, uint256 id, bytes calldata data)
        public
        payable
        virtual
    {
        transferFrom(from, to, id);
        if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
    }

    /// @dev Returns true if this contract implements the interface defined by `interfaceId`.
    /// See: https://eips.ethereum.org/EIPS/eip-165
    /// This function call must use less than 30000 gas.
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            let s := shr(224, interfaceId)
            // ERC165: 0x01ffc9a7, ERC721: 0x80ac58cd, ERC721Metadata: 0x5b5e139f.
            result := or(or(eq(s, 0x01ffc9a7), eq(s, 0x80ac58cd)), eq(s, 0x5b5e139f))
        }
    }

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

    /// @dev Returns if token `id` exists.
    function _exists(uint256 id) internal view virtual returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            result := iszero(iszero(shl(96, sload(add(id, add(id, keccak256(0x00, 0x20)))))))
        }
    }

    /// @dev Returns the owner of token `id`.
    /// Returns the zero address instead of reverting if the token does not exist.
    function _ownerOf(uint256 id) internal view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            result := shr(96, shl(96, sload(add(id, add(id, keccak256(0x00, 0x20))))))
        }
    }

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

    // For performance, no events are emitted for the hitchhiking setters.
    // Please emit your own events if required.

    /// @dev Returns the auxiliary data for `owner`.
    /// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
    /// Auxiliary data can be set for any address, even if it does not have any tokens.
    function _getAux(address owner) internal view virtual returns (uint224 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            mstore(0x00, owner)
            result := shr(32, sload(keccak256(0x0c, 0x1c)))
        }
    }

    /// @dev Set the auxiliary data for `owner` to `value`.
    /// Minting, transferring, burning the tokens of `owner` will not change the auxiliary data.
    /// Auxiliary data can be set for any address, even if it does not have any tokens.
    function _setAux(address owner, uint224 value) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            mstore(0x00, owner)
            let balanceSlot := keccak256(0x0c, 0x1c)
            let packed := sload(balanceSlot)
            sstore(balanceSlot, xor(packed, shl(32, xor(value, shr(32, packed)))))
        }
    }

    /// @dev Returns the extra data for token `id`.
    /// Minting, transferring, burning a token will not change the extra data.
    /// The extra data can be set on a non-existent token.
    function _getExtraData(uint256 id) internal view virtual returns (uint96 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            result := shr(160, sload(add(id, add(id, keccak256(0x00, 0x20)))))
        }
    }

    /// @dev Sets the extra data for token `id` to `value`.
    /// Minting, transferring, burning a token will not change the extra data.
    /// The extra data can be set on a non-existent token.
    function _setExtraData(uint256 id, uint96 value) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            let packed := sload(ownershipSlot)
            sstore(ownershipSlot, xor(packed, shl(160, xor(value, shr(160, packed)))))
        }
    }

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

    /// @dev Mints token `id` to `to`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must not exist.
    /// - `to` cannot be the zero address.
    ///
    /// Emits a {Transfer} event.
    function _mint(address to, uint256 id) internal virtual {
        _beforeTokenTransfer(address(0), to, id);
        /// @solidity memory-safe-assembly
        assembly {
            // Clear the upper 96 bits.
            to := shr(96, shl(96, to))
            // Load the ownership data.
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            let ownershipPacked := sload(ownershipSlot)
            // Revert if the token already exists.
            if shl(96, ownershipPacked) {
                mstore(0x00, 0xc991cbb1) // `TokenAlreadyExists()`.
                revert(0x1c, 0x04)
            }
            // Update with the owner.
            sstore(ownershipSlot, or(ownershipPacked, to))
            // Increment the balance of the owner.
            {
                mstore(0x00, to)
                let balanceSlot := keccak256(0x0c, 0x1c)
                let balanceSlotPacked := add(sload(balanceSlot), 1)
                // Revert if `to` is the zero address, or if the account balance overflows.
                if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
                    // `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
                    mstore(shl(2, iszero(to)), 0xea553b3401336cea)
                    revert(0x1c, 0x04)
                }
                sstore(balanceSlot, balanceSlotPacked)
            }
            // Emit the {Transfer} event.
            log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
        }
        _afterTokenTransfer(address(0), to, id);
    }

    /// @dev Mints token `id` to `to`, and updates the extra data for token `id` to `value`.
    /// Does NOT check if token `id` already exists (assumes `id` is auto-incrementing).
    ///
    /// Requirements:
    ///
    /// - `to` cannot be the zero address.
    ///
    /// Emits a {Transfer} event.
    function _mintAndSetExtraDataUnchecked(address to, uint256 id, uint96 value) internal virtual {
        _beforeTokenTransfer(address(0), to, id);
        /// @solidity memory-safe-assembly
        assembly {
            // Clear the upper 96 bits.
            to := shr(96, shl(96, to))
            // Update with the owner and extra data.
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            sstore(add(id, add(id, keccak256(0x00, 0x20))), or(shl(160, value), to))
            // Increment the balance of the owner.
            {
                mstore(0x00, to)
                let balanceSlot := keccak256(0x0c, 0x1c)
                let balanceSlotPacked := add(sload(balanceSlot), 1)
                // Revert if `to` is the zero address, or if the account balance overflows.
                if iszero(mul(to, and(balanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
                    // `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
                    mstore(shl(2, iszero(to)), 0xea553b3401336cea)
                    revert(0x1c, 0x04)
                }
                sstore(balanceSlot, balanceSlotPacked)
            }
            // Emit the {Transfer} event.
            log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, 0, to, id)
        }
        _afterTokenTransfer(address(0), to, id);
    }

    /// @dev Equivalent to `_safeMint(to, id, "")`.
    function _safeMint(address to, uint256 id) internal virtual {
        _safeMint(to, id, "");
    }

    /// @dev Mints token `id` to `to`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must not exist.
    /// - `to` cannot be the zero address.
    /// - If `to` refers to a smart contract, it must implement
    ///   {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
    ///
    /// Emits a {Transfer} event.
    function _safeMint(address to, uint256 id, bytes memory data) internal virtual {
        _mint(to, id);
        if (_hasCode(to)) _checkOnERC721Received(address(0), to, id, data);
    }

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

    /// @dev Equivalent to `_burn(address(0), id)`.
    function _burn(uint256 id) internal virtual {
        _burn(address(0), id);
    }

    /// @dev Destroys token `id`, using `by`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must exist.
    /// - If `by` is not the zero address,
    ///   it must be the owner of the token, or be approved to manage the token.
    ///
    /// Emits a {Transfer} event.
    function _burn(address by, uint256 id) internal virtual {
        address owner = ownerOf(id);
        _beforeTokenTransfer(owner, address(0), id);
        /// @solidity memory-safe-assembly
        assembly {
            // Clear the upper 96 bits.
            by := shr(96, shl(96, by))
            // Load the ownership data.
            mstore(0x00, id)
            mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            let ownershipPacked := sload(ownershipSlot)
            // Reload the owner in case it is changed in `_beforeTokenTransfer`.
            owner := shr(96, shl(96, ownershipPacked))
            // Revert if the token does not exist.
            if iszero(owner) {
                mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
                revert(0x1c, 0x04)
            }
            // Load and check the token approval.
            {
                mstore(0x00, owner)
                let approvedAddress := sload(add(1, ownershipSlot))
                // If `by` is not the zero address, do the authorization check.
                // Revert if the `by` is not the owner, nor approved.
                if iszero(or(iszero(by), or(eq(by, owner), eq(by, approvedAddress)))) {
                    if iszero(sload(keccak256(0x0c, 0x30))) {
                        mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
                        revert(0x1c, 0x04)
                    }
                }
                // Delete the approved address if any.
                if approvedAddress { sstore(add(1, ownershipSlot), 0) }
            }
            // Clear the owner.
            sstore(ownershipSlot, xor(ownershipPacked, owner))
            // Decrement the balance of `owner`.
            {
                let balanceSlot := keccak256(0x0c, 0x1c)
                sstore(balanceSlot, sub(sload(balanceSlot), 1))
            }
            // Emit the {Transfer} event.
            log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, owner, 0, id)
        }
        _afterTokenTransfer(owner, address(0), id);
    }

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

    /// @dev Returns whether `account` is the owner of token `id`, or is approved to manage it.
    ///
    /// Requirements:
    /// - Token `id` must exist.
    function _isApprovedOrOwner(address account, uint256 id)
        internal
        view
        virtual
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := 1
            // Clear the upper 96 bits.
            account := shr(96, shl(96, account))
            // Load the ownership data.
            mstore(0x00, id)
            mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, account))
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            let owner := shr(96, shl(96, sload(ownershipSlot)))
            // Revert if the token does not exist.
            if iszero(owner) {
                mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
                revert(0x1c, 0x04)
            }
            // Check if `account` is the `owner`.
            if iszero(eq(account, owner)) {
                mstore(0x00, owner)
                // Check if `account` is approved to manage the token.
                if iszero(sload(keccak256(0x0c, 0x30))) {
                    result := eq(account, sload(add(1, ownershipSlot)))
                }
            }
        }
    }

    /// @dev Returns the account approved to manage token `id`.
    /// Returns the zero address instead of reverting if the token does not exist.
    function _getApproved(uint256 id) internal view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, id)
            mstore(0x1c, _ERC721_MASTER_SLOT_SEED)
            result := sload(add(1, add(id, add(id, keccak256(0x00, 0x20)))))
        }
    }

    /// @dev Equivalent to `_approve(address(0), account, id)`.
    function _approve(address account, uint256 id) internal virtual {
        _approve(address(0), account, id);
    }

    /// @dev Sets `account` as the approved account to manage token `id`, using `by`.
    ///
    /// Requirements:
    /// - Token `id` must exist.
    /// - If `by` is not the zero address, `by` must be the owner
    ///   or an approved operator for the token owner.
    ///
    /// Emits a {Approval} event.
    function _approve(address by, address account, uint256 id) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Clear the upper 96 bits.
            let bitmaskAddress := shr(96, not(0))
            account := and(bitmaskAddress, account)
            by := and(bitmaskAddress, by)
            // Load the owner of the token.
            mstore(0x00, id)
            mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            let owner := and(bitmaskAddress, sload(ownershipSlot))
            // Revert if the token does not exist.
            if iszero(owner) {
                mstore(0x00, 0xceea21b6) // `TokenDoesNotExist()`.
                revert(0x1c, 0x04)
            }
            // If `by` is not the zero address, do the authorization check.
            // Revert if `by` is not the owner, nor approved.
            if iszero(or(iszero(by), eq(by, owner))) {
                mstore(0x00, owner)
                if iszero(sload(keccak256(0x0c, 0x30))) {
                    mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
                    revert(0x1c, 0x04)
                }
            }
            // Sets `account` as the approved account to manage `id`.
            sstore(add(1, ownershipSlot), account)
            // Emit the {Approval} event.
            log4(codesize(), 0x00, _APPROVAL_EVENT_SIGNATURE, owner, account, id)
        }
    }

    /// @dev Approve or remove the `operator` as an operator for `by`,
    /// without authorization checks.
    ///
    /// Emits an {ApprovalForAll} event.
    function _setApprovalForAll(address by, address operator, bool isApproved) internal virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Clear the upper 96 bits.
            by := shr(96, shl(96, by))
            operator := shr(96, shl(96, operator))
            // Convert to 0 or 1.
            isApproved := iszero(iszero(isApproved))
            // Update the `isApproved` for (`by`, `operator`).
            mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, operator))
            mstore(0x00, by)
            sstore(keccak256(0x0c, 0x30), isApproved)
            // Emit the {ApprovalForAll} event.
            mstore(0x00, isApproved)
            log3(0x00, 0x20, _APPROVAL_FOR_ALL_EVENT_SIGNATURE, by, operator)
        }
    }

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

    /// @dev Equivalent to `_transfer(address(0), from, to, id)`.
    function _transfer(address from, address to, uint256 id) internal virtual {
        _transfer(address(0), from, to, id);
    }

    /// @dev Transfers token `id` from `from` to `to`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must exist.
    /// - `from` must be the owner of the token.
    /// - `to` cannot be the zero address.
    /// - If `by` is not the zero address,
    ///   it must be the owner of the token, or be approved to manage the token.
    ///
    /// Emits a {Transfer} event.
    function _transfer(address by, address from, address to, uint256 id) internal virtual {
        _beforeTokenTransfer(from, to, id);
        /// @solidity memory-safe-assembly
        assembly {
            // Clear the upper 96 bits.
            let bitmaskAddress := shr(96, not(0))
            from := and(bitmaskAddress, from)
            to := and(bitmaskAddress, to)
            by := and(bitmaskAddress, by)
            // Load the ownership data.
            mstore(0x00, id)
            mstore(0x1c, or(_ERC721_MASTER_SLOT_SEED, by))
            let ownershipSlot := add(id, add(id, keccak256(0x00, 0x20)))
            let ownershipPacked := sload(ownershipSlot)
            let owner := and(bitmaskAddress, ownershipPacked)
            // Revert if the token does not exist, or if `from` is not the owner.
            if iszero(mul(owner, eq(owner, from))) {
                // `TokenDoesNotExist()`, `TransferFromIncorrectOwner()`.
                mstore(shl(2, iszero(owner)), 0xceea21b6a1148100)
                revert(0x1c, 0x04)
            }
            // Load, check, and update the token approval.
            {
                mstore(0x00, from)
                let approvedAddress := sload(add(1, ownershipSlot))
                // If `by` is not the zero address, do the authorization check.
                // Revert if the `by` is not the owner, nor approved.
                if iszero(or(iszero(by), or(eq(by, from), eq(by, approvedAddress)))) {
                    if iszero(sload(keccak256(0x0c, 0x30))) {
                        mstore(0x00, 0x4b6e7f18) // `NotOwnerNorApproved()`.
                        revert(0x1c, 0x04)
                    }
                }
                // Delete the approved address if any.
                if approvedAddress { sstore(add(1, ownershipSlot), 0) }
            }
            // Update with the new owner.
            sstore(ownershipSlot, xor(ownershipPacked, xor(from, to)))
            // Decrement the balance of `from`.
            {
                let fromBalanceSlot := keccak256(0x0c, 0x1c)
                sstore(fromBalanceSlot, sub(sload(fromBalanceSlot), 1))
            }
            // Increment the balance of `to`.
            {
                mstore(0x00, to)
                let toBalanceSlot := keccak256(0x0c, 0x1c)
                let toBalanceSlotPacked := add(sload(toBalanceSlot), 1)
                // Revert if `to` is the zero address, or if the account balance overflows.
                if iszero(mul(to, and(toBalanceSlotPacked, _MAX_ACCOUNT_BALANCE))) {
                    // `TransferToZeroAddress()`, `AccountBalanceOverflow()`.
                    mstore(shl(2, iszero(to)), 0xea553b3401336cea)
                    revert(0x1c, 0x04)
                }
                sstore(toBalanceSlot, toBalanceSlotPacked)
            }
            // Emit the {Transfer} event.
            log4(codesize(), 0x00, _TRANSFER_EVENT_SIGNATURE, from, to, id)
        }
        _afterTokenTransfer(from, to, id);
    }

    /// @dev Equivalent to `_safeTransfer(from, to, id, "")`.
    function _safeTransfer(address from, address to, uint256 id) internal virtual {
        _safeTransfer(from, to, id, "");
    }

    /// @dev Transfers token `id` from `from` to `to`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must exist.
    /// - `from` must be the owner of the token.
    /// - `to` cannot be the zero address.
    /// - The caller must be the owner of the token, or be approved to manage the token.
    /// - If `to` refers to a smart contract, it must implement
    ///   {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
    ///
    /// Emits a {Transfer} event.
    function _safeTransfer(address from, address to, uint256 id, bytes memory data)
        internal
        virtual
    {
        _transfer(address(0), from, to, id);
        if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
    }

    /// @dev Equivalent to `_safeTransfer(by, from, to, id, "")`.
    function _safeTransfer(address by, address from, address to, uint256 id) internal virtual {
        _safeTransfer(by, from, to, id, "");
    }

    /// @dev Transfers token `id` from `from` to `to`.
    ///
    /// Requirements:
    ///
    /// - Token `id` must exist.
    /// - `from` must be the owner of the token.
    /// - `to` cannot be the zero address.
    /// - If `by` is not the zero address,
    ///   it must be the owner of the token, or be approved to manage the token.
    /// - If `to` refers to a smart contract, it must implement
    ///   {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
    ///
    /// Emits a {Transfer} event.
    function _safeTransfer(address by, address from, address to, uint256 id, bytes memory data)
        internal
        virtual
    {
        _transfer(by, from, to, id);
        if (_hasCode(to)) _checkOnERC721Received(from, to, id, data);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                    HOOKS FOR OVERRIDING                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Hook that is called before any token transfers, including minting and burning.
    function _beforeTokenTransfer(address from, address to, uint256 id) internal virtual {}

    /// @dev Hook that is called after any token transfers, including minting and burning.
    function _afterTokenTransfer(address from, address to, uint256 id) internal virtual {}

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      PRIVATE HELPERS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns if `a` has bytecode of non-zero length.
    function _hasCode(address a) private view returns (bool result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := extcodesize(a) // Can handle dirty upper bits.
        }
    }

    /// @dev Perform a call to invoke {IERC721Receiver-onERC721Received} on `to`.
    /// Reverts if the target does not support the function correctly.
    function _checkOnERC721Received(address from, address to, uint256 id, bytes memory data)
        private
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Prepare the calldata.
            let m := mload(0x40)
            let onERC721ReceivedSelector := 0x150b7a02
            mstore(m, onERC721ReceivedSelector)
            mstore(add(m, 0x20), caller()) // The `operator`, which is always `msg.sender`.
            mstore(add(m, 0x40), shr(96, shl(96, from)))
            mstore(add(m, 0x60), id)
            mstore(add(m, 0x80), 0x80)
            let n := mload(data)
            mstore(add(m, 0xa0), n)
            if n { pop(staticcall(gas(), 4, add(data, 0x20), n, add(m, 0xc0), n)) }
            // Revert if the call reverts.
            if iszero(call(gas(), to, 0, add(m, 0x1c), add(n, 0xa4), m, 0x20)) {
                if returndatasize() {
                    // Bubble up the revert if the call reverts.
                    returndatacopy(m, 0x00, returndatasize())
                    revert(m, returndatasize())
                }
            }
            // Load the returndata and compare it.
            if iszero(eq(mload(m), shl(224, onERC721ReceivedSelector))) {
                mstore(0x00, 0xd1a57ed6) // `TransferToNonERC721ReceiverImplementer()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

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` implements `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), 0x84, 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/FWAConfigKeys.sol

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

/// @title FWAConfigKeys
/// @notice Keys for FWA's consolidated owner-config setters (`setUint`/`setBool`/`setAddr`). The former
///         per-knob setters were merged into three generic dispatchers to keep FWA's runtime
///         bytecode under the 24,576-byte EIP-170 limit; these named constants keep call sites readable
///         (`pool.setUint(FWAConfigKeys.SURCHARGE_BPS, 1200)`). Constants live in a library so they inline
///         at zero bytecode cost in both FWA and its callers. Values are globally unique across all three
///         dispatchers so the emitted `ConfigSet(key, value)` event is unambiguous for indexers.
library FWAConfigKeys {
    // --- constructor / FWAVRFService request-tuple events (not accepted by setUint) ---
    uint256 internal constant CALLBACK_GAS_LIMIT = 1;
    uint256 internal constant VRF_KEY_HASH = 24;

    // --- setUint (uint256 value) ---
    uint256 internal constant VRF_SUB_ID = 2;
    // Values 3..6 are intentionally unused. VRF service-fee pricing, callback coverage and subscription
    // funding moved into the external FWAVRFService before deployment.
    uint256 internal constant REQUEST_CONFIRMATIONS = 7;
    // Values 8 and 9 are intentionally unused. Block maturity and the separate callback window were
    // replaced before deployment by request-time reservation plus `SELECTION_TIMEOUT_BLOCKS`.
    uint256 internal constant MAX_ACTIVATIONS_PER_ACQUISITION = 10;
    uint256 internal constant SELECTION_TIMEOUT_BLOCKS = 11;
    uint256 internal constant MAX_ACQUISITIONS_PER_TX = 12;
    uint256 internal constant SURCHARGE_BPS = 13;
    uint256 internal constant SELECTION_SLIPPAGE_BPS = 14;
    uint256 internal constant TOP_LISTING_SHARE_BPS = 15;
    uint256 internal constant TOP_THRESHOLD_BPS = 16;
    uint256 internal constant SETTLEMENT_DISCOUNT_BPS = 17;
    uint256 internal constant OWNER_ACQUISITION_FEE_BPS = 18;
    uint256 internal constant OWNER_SETTLEMENT_FEE_BPS = 19;
    uint256 internal constant SETTLEMENT_WINDOW = 20;
    uint256 internal constant FINALIZE_WINDOW = 21;
    uint256 internal constant MIN_BACKING = 22;
    uint256 internal constant PROTOCOL_FEE_TO_TOKEN_BPS = 23;
    uint256 internal constant MAX_STAGED_LISTINGS = 25;

    // --- setBool (bool value) ---
    uint256 internal constant RETAINED_TO_PROTOCOL = 40;
    uint256 internal constant ACQUISITIONS_ENABLED = 41;
    uint256 internal constant WITHDRAW_ONLY = 42;
    uint256 internal constant WHITELIST_ENABLED = 43;
    uint256 internal constant ACCEPT_BID_AS_TOKENS_ENABLED = 44;
    uint256 internal constant ROUTE_ACQUISITION_PROCEEDS_TO_AUTO_RELOAD = 45;

    // --- setAddr (address value) ---
    uint256 internal constant VRF_COORDINATOR = 60;
    uint256 internal constant PAYOUT_ADDRESS = 61;
    uint256 internal constant WHITELIST_MANAGER = 62;
    /// @dev Constructor-only immutable address, emitted through ConfigSet but not accepted by setAddr.
    uint256 internal constant VRF_SERVICE = 63;
}

src/interfaces/IFWAPurchaseCallback.sol

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

/// @title IFWAPurchaseCallback
/// @notice Settlement notification for a registry-recognized FWAIR launch or an ERC-165-opted-in NFT collection.
/// @dev Implementations must authenticate both `msg.sender` (the notifier trusted by `fwa`) and
///      `fwa`. Notifications are best-effort, so correctness must not depend on receiving one.
interface IFWAPurchaseCallback {
    enum Outcome {
        PurchaserKeptNFT,
        PurchaserTookETH,
        PurchaserTookFWA,
        PurchaserRelistedNFT
    }

    /// @param fwa Pool in which the purchase settled.
    /// @param listingId Settled FWA listing.
    /// @param purchaser Address originally allocated the NFT by FWA.
    /// @param resolver Address that submitted the successful settlement transaction.
    /// @param backing Gross ETH backing attached to the listing.
    /// @param settlementAmount Net ETH returned to the depositor for NFT/relist outcomes, or the ETH paid
    ///        to the purchaser/consumed by the token buy for backing outcomes.
    /// @param outcome Asset/result selected by the successful resolution path.
    function onFWAPurchase(
        address fwa,
        uint256 listingId,
        address purchaser,
        address resolver,
        uint256 backing,
        uint256 settlementAmount,
        Outcome outcome
    ) external;
}

src/interfaces/IPoolPurchaseCallback.sol

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

/// @title IPoolPurchaseCallback
/// @notice Optional ERC-165 collection notification after a PoolsV2 NFT purchase is delivered.
/// @dev Receivers must authenticate both the notifier (`msg.sender`) and `purchase.pool`, and may
///      verify the canonical listing and acquisition. Notifications are best-effort, have bounded
///      gas, and are not retried. A receiver must not depend on a notification for correctness.
interface IPoolPurchaseCallback {
    struct Purchase {
        address pool;
        uint256 requestId;
        uint256 listingId;
        uint256 tokenId;
        address purchaser;
        address resolver;
        // Zero for native ETH; otherwise the pool's payment token.
        address paymentToken;
        // Gross acquisition payment in wei or payment-token base units, excluding the VRF fee.
        uint256 amountPaid;
        // Owner-assigned listing price in wei; this is neither backing nor an appraisal.
        uint256 listingPrice;
        // Exact authenticated VRF word, including zero; no modulo or other transformation.
        uint256 randomWord;
    }

    /// @notice Called once after verified NFT delivery and final settlement accounting.
    /// @param purchase Canonical purchase receipt; `resolver` called the successful processor/retry
    ///        path, or is the pool itself when the VRF callback's self-call delivered the NFT.
    function onPoolPurchase(Purchase calldata purchase) external;
}

src/poolsV2/PoolPurchaseNotifier.sol

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

import {IFWAPurchaseCallback} from "../interfaces/IFWAPurchaseCallback.sol";
import {IPoolPurchaseCallback} from "../interfaces/IPoolPurchaseCallback.sol";

interface IPoolPurchaseNotifierFactory {
    function isPool(address pool) external view returns (bool);
    function poolImplementation(address pool) external view returns (address);
}

interface IPoolPurchaseNotifierPool {
    function purchaseNotifier() external view returns (address);
    function paymentToken() external view returns (address);

    function listings(uint256 listingId)
        external
        view
        returns (
            address collection,
            address depositor,
            address purchaser,
            uint256 tokenId,
            uint256 weight,
            uint256 price,
            uint256 slot,
            uint8 status
        );

    function acquisitions(uint256 requestId)
        external
        view
        returns (
            address purchaser,
            uint256 requestBlock,
            uint256 priceEscrowed,
            uint256 listingId,
            uint8 status,
            bool tokenPayment
        );

    function acquisitionMeta(uint256 requestId)
        external
        view
        returns (
            uint64 sequence,
            uint64 wordDeadlineBlock,
            uint64 rewardEpoch,
            uint16 maxPositiveSlippageBps,
            uint16 maxNegativeSlippageBps,
            uint256 randomWord
        );
}

/// @title PoolPurchaseNotifier
/// @notice Authenticated, bounded collection callbacks for one PoolsV2 implementation's clones.
/// @dev The implementation creates this immutable adapter. Only its registered clones can dispatch,
///      and every receipt is read from their completed settlement state. Downstream failures never
///      propagate. Receivers must authenticate the notifier and originating pool themselves.
contract PoolPurchaseNotifier {
    uint256 internal constant MIN_ENTRY_GAS = 290_000;
    uint256 internal constant ERC165_GAS_STIPEND = 30_000;
    uint256 internal constant CALLBACK_GAS_STIPEND = 100_000;
    uint8 internal constant LISTING_SETTLED = 4;
    uint8 internal constant ACQUISITION_FULFILLED = 2;

    address public immutable factory;
    address public immutable implementation;

    error InvalidFactory();
    error UnauthorizedPool();
    error InvalidPurchase();

    event PurchaseCallbackAttempted(
        address indexed pool,
        address indexed collection,
        uint256 indexed requestId,
        uint256 listingId,
        bool withRandomness,
        bool success
    );

    constructor(address factory_) {
        if (factory_ == address(0) || factory_.code.length == 0) revert InvalidFactory();
        factory = factory_;
        implementation = msg.sender;
    }

    function notifyPurchase(uint256 listingId, uint256 requestId, address resolver, uint256 ownerProceeds) external {
        // The pool must propagate this failure so underfunding the outer transaction cannot silently
        // omit dispatch. The fixed budget covers canonical reads, both probes and one receiver call.
        if (gasleft() < MIN_ENTRY_GAS) {
            assembly ("memory-safe") {
                revert(0, 0)
            }
        }

        IPoolPurchaseNotifierFactory registry = IPoolPurchaseNotifierFactory(factory);
        IPoolPurchaseNotifierPool pool = IPoolPurchaseNotifierPool(msg.sender);
        if (
            !registry.isPool(msg.sender) || registry.poolImplementation(msg.sender) != implementation
                || pool.purchaseNotifier() != address(this)
        ) revert UnauthorizedPool();

        (address collection,, address listingPurchaser, uint256 tokenId,, uint256 price,, uint8 listingStatus) =
            pool.listings(listingId);
        (address purchaser,, uint256 paid, uint256 acquiredListingId, uint8 acquisitionStatus, bool tokenPayment) =
            pool.acquisitions(requestId);
        if (
            listingStatus != LISTING_SETTLED || acquisitionStatus != ACQUISITION_FULFILLED
                || acquiredListingId != listingId || purchaser == address(0) || listingPurchaser != purchaser
                || collection == address(0)
        ) revert InvalidPurchase();

        (,,,,, uint256 randomWord) = pool.acquisitionMeta(requestId);
        address paymentToken = tokenPayment ? pool.paymentToken() : address(0);
        if (tokenPayment && paymentToken == address(0)) revert InvalidPurchase();

        if (_supportsCallback(collection, type(IPoolPurchaseCallback).interfaceId)) {
            IPoolPurchaseCallback.Purchase memory purchase = IPoolPurchaseCallback.Purchase({
                pool: msg.sender,
                requestId: requestId,
                listingId: listingId,
                tokenId: tokenId,
                purchaser: purchaser,
                resolver: resolver,
                paymentToken: paymentToken,
                amountPaid: paid,
                listingPrice: price,
                randomWord: randomWord
            });
            _callReceiver(
                collection, requestId, listingId, true, abi.encodeCall(IPoolPurchaseCallback.onPoolPurchase, (purchase))
            );
            // A failed rich callback must not trigger a second call through the legacy interface.
            return;
        }

        // Legacy settlement amounts are ETH-denominated. Token burns have no compatible outcome.
        if (!tokenPayment && _supportsCallback(collection, type(IFWAPurchaseCallback).interfaceId)) {
            uint256 settlementAmount = ownerProceeds < paid ? ownerProceeds : paid;
            _callReceiver(
                collection,
                requestId,
                listingId,
                false,
                abi.encodeCall(
                    IFWAPurchaseCallback.onFWAPurchase,
                    (
                        msg.sender,
                        listingId,
                        purchaser,
                        resolver,
                        0,
                        settlementAmount,
                        IFWAPurchaseCallback.Outcome.PurchaserKeptNFT
                    )
                )
            );
        }
    }

    function _callReceiver(
        address collection,
        uint256 requestId,
        uint256 listingId,
        bool withRandomness,
        bytes memory callData
    ) internal {
        bool success;
        uint256 gasStipend = CALLBACK_GAS_STIPEND;
        // Never copy receiver returndata, including unbounded revert data.
        assembly ("memory-safe") {
            success := call(gasStipend, collection, 0, add(callData, 0x20), mload(callData), 0, 0)
        }
        emit PurchaseCallbackAttempted(msg.sender, collection, requestId, listingId, withRandomness, success);
    }

    /// @dev Reject malformed/noncanonical responses using fixed input and output buffers. A probe
    ///      that reverts or exhausts its stipend is treated as unsupported.
    function _supportsCallback(address target, bytes4 callbackInterface) internal view returns (bool) {
        if (target.code.length == 0) return false;

        uint32 selector = uint32(0x01ffc9a7); // supportsInterface(bytes4)
        uint32 interfaceId = uint32(callbackInterface);
        uint256 gasStipend = ERC165_GAS_STIPEND;
        uint256 result;
        bool success;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            mstore(ptr, shl(224, selector))
            mstore(add(ptr, 0x04), shl(224, interfaceId))
            success := staticcall(gasStipend, target, ptr, 0x24, ptr, 0x20)
            success := and(success, eq(returndatasize(), 0x20))
            result := mload(ptr)
        }
        return success && result == 1;
    }
}

src/poolsV2/StandardPool.sol

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

// Solady
import {ERC721} from "solady/src/tokens/ERC721.sol";
import {Ownable} from "solady/src/auth/Ownable.sol";
import {ReentrancyGuard} from "solady/src/utils/ReentrancyGuard.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";

// Chainlink VRF v2.5 — singleton subscription model. The shared service/router is this pool's logical
// coordinator and is the only caller authorized to forward an authenticated word. The router alone
// inherits Chainlink's official consumer base and is the real subscription's sole consumer.
import {IVRFCoordinatorV2Plus} from "@chainlink/contracts/src/v0.8/vrf/interfaces/IVRFCoordinatorV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/libraries/VRFV2PlusClient.sol";

import {FWAConfigKeys} from "../FWAConfigKeys.sol";
import {IFWACloneFactory} from "../userowned/interfaces/IFWACloneFactory.sol";
import {IPurchaseOperator} from "../userowned/interfaces/IPurchaseOperator.sol";
import {PoolPurchaseNotifier} from "./PoolPurchaseNotifier.sol";

interface IPoolsV2TokenFactory {
    function poolToken(address pool) external view returns (address);
}

interface IPoolFeeRouterV2 {
    function depositFees() external payable;
}

interface IPoolPaymentToken {
    function burn(uint256 amount) external;
}

interface IFWAVRFService {
    function requestFee() external view returns (uint256);
    function prepareRequests(uint256 requestCount) external payable;
}

/// @title StandardPool
/// @notice A factory-created, user-owned randomized NFT pool. The pool owner is the only inventory
///         supplier and assigns each escrowed NFT an arbitrary notional price. Price determines both
///         the acquisition cost and inverse selection weight (`NUM / price`). A successful ordered
///         Chainlink VRF draw removes the selected listing and delivers its NFT directly to the buyer.
/// @dev Economic design:
///      - Acquisitions are priced at the pool's expected value times a protocol surcharge:
///        `EV = Σ(weightᵢ·priceᵢ) / Σweightᵢ`. With inverse weights this is the harmonic
///        mean of owner-assigned prices. Prices are not appraisals or escrowed backing.
///      - The base acquisition price accrues to the pool owner. The entire factory edge accrues
///        for the protocol. Optional custom-token promotions burn the entire token payment.
///      - Owner-driven listing, withdrawal, and repricing changes increment an exact version.
///        Buyers bind requests to that version and a deadline, with no timed inventory-change delay.
///      Selection runs in O(TREE_DEPTH) via a sparse segment tree over active listing slots.
///      Uses Chainlink VRF v2.5 SUBSCRIPTION (native payment): an external `FWAVRFService` receives each
///      purchaser's service fee, pre-funds callback coverage, and may use only proven surplus to sponsor
///      canonical processing. Request IDs, cached callbacks, staging, and ordered settlement retain
///      FWA's original anti-steering behavior.
contract StandardPool is Ownable, ReentrancyGuard {
    /*//////////////////////////////////////////////////////////////
                                TYPES
    //////////////////////////////////////////////////////////////*/

    enum ListingStatus {
        None,
        Active,
        Allocated,
        Withdrawn,
        Settled,
        // A listing made while an acquisition is unresolved: escrowed but NOT yet in the selection
        // pool. A later request may reserve it before asking VRF; otherwise it activates once the
        // sequencer is idle. Appended last so pre-existing numeric listing states remain stable.
        Staged,
        // The selected NFT could not be atomically delivered. Its purchaser and paid price are
        // immutable while permissionless retries remain open.
        DeliveryPending,
        // The delivery deadline elapsed and the purchaser took a refund. The NFT remains quarantined
        // until the pool owner atomically recovers it; it is never reinserted automatically.
        DeliveryRefunded
    }

    enum AcquisitionStatus {
        None,
        Pending, // waiting for an on-time VRF word
        Fulfilled,
        Expired, // skipped in sequence after its word deadline; escrowed fee credited for withdrawal
        Refunded, // no listing / slippage refund; escrowed fee credited for withdrawal
        Ready, // an on-time word is cached and must be settled in request order
        TimedOut, // a callback arrived after its deadline; the request is skipped when it reaches the head
        DeliveryPending, // selected NFT quarantined; acquisition payment remains in delivery escrow
        DeliveryRefunded // delivery deadline elapsed and the purchaser converted escrow to refund credit
    }

    struct ListingInput {
        address collection;
        uint256 tokenId;
        uint256 price;
    }

    struct Listing {
        address collection;
        address depositor;
        address purchaser;
        uint256 tokenId;
        uint256 weight; // selection weight; derived as NUM / price (weight ∝ 1 / price)
        uint256 price; // owner-assigned notional price; no ETH backs this amount
        uint256 slot;
        ListingStatus status;
    }

    struct Acquisition {
        address purchaser;
        uint256 requestBlock;
        uint256 priceEscrowed; // acquisition fee held until the acquisition settles (distributed) or is refunded
        uint256 listingId;
        AcquisitionStatus status;
        bool tokenPayment; // full payment burns only after verified NFT delivery
    }

    /// @dev Sequencing fields are separate so the existing public `acquisitions(requestId)` getter ABI
    ///      remains stable for indexers. Every value is fixed at request time except `randomWord`, which
    ///      the authenticated VRF callback writes exactly once.
    struct AcquisitionMeta {
        uint64 sequence;
        uint64 wordDeadlineBlock;
        uint64 rewardEpoch;
        uint16 maxPositiveSlippageBps;
        uint16 maxNegativeSlippageBps;
        uint256 randomWord;
    }

    struct PendingDelivery {
        uint256 requestId;
        uint64 deadline;
    }

    /*//////////////////////////////////////////////////////////////
                               CONSTANTS
    //////////////////////////////////////////////////////////////*/

    /*
        Supports 2^32 simultaneously active listings.

        This does NOT allocate 2^32 storage slots. The tree is a mapping,
        so only nodes that are actually touched consume storage.

        Each insertion/removal/selection takes roughly TREE_DEPTH steps.
    */
    uint256 internal constant TREE_DEPTH = 32;
    uint256 internal constant CAPACITY = 1 << TREE_DEPTH;

    /*
        Segment tree layout:

                           node 1
                         /        \
                    node 2         node 3
                    / ...           ... \

        Leaves begin at index CAPACITY.

        Listing slot 1           => tree node CAPACITY
        Listing slot 2           => tree node CAPACITY + 1
        Listing slot CAPACITY    => tree node (2 * CAPACITY) - 1
    */
    uint256 internal constant LEAF_BASE = CAPACITY;

    /// @notice Denominator for basis-point math.
    uint256 public constant BPS = 10_000;

    /// @notice Factory compatibility discriminator for standard, unbacked pools.
    uint8 public constant IMPLEMENTATION_KIND = 1;

    /// @notice Maximum listings supplied or withdrawn atomically by one inventory call.
    uint256 public constant MAX_INVENTORY_BATCH = 20;

    /// @notice Fixed-point numerator for the inverse selection weight. A listing's acquisition weight is
    ///         `INVERSE_WEIGHT_NUMERATOR / price`, so selection weight is inversely proportional to price.
    ///         As a shared constant it cancels in the relative selection weight between any two listings and
    ///         only sets the absolute precision of the weights; sized far above any realistic
    ///         price so `NUM / price` never rounds to zero for a sane listing.
    uint256 internal constant INVERSE_WEIGHT_NUMERATOR = 1e36;
    uint256 internal constant NFT_DELIVERY_GAS = 150_000;
    uint256 internal constant PURCHASE_OPERATOR_GAS = 100_000;

    /// @notice Fixed time allowed for permissionless delivery retries before the purchaser may refund.
    uint256 public constant DELIVERY_WINDOW = 7 days;

    /*//////////////////////////////////////////////////////////////
                              VRF CONFIG
    //////////////////////////////////////////////////////////////*/

    /// @notice Logical coordinator: the immutable singleton service/router, which requests from the
    ///         real Chainlink coordinator and forwards only authenticated stored words.
    IVRFCoordinatorV2Plus internal s_vrfCoordinator;

    /// @notice Singleton subscription ID embedded in the exact request tuple validated by the router.
    uint256 internal vrfSubId;

    /// @notice Immutable fee, subscription-funding, request-routing, and callback-forwarding module.
    IFWAVRFService public immutable vrfService;

    /// @notice Factory that deployed and permanently governs the clone's global policy.
    address public immutable FACTORY;

    /// @notice Shared, authenticated collection callback adapter for this implementation's clones.
    PoolPurchaseNotifier public immutable purchaseNotifier;

    /// @notice VRF gas lane (key hash) selecting the price ceiling for requests. It can be changed only
    ///         through the immutable service together with the callback coverage underwriting it.
    bytes32 internal vrfKeyHash;

    /// @notice Number of random words requested per acquisition.
    uint32 internal constant NUM_WORDS = 1;

    /// @notice Gas limit for the cache-first VRF callback. With at least
    ///         `MIN_FAST_PATH_CALLBACK_GAS_LIMIT`, an in-order word whose request owns no reserved
    ///         listings gets one failure-isolated settlement attempt; every other word remains cached
    ///         for the public processor. Adjustable only through the immutable service while paused.
    uint32 public callbackGasLimit;
    uint32 public constant MIN_CALLBACK_GAS_LIMIT = 150_000;
    uint32 public constant MAX_CALLBACK_GAS_LIMIT = 2_500_000;

    /// @dev The fast path forwards a fixed stipend into the existing guarded one-item processor and
    ///      retains enough parent gas to return successfully even if the subcall consumes its stipend.
    // Budget for cold tree/accounting state, a near-limit successful NFT transfer, and the
    // notifier's mandatory 290k admission reserve. Parent limits must cover caching and EIP-150.
    uint32 internal constant MIN_FAST_PATH_CALLBACK_GAS_LIMIT = 1_200_000;
    uint256 internal constant CALLBACK_FAST_PATH_GAS = 1_000_000;
    uint256 internal constant CALLBACK_RETURN_GAS_RESERVE = 50_000;

    /// @notice Block confirmations the coordinator waits before responding. Constrained to Chainlink's
    ///         supported 3..200 range, with at least `MIN_CALLBACK_SLACK_BLOCKS` before the word deadline.
    uint16 internal requestConfirmations = 3;

    /// @notice Floor on `requestConfirmations`. It is the security axiom — no VRF word can exist before
    ///         this many blocks — so the setters never let it drop below the Chainlink minimum of 3.
    uint256 internal constant MIN_REQUEST_CONFIRMATIONS = 3;
    uint256 internal constant MAX_REQUEST_CONFIRMATIONS = 200;
    uint256 internal constant MIN_CALLBACK_SLACK_BLOCKS = 2;

    /*//////////////////////////////////////////////////////////////
                         ACQUISITION SEQUENCER
    //////////////////////////////////////////////////////////////*/

    /// @notice Maximum FIFO staged listings committed to each acquisition before its VRF request.
    ///         The callback never activates them; the canonical processor activates exactly this
    ///         request-time batch immediately before settling that sequence.
    uint256 internal maxActivationsPerAcquisition = 6;
    uint256 internal constant MAX_ACTIVATIONS_PER_ACQUISITION = 16;

    /// @notice Number of requests still waiting for a callback. A cached word reduces this counter but
    ///         remains unresolved until canonical processing advances its sequence.
    uint256 public pendingAcquisitionCount;

    /// @notice Number of issued VRF requests for which the authenticated coordinator callback has not
    ///         yet been observed. Unlike `pendingAcquisitionCount`, local expiry does not reduce this:
    ///         Chainlink may still fulfill and bill the subscription later.
    uint256 public unfulfilledVrfCount;

    /// @dev First-callback marker keeps `unfulfilledVrfCount` duplicate-safe, including after local expiry.
    mapping(uint256 requestId => bool observed) internal callbackObserved;

    /// @notice Number of issued acquisitions not yet terminally processed. This is the pool-mutation
    ///         lock: it remains non-zero after words are cached and only falls as the sequence advances.
    uint256 public unsettledAcquisitionCount;

    /// @notice Absolute per-request word deadline offset. A callback at `requestBlock + timeout` is
    ///         accepted; a callback after it is permanently late. Snapshotted into each acquisition.
    uint256 public selectionTimeoutBlocks = 30;

    /// @notice Upper bound on the configurable word deadline.
    uint256 internal constant MAX_WINDOW_BLOCKS = 7_200;

    /// @notice Max acquisitions a single `acquireBatch` batch may fire, bounding the request-tx loop.
    ///         Owner-adjustable.
    uint256 internal maxAcquisitionsPerTx = 5;

    /// @notice Monotonic request sequence. VRF callbacks may arrive in any order, but only
    ///         `nextSequenceToProcess` may mutate the pool.
    uint64 public lastIssuedSequence;
    uint64 public nextSequenceToProcess = 1;

    /// @notice Gates acquisitions. Starts `false` so the pool deploys in a "loading" phase: listings
    ///         and withdrawals work, but no one can acquisition until the owner opens the game. Owner
    ///         flips it on with `setBool(ACQUISITIONS_ENABLED, true)`.
    bool internal acquisitionsEnabled;

    /// @notice Irreversible owner-selected retirement state. Retirement blocks every new purchase and
    ///         owner configuration/inventory input while preserving all settlement and exit paths.
    bool public retired;

    /// @notice Optional pool-local purchase policy. Zero keeps purchases permissionless; otherwise the
    ///         configured contract must return canonical ABI `true` for the purchaser at request time.
    address public purchaseOperator;

    /*//////////////////////////////////////////////////////////////
                            ECONOMIC CONFIG
    //////////////////////////////////////////////////////////////*/

    /// @notice Protocol maximum positive price drift accepted at ordered settlement. Snapshotted per
    ///         request. Purchasers may separately choose their maximum negative drift, up to 100%.
    uint256 public selectionSlippageBps = 1_000; // 10%

    /// @notice Monotonic version of owner-driven selection changes. Buyers must submit the exact
    ///         version they quoted so a listing, withdrawal, or reprice cannot execute ahead of them.
    uint256 public inventoryVersion;

    /// @notice Timestamp of the latest owner-driven inventory or price mutation in this clone.
    uint64 public lastInventoryChangeAt;

    /*//////////////////////////////////////////////////////////////
                            LISTING STORAGE
    //////////////////////////////////////////////////////////////*/

    uint256 public nextListingId = 1;

    mapping(uint256 listingId => Listing) public listings;

    /// @notice Request and immutable deadline for a quarantined selected NFT.
    mapping(uint256 listingId => PendingDelivery delivery) public pendingDeliveries;

    /// @notice Acquisition payments held until verified NFT delivery or a purchaser refund.
    uint256 public deliveryEscrowTotal;

    /// @dev One authoritative custody record per collection/token. It remains set across Active,
    ///      Staged, and DeliveryPending/DeliveryRefunded states and is cleared only by a verified exit.
    mapping(address collection => mapping(uint256 tokenId => uint256 listingId)) internal liveNFTListing;

    /*//////////////////////////////////////////////////////////////
                          STAGING QUEUE (FIFO)
    //////////////////////////////////////////////////////////////*/

    /*
        Deposits made while an acquisition is unresolved are parked here — escrowed but excluded from
        every pool total and from the selection tree. Each later acquisition detaches up to
        `maxActivationsPerAcquisition` entries from the FIFO into its immutable reserved batch before
        requesting VRF. The canonical processor activates exactly that batch at the acquisition's turn.
    */
    uint256 internal stagingHead; // first (oldest) staged listing; 0 when empty
    uint256 internal stagingTail; // last (newest) staged listing; 0 when empty
    mapping(uint256 listingId => uint256) internal stagingNext; // toward the tail; 0 = none
    mapping(uint256 listingId => uint256) internal stagingPrev; // toward the head; 0 = none

    /// @notice Unreserved staging-queue length, kept in lockstep with the FIFO.
    uint256 internal stagedCount;

    /// @notice Optional cap on the unreserved staging FIFO (`0` = unlimited, the default). This is
    ///         an operational throttle only; request-time reservation, not queue length, provides the
    ///         anti-steering boundary. Owner-set via `setUint(MAX_STAGED_LISTINGS, ...)`.
    uint256 internal maxStagedListings;

    /// @notice Sequence that owns a detached staged listing; zero means it remains unreserved.
    mapping(uint256 listingId => uint64 sequence) public reservedForSequence;
    uint256 public reservedStagedCount;

    /// @dev Exact request-time activation batch. Its length is bounded by
    ///      `maxActivationsPerAcquisition`, and its entries are removed from the public staging FIFO.
    mapping(uint64 sequence => uint256[]) internal reservedListingsBySequence;

    /*
        Active slot => permanent listing ID.

        A listing ID is never reused.
        A tree slot can be reused after its listing leaves the active pool.
    */
    mapping(uint256 slot => uint256 listingId) public slotToListing;

    uint256 public activeListingCount;
    uint256 public totalWeight;

    /// @notice Σ(weightᵢ · priceᵢ) over active listings. Drives the expected-value acquisition price:
    ///         with inverse weights each term `weightᵢ·priceᵢ ≈ NUM`, so this tracks
    ///         ≈ `activeListingCount · NUM` and `weightedBackingTotal / totalWeight` works out to
    ///         the harmonic mean of the owner-assigned prices. The historical variable name is retained
    ///         in the ABI for compatibility; it does not represent escrowed backing.
    uint256 public weightedBackingTotal;

    /// @notice Purchase proceeds withdrawable by this clone's permanently locked owner.
    uint256 public ownerProceeds;

    /// @notice Full-markup protocol fees awaiting a permissionless push to the factory-wired router.
    uint256 public accruedProtocolFees;

    /*//////////////////////////////////////////////////////////////
                          SPARSE SEGMENT TREE
    //////////////////////////////////////////////////////////////*/

    /*
        tree[node] contains the total weight beneath that node.

        This replaces a giant array. Unused nodes simply return zero.
    */
    mapping(uint256 node => uint256 weight) internal tree;

    /*//////////////////////////////////////////////////////////////
                            SLOT FREE LIST
    //////////////////////////////////////////////////////////////*/

    /*
        Slots are initially allocated sequentially.

        When a listing is allocated or withdrawn, its slot is placed into
        a linked-list free pool and can be assigned to another listing.
    */
    uint256 internal nextUnusedSlot = 1;
    uint256 internal freeSlotHead;

    mapping(uint256 slot => uint256 nextFreeSlot) internal nextFreeSlot;

    /*//////////////////////////////////////////////////////////////
                              ACQUISITION STORAGE
    //////////////////////////////////////////////////////////////*/

    mapping(uint256 requestId => Acquisition) public acquisitions;
    mapping(uint256 requestId => AcquisitionMeta) public acquisitionMeta;
    mapping(uint64 sequence => uint256 requestId) public requestIdAtSequence;

    /// @notice Pull-based acquisition refunds. Ordered processing never calls an untrusted purchaser.
    mapping(address purchaser => uint256 amount) public acquisitionRefundCredit;
    uint256 public acquisitionRefundCreditTotal;
    uint256 public acquisitionEscrowTotal;

    /// @dev The base price is snapshotted at request time so a later global edge change cannot alter
    ///      the already-paid owner/protocol split.
    mapping(uint256 requestId => uint256 basePrice) internal requestBasePrice;

    /// @notice Promotional payment token, fixed to the factory-launched token on first configuration.
    address public paymentToken;
    uint256 public tokenOfferVersion;
    uint256 public tokenOfferPrice;
    uint256 public tokenOfferMaxPulls;
    uint256 public tokenOfferPullsUsed;
    bool public tokenOfferEnabled;

    /// @notice Token liabilities remain separate from all native-ETH accounting.
    uint256 public tokenAcquisitionEscrowTotal;
    uint256 public tokenDeliveryEscrowTotal;
    uint256 public tokenRefundCreditTotal;
    uint256 public tokenBurnablePayments;
    mapping(address purchaser => uint256 amount) public tokenRefundCredit;
    mapping(uint256 requestId => uint256 referenceFee) internal tokenReferenceEthFee;

    /*//////////////////////////////////////////////////////////////
                                EVENTS
    //////////////////////////////////////////////////////////////*/

    event TokenOfferConfigured(uint256 indexed version, uint256 price, uint256 maxPulls, bool enabled);
    event TokenAcquisitionRequested(uint256 indexed requestId, uint256 indexed offerVersion, address indexed token);
    event TokenRefundWithdrawn(address indexed purchaser, uint256 amount);
    event TokenPaymentsBurned(address indexed token, uint256 amount);

    event NFTListed(
        uint256 indexed listingId,
        uint256 indexed slot,
        address indexed depositor,
        address collection,
        uint256 tokenId,
        uint256 weight,
        uint256 price
    );

    /// @param price The listing's notional price, so an indexer can debit the pool's active value
    ///        from this event alone (no join back to `NFTListed`).
    event ListingWithdrawn(uint256 indexed listingId, address indexed depositor, uint256 price);

    /// @dev A listing landed while an acquisition was unresolved (or behind an older FIFO entry), so
    ///      it was parked outside the selection tree. `stagedAtBlock` is informational; a later request
    ///      may reserve the listing before VRF, otherwise it activates after the sequencer becomes idle.
    event ListingStaged(
        uint256 indexed listingId,
        address indexed depositor,
        address collection,
        uint256 tokenId,
        uint256 price,
        uint256 stagedAtBlock
    );

    /// @dev The owner re-priced an active listing. `newWeight` lets an indexer update
    ///      the active pool weight/value from this event alone.
    event PriceUpdated(
        uint256 indexed listingId, address indexed depositor, uint256 oldPrice, uint256 newPrice, uint256 newWeight
    );

    event InventoryChanged(uint256 indexed version, uint64 changedAt);

    event AcquisitionRequested(
        uint256 indexed requestId, address indexed purchaser, uint256 acquisitionFee, uint256 totalWeight
    );

    /// @dev Local sequence and immutable timeout assigned to a VRF request. `reservedCount` is the
    ///      exact FIFO activation batch committed before randomness was requested.
    event AcquisitionSequenced(
        uint256 indexed requestId, uint64 indexed sequence, uint64 wordDeadlineBlock, uint256 reservedCount
    );

    event RandomnessCached(uint256 indexed requestId, uint64 indexed sequence, uint256 randomWord);
    event RandomnessTimedOut(
        uint256 indexed requestId, uint64 indexed sequence, uint64 wordDeadlineBlock, uint256 callbackBlock
    );
    event FulfillmentIgnored(uint256 indexed requestId, AcquisitionStatus status);
    event UnfulfilledVrfReconciled(uint256 count);
    /// @dev `processor` is `address(this)` when the failure-isolated callback self-call succeeds;
    ///      otherwise it is the address that called the public processor.
    event AcquisitionProcessed(
        uint256 indexed requestId, uint64 indexed sequence, AcquisitionStatus status, address indexed processor
    );
    event AcquisitionRefundWithdrawn(address indexed purchaser, uint256 amount);

    event AcquisitionExpired(
        uint256 indexed requestId, uint64 indexed sequence, address indexed purchaser, uint256 refund
    );

    /// @dev Ordered processing reached an empty pool, so no listing could be allocated and the
    ///      escrowed acquisition fee became a purchaser pull credit.
    event AcquisitionRefundedNoListing(uint256 indexed requestId, address indexed purchaser, uint256 refund);

    /// @dev Ordered processing found price drift beyond the request's positive / negative tolerances,
    ///      so the acquisition was refunded instead of paid out. Distinct from
    ///      `AcquisitionRefundedNoListing` so the two refund causes are distinguishable off-chain.
    event AcquisitionRefundedSlippage(
        uint256 indexed requestId, address indexed purchaser, uint256 refund, uint256 escrowedFee, uint256 liveFee
    );

    /// @param depositor The pool owner that supplied the listing, and `price` its notional value, so an indexer can
    ///        debit the pool's active value and attribute the deposit duration from this event
    ///        alone (no join back to `NFTListed`).
    event NFTAllocated(
        uint256 indexed requestId,
        uint256 indexed listingId,
        address indexed purchaser,
        address depositor,
        uint256 price,
        uint256 randomWord
    );

    /// @dev A selected NFT could not be atomically delivered. Its payment remains escrowed and anyone
    ///      may retry the same immutable purchaser destination before the refund path is exercised.
    event NFTDeliveryFailed(uint256 indexed listingId, address indexed recipient, address collection, uint256 tokenId);
    event NFTDeliveryCompleted(uint256 indexed listingId, uint256 indexed requestId, address indexed purchaser);
    event NFTDeliveryRefunded(
        uint256 indexed listingId, uint256 indexed requestId, address indexed purchaser, uint256 amount
    );
    event RefundedNFTRecovered(uint256 indexed listingId, address indexed owner);

    event OwnerProceedsAccrued(uint256 indexed requestId, uint256 amount, uint256 total);
    event OwnerProceedsWithdrawn(address indexed owner, uint256 amount);

    /// @dev A single-value owner-config change (`setUint`/`setBool`/`setAddr`). `key` is a
    ///      `FWAConfigKeys` constant (globally unique across the three dispatchers); bools encode
    ///      as 0/1, addresses as `uint256(uint160(a))`, the VRF key hash as `uint256(keyHash)`.
    event ConfigSet(uint256 indexed key, uint256 value);
    /// @dev The payer supplied `amount` wei to the immutable external VRF service.
    event VrfServiceFeePaid(address indexed payer, uint256 amount);
    event ProtocolFeesAccrued(uint256 indexed requestId, uint256 amount, uint256 total);
    event ProtocolFeesPaidOut(address indexed to, uint256 amount);

    event FWACloneInitialized(address indexed owner, address indexed factory, uint256 indexed vrfSubId);
    event PurchaseProceedsAccrued(
        uint256 indexed requestId, address indexed owner, uint256 ownerAmount, uint256 protocolAmount
    );
    event PurchaseOperatorSet(address indexed oldOperator, address indexed newOperator);
    event PoolRetired(address indexed owner);

    /*//////////////////////////////////////////////////////////////
                                ERRORS
    //////////////////////////////////////////////////////////////*/

    error TokenOfferUnavailable();
    error TokenOfferVersionMismatch();
    error TokenOfferExhausted();
    error InexactTokenTransfer();
    error ZeroPrice();
    error PriceTooHigh();
    error InvalidCollection();
    error ListingNotActive();
    error NotDepositor();
    error NoActiveListings();
    error WithdrawLocked();
    error InvalidTreeResult();
    error ActiveListingCapacityReached();
    error StagingQueueFull();
    error NFTTransferFailed();
    error InsufficientPayment();
    error AcquisitionFeeTooHigh();
    error InvalidAcquisitionCount();
    error InvalidInventoryBatch();
    error PoolValueTooLow();
    error InvalidConfig();
    error NoProceeds();
    error DeliveryNotPending();
    error DeliveryNotRefunded();
    error DeliveryWindowNotElapsed();
    error DeliveryWindowElapsed();
    error NotPurchaser();
    error OnlySelf();
    error NFTAlreadyControlled();
    error StaleNFTController();
    error AcquisitionsNotEnabled();
    error NoProtocolFees();
    error OnlyCoordinator();
    error SequenceInvariantBroken();
    error NoAcquisitionRefund();
    error AcquisitionStateLocked();
    error OnlyVrfService();
    error VrfRequestsPending();
    error DuplicateRequestId();
    error OnlyFactory();
    error OwnerOnlyInventory();
    error FactoryPurchasesDisabled();
    error FactoryWithdrawOnly();
    error VrfRequestsPaused();
    error ConsumerNotReady();
    error FactoryManagedConfig();
    error InventoryVersionMismatch(uint256 expected, uint256 actual);
    error TransactionExpired(uint256 deadline);
    error OwnershipLocked();
    error PoolAlreadyRetired();
    error InvalidPurchaseOperator();
    error PurchaseNotAllowed();
    error PurchaseOperatorCheckFailed();

    // `Unauthorized()` is inherited from Solady's Ownable.

    /*//////////////////////////////////////////////////////////////
                              CONSTRUCTOR
    //////////////////////////////////////////////////////////////*/

    /// @dev Constructor state belongs only to the implementation. Every mutable pool default is
    ///      written by `initialize` because factory pools are minimal proxies.
    constructor(address factory_, address service_) {
        if (factory_ == address(0) || factory_.code.length == 0 || service_ == address(0) || service_.code.length == 0)
        {
            revert InvalidConfig();
        }
        FACTORY = factory_;
        vrfService = IFWAVRFService(service_);
        purchaseNotifier = new PoolPurchaseNotifier(factory_);
        _initializeOwner(address(1));
    }

    modifier onlyFactory() {
        if (msg.sender != FACTORY) revert OnlyFactory();
        _;
    }

    function _guardInitializeOwner() internal pure override returns (bool) {
        return true;
    }

    /// @dev A pool permanently belongs to its factory-recorded creator. This also keeps inventory
    ///      authority and request-snapshotted revenue ownership aligned.
    function _setOwner(address) internal pure override {
        revert OwnershipLocked();
    }

    /// @notice Initialize a deterministic factory clone. Purchases begin locally disabled.
    function initialize(address poolOwner) external onlyFactory {
        if (owner() != address(0) || poolOwner == address(0)) revert InvalidConfig();

        IFWACloneFactory.PoolInitializationConfig memory config =
            IFWACloneFactory(FACTORY).getPoolInitializationConfig();
        address service = address(vrfService);
        if (config.coordinator != service) revert InvalidConfig();

        uint256 subId = config.subId;
        bytes32 keyHash = config.keyHash;
        uint32 gasLimit = config.gasLimit;
        uint16 confirmations = config.confirmations;
        uint32 timeoutBlocks = config.timeoutBlocks;
        uint16 activationLimit = config.activationLimit;
        uint16 acquisitionLimit = config.acquisitionLimit;
        uint16 slippageBps = config.slippageBps;

        if (
            subId == 0 || keyHash == bytes32(0) || gasLimit < MIN_CALLBACK_GAS_LIMIT
                || gasLimit > MAX_CALLBACK_GAS_LIMIT || confirmations < MIN_REQUEST_CONFIRMATIONS
                || confirmations > MAX_REQUEST_CONFIRMATIONS
                || timeoutBlocks < uint256(confirmations) + MIN_CALLBACK_SLACK_BLOCKS
                || timeoutBlocks > MAX_WINDOW_BLOCKS || activationLimit == 0
                || activationLimit > MAX_ACTIVATIONS_PER_ACQUISITION || acquisitionLimit == 0 || slippageBps > BPS
        ) revert InvalidConfig();

        _initializeOwner(poolOwner);

        s_vrfCoordinator = IVRFCoordinatorV2Plus(service);
        vrfSubId = subId;
        vrfKeyHash = keyHash;
        callbackGasLimit = gasLimit;
        requestConfirmations = confirmations;

        maxActivationsPerAcquisition = activationLimit;
        selectionTimeoutBlocks = timeoutBlocks;
        maxAcquisitionsPerTx = acquisitionLimit;
        nextSequenceToProcess = 1;

        acquisitionsEnabled = false;

        selectionSlippageBps = slippageBps;
        maxStagedListings = config.maxStagedListings;

        nextListingId = 1;
        nextUnusedSlot = 1;
        if (config.protocolFeeRecipient == address(0)) revert InvalidConfig();

        emit FWACloneInitialized(poolOwner, FACTORY, subId);
    }

    function localPurchasesEnabled() external view returns (bool) {
        return acquisitionsEnabled;
    }

    /*//////////////////////////////////////////////////////////////
                           DEPOSIT AN ERC721
    //////////////////////////////////////////////////////////////*/

    /// @notice Escrow an ERC721 at an owner-assigned notional price. No backing ETH is accepted.
    /// @dev The owner must approve this contract for the token first. Listings created while an
    ///      acquisition is unresolved retain the canonical staging behavior and cannot steer it.
    function listNFT(address collection, uint256 tokenId, uint256 price)
        external
        nonReentrant
        returns (uint256 listingId)
    {
        _requireInventoryInputAllowed();
        listingId = _listNFT(collection, tokenId, price);
        _recordInventoryChange();
    }

    /// @notice Atomically escrow up to `MAX_INVENTORY_BATCH` NFTs and publish one inventory version.
    /// @dev Each item preserves the single-listing FIFO activation and request-reservation rules.
    function listNFTs(ListingInput[] calldata items) external nonReentrant returns (uint256[] memory listingIds) {
        _requireInventoryInputAllowed();
        uint256 length = items.length;
        _validateInventoryBatch(length);
        listingIds = new uint256[](length);
        for (uint256 i; i < length; ++i) {
            ListingInput calldata item = items[i];
            listingIds[i] = _listNFT(item.collection, item.tokenId, item.price);
        }
        _recordInventoryChange();
    }

    function _requireInventoryInputAllowed() internal view {
        if (msg.sender != owner()) revert OwnerOnlyInventory();
        if (retired) revert PoolAlreadyRetired();
        if (IFWACloneFactory(FACTORY).globalWithdrawOnly()) revert FactoryWithdrawOnly();
    }

    function _validateInventoryBatch(uint256 length) internal pure {
        if (length == 0 || length > MAX_INVENTORY_BATCH) revert InvalidInventoryBatch();
    }

    function _listNFT(address collection, uint256 tokenId, uint256 price) internal returns (uint256 listingId) {
        if (price == 0) revert ZeroPrice();
        if (collection.code.length == 0) revert InvalidCollection();
        if (liveNFTListing[collection][tokenId] != 0) revert NFTAlreadyControlled();

        uint256 weight = INVERSE_WEIGHT_NUMERATOR / price;
        if (weight == 0) revert PriceTooHigh();

        /*
            Using transferFrom deliberately instead of safeTransferFrom:

            1. The destination is this known contract.
            2. We do not need an ERC721 receiver callback.
            3. Random safe transfers sent directly to this contract revert
               instead of becoming untracked listings.

            The owner must approve this contract first.
        */
        ERC721(collection).transferFrom(msg.sender, address(this), tokenId);

        if (ERC721(collection).ownerOf(tokenId) != address(this)) {
            revert NFTTransferFailed();
        }

        listingId = nextListingId++;
        liveNFTListing[collection][tokenId] = listingId;

        listings[listingId] = Listing({
            collection: collection,
            depositor: msg.sender,
            purchaser: address(0),
            tokenId: tokenId,
            weight: weight,
            price: price,
            slot: 0,
            status: ListingStatus.Active // provisional — set precisely in the branch below
        });
        // With no unresolved acquisition and no older staging backlog, activate immediately. Otherwise
        // append to staging. A request issued later may reserve it, but every already-issued request has
        // already committed its exact batch and can never observe this new input.
        if (unsettledAcquisitionCount == 0 && stagingHead == 0) {
            _activateListing(listingId);
        } else {
            if (maxStagedListings != 0 && stagedCount >= maxStagedListings) revert StagingQueueFull();
            listings[listingId].status = ListingStatus.Staged;
            _stagingPush(listingId);
            emit ListingStaged(listingId, msg.sender, collection, tokenId, price, block.number);

            // Preserve FIFO if an old unreserved tail survived the last acquisition window: a fresh
            // listing never leapfrogs it merely because the pool is currently idle.
            if (unsettledAcquisitionCount == 0) _drainStaging(maxActivationsPerAcquisition);
        }
    }

    /// @notice Compatibility timestamp for the latest inventory change; no timed purchase delay applies.
    /// @dev A matching inventory version and valid deadline are still required, along with other purchase gates.
    function purchasesResumeAt() public view returns (uint256) {
        return uint256(lastInventoryChangeAt);
    }

    function _recordInventoryChange() internal {
        uint256 version = inventoryVersion + 1;
        inventoryVersion = version;
        uint64 changedAt = uint64(block.timestamp);
        lastInventoryChangeAt = changedAt;
        emit InventoryChanged(version, changedAt);
    }

    /*//////////////////////////////////////////////////////////////
                          STAGING QUEUE
    //////////////////////////////////////////////////////////////*/

    /// @notice Permissionlessly activate up to `maxCount` unreserved FIFO listings while no acquisition
    ///         remains unresolved. During a window, only the ordered processor may activate the exact
    ///         request-time batches.
    function activateListings(uint256 maxCount) external nonReentrant {
        if (unsettledAcquisitionCount != 0) return;
        _drainStaging(maxCount);
    }

    /// @dev Move a listing — fresh, idle-drained, or from a request's reserved batch — into the active
    ///      selection pool. This function intentionally retains the canonical staging activation points.
    function _activateListing(uint256 listingId) internal {
        Listing storage listing = listings[listingId];

        uint256 price = listing.price;
        uint256 weight = listing.weight;

        uint256 slot = _allocateSlot();
        listing.slot = slot;
        slotToListing[slot] = listingId;

        _addTreeWeight(slot, weight);
        totalWeight += weight;
        weightedBackingTotal += weight * price;
        activeListingCount++;

        listing.status = ListingStatus.Active;

        emit NFTListed(listingId, slot, listing.depositor, listing.collection, listing.tokenId, weight, price);
    }

    /// @dev Activate an unreserved FIFO prefix. Only callable through paths that have established there
    ///      is no unresolved acquisition, so block maturity is unnecessary: sequence commitment is the
    ///      anti-steering boundary.
    function _drainStaging(uint256 maxCount) internal {
        uint256 drained = 0;
        while (drained < maxCount) {
            uint256 head = stagingHead;
            if (head == 0) return;

            _stagingUnlink(head);
            _activateListing(head);
            unchecked {
                drained++;
            }
        }
    }

    /// @dev Detach the exact next FIFO batch before requesting randomness. Listings remain `Staged`
    ///      but no public queue operation can reach them; only their owning sequence can activate them.
    function _reserveStagedBatch(uint64 sequence) internal returns (uint256 count) {
        uint256 maxCount = maxActivationsPerAcquisition;
        while (count < maxCount) {
            uint256 head = stagingHead;
            if (head == 0) break;

            _stagingUnlink(head);
            reservedForSequence[head] = sequence;
            reservedListingsBySequence[sequence].push(head);
            unchecked {
                ++reservedStagedCount;
                ++count;
            }
        }
    }

    /// @dev Activate exactly the batch committed by `sequence`. Called on success and every refund /
    ///      expiry path so timeout changes only the missing random removal, never the staged prefix.
    function _activateReservedBatch(uint64 sequence) internal {
        uint256[] storage batch = reservedListingsBySequence[sequence];
        uint256 length = batch.length;
        for (uint256 i = 0; i < length; i++) {
            uint256 listingId = batch[i];
            if (reservedForSequence[listingId] != sequence || listings[listingId].status != ListingStatus.Staged) {
                revert SequenceInvariantBroken();
            }
            delete reservedForSequence[listingId];
            unchecked {
                --reservedStagedCount;
            }
            _activateListing(listingId);
        }
        delete reservedListingsBySequence[sequence];
    }

    function reservedListingCount(uint64 sequence) external view returns (uint256) {
        return reservedListingsBySequence[sequence].length;
    }

    function reservedListingAt(uint64 sequence, uint256 index) external view returns (uint256) {
        return reservedListingsBySequence[sequence][index];
    }

    /// @dev Push a listing onto the tail of the staging FIFO (doubly-linked).
    function _stagingPush(uint256 listingId) internal {
        uint256 tail = stagingTail;
        stagingPrev[listingId] = tail;
        stagingNext[listingId] = 0;
        if (tail == 0) {
            stagingHead = listingId;
        } else {
            stagingNext[tail] = listingId;
        }
        stagingTail = listingId;
        unchecked {
            ++stagedCount;
        }
    }

    /// @dev Unlink a listing from the staging FIFO in O(1), so reservation / idle activation leaves
    ///      no tombstone for a later prefix walk to scan.
    function _stagingUnlink(uint256 listingId) internal {
        uint256 prev = stagingPrev[listingId];
        uint256 next = stagingNext[listingId];
        if (prev == 0) {
            stagingHead = next;
        } else {
            stagingNext[prev] = next;
        }
        if (next == 0) {
            stagingTail = prev;
        } else {
            stagingPrev[next] = prev;
        }
        delete stagingPrev[listingId];
        delete stagingNext[listingId];
        unchecked {
            --stagedCount;
        }
    }

    /*//////////////////////////////////////////////////////////////
                          WITHDRAW ACTIVE LISTING
    //////////////////////////////////////////////////////////////*/

    /// @dev Withdrawing or repricing could change an
    ///      already-issued draw. Keep them locked until every issued sequence is terminal, including
    ///      after its word has been cached but before the ordered processor reaches it.
    function _requireExitUnlocked() internal view {
        if (unsettledAcquisitionCount != 0) revert WithdrawLocked();
    }

    /// @notice Withdraw an active listing. There is no backing ETH to return.
    /// @dev Load `listingId` and require it Active and supplied by `msg.sender`.
    function _activeOwned(uint256 listingId) internal view returns (Listing storage listing) {
        listing = listings[listingId];
        if (listing.status != ListingStatus.Active) revert ListingNotActive();
        if (listing.depositor != msg.sender) revert NotDepositor();
    }

    /// @notice Withdraw active or unreserved staged inventory to its depositor.
    function withdrawListing(uint256 listingId) external nonReentrant {
        _withdrawListing(listingId, msg.sender);
        _recordInventoryChange();
    }

    /// @notice Withdraw inventory to a receiver chosen by its depositor.
    function withdrawListingTo(uint256 listingId, address recipient) external nonReentrant {
        _validateInventoryRecipient(recipient);
        _withdrawListing(listingId, recipient);
        _recordInventoryChange();
    }

    /// @notice Atomically withdraw up to `MAX_INVENTORY_BATCH` listings and publish one inventory version.
    function withdrawListingsTo(uint256[] calldata listingIds, address recipient) external nonReentrant {
        _validateInventoryRecipient(recipient);
        uint256 length = listingIds.length;
        _validateInventoryBatch(length);
        for (uint256 i; i < length; ++i) {
            _withdrawListing(listingIds[i], recipient);
        }
        _recordInventoryChange();
    }

    function _validateInventoryRecipient(address recipient) internal view {
        if (recipient == address(0) || recipient == address(this)) revert InvalidConfig();
    }

    function _withdrawListing(uint256 listingId, address recipient) internal {
        Listing storage listing = listings[listingId];
        ListingStatus status = listing.status;
        if (status == ListingStatus.Active) {
            _requireExitUnlocked();
        } else if (status == ListingStatus.Staged) {
            // Only unreserved inventory is outside every already-issued draw commitment.
            if (reservedForSequence[listingId] != 0) revert WithdrawLocked();
        } else {
            revert ListingNotActive();
        }
        if (listing.depositor != msg.sender) revert NotDepositor();

        uint256 price = listing.price;
        address collection = listing.collection;
        uint256 tokenId = listing.tokenId;
        if (status == ListingStatus.Active) _settleAndRemove(listingId);
        else _stagingUnlink(listingId);
        listing.status = ListingStatus.Withdrawn;
        if (liveNFTListing[collection][tokenId] != listingId) revert StaleNFTController();
        delete liveNFTListing[collection][tokenId];

        ERC721(collection).safeTransferFrom(address(this), recipient, tokenId);

        emit ListingWithdrawn(listingId, msg.sender, price);
    }

    /*//////////////////////////////////////////////////////////////
                           UPDATE LISTING PRICE
    //////////////////////////////////////////////////////////////*/

    /// @notice Change an active listing's notional price and inverse selection weight.
    /// @dev Repricing remains locked while any acquisition is unresolved. It also increments the
    ///      exact inventory version. Fresh quotes may be purchased immediately.
    /// @param listingId The active listing to re-price.
    /// @param newPrice The new owner-assigned notional price.
    function updatePrice(uint256 listingId, uint256 newPrice) external nonReentrant {
        if (retired) revert PoolAlreadyRetired();
        Listing storage listing = _activeOwned(listingId);

        if (IFWACloneFactory(FACTORY).globalWithdrawOnly()) revert FactoryWithdrawOnly();
        if (newPrice == 0) revert ZeroPrice();
        uint256 oldPrice = listing.price;
        if (newPrice == oldPrice) revert InvalidConfig();
        _requireExitUnlocked();

        uint256 newWeight = INVERSE_WEIGHT_NUMERATOR / newPrice;
        if (newWeight == 0) revert PriceTooHigh();

        uint256 oldWeight = listing.weight;
        uint256 slot = listing.slot;
        if (newWeight > oldWeight) {
            _addTreeWeight(slot, newWeight - oldWeight);
        } else if (newWeight < oldWeight) {
            _removeTreeWeight(slot, oldWeight - newWeight);
        }
        totalWeight = totalWeight - oldWeight + newWeight;
        weightedBackingTotal = weightedBackingTotal - oldWeight * oldPrice + newWeight * newPrice;

        listing.price = newPrice;
        listing.weight = newWeight;
        _recordInventoryChange();

        emit PriceUpdated(listingId, msg.sender, oldPrice, newPrice, newWeight);
    }

    /*//////////////////////////////////////////////////////////////
                             REQUEST A ACQUISITION
    //////////////////////////////////////////////////////////////*/

    /// @notice The external VRF service's purchaser charge for one request.
    /// @dev Relies on `tx.gasprice`; quote via an `eth_call` using the intended transaction gas price.
    function vrfServiceFee() public view returns (uint256) {
        return vrfService.requestFee();
    }

    /// @notice The expected-value-based pool price right now. With
    ///         inverse selection weight the EV is the harmonic mean of the pool's values, so a pool of
    ///         richer listings prices cheaper — you're far more likely to acquisition a low-value listing.
    /// @return acquisitionFee The pool price, `EV · (1 + factory edge)`.
    function acquisitionFee() public view returns (uint256) {
        if (totalWeight == 0) return 0;
        uint256 ev = weightedBackingTotal / totalWeight;
        return ev * (BPS + IFWACloneFactory(FACTORY).edgeBps()) / BPS;
    }

    /// @notice Quote a purchase of `count` acquisitions against its hypothetical idle FIFO activation.
    /// @return fee Pool price per acquisition after that activation.
    /// @return vrf VRF service fee per acquisition (quote using the intended transaction gas price).
    /// @return total Full minimum payment, `count * (fee + vrf)`.
    function quoteAcquisitionPrice(uint256 count) public view returns (uint256 fee, uint256 vrf, uint256 total) {
        if (count == 0 || count > maxAcquisitionsPerTx) revert InvalidAcquisitionCount();
        uint256 weight = totalWeight;
        uint256 weightedValue = weightedBackingTotal;
        if (unsettledAcquisitionCount == 0) {
            uint256 remaining = count * maxActivationsPerAcquisition;
            uint256 listingId = stagingHead;
            while (listingId != 0 && remaining != 0) {
                Listing storage listing = listings[listingId];
                weight += listing.weight;
                weightedValue += listing.weight * listing.price;
                listingId = stagingNext[listingId];
                --remaining;
            }
        }
        if (weight != 0) fee = (weightedValue / weight) * (BPS + IFWACloneFactory(FACTORY).edgeBps()) / BPS;
        vrf = vrfServiceFee();
        total = count * (fee + vrf);
    }

    /// @notice Pay for and request a VRF acquisition against an exact published inventory version. Send at least
    ///         `quoteAcquisitionPrice(1).total`; any excess is refunded to the caller. Requests are fully concurrent,
    ///         while their cached words settle strictly in the local sequence assigned on-chain.
    /// @dev The acquisition fee remains escrowed until ordered processing distributes it or converts it
    ///      to a pull refund. The separate VRF fee is forwarded before requesting randomness, allowing
    ///      the service to fund callback coverage without touching purchase proceeds.
    /// @param purchaser Recipient of the acquisition, including its NFT and later refund rights.
    /// @param maxAcquisitionFee Slippage guard: revert if the pool fee exceeds this. `0` disables
    ///        the check. Protects the purchaser from a listing front-running the request and
    ///        raising the price under them.
    /// @param minWeightedValue Slippage guard: revert if `weightedBackingTotal` is below this.
    ///        `0` disables the check. Protects the purchaser from a withdrawal front-running the
    ///        request and pulling listing value out of the pool they paid to acquisition against.
    /// @param expectedInventoryVersion Exact owner-mutation version observed by the buyer.
    /// @param deadline Last timestamp at which this transaction may execute.
    function acquire(
        address purchaser,
        uint256 maxAcquisitionFee,
        uint256 minWeightedValue,
        uint256 maxNegativeSlippageBps,
        uint256 expectedInventoryVersion,
        uint256 deadline
    ) external payable nonReentrant returns (uint256 requestId) {
        requestId = _acquire(
            purchaser, maxAcquisitionFee, minWeightedValue, maxNegativeSlippageBps, expectedInventoryVersion, deadline
        );
    }

    function _acquire(
        address purchaser,
        uint256 maxAcquisitionFee,
        uint256 minWeightedValue,
        uint256 maxNegativeSlippageBps,
        uint256 expectedInventoryVersion,
        uint256 deadline
    ) internal returns (uint256 requestId) {
        if (purchaser == address(0)) revert InvalidConfig();
        if (retired) revert PoolAlreadyRetired();
        if (maxNegativeSlippageBps > BPS) revert InvalidConfig();
        _validateInventoryCommitment(expectedInventoryVersion, deadline);
        _validatePurchaseOperator(purchaser);
        if (unsettledAcquisitionCount == 0) _drainStaging(maxActivationsPerAcquisition);

        uint256 fee = _validateAcquisition(maxAcquisitionFee, minWeightedValue);

        uint256 vrf = vrfServiceFee();
        uint256 cost = fee + vrf;
        if (msg.value < cost) revert InsufficientPayment();

        // Effects in the service (including any subscription top-up) roll back if the later VRF request fails.
        vrfService.prepareRequests{value: vrf}(1);
        emit VrfServiceFeePaid(msg.sender, vrf);

        requestId = _openAcquisition(purchaser, fee, maxNegativeSlippageBps, false);

        // Refund any overpayment above the pool fee + VRF service fee.
        _refund(msg.value - cost);
    }

    /// @notice Acquisition `count` times in one call: fires `count` independent VRF requests (one callback
    ///         each), every one priced, escrowed, settled and slippage-checked exactly like a single
    ///         `acquire`. The caller pays `count * (acquisitionFee + vrfFee)` and receives any overpayment. The pool
    ///         is static during this request, so the slippage guards are checked once for all `count`;
    ///         each acquisition re-checks drift at its own ordered processing turn.
    /// @param purchaser Recipient of every acquisition, including its NFT and later refund rights.
    function acquireBatch(
        address purchaser,
        uint256 count,
        uint256 maxAcquisitionFee,
        uint256 minWeightedValue,
        uint256 maxNegativeSlippageBps,
        uint256 expectedInventoryVersion,
        uint256 deadline
    ) external payable nonReentrant returns (uint256[] memory requestIds) {
        requestIds = _acquireBatch(
            purchaser,
            count,
            maxAcquisitionFee,
            minWeightedValue,
            maxNegativeSlippageBps,
            expectedInventoryVersion,
            deadline
        );
    }

    function _acquireBatch(
        address purchaser,
        uint256 count,
        uint256 maxAcquisitionFee,
        uint256 minWeightedValue,
        uint256 maxNegativeSlippageBps,
        uint256 expectedInventoryVersion,
        uint256 deadline
    ) internal returns (uint256[] memory requestIds) {
        if (purchaser == address(0)) revert InvalidConfig();
        if (retired) revert PoolAlreadyRetired();
        if (count == 0 || count > maxAcquisitionsPerTx) revert InvalidAcquisitionCount();
        if (maxNegativeSlippageBps > BPS) revert InvalidConfig();
        _validateInventoryCommitment(expectedInventoryVersion, deadline);
        _validatePurchaseOperator(purchaser);

        if (unsettledAcquisitionCount == 0) _drainStaging(count * maxActivationsPerAcquisition);

        uint256 fee = _validateAcquisition(maxAcquisitionFee, minWeightedValue);

        uint256 vrf = vrfServiceFee();
        uint256 cost = count * (fee + vrf);
        if (msg.value < cost) revert InsufficientPayment();

        uint256 vrfTotal = count * vrf;
        // Reserve all batch callbacks before request #1. The whole transaction is atomic if any request fails.
        vrfService.prepareRequests{value: vrfTotal}(count);
        emit VrfServiceFeePaid(msg.sender, vrfTotal);

        requestIds = new uint256[](count);
        for (uint256 i = 0; i < count; i++) {
            requestIds[i] = _openAcquisition(purchaser, fee, maxNegativeSlippageBps, false);
        }

        _refund(msg.value - cost);
    }

    /// @notice Configure a promotional token price and a global offer cap; zero cap means unlimited.
    /// @dev A new version starts a new offer. Accepted requests consume its cap even if later refunded.
    ///      Existing escrows retain their price and cannot be changed by replacing or closing the offer.
    function configureTokenOffer(uint256 price, uint256 maxPulls, bool enabled) external onlyOwner {
        if (retired) revert PoolAlreadyRetired();
        address token = IPoolsV2TokenFactory(FACTORY).poolToken(address(this));
        if (token == address(0) || token.code.length == 0 || (enabled && price == 0)) revert InvalidConfig();
        if (paymentToken != address(0) && paymentToken != token) revert InvalidConfig();
        paymentToken = token;
        tokenOfferPrice = price;
        tokenOfferMaxPulls = maxPulls;
        tokenOfferPullsUsed = 0;
        tokenOfferEnabled = enabled;
        emit TokenOfferConfigured(++tokenOfferVersion, price, maxPulls, enabled);
    }

    function _validateTokenOffer(uint256 count, uint256 expectedOfferVersion) internal view {
        if (!tokenOfferEnabled) revert TokenOfferUnavailable();
        if (expectedOfferVersion != tokenOfferVersion) revert TokenOfferVersionMismatch();
        if (count == 0 || count > maxAcquisitionsPerTx) revert InvalidAcquisitionCount();
        uint256 cap = tokenOfferMaxPulls;
        if (cap != 0 && tokenOfferPullsUsed + count > cap) revert TokenOfferExhausted();
    }

    /// @notice Request promotional pulls paid entirely in the launched token, plus native VRF fees.
    /// @dev The full token price burns only after delivery. ETH EV is only a selection-drift reference.
    ///      `expectedOfferVersion` commits the exact token price and global cap before any token transfer.
    function acquireWithToken(
        address purchaser,
        uint256 count,
        uint256 minWeightedValue,
        uint256 maxNegativeSlippageBps,
        uint256 expectedInventoryVersion,
        uint256 expectedOfferVersion,
        uint256 deadline
    ) external payable nonReentrant returns (uint256[] memory requestIds) {
        if (purchaser == address(0) || maxNegativeSlippageBps > BPS) revert InvalidConfig();
        if (retired) revert PoolAlreadyRetired();
        _validateTokenOffer(count, expectedOfferVersion);
        _validateInventoryCommitment(expectedInventoryVersion, deadline);
        _validatePurchaseOperator(purchaser);
        if (unsettledAcquisitionCount == 0) _drainStaging(count * maxActivationsPerAcquisition);
        _validateAcquisition(0, minWeightedValue);

        uint256 price = tokenOfferPrice;
        uint256 amount = count * price;
        uint256 vrfTotal = count * vrfServiceFee();
        if (msg.value < vrfTotal) revert InsufficientPayment();
        tokenOfferPullsUsed += count;
        address token = paymentToken;
        uint256 beforeBalance = SafeTransferLib.balanceOf(token, address(this));
        SafeTransferLib.safeTransferFrom(token, msg.sender, address(this), amount);
        if (SafeTransferLib.balanceOf(token, address(this)) != beforeBalance + amount) revert InexactTokenTransfer();
        vrfService.prepareRequests{value: vrfTotal}(count);
        emit VrfServiceFeePaid(msg.sender, vrfTotal);
        requestIds = new uint256[](count);
        for (uint256 i; i < count; ++i) {
            requestIds[i] = _openAcquisition(purchaser, price, maxNegativeSlippageBps, true);
        }
        _refund(msg.value - vrfTotal);
    }

    /// @notice Withdraw a failed promotion's full token payment; native VRF fees are not refundable.
    function withdrawTokenRefund() external nonReentrant returns (uint256 amount) {
        amount = tokenRefundCredit[msg.sender];
        if (amount == 0) revert NoAcquisitionRefund();
        tokenRefundCredit[msg.sender] = 0;
        tokenRefundCreditTotal -= amount;
        SafeTransferLib.safeTransfer(paymentToken, msg.sender, amount);
        emit TokenRefundWithdrawn(msg.sender, amount);
    }

    /// @notice Permissionlessly burn only payments whose NFT delivery has succeeded.
    function burnTokenPayments() external nonReentrant returns (uint256 amount) {
        amount = tokenBurnablePayments;
        if (amount == 0) revert NoProceeds();
        tokenBurnablePayments = 0;
        IPoolPaymentToken(paymentToken).burn(amount);
        emit TokenPaymentsBurned(paymentToken, amount);
    }

    function _validateInventoryCommitment(uint256 expectedInventoryVersion, uint256 deadline) internal view {
        if (block.timestamp > deadline) revert TransactionExpired(deadline);
        uint256 currentVersion = inventoryVersion;
        if (expectedInventoryVersion != currentVersion) {
            revert InventoryVersionMismatch(expectedInventoryVersion, currentVersion);
        }
    }

    /// @dev A bounded, fixed-output staticcall prevents a configured policy from consuming all
    ///      purchase gas or returning an oversized payload. Only an exact ABI bool word of `1` allows
    ///      the purchase; a canonical `0` denies it and every failed or malformed response fails closed.
    function _validatePurchaseOperator(address purchaser) internal view {
        address operator = purchaseOperator;
        if (operator == address(0)) return;

        bytes memory callData = abi.encodeCall(IPurchaseOperator.canPurchase, (purchaser));
        bool checked;
        bool allowed;
        uint256 gasStipend = PURCHASE_OPERATOR_GAS;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            checked := staticcall(gasStipend, operator, add(callData, 0x20), mload(callData), ptr, 0x20)
            if iszero(eq(returndatasize(), 0x20)) { checked := 0 }
            if checked {
                let result := mload(ptr)
                // Only the two canonical ABI bool words are well formed.
                if gt(result, 1) { checked := 0 }
                allowed := eq(result, 1)
            }
        }

        if (!checked) revert PurchaseOperatorCheckFailed();
        if (!allowed) revert PurchaseNotAllowed();
    }

    /// @dev Shared acquisition precondition + slippage checks. Returns the current `acquisitionFee()`. Reverts if
    ///      acquisitions are disabled, the pool is empty, the pool value drifted below `minWeightedValue`, or
    ///      the fee exceeds `maxAcquisitionFee`.
    function _validateAcquisition(uint256 maxAcquisitionFee, uint256 minWeightedValue)
        internal
        view
        returns (uint256 fee)
    {
        if (!acquisitionsEnabled) revert AcquisitionsNotEnabled(); // still in the loading phase

        IFWACloneFactory factory = IFWACloneFactory(FACTORY);
        if (factory.globalWithdrawOnly()) revert FactoryWithdrawOnly();
        if (!factory.globalPurchasesEnabled()) revert FactoryPurchasesDisabled();
        if (!factory.consumerReady(address(this))) revert ConsumerNotReady();
        if (factory.vrfRequestsPaused()) revert VrfRequestsPaused();

        if (totalWeight == 0) revert NoActiveListings();

        // Slippage guards: assert the pool the purchaser saw hasn't shifted under them before
        // this request is mined.
        if (minWeightedValue != 0 && weightedBackingTotal < minWeightedValue) revert PoolValueTooLow();

        fee = acquisitionFee();
        if (maxAcquisitionFee != 0 && fee > maxAcquisitionFee) revert AcquisitionFeeTooHigh();
    }

    /// @dev Open one VRF-backed acquisition and commit its local sequence/batch.
    function _openAcquisition(address purchaser, uint256 fee, uint256 maxNegativeSlippageBps, bool tokenPayment)
        internal
        returns (uint256 requestId)
    {
        uint64 sequence = ++lastIssuedSequence;
        uint256 reservedCount = _reserveStagedBatch(sequence);
        uint64 deadline = uint64(block.number + selectionTimeoutBlocks);

        // The sequence and exact staged batch are committed before the external VRF request. If the
        // coordinator reverts, the entire transaction rolls both commitments back.
        requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: vrfKeyHash,
                subId: vrfSubId,
                requestConfirmations: requestConfirmations,
                callbackGasLimit: callbackGasLimit,
                numWords: NUM_WORDS,
                extraArgs: VRFV2PlusClient._argsToBytes(VRFV2PlusClient.ExtraArgsV1({nativePayment: true}))
            })
        );
        if (requestId == 0 || acquisitions[requestId].status != AcquisitionStatus.None) {
            revert DuplicateRequestId();
        }

        acquisitions[requestId] = Acquisition({
            purchaser: purchaser,
            requestBlock: block.number,
            priceEscrowed: fee,
            listingId: 0,
            status: AcquisitionStatus.Pending,
            tokenPayment: tokenPayment
        });

        acquisitionMeta[requestId] = AcquisitionMeta({
            sequence: sequence,
            wordDeadlineBlock: deadline,
            rewardEpoch: 0,
            maxPositiveSlippageBps: uint16(selectionSlippageBps),
            maxNegativeSlippageBps: uint16(maxNegativeSlippageBps),
            randomWord: 0
        });
        requestIdAtSequence[sequence] = requestId;

        pendingAcquisitionCount += 1;
        unfulfilledVrfCount += 1;
        unsettledAcquisitionCount += 1;
        if (tokenPayment) {
            tokenAcquisitionEscrowTotal += fee;
            tokenReferenceEthFee[requestId] = acquisitionFee();
            emit TokenAcquisitionRequested(requestId, tokenOfferVersion, paymentToken);
        } else {
            acquisitionEscrowTotal += fee;
        }

        emit AcquisitionRequested(requestId, purchaser, fee, totalWeight);
        emit AcquisitionSequenced(requestId, sequence, deadline, reservedCount);

        if (!tokenPayment) {
            uint256 basePrice = weightedBackingTotal / totalWeight;
            if (basePrice > fee) basePrice = fee;
            requestBasePrice[requestId] = basePrice;
        }
    }

    /// @dev Refund overpayment above the total acquisition cost, if any.
    function _refund(uint256 amount) internal {
        if (amount != 0) SafeTransferLib.forceSafeTransferETH(msg.sender, amount);
    }

    /// @notice Logical router and singleton subscription tuple used by registration checks.
    function vrfCoordinatorAndSubId() external view returns (address coordinator, uint256 subId) {
        coordinator = address(s_vrfCoordinator);
        subId = vrfSubId;
    }

    /// @notice Current gas lane and callback budget, used by the immutable service to bind request
    ///         coverage to the exact tuple FWA will send to Chainlink.
    function vrfRequestConfig() external view returns (bytes32 keyHash, uint32 gasLimit) {
        keyHash = vrfKeyHash;
        gasLimit = callbackGasLimit;
    }

    /// @notice Service-only gas-lane synchronization after an official coordinator migration. The
    ///         singleton must be globally paused and this pool must have no issued work; the owner's
    ///         local purchase preference need not be changed merely to follow Chainlink infrastructure.
    function configureVrfRequest(bytes32 keyHash, uint32 gasLimit) external {
        if (msg.sender != address(vrfService)) revert OnlyVrfService();
        IFWACloneFactory factory = IFWACloneFactory(FACTORY);
        if (
            factory.globalPurchasesEnabled() || !factory.vrfRequestsPaused() || unsettledAcquisitionCount != 0
                || unfulfilledVrfCount != 0
        ) {
            revert AcquisitionStateLocked();
        }
        if (keyHash == bytes32(0) || gasLimit < MIN_CALLBACK_GAS_LIMIT || gasLimit > MAX_CALLBACK_GAS_LIMIT) {
            revert InvalidConfig();
        }
        vrfKeyHash = keyHash;
        callbackGasLimit = gasLimit;
        emit ConfigSet(FWAConfigKeys.VRF_KEY_HASH, uint256(keyHash));
        emit ConfigSet(FWAConfigKeys.CALLBACK_GAS_LIMIT, gasLimit);
    }

    /// @notice Clear callback liabilities that the coordinator has already completed (and potentially
    ///         billed) without a successful consumer callback. Safe only for FWA's dedicated subscription.
    /// @dev Permissionless and fail-closed: the coordinator must report that the subscription has no
    ///      remaining request commitment. Acquisition expiry/processing remains a separate ordered step.
    function reconcileUnfulfilledVrfCount() external returns (uint256 reconciled) {
        reconciled = unfulfilledVrfCount;
        if (reconciled == 0) return 0;
        if (s_vrfCoordinator.pendingRequestExists(vrfSubId)) revert VrfRequestsPending();
        unfulfilledVrfCount = 0;
        emit UnfulfilledVrfReconciled(reconciled);
    }

    /*//////////////////////////////////////////////////////////////
                           CHAINLINK CALLBACK
    //////////////////////////////////////////////////////////////*/

    /// @notice VRF v2.5 fulfillment entrypoint. The coordinator is the ONLY authorized caller — this is
    ///         the hand-rolled equivalent of the Chainlink base's `rawFulfillRandomWords` (we don't
    ///         inherit the base; see the contract header). It caches or rejects the delivered word first,
    ///         then may make one failure-isolated attempt to process the canonical head.
    function rawFulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) external {
        if (msg.sender != address(s_vrfCoordinator)) revert OnlyCoordinator();
        fulfillRandomWords(requestId, randomWords);
    }

    /// @dev Coordinator callback: cache an on-time word or permanently classify it late. Unknown,
    ///      duplicate, terminal and malformed fulfillments return without reverting. Fast-path settlement
    ///      is best effort only; its child failure cannot roll back the cached word.
    function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal {
        Acquisition storage acquisition = acquisitions[requestId];

        // Chainlink bills when the authenticated callback is attempted, even if this acquisition already
        // expired locally or the word array is malformed. Release its external coverage exactly once only
        // for a request this FWA actually issued. Unknown and duplicate callbacks remain harmless.
        if (acquisition.status != AcquisitionStatus.None && !callbackObserved[requestId]) {
            callbackObserved[requestId] = true;
            uint256 count = unfulfilledVrfCount;
            if (count != 0) unfulfilledVrfCount = count - 1;
        }

        if (acquisition.status != AcquisitionStatus.Pending) {
            emit FulfillmentIgnored(requestId, acquisition.status);
            return;
        }

        AcquisitionMeta storage meta = acquisitionMeta[requestId];
        if (block.number > meta.wordDeadlineBlock) {
            acquisition.status = AcquisitionStatus.TimedOut;
            pendingAcquisitionCount -= 1;
            emit RandomnessTimedOut(requestId, meta.sequence, meta.wordDeadlineBlock, block.number);
            return;
        }

        if (randomWords.length == 0) {
            emit FulfillmentIgnored(requestId, acquisition.status);
            return;
        }

        meta.randomWord = randomWords[0];
        acquisition.status = AcquisitionStatus.Ready;
        pendingAcquisitionCount -= 1;
        emit RandomnessCached(requestId, meta.sequence, randomWords[0]);

        _tryProcessCallbackHead(meta.sequence);
    }

    /// @dev Best-effort fast path. The word and callback-liability effects are committed in the parent
    ///      frame before this function runs. The child call reuses the exact permissionless processor,
    ///      including its reentrancy guard; any OOG or invariant failure rolls
    ///      back only the child frame and leaves this acquisition `Ready` for a later processor.
    ///      Return data is deliberately not copied, preventing a reverting callee from consuming the
    ///      parent's return reserve with an oversized revert payload.
    function _tryProcessCallbackHead(uint64 sequence) internal {
        if (
            callbackGasLimit < MIN_FAST_PATH_CALLBACK_GAS_LIMIT || sequence != nextSequenceToProcess
                || reservedListingsBySequence[sequence].length != 0
        ) return;

        if (gasleft() < CALLBACK_FAST_PATH_GAS + CALLBACK_RETURN_GAS_RESERVE) {
            return;
        }

        bytes memory callData = abi.encodeCall(this.processAcquisitions, (1));
        uint256 gasStipend = CALLBACK_FAST_PATH_GAS;
        assembly ("memory-safe") {
            pop(call(gasStipend, address(), 0, add(callData, 0x20), mload(callData), 0, 0))
        }
    }

    /// @notice Process the canonical ready/expired acquisition prefix. The caller chooses only a gas
    ///         batching bound; request IDs and ordering are fixed by `nextSequenceToProcess`.
    function processAcquisitions(uint256 maxCount) external nonReentrant returns (uint256 processed) {
        while (processed < maxCount && nextSequenceToProcess <= lastIssuedSequence) {
            uint64 sequence = nextSequenceToProcess;
            uint256 requestId = requestIdAtSequence[sequence];
            Acquisition storage acquisition = acquisitions[requestId];
            AcquisitionMeta storage meta = acquisitionMeta[requestId];
            if (requestId == 0 || meta.sequence != sequence) revert SequenceInvariantBroken();

            uint256 basePrice = requestBasePrice[requestId];

            AcquisitionStatus status = acquisition.status;
            if (status == AcquisitionStatus.Pending) {
                if (block.number <= meta.wordDeadlineBlock) break;
                pendingAcquisitionCount -= 1;
                _activateReservedBatch(sequence);
                uint256 refund = _creditAcquisitionRefund(acquisition, AcquisitionStatus.Expired);
                emit AcquisitionExpired(requestId, sequence, acquisition.purchaser, refund);
            } else if (status == AcquisitionStatus.TimedOut) {
                _activateReservedBatch(sequence);
                uint256 refund = _creditAcquisitionRefund(acquisition, AcquisitionStatus.Expired);
                emit AcquisitionExpired(requestId, sequence, acquisition.purchaser, refund);
            } else if (status == AcquisitionStatus.Ready) {
                _activateReservedBatch(sequence);
                _settleReadyAcquisition(requestId, acquisition, meta);
            } else {
                revert SequenceInvariantBroken();
            }

            _finishAcquisition(requestId, acquisition, meta, msg.sender);
            unchecked {
                ++nextSequenceToProcess;
                ++processed;
            }
            // Notify only once final accounting and the canonical queue agree with NFT ownership.
            if (acquisition.status == AcquisitionStatus.Fulfilled) {
                _notifyPurchase(acquisition.listingId, requestId, basePrice);
            }
        }
    }

    function _creditAcquisitionRefund(Acquisition storage acquisition, AcquisitionStatus status)
        internal
        returns (uint256 refund)
    {
        refund = acquisition.priceEscrowed;
        acquisition.status = status;
        if (acquisition.tokenPayment) {
            tokenRefundCredit[acquisition.purchaser] += refund;
            tokenRefundCreditTotal += refund;
        } else {
            acquisitionRefundCredit[acquisition.purchaser] += refund;
            acquisitionRefundCreditTotal += refund;
        }
    }

    function _finishAcquisition(
        uint256 requestId,
        Acquisition storage acquisition,
        AcquisitionMeta storage meta,
        address processor
    ) internal {
        // A failed NFT delivery retains its request-time base price until verified delivery or refund,
        // so later governance changes cannot rewrite the already-paid split.
        if (acquisition.status != AcquisitionStatus.DeliveryPending) {
            delete requestBasePrice[requestId];
        }
        if (acquisition.tokenPayment) {
            tokenAcquisitionEscrowTotal -= acquisition.priceEscrowed;
            delete tokenReferenceEthFee[requestId];
        } else {
            acquisitionEscrowTotal -= acquisition.priceEscrowed;
        }
        unsettledAcquisitionCount -= 1;
        emit AcquisitionProcessed(requestId, meta.sequence, acquisition.status, processor);
    }

    /// @dev Settle a cached word against the pool after its immutable activation batch is applied.
    function _settleReadyAcquisition(uint256 requestId, Acquisition storage acquisition, AcquisitionMeta storage meta)
        internal
    {
        /*
            Empty pool: earlier canonical sequences removed every listing, so nothing can be selected.
            Convert the purchaser's escrowed acquisition fee into a pull credit without any external call.
        */
        if (totalWeight == 0) {
            uint256 refund = _creditAcquisitionRefund(acquisition, AcquisitionStatus.Refunded);
            emit AcquisitionRefundedNoListing(requestId, acquisition.purchaser, refund);
            return;
        }

        /*
            Ordered-settlement slippage guard: re-price against the canonical live pool after this
            sequence's immutable reserved batch is activated. Earlier sequences may have removed listings
            and shifted the fee. Drift outside the request's snapshotted tolerances becomes a pull refund;
            the would-be selected listing remains active.
        */
        {
            uint256 liveFee = acquisitionFee();
            // The promotion's token units never enter ETH-value slippage arithmetic.
            uint256 escrowed = acquisition.tokenPayment ? tokenReferenceEthFee[requestId] : acquisition.priceEscrowed;
            uint256 positiveTolerance = escrowed * meta.maxPositiveSlippageBps / BPS;
            uint256 negativeTolerance = escrowed * meta.maxNegativeSlippageBps / BPS;
            if (
                (liveFee > escrowed && liveFee - escrowed > positiveTolerance)
                    || (liveFee < escrowed && escrowed - liveFee > negativeTolerance)
            ) {
                _creditAcquisitionRefund(acquisition, AcquisitionStatus.Refunded);
                emit AcquisitionRefundedSlippage(
                    requestId, acquisition.purchaser, acquisition.priceEscrowed, escrowed, liveFee
                );
                return;
            }
        }

        /*
            Selection resolves against the canonical live pool produced by every earlier sequence plus
            this request's reserved activation batch. Find the slot whose cumulative weight range contains
            the target in TREE_DEPTH descents.
        */
        uint256 randomWord = meta.randomWord;
        uint256 target = randomWord % totalWeight;

        uint256 slot = _selectSlot(target);
        uint256 listingId = slotToListing[slot];

        if (listingId == 0) revert InvalidTreeResult();

        Listing storage listing = listings[listingId];

        if (listing.status != ListingStatus.Active) revert InvalidTreeResult();

        _settleAndRemove(listingId);

        listing.purchaser = acquisition.purchaser;
        listing.status = ListingStatus.DeliveryPending;

        acquisition.listingId = listingId;
        acquisition.status = AcquisitionStatus.DeliveryPending;

        pendingDeliveries[listingId] =
            PendingDelivery({requestId: requestId, deadline: uint64(block.timestamp + DELIVERY_WINDOW)});
        if (acquisition.tokenPayment) tokenDeliveryEscrowTotal += acquisition.priceEscrowed;
        else deliveryEscrowTotal += acquisition.priceEscrowed;

        if (_tryAtomicNFTDelivery(listingId)) {
            _completeNFTDelivery(listingId);
        } else {
            emit NFTDeliveryFailed(listingId, acquisition.purchaser, listing.collection, listing.tokenId);
        }

        emit NFTAllocated(requestId, listingId, acquisition.purchaser, listing.depositor, listing.price, randomWord);
    }

    /// @notice Pull acquisition fees credited by ordered expiry, empty-pool, or slippage refunds.
    function withdrawAcquisitionRefund() external nonReentrant returns (uint256 amount) {
        amount = acquisitionRefundCredit[msg.sender];
        if (amount == 0) revert NoAcquisitionRefund();
        acquisitionRefundCredit[msg.sender] = 0;
        acquisitionRefundCreditTotal -= amount;
        SafeTransferLib.forceSafeTransferETH(msg.sender, amount);
        emit AcquisitionRefundWithdrawn(msg.sender, amount);
    }

    /*//////////////////////////////////////////////////////////////
                         NFT DELIVERY ESCROW
    //////////////////////////////////////////////////////////////*/

    /// @notice Permissionlessly retry the exact selected NFT-to-purchaser delivery without a gas stipend.
    function retryNFTDelivery(uint256 listingId) external nonReentrant {
        if (listings[listingId].status != ListingStatus.DeliveryPending) revert DeliveryNotPending();
        if (block.timestamp >= pendingDeliveries[listingId].deadline) revert DeliveryWindowElapsed();
        uint256 requestId = pendingDeliveries[listingId].requestId;
        this.executeNFTDelivery(listingId);
        uint256 basePrice = _completeNFTDelivery(listingId);
        _notifyPurchase(listingId, requestId, basePrice);
    }

    /// @notice After the fixed delivery window, the immutable purchaser may convert escrow to a pull refund.
    function refundFailedDelivery(uint256 listingId) external nonReentrant {
        Listing storage listing = listings[listingId];
        if (listing.status != ListingStatus.DeliveryPending) revert DeliveryNotPending();
        if (msg.sender != listing.purchaser) revert NotPurchaser();

        PendingDelivery memory delivery = pendingDeliveries[listingId];
        if (block.timestamp < delivery.deadline) revert DeliveryWindowNotElapsed();

        Acquisition storage acquisition = acquisitions[delivery.requestId];
        uint256 refund = acquisition.priceEscrowed;
        if (acquisition.tokenPayment) tokenDeliveryEscrowTotal -= refund;
        else deliveryEscrowTotal -= refund;
        _creditAcquisitionRefund(acquisition, AcquisitionStatus.DeliveryRefunded);
        listing.status = ListingStatus.DeliveryRefunded;

        delete requestBasePrice[delivery.requestId];
        delete pendingDeliveries[listingId];
        emit NFTDeliveryRefunded(listingId, delivery.requestId, msg.sender, refund);
    }

    /// @notice Recover a quarantined NFT only after its purchaser has taken the delivery refund.
    function recoverRefundedNFT(uint256 listingId) external nonReentrant {
        if (msg.sender != owner()) revert OwnerOnlyInventory();
        Listing storage listing = listings[listingId];
        if (listing.status != ListingStatus.DeliveryRefunded) revert DeliveryNotRefunded();
        this.executeNFTDelivery(listingId);
        listing.status = ListingStatus.Withdrawn;
        emit RefundedNFTRecovered(listingId, msg.sender);
    }

    /// @dev Narrow child frame: controller clear, transfer, and ownership verification commit together.
    ///      Only the pool may invoke it, and the listing state fixes the recipient.
    function executeNFTDelivery(uint256 listingId) external {
        if (msg.sender != address(this)) revert OnlySelf();
        Listing storage listing = listings[listingId];
        address recipient;
        if (listing.status == ListingStatus.DeliveryPending) {
            recipient = listing.purchaser;
        } else if (listing.status == ListingStatus.DeliveryRefunded) {
            recipient = owner();
        } else {
            revert DeliveryNotPending();
        }

        address collection = listing.collection;
        uint256 tokenId = listing.tokenId;
        if (liveNFTListing[collection][tokenId] != listingId) revert StaleNFTController();
        delete liveNFTListing[collection][tokenId];

        ERC721(collection).transferFrom(address(this), recipient, tokenId);
        if (ERC721(collection).ownerOf(tokenId) != recipient) revert NFTTransferFailed();
    }

    /// @dev Initial ordered processing bounds the entire atomic child and ignores revert data, keeping
    ///      a malicious collection from blocking the canonical queue.
    function _tryAtomicNFTDelivery(uint256 listingId) internal returns (bool success) {
        bytes memory callData = abi.encodeCall(this.executeNFTDelivery, (listingId));
        uint256 gasStipend = NFT_DELIVERY_GAS;
        assembly ("memory-safe") {
            success := call(gasStipend, address(), 0, add(callData, 0x20), mload(callData), 0, 0)
        }
    }

    function _completeNFTDelivery(uint256 listingId) internal returns (uint256 basePrice) {
        Listing storage listing = listings[listingId];
        if (listing.status != ListingStatus.DeliveryPending) revert DeliveryNotPending();
        PendingDelivery memory delivery = pendingDeliveries[listingId];
        Acquisition storage acquisition = acquisitions[delivery.requestId];
        uint256 paid = acquisition.priceEscrowed;
        basePrice = requestBasePrice[delivery.requestId];
        if (basePrice > paid) basePrice = paid;
        if (acquisition.tokenPayment) {
            tokenDeliveryEscrowTotal -= paid;
            tokenBurnablePayments += paid;
        } else {
            uint256 protocolAmount = paid - basePrice;
            deliveryEscrowTotal -= paid;
            ownerProceeds += basePrice;
            accruedProtocolFees += protocolAmount;
            emit OwnerProceedsAccrued(delivery.requestId, basePrice, ownerProceeds);
            emit ProtocolFeesAccrued(delivery.requestId, protocolAmount, accruedProtocolFees);
            emit PurchaseProceedsAccrued(delivery.requestId, owner(), basePrice, protocolAmount);
        }
        listing.status = ListingStatus.Settled;
        acquisition.status = AcquisitionStatus.Fulfilled;

        delete requestBasePrice[delivery.requestId];
        delete pendingDeliveries[listingId];

        emit NFTDeliveryCompleted(listingId, delivery.requestId, listing.purchaser);
    }

    function _notifyPurchase(uint256 listingId, uint256 requestId, uint256 basePrice) internal {
        bytes memory callData =
            abi.encodeCall(PoolPurchaseNotifier.notifyPurchase, (listingId, requestId, msg.sender, basePrice));
        address notifier = address(purchaseNotifier);
        // The notifier isolates receiver failures. Propagate adapter/admission failures atomically,
        // so gas estimation cannot select a successful settlement that omits notification dispatch.
        assembly ("memory-safe") {
            if iszero(call(300000, notifier, 0, add(callData, 0x20), mload(callData), 0, 0)) { revert(0, 0) }
        }
    }

    /*//////////////////////////////////////////////////////////////
                         PROCEEDS WITHDRAWALS
    //////////////////////////////////////////////////////////////*/

    function withdrawOwnerProceeds() external onlyOwner nonReentrant returns (uint256 amount) {
        amount = ownerProceeds;
        if (amount == 0) revert NoProceeds();
        ownerProceeds = 0;
        SafeTransferLib.forceSafeTransferETH(msg.sender, amount);
        emit OwnerProceedsWithdrawn(msg.sender, amount);
    }

    /// @notice Permissionlessly deposit the protocol's entire markup into its pool-aware fee router.
    function payoutProtocolFees() external virtual nonReentrant returns (uint256 amount) {
        amount = accruedProtocolFees;
        if (amount == 0) revert NoProtocolFees();
        accruedProtocolFees = 0;
        address to = IFWACloneFactory(FACTORY).protocolFeeRecipient();
        if (to == address(0)) revert InvalidConfig();
        IPoolFeeRouterV2(to).depositFees{value: amount}();
        emit ProtocolFeesPaidOut(to, amount);
    }

    /// @dev A listing's notional EV contribution. With inverse weights this is approximately the
    ///      common numerator for every listing.
    function _evOf(Listing storage listing) internal view returns (uint256) {
        return listing.weight * listing.price;
    }

    /// @dev Remove a listing from the active selection tree and release its reusable slot.
    function _settleAndRemove(uint256 listingId) internal {
        Listing storage listing = listings[listingId];

        uint256 slot = listing.slot;

        _removeTreeWeight(slot, listing.weight);
        totalWeight -= listing.weight;
        weightedBackingTotal -= _evOf(listing);
        activeListingCount--;

        delete slotToListing[slot];
        _releaseSlot(slot);

        listing.slot = 0;
    }

    /*//////////////////////////////////////////////////////////////
                      SEGMENT TREE: ADD WEIGHT
    //////////////////////////////////////////////////////////////*/

    function _addTreeWeight(uint256 slot, uint256 amount) internal {
        uint256 node = LEAF_BASE + slot - 1;

        /*
            Update leaf, then every ancestor through the root.
        */
        while (true) {
            tree[node] += amount;

            if (node == 1) break;

            node >>= 1;
        }
    }

    /*//////////////////////////////////////////////////////////////
                     SEGMENT TREE: REMOVE WEIGHT
    //////////////////////////////////////////////////////////////*/

    function _removeTreeWeight(uint256 slot, uint256 amount) internal {
        uint256 node = LEAF_BASE + slot - 1;

        while (true) {
            tree[node] -= amount;

            if (node == 1) break;

            node >>= 1;
        }
    }

    /*//////////////////////////////////////////////////////////////
                    SEGMENT TREE: SELECT LISTING
    //////////////////////////////////////////////////////////////*/

    function _selectSlot(uint256 target) internal view returns (uint256 slot) {
        /*
            target must be in:

                0 <= target < tree[1]

            At each branch:

            - If target is inside the left subtree, descend left.
            - Otherwise subtract the left subtree's range and descend right.
        */
        uint256 node = 1;

        while (node < LEAF_BASE) {
            uint256 leftChild = node << 1;
            uint256 leftWeight = tree[leftChild];

            if (target < leftWeight) {
                node = leftChild;
            } else {
                target -= leftWeight;
                node = leftChild | 1;
            }
        }

        slot = node - LEAF_BASE + 1;
    }

    /*//////////////////////////////////////////////////////////////
                           SLOT ALLOCATION
    //////////////////////////////////////////////////////////////*/

    function _allocateSlot() internal returns (uint256 slot) {
        /*
            Reuse a previously released slot when possible.
        */
        if (freeSlotHead != 0) {
            slot = freeSlotHead;
            freeSlotHead = nextFreeSlot[slot];

            delete nextFreeSlot[slot];

            return slot;
        }

        /*
            Otherwise expand into the next unused logical slot.

            No array is expanded and no storage is preallocated.
        */
        slot = nextUnusedSlot++;

        if (slot > CAPACITY) revert ActiveListingCapacityReached();
    }

    function _releaseSlot(uint256 slot) internal {
        nextFreeSlot[slot] = freeSlotHead;
        freeSlotHead = slot;
    }

    /*//////////////////////////////////////////////////////////////
                              OWNER CONFIG
    //////////////////////////////////////////////////////////////*/

    /// @notice Let the permanently locked pool owner enable or disable local purchases.
    function setBool(uint256 key, bool value) external onlyOwner {
        if (retired) revert PoolAlreadyRetired();
        if (key != FWAConfigKeys.ACQUISITIONS_ENABLED) revert FactoryManagedConfig();
        acquisitionsEnabled = value;
        emit ConfigSet(key, value ? 1 : 0);
    }

    /// @notice Set or clear this pool's optional purchaser-eligibility policy.
    /// @dev Zero disables the hook. Nonzero values must already contain contract code.
    function setPurchaseOperator(address newOperator) external onlyOwner {
        if (retired) revert PoolAlreadyRetired();
        if (newOperator != address(0) && newOperator.code.length == 0) revert InvalidPurchaseOperator();
        address oldOperator = purchaseOperator;
        purchaseOperator = newOperator;
        emit PurchaseOperatorSet(oldOperator, newOperator);
    }

    /// @notice Permanently close this pool to new purchases, inventory, and owner configuration.
    /// @dev Existing callbacks, ordered processing, claims, withdrawals, and VRF synchronization remain
    ///      available. Retirement deliberately does not require issued work or inventory to be empty.
    function retirePool() external onlyOwner {
        if (retired) revert PoolAlreadyRetired();
        retired = true;
        acquisitionsEnabled = false;
        emit ConfigSet(FWAConfigKeys.ACQUISITIONS_ENABLED, 0);
        emit PoolRetired(msg.sender);
    }

    /*//////////////////////////////////////////////////////////////
                              TREE VIEWS
    //////////////////////////////////////////////////////////////*/

    function treeRootWeight() external view returns (uint256) {
        return tree[1];
    }
}

src/userowned/interfaces/IFWACloneFactory.sol

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

/// @notice Read-only factory surface consumed by user-owned FWA pool clones.
/// @dev `vrfCoordinator()` is deliberately the logical coordinator seen by every clone: the singleton
///      router/service. `chainlinkCoordinator()` is the mutable real Chainlink coordinator and is never
///      called directly by a clone.
interface IFWACloneFactory {
    struct PoolInitializationConfig {
        address coordinator;
        uint256 subId;
        bytes32 keyHash;
        uint32 gasLimit;
        uint16 confirmations;
        uint32 timeoutBlocks;
        uint16 activationLimit;
        uint16 acquisitionLimit;
        uint16 slippageBps;
        uint256 maxStagedListings;
        address protocolFeeRecipient;
    }

    function getPoolInitializationConfig() external view returns (PoolInitializationConfig memory config);
    function vrfCoordinator() external view returns (address);
    function chainlinkCoordinator() external view returns (address);
    function vrfSubscriptionId() external view returns (uint256);
    function vrfKeyHash() external view returns (bytes32);
    function callbackGasLimit() external view returns (uint32);
    function routerCallbackGasLimit() external view returns (uint32);
    function requestConfirmations() external view returns (uint16);
    function selectionTimeoutBlocks() external view returns (uint32);
    function maxActivationsPerAcquisition() external view returns (uint16);
    function maxAcquisitionsPerTx() external view returns (uint16);
    function selectionSlippageBps() external view returns (uint16);
    function maxStagedListings() external view returns (uint256);

    function edgeBps() external view returns (uint16);
    function inventoryChangeCooldown() external view returns (uint32);
    function buybackPurchaserBps() external view returns (uint16);
    function buybackOwnerBps() external view returns (uint16);
    function buybackProtocolBps() external view returns (uint16);
    function buybackPurchaserWindow() external view returns (uint32);
    function buybackFinalizationWindow() external view returns (uint32);
    function getBuybackTerms()
        external
        view
        returns (
            uint16 purchaserBps,
            uint16 ownerBps,
            uint16 protocolBps,
            uint32 purchaserWindow,
            uint32 finalizationWindow
        );
    function globalPurchasesEnabled() external view returns (bool);
    function globalWithdrawOnly() external view returns (bool);
    function poolCreationEnabled() external view returns (bool);
    function vrfSubscriptionActive() external view returns (bool);
    function vrfSubscriptionTerminated() external view returns (bool);
    function vrfRecoveryRecipient() external view returns (address);
    function vrfRequestsPaused() external view returns (bool);
    function consumerReady(address pool) external view returns (bool);
    function isPool(address pool) external view returns (bool);
    function protocolFeeRecipient() external view returns (address);
    function maxOutstandingRequestsPerPool() external view returns (uint256);
    function maxOutstandingRequestsGlobal() external view returns (uint256);
}

/// @notice Factory-only control and inspection surface implemented by the singleton VRF router/service.
/// @dev The factory intentionally has no generic executor and no wrapper around the consumer base's
///      `setCoordinator`. Only the old authenticated Chainlink coordinator may change that value during
///      an official subscription migration.
interface IFWACloneVRFServiceAdmin {
    function factory() external view returns (address);
    function coordinator() external view returns (address);
    function subscriptionId() external view returns (uint256);
    function approvedVrfKeyHash() external view returns (bytes32);
    function approvedCallbackGasLimit() external view returns (uint32);
    function routerCallbackGasLimit() external view returns (uint32);
    function requestConfirmations() external view returns (uint16);

    function owner() external view returns (address);
    function acceptOwnership() external;

    function subscriptionActive() external view returns (bool);
    function subscriptionTerminated() external view returns (bool);
    function requestsPaused() external view returns (bool);
    function registeredPool(address pool) external view returns (bool);
    function totalPrepared() external view returns (uint256);
    function totalCoordinatorOutstanding() external view returns (uint256);
    function minimumSubscriptionBuffer() external view returns (uint256);
    function maxFulfillmentCostWei() external view returns (uint256);
    function usedVrfKeyHash(bytes32 keyHash) external view returns (bool);

    function registerPool(address pool) external;
    function activateSubscription() external;
    function terminateSubscription(address payable recoveryRecipient) external returns (uint256 serviceEthRefund);
    function setVrfKeyHash(bytes32 keyHash) external;
    function syncPoolRequestConfig(address pool) external;
    function setRequestLimits(uint256 perPoolLimit, uint256 globalLimit) external;
    function setRequestsPaused(bool paused) external;
    function setFeeConfig(uint256 gasEstimate, uint256 marginBps, uint256 flatWei) external;
    function setCoverageConfig(uint256 minimumBuffer, uint256 maxFulfillmentCost) external;
    function setOperator(address operator, bool allowed) external;
    function setReimbursementConfig(
        uint256 sponsoredCount,
        uint256 reimbursementGas,
        uint256 gasOverhead,
        uint256 maxBaseFeeWei,
        uint256 maxPriorityFeeWei,
        uint256 reimbursementWei
    ) external;
    function withdrawSurplus(address recipient, uint256 amount) external;
}

/// @notice Pool configuration surface used by the singleton router/service when registering clones.
interface IFWACloneVRFHost {
    function processAcquisitions(uint256 maxCount) external returns (uint256 processed);
    function unfulfilledVrfCount() external view returns (uint256);
    function vrfCoordinatorAndSubId() external view returns (address coordinator, uint256 subId);
    function vrfRequestConfig() external view returns (bytes32 keyHash, uint32 gasLimit);
    function vrfService() external view returns (address);
    function configureVrfRequest(bytes32 keyHash, uint32 gasLimit) external;
}

src/userowned/interfaces/IPurchaseOperator.sol

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

/// @title IPurchaseOperator
/// @notice Optional pool-local policy hook that decides whether a wallet may start a new purchase.
/// @dev The calling pool is available as `msg.sender`, allowing one operator to serve multiple pools.
interface IPurchaseOperator {
    function canPurchase(address wallet) external view returns (bool allowed);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "solady/=lib/solady/",
    "forge-std/=lib/forge-std/src/",
    "@chainlink/contracts/=lib/chainlink-evm/contracts/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "@openzeppelin/contracts/=lib/v4-core/lib/openzeppelin-contracts/contracts/",
    "@openzeppelin/[email protected]/=test/bitmons/vendor/openzeppelin-4.9.6/",
    "solady-0.1.26/=lib/solady-0.1.26/",
    "lib/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/:ds-test/=lib/v4-core/lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/forge-std/:ds-test/=lib/v4-periphery/lib/permit2/lib/forge-std/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/lib/solmate/:ds-test/=lib/v4-periphery/lib/permit2/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/v4-core/lib/solmate/:ds-test/=lib/v4-periphery/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/lib/v4-core/lib/solmate/:ds-test/=lib/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/lib/v4-core/lib/solmate/:ds-test/=lib/lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/lib/v4-periphery/lib/permit2/:solmate/=lib/lib/v4-periphery/lib/permit2/lib/solmate/src/",
    "lib/lib/v4-periphery/lib/permit2/:solmate/=lib/lib/v4-periphery/lib/permit2/lib/solmate/src/",
    "lib/lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/lib/v4-periphery/lib/v4-core/:solmate/=lib/lib/v4-periphery/lib/v4-core/lib/solmate/src/",
    "lib/lib/v4-periphery/lib/v4-core/:solmate/=lib/lib/v4-periphery/lib/v4-core/lib/solmate/src/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/openzeppelin-contracts/:erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-core/lib/solmate/:ds-test/=lib/v4-core/lib/solmate/lib/ds-test/src/",
    "lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
    "lib/v4-periphery/lib/permit2/:solmate/=lib/v4-periphery/lib/permit2/lib/solmate/",
    "lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/v4-periphery/lib/permit2/:forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/permit2/:openzeppelin-contracts/=lib/v4-periphery/lib/permit2/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "lib/v4-periphery/lib/v4-core/:solmate/=lib/v4-periphery/lib/v4-core/lib/solmate/",
    "lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-periphery/lib/v4-core/:openzeppelin-contracts/=lib/v4-periphery/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/lib/v4-core/:openzeppelin-contracts/=lib/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/lib/v4-core/:openzeppelin-contracts/=lib/lib/v4-core/lib/openzeppelin-contracts/",
    "lib/lib/v4-core/:solmate/=lib/lib/v4-core/lib/solmate/src/",
    "lib/lib/v4-core/:solmate/=lib/lib/v4-core/lib/solmate/src/",
    "lib/lib/v4-periphery/:permit2/=lib/lib/v4-periphery/lib/permit2/",
    "lib/lib/v4-periphery/:permit2/=lib/lib/v4-periphery/lib/permit2/",
    "lib/lib/v4-periphery/:v4-core/=lib/lib/v4-periphery/lib/v4-core/src/",
    "lib/lib/v4-periphery/:v4-core/=lib/lib/v4-periphery/lib/v4-core/src/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:solmate/=lib/v4-core/lib/solmate/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-core/:openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "lib/v4-periphery/:permit2/=lib/v4-periphery/lib/permit2/",
    "lib/v4-periphery/:permit2/=lib/v4-periphery/lib/permit2/",
    "lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "lib/v4-periphery/:v4-core/=lib/v4-periphery/lib/v4-core/src/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "@openzeppelin/=lib/v4-core/lib/openzeppelin-contracts/",
    "chainlink-evm/=lib/chainlink-evm/contracts/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/v4-core/lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/v4-core/lib/openzeppelin-contracts/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "solmate/=lib/v4-core/lib/solmate/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.