Skip to content
Verified contractExactMIT

CampaignFactory

Address0xc9b7ec1f6fe1bdd4b9ea492dcfaeba1c0710561f
Balance

0 ETH

 

Transactions

3

 

Compiler

solc 0.8.26

 

Same code

1 more contract

 

Details

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

src/CampaignFactory.sol

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

// +------------------------------------------------------------------------------------------------+
// |  #  #  #  #                         #  #  #  #  |                                              |
// |  #                                           #  |                                              |
// |  #    ##########################             #  |                                              |
// |  #    ### ###########################        #  |                                              |
// |       ### ###                  #########        |                                              |
// |       ### ###                     ########      |                                              |
// |       ### ###                      ########     |      _____  _           _       _     _      |
// |       ### ###                       #######     |     |  __ \(_)         | |     (_)   | |     |
// |       ### ###                        #######    |     | |  | |_ ___ _ __ | | __ _ _  __| |     |
// |       ### ###                        #####      |     | |  | | / __| '_ \| |/ _` | |/ _` |     |
// |       ### ###                        ### ###    |     | |__| | \__ \ |_) | | (_| | | (_| |     |
// |       ### ###                         #####     |     |_____/|_|___/ .__/|_|\__,_|_|\__,_|     |
// |       ### ###                       ######      |                  | |                         |
// |       ### ###             ##       ######       |                  |_|                         |
// |       ### ###           ######   ######         |                                              |
// |       ### ###             ##### #####           |        DISPLAY  ->  VERIFY  ->  REWARD       |
// |  #    ### ##############   ########          #  |                                              |
// |  #    ###################    ####            #  |                                              |
// |  #                                           #  |                                              |
// |  #  #  #  #                         #  #  #  #  |                                              |
// +------------------------------------------------------------------------------------------------+

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {CampaignVault} from "./CampaignVault.sol";

/// @title CampaignFactory
/// @author Displaid
/// @notice Creates and initialises campaign vaults, each in one transaction. Holds the rules every new vault must
/// follow: who may create vaults, which reward tokens are allowed, the deposit fee and fee recipient, and the proof
/// checker. Every factory setting waits 24 hours; the proof checker waits 7 days. Factory settings never change
/// vaults that already exist.
/// @notice `isCampaign(vault)` is the public record of which vaults this factory made.
/// @dev Vaults are minimal clones of one implementation, deployed by this factory's constructor. A new vault takes
/// deposits only after its first list is final.
contract CampaignFactory is ReentrancyGuard {
    // ---------------------------------------------------------------- constants

    /// @notice Wait for every factory setting except the proof checker.
    uint64 public immutable TIMELOCK;
    /// @notice Wait for a proof checker change.
    uint64 public constant PROOF_CHECKER_TIMELOCK = 7 days;
    /// @dev Tag of the salts chosen with `createCampaignWithSalt`.
    bytes32 private constant CHOSEN_SALT = keccak256("DISPLAID_VAULT_SALT_V1");

    // Ids of the timelocked actions (`queue` / `applyAction`), with their target and value.

    /// @notice Switch the creator allowlist on or off. Value: 1 = on, 0 = off.
    bytes32 public constant SET_ALLOWLIST_ENABLED = keccak256("SET_ALLOWLIST_ENABLED");
    /// @notice Allow or remove a creator. Target: the creator. Value: 1 = allow, 0 = remove.
    bytes32 public constant SET_CREATOR = keccak256("SET_CREATOR");
    /// @notice Allow or remove a reward token. Target: the token. Value: 1 = allow, 0 = remove.
    bytes32 public constant SET_TOKEN = keccak256("SET_TOKEN");
    /// @notice The base fee new vaults must use. Value: basis points.
    bytes32 public constant SET_DEFAULT_FEE = keccak256("SET_DEFAULT_FEE");
    /// @notice The fee contract new vaults must use. Target: the contract, or zero for none.
    bytes32 public constant SET_DEFAULT_FEE_CONTRACT = keccak256("SET_DEFAULT_FEE_CONTRACT");
    /// @notice The fee recipient new vaults must use. Target: the recipient.
    bytes32 public constant SET_FEE_RECIPIENT = keccak256("SET_FEE_RECIPIENT");
    /// @notice A new guardian. Target: the guardian.
    bytes32 public constant SET_GUARDIAN = keccak256("SET_GUARDIAN");
    /// @notice A new owner, who must then accept. Target: the owner.
    bytes32 public constant SET_OWNER = keccak256("SET_OWNER");
    /// @notice The proof checker new vaults must use. Target: the checker. Value: the program key.
    bytes32 public constant SET_PROOF_CHECKER = keccak256("SET_PROOF_CHECKER");

    // ---------------------------------------------------------------- storage

    /// @notice The vault code every clone runs.
    address public immutable implementation;

    /// @notice The owner (a multisig).
    address public owner;
    /// @notice A new owner waiting to accept. Zero = none.
    address public pendingOwner;
    /// @notice The guardian: may cancel queued actions.
    address public guardian;
    /// @notice Whether only allowed creators may create vaults.
    bool public creatorAllowlistEnabled = true;
    /// @notice Allowed creators.
    mapping(address => bool) public allowedCreator;
    /// @notice Allowed reward tokens.
    mapping(address => bool) public allowedToken;
    /// @notice The base deposit fee new vaults must use, in basis points.
    uint16 public defaultFeeBps;
    /// @notice The fee contract new vaults must use. Zero = none.
    address public defaultFeeContract;
    /// @notice The fee recipient new vaults must use.
    address public feeRecipient;
    /// @notice The proof checker new vaults must use.
    address public proofChecker;
    /// @notice The program key new vaults must use.
    bytes32 public programVKey;

    /// @notice When a queued action may be applied, by keccak256(abi.encode(action, target, value)). 0 = not queued.
    mapping(bytes32 => uint64) public etaOf;
    /// @notice Vaults created so far, per creator.
    mapping(address => uint256) public nonceOf;
    /// @notice True for every vault this factory created.
    mapping(address => bool) public isCampaign;
    /// @notice Every vault this factory created, in order.
    address[] public campaigns;

    // ---------------------------------------------------------------- events

    /// @notice `creator` created `vault` for `rewardToken`.
    event CampaignCreated(address indexed vault, address indexed creator, address indexed rewardToken);
    /// @notice An action was queued, to apply from `eta`.
    event ActionQueued(bytes32 indexed action, address target, uint256 value, uint64 eta);
    /// @notice `by` cancelled a queued action.
    event ActionCancelled(bytes32 indexed action, address target, uint256 value, address by);
    /// @notice A queued action was applied.
    event ActionApplied(bytes32 indexed action, address target, uint256 value);
    /// @notice `newOwner` accepted ownership.
    event OwnershipAccepted(address indexed newOwner);

    // ---------------------------------------------------------------- errors

    /// @notice Only the owner may do this.
    error NotOwner();
    /// @notice Only the owner or the guardian may do this.
    error NotOwnerOrGuardian();
    /// @notice Only the pending owner may accept.
    error NotPendingOwner();
    /// @notice The sender may not create vaults.
    error CreatorNotAllowed();
    /// @notice The reward token is not allowed.
    error TokenNotAllowed();
    /// @notice The vault's fee or fee recipient is not the factory's.
    error WrongFeeSettings();
    /// @notice The vault's proof checker or program key is not the factory's.
    error WrongProofChecker();
    /// @notice One key would hold two roles.
    error RoleClash();
    /// @notice Nothing is queued for this action.
    error NothingQueued();
    /// @notice The wait is not over until `eta`.
    error TooEarly(uint64 eta);
    /// @notice The guardian may not cancel a change of the guardian.
    error GuardianCannotCancel();
    /// @notice No such action.
    error UnknownAction();
    /// @notice A value is outside its allowed range.
    error OutOfBounds();
    /// @notice An address is zero or has no code where code is needed.
    error ZeroAddress();

    // ---------------------------------------------------------------- modifiers

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    // ---------------------------------------------------------------- constructor

    /// @param owner_ The owner (a multisig).
    /// @param guardian_ The guardian.
    /// @param feeRecipient_ The fee recipient new vaults must use.
    /// @param proofChecker_ The proof checker new vaults must use (a contract).
    /// @param programVKey_ The program key new vaults must use.
    /// @param tokens Reward tokens allowed from the start.
    /// @param creators Creators allowed from the start.
    /// @param defaultFeeBps_ The base fee new vaults must use.
    /// @param defaultFeeContract_ The fee contract new vaults must use. May be zero.
    /// @param wait The settings wait here and in every vault, and the list wait. See CampaignVault's constructor.
    constructor(
        address owner_,
        address guardian_,
        address feeRecipient_,
        address proofChecker_,
        bytes32 programVKey_,
        address[] memory tokens,
        address[] memory creators,
        uint16 defaultFeeBps_,
        address defaultFeeContract_,
        uint64 wait
    ) {
        if (owner_ == address(0) || guardian_ == address(0) || feeRecipient_ == address(0)) {
            revert ZeroAddress();
        }
        if (proofChecker_ == address(0) || proofChecker_.code.length == 0) revert ZeroAddress();
        if (owner_ == guardian_) revert RoleClash();
        implementation = address(new CampaignVault(wait));
        if (defaultFeeBps_ > CampaignVault(implementation).MAX_FEE_BPS()) revert OutOfBounds();
        if (defaultFeeContract_ != address(0) && defaultFeeContract_.code.length == 0) revert ZeroAddress();
        TIMELOCK = wait;
        defaultFeeBps = defaultFeeBps_;
        defaultFeeContract = defaultFeeContract_;
        owner = owner_;
        guardian = guardian_;
        feeRecipient = feeRecipient_;
        proofChecker = proofChecker_;
        programVKey = programVKey_;
        for (uint256 i; i < tokens.length; ++i) {
            allowedToken[tokens[i]] = true;
        }
        for (uint256 i; i < creators.length; ++i) {
            allowedCreator[creators[i]] = true;
        }
    }

    // ================================================================ create

    /// @notice Create and initialise a vault in one transaction. Its fee, fee recipient, proof checker and program
    /// key must equal the factory's. Deposits open once the vault's first list is final.
    /// @param p The vault's settings.
    /// @return vault The new vault.
    function createCampaign(CampaignVault.InitParams calldata p) external nonReentrant returns (address vault) {
        vault = _create(p, keccak256(abi.encode(msg.sender, nonceOf[msg.sender]++)));
    }

    /// @notice `createCampaign` at an address chosen in advance: the vault lands at
    /// `predictAddressWithSalt(msg.sender, salt)`. Same checks. A salt works once per creator, and no other
    /// creator can reach the same address.
    /// @param p The vault's settings.
    /// @param salt Any value, chosen by the creator.
    /// @return vault The new vault.
    function createCampaignWithSalt(CampaignVault.InitParams calldata p, bytes32 salt)
        external
        nonReentrant
        returns (address vault)
    {
        vault = _create(p, _chosenSalt(msg.sender, salt));
    }

    /// @notice The address of the vault `creator` gets on its `nonce`-th `createCampaign` (counting from 0).
    /// @param creator The creator.
    /// @param nonce The creator's creation count at that time.
    /// @return The vault address.
    function predictAddress(address creator, uint256 nonce) external view returns (address) {
        return Clones.predictDeterministicAddress(implementation, keccak256(abi.encode(creator, nonce)));
    }

    /// @notice The address of the vault `creator` gets from `createCampaignWithSalt` with `salt`.
    /// @param creator The creator.
    /// @param salt The salt.
    /// @return The vault address.
    function predictAddressWithSalt(address creator, bytes32 salt) external view returns (address) {
        return Clones.predictDeterministicAddress(implementation, _chosenSalt(creator, salt));
    }

    function _create(CampaignVault.InitParams calldata p, bytes32 salt) private returns (address vault) {
        if (creatorAllowlistEnabled && !allowedCreator[msg.sender]) revert CreatorNotAllowed();
        if (!allowedToken[p.rewardToken]) revert TokenNotAllowed();
        if (p.feeBps != defaultFeeBps || p.feeContract != defaultFeeContract || p.feeRecipient != feeRecipient) {
            revert WrongFeeSettings();
        }
        if (p.proofChecker != proofChecker || p.programVKey != programVKey) revert WrongProofChecker();

        vault = Clones.cloneDeterministic(implementation, salt);
        CampaignVault(vault).initialize(p);
        isCampaign[vault] = true;
        campaigns.push(vault);
        emit CampaignCreated(vault, msg.sender, p.rewardToken);
    }

    /// @dev Bound to the creator, and tagged so it can never equal a `createCampaign` salt.
    function _chosenSalt(address creator, bytes32 salt) private pure returns (bytes32) {
        return keccak256(abi.encode(CHOSEN_SALT, creator, salt));
    }

    /// @notice Number of vaults this factory created.
    /// @return The count.
    function campaignCount() external view returns (uint256) {
        return campaigns.length;
    }

    // ================================================================ timelocked settings

    /// @notice Queue an action. It can be applied after `TIMELOCK`, or `PROOF_CHECKER_TIMELOCK` for the checker.
    /// @param action The action id (see the constants above).
    /// @param target The address the action is about, if any.
    /// @param value The value, if any.
    function queue(bytes32 action, address target, uint256 value) external onlyOwner {
        _validate(action, target, value);
        uint64 eta = uint64(block.timestamp) + (action == SET_PROOF_CHECKER ? PROOF_CHECKER_TIMELOCK : TIMELOCK);
        etaOf[keccak256(abi.encode(action, target, value))] = eta;
        emit ActionQueued(action, target, value, eta);
    }

    /// @notice Cancel a queued action. The owner may cancel any; the guardian may cancel any except a change of the
    /// guardian.
    /// @param action The action id.
    /// @param target The target it was queued with.
    /// @param value The value it was queued with.
    function cancel(bytes32 action, address target, uint256 value) external {
        if (msg.sender != owner) {
            if (msg.sender != guardian) revert NotOwnerOrGuardian();
            if (action == SET_GUARDIAN) revert GuardianCannotCancel();
        }
        bytes32 k = keccak256(abi.encode(action, target, value));
        if (etaOf[k] == 0) revert NothingQueued();
        delete etaOf[k];
        emit ActionCancelled(action, target, value, msg.sender);
    }

    /// @notice Apply a queued action once its wait is over. It is checked again first.
    /// @param action The action id.
    /// @param target The target it was queued with.
    /// @param value The value it was queued with.
    function applyAction(bytes32 action, address target, uint256 value) external onlyOwner {
        bytes32 k = keccak256(abi.encode(action, target, value));
        uint64 eta = etaOf[k];
        if (eta == 0) revert NothingQueued();
        if (block.timestamp < eta) revert TooEarly(eta);
        _validate(action, target, value); // another role change may have landed since queueing
        delete etaOf[k];
        if (action == SET_ALLOWLIST_ENABLED) creatorAllowlistEnabled = value == 1;
        else if (action == SET_CREATOR) allowedCreator[target] = value == 1;
        else if (action == SET_TOKEN) allowedToken[target] = value == 1;
        else if (action == SET_DEFAULT_FEE) defaultFeeBps = uint16(value);
        else if (action == SET_DEFAULT_FEE_CONTRACT) defaultFeeContract = target;
        else if (action == SET_FEE_RECIPIENT) feeRecipient = target;
        else if (action == SET_GUARDIAN) guardian = target;
        else if (action == SET_OWNER) pendingOwner = target;
        else if (action == SET_PROOF_CHECKER) (proofChecker, programVKey) = (target, bytes32(value));
        emit ActionApplied(action, target, value);
    }

    /// @notice The pending owner accepts ownership. The guardian can never become the owner.
    function acceptOwnership() external {
        if (msg.sender != pendingOwner || msg.sender == address(0)) revert NotPendingOwner();
        if (msg.sender == guardian) revert RoleClash();
        owner = msg.sender;
        pendingOwner = address(0);
        emit OwnershipAccepted(msg.sender);
    }

    function _validate(bytes32 action, address target, uint256 value) private view {
        if (action == SET_ALLOWLIST_ENABLED) {
            if (value > 1) revert OutOfBounds();
        } else if (action == SET_CREATOR || action == SET_TOKEN) {
            if (target == address(0)) revert ZeroAddress();
            if (value > 1) revert OutOfBounds();
        } else if (action == SET_DEFAULT_FEE) {
            if (value > CampaignVault(implementation).MAX_FEE_BPS()) revert OutOfBounds();
        } else if (action == SET_DEFAULT_FEE_CONTRACT) {
            if (target != address(0) && target.code.length == 0) revert ZeroAddress();
        } else if (action == SET_FEE_RECIPIENT || action == SET_GUARDIAN || action == SET_OWNER) {
            if (target == address(0)) revert ZeroAddress();
            // the owner and the guardian are never the same key; a pending owner counts as the owner
            if (
                (action == SET_GUARDIAN && (target == owner || target == pendingOwner))
                    || (action == SET_OWNER && target == guardian)
            ) {
                revert RoleClash();
            }
        } else if (action == SET_PROOF_CHECKER) {
            if (target == address(0) || target.code.length == 0) revert ZeroAddress();
        } else {
            revert UnknownAction();
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

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

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

pragma solidity ^0.8.20;

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

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

    /**
     * @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
     * to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function clone(address implementation, uint256 value) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(value, 0x09, 0x37)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        return cloneDeterministic(implementation, salt, 0);
    }

    /**
     * @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
     * a `value` parameter to send native currency to the new contract.
     *
     * NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
     * to always have enough balance for new deployments. Consider exposing this function under a payable method.
     */
    function cloneDeterministic(
        address implementation,
        bytes32 salt,
        uint256 value
    ) internal returns (address instance) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        assembly ("memory-safe") {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(value, 0x09, 0x37, salt)
        }
        if (instance == address(0)) {
            revert Errors.FailedDeployment();
        }
    }

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

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

lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.20;

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```solidity
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 *
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Storage of the initializable contract.
     *
     * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
     * when using with upgradeable contracts.
     *
     * @custom:storage-location erc7201:openzeppelin.storage.Initializable
     */
    struct InitializableStorage {
        /**
         * @dev Indicates that the contract has been initialized.
         */
        uint64 _initialized;
        /**
         * @dev Indicates that the contract is in the process of being initialized.
         */
        bool _initializing;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint64 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reininitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint64) {
        return _getInitializableStorage()._initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _getInitializableStorage()._initializing;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        assembly {
            $.slot := INITIALIZABLE_STORAGE
        }
    }
}

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * ==== Security Considerations
 *
 * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
 * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
 * considered as an intention to spend the allowance in any specific way. The second is that because permits have
 * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
 * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
 * generally recommended is:
 *
 * ```solidity
 * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
 *     try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
 *     doThing(..., value);
 * }
 *
 * function doThing(..., uint256 value) public {
 *     token.safeTransferFrom(msg.sender, address(this), value);
 *     ...
 * }
 * ```
 *
 * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
 * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
 * {SafeERC20-safeTransferFrom}).
 *
 * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
 * contracts should have entry points that don't rely on permit.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     *
     * CAUTION: See Security Considerations above.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

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

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

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

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

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

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

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

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

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

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

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

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

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }

        (bool success, ) = recipient.call{value: amount}("");
        if (!success) {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            // only check if target is a contract if the call was successful and the return data is empty
            // otherwise we already know that it was a contract
            if (returndata.length == 0 && target.code.length == 0) {
                revert AddressEmptyCode(target);
            }
            return returndata;
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (!success) {
            _revert(returndata);
        } else {
            return returndata;
        }
    }

    /**
     * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
     */
    function _revert(bytes memory returndata) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            assembly ("memory-safe") {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert Errors.FailedCall();
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}

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

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

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        REENTRANCY_GUARD_STORAGE.asBoolean().tstore(false);
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return REENTRANCY_GUARD_STORAGE.asBoolean().tload();
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represent a slot holding a address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represent a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library of standard hash functions.
 *
 * _Available since v5.1._
 */
library Hashes {
    /**
     * @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
     *
     * NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
     */
    function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
        return a < b ? _efficientKeccak256(a, b) : _efficientKeccak256(b, a);
    }

    /**
     * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
     */
    function _efficientKeccak256(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        assembly ("memory-safe") {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

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

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.

pragma solidity ^0.8.20;

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

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the Merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates Merkle trees that are safe
 * against this attack out of the box.
 *
 * IMPORTANT: Consider memory side-effects when using custom hashing functions
 * that access memory in an unsafe way.
 *
 * NOTE: This library supports proof verification for merkle trees built using
 * custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
 * leaf inclusion in trees built using non-commutative hashing functions requires
 * additional logic that is not supported by this library.
 */
library MerkleProof {
    /**
     *@dev The multiproof provided is not valid.
     */
    error MerkleProofInvalidMultiproof();

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with the default hashing function.
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function verify(
        bytes32[] memory proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProof(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in memory with a custom hashing function.
     */
    function processProof(
        bytes32[] memory proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with the default hashing function.
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function verifyCalldata(
        bytes32[] calldata proof,
        bytes32 root,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processProofCalldata(proof, leaf, hasher) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leaves & pre-images are assumed to be sorted.
     *
     * This version handles proofs in calldata with a custom hashing function.
     */
    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = hasher(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProof}.
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProof(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in memory with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with the default hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = Hashes.commutativeKeccak256(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
     * The `leaves` must be validated independently. See {processMultiProofCalldata}.
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * This version handles multiproofs in calldata with a custom hashing function.
     *
     * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
     * and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
     * validating the leaves elsewhere.
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves,
        function(bytes32, bytes32) view returns (bytes32) hasher
    ) internal view returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the Merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofFlagsLen = proofFlags.length;

        // Check proof validity.
        if (leavesLen + proof.length != proofFlagsLen + 1) {
            revert MerkleProofInvalidMultiproof();
        }

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](proofFlagsLen);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < proofFlagsLen; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = hasher(a, b);
        }

        if (proofFlagsLen > 0) {
            if (proofPos != proof.length) {
                revert MerkleProofInvalidMultiproof();
            }
            unchecked {
                return hashes[proofFlagsLen - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

lib/openzeppelin-contracts/contracts/utils/structs/BitMaps.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/BitMaps.sol)
pragma solidity ^0.8.20;

/**
 * @dev Library for managing uint256 to bool mapping in a compact and efficient way, provided the keys are sequential.
 * Largely inspired by Uniswap's https://github.com/Uniswap/merkle-distributor/blob/master/contracts/MerkleDistributor.sol[merkle-distributor].
 *
 * BitMaps pack 256 booleans across each bit of a single 256-bit slot of `uint256` type.
 * Hence booleans corresponding to 256 _sequential_ indices would only consume a single slot,
 * unlike the regular `bool` which would consume an entire slot for a single value.
 *
 * This results in gas savings in two ways:
 *
 * - Setting a zero value to non-zero only once every 256 times
 * - Accessing the same warm slot for every 256 _sequential_ indices
 */
library BitMaps {
    struct BitMap {
        mapping(uint256 bucket => uint256) _data;
    }

    /**
     * @dev Returns whether the bit at `index` is set.
     */
    function get(BitMap storage bitmap, uint256 index) internal view returns (bool) {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        return bitmap._data[bucket] & mask != 0;
    }

    /**
     * @dev Sets the bit at `index` to the boolean `value`.
     */
    function setTo(BitMap storage bitmap, uint256 index, bool value) internal {
        if (value) {
            set(bitmap, index);
        } else {
            unset(bitmap, index);
        }
    }

    /**
     * @dev Sets the bit at `index`.
     */
    function set(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] |= mask;
    }

    /**
     * @dev Unsets the bit at `index`.
     */
    function unset(BitMap storage bitmap, uint256 index) internal {
        uint256 bucket = index >> 8;
        uint256 mask = 1 << (index & 0xff);
        bitmap._data[bucket] &= ~mask;
    }
}

src/CampaignVault.sol

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

// +------------------------------------------------------------------------------------------------+
// |  #  #  #  #                         #  #  #  #  |                                              |
// |  #                                           #  |                                              |
// |  #    ##########################             #  |                                              |
// |  #    ### ###########################        #  |                                              |
// |       ### ###                  #########        |                                              |
// |       ### ###                     ########      |                                              |
// |       ### ###                      ########     |      _____  _           _       _     _      |
// |       ### ###                       #######     |     |  __ \(_)         | |     (_)   | |     |
// |       ### ###                        #######    |     | |  | |_ ___ _ __ | | __ _ _  __| |     |
// |       ### ###                        #####      |     | |  | | / __| '_ \| |/ _` | |/ _` |     |
// |       ### ###                        ### ###    |     | |__| | \__ \ |_) | | (_| | | (_| |     |
// |       ### ###                         #####     |     |_____/|_|___/ .__/|_|\__,_|_|\__,_|     |
// |       ### ###                       ######      |                  | |                         |
// |       ### ###             ##       ######       |                  |_|                         |
// |       ### ###           ######   ######         |                                              |
// |       ### ###             ##### #####           |        DISPLAY  ->  VERIFY  ->  REWARD       |
// |  #    ### ##############   ########          #  |                                              |
// |  #    ###################    ####            #  |                                              |
// |  #                                           #  |                                              |
// |  #  #  #  #                         #  #  #  #  |                                              |
// +------------------------------------------------------------------------------------------------+

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {BitMaps} from "@openzeppelin/contracts/utils/structs/BitMaps.sol";
import {IFeeContract} from "./interfaces/IFeeContract.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IProofChecker} from "./interfaces/IProofChecker.sol";
import {IListHub} from "./interfaces/IListHub.sol";

/// @title CampaignVault
/// @author Displaid
/// @notice One vault per campaign, holding one reward token. Rewarders deposit; once a day a list is posted that
/// states, for every wallet, the total it has earned so far. The vault remembers what each wallet has been paid,
/// and a claim pays the difference, so a claim costs the same after one day or a hundred.
/// @notice Lists arrive through the list hub (the paymaster): one transaction a night covers every vault. A list is
/// accepted only if the approver signed that night's lines (checked once, in the hub) and a valid proof shows it is the
/// previous list plus today's additions, with no wallet lowered or left out. Each list is pending for 24 hours and can
/// be cancelled in that window; after that it is final.
/// @notice The reward token leaves the vault in only three ways: a claim, an emergency claim (both to a wallet on a
/// posted list), and the deposit fee. The vault keeps its own books and never trusts its raw token balance.
/// @dev Deployed as a clone by the CampaignFactory, which initialises it in the same transaction.
contract CampaignVault is Initializable, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;
    using BitMaps for BitMaps.BitMap;

    // ---------------------------------------------------------------- constants

    /// @notice Release name of this vault code.
    string public constant RELEASE = "1.0.0";
    uint256 private constant MAX_CAP_NIGHTS = 400;
    /// @notice Highest daily rate: 10% of the pool per day.
    uint16 public constant MAX_RATE_BPS = 1_000;
    /// @notice Highest deposit fee: 10%.
    uint16 public constant MAX_FEE_BPS = 1_000;
    /// @dev The sample deposit the fee lock asks the fee contract about before it locks (see LOCK_FEE in _validate).
    uint256 private constant LOCK_FEE_SAMPLE = 1e18;
    /// @notice Length of one day: one list per UTC day.
    uint64 public constant EPOCH = 1 days;
    /// @notice Longest allowed wait for a settings change.
    uint64 private constant MAX_TIMELOCK = 30 days;
    /// @notice Shortest allowed time without a list before the emergency can start.
    uint64 public constant MIN_EMERGENCY_TIMEOUT = 90 days;
    /// @notice Longest allowed time without a list before the emergency can start.
    uint64 private constant MAX_EMERGENCY_TIMEOUT = 365 days;
    /// @notice How long a new list stays pending and can be cancelled. Also the shortest allowed wait for a settings
    /// change.
    uint64 public immutable CHALLENGE_PERIOD;
    /// @notice How long a pause lasts at most. It ends by itself.
    uint64 public constant PAUSE_WINDOW = 48 hours;
    /// @notice Gap after a pause ends before the next pause.
    uint64 public constant PAUSE_COOLDOWN = 48 hours;
    /// @notice Wait for a proof checker change.
    uint64 public constant PROOF_CHECKER_DELAY = 7 days;
    /// @notice Longest deposit pause, in days.
    uint64 public constant MAX_DEPOSIT_PAUSE_DAYS = 30;
    /// @notice Pool limit value meaning "no limit".
    uint256 public constant NO_POOL_LIMIT = type(uint256).max;
    /// @dev Number of list slots. Slots are reused; a claim may use any of the last 33 lists.
    uint256 private constant RING = 33;

    /// @dev Domain tags of the Merkle leaves and the proof's public values.
    bytes32 private constant TOTAL_LEAF = keccak256("DISPLAID_TOTAL_LEAF_V1");
    bytes32 private constant EMERGENCY_LEAF = keccak256("DISPLAID_EMERGENCY_LEAF_V1");
    bytes32 private constant PROOF_TAG = keccak256("DISPLAID_LIST_PROOF_V2");
    // Ids of the timelocked settings (`queue` / `applyChange`). The value is a number or an address.

    /// @notice Daily rate, in basis points of the pool.
    bytes32 internal constant RATE = keccak256("RATE");
    /// @notice Base deposit fee, in basis points.
    bytes32 internal constant FEE = keccak256("FEE");
    /// @notice The contract that answers the fee on a deposit (zero = none, the base fee applies).
    bytes32 internal constant FEE_CONTRACT = keccak256("FEE_CONTRACT");
    /// @notice Where deposit fees go.
    bytes32 internal constant FEE_RECIPIENT = keccak256("FEE_RECIPIENT");
    /// @notice The key that posts lists.
    bytes32 internal constant PAYMASTER = keccak256("PAYMASTER");
    /// @notice The key that co-signs lists. A change starts a new approver era.
    bytes32 internal constant APPROVER = keccak256("APPROVER");
    /// @notice The guardian key (emergency stops, cancels queued changes).
    bytes32 internal constant GUARDIAN = keccak256("GUARDIAN");
    /// @notice The watcher key (emergency stops).
    bytes32 internal constant SENTINEL = keccak256("SENTINEL");
    /// @notice A new owner, who must then accept.
    bytes32 internal constant OWNER = keccak256("OWNER");
    /// @notice Closes deposits forever.
    bytes32 internal constant CLOSE_DEPOSITS = keccak256("CLOSE_DEPOSITS");
    /// @notice Pauses deposits for a number of days (1 to 30).
    bytes32 internal constant PAUSE_DEPOSITS = keccak256("PAUSE_DEPOSITS");
    /// @notice Largest pool, in token units. `NO_POOL_LIMIT` = no limit.
    bytes32 internal constant POOL_LIMIT = keccak256("POOL_LIMIT");
    /// @notice Locks the rate forever.
    bytes32 internal constant LOCK_RATE = keccak256("LOCK_RATE");
    /// @notice Locks the base fee and the fee contract forever.
    bytes32 internal constant LOCK_FEE = keccak256("LOCK_FEE");
    /// @notice Locks "no pool limit" forever.
    bytes32 internal constant LOCK_NO_POOL_LIMIT = keccak256("LOCK_NO_POOL_LIMIT");
    /// @notice A list number. Once the emergency is on and before any emergency claim, the owner may point the
    /// emergency split at an earlier final list that is still kept, for example when the newest list's file was
    /// withheld.
    bytes32 internal constant EMERGENCY_LIST = keccak256("EMERGENCY_LIST");

    /// @notice All 16 setting ids in one read. Each id is keccak256 of its name, in this order: RATE, FEE,
    /// FEE_CONTRACT, FEE_RECIPIENT, PAYMASTER, APPROVER, GUARDIAN, SENTINEL, OWNER, CLOSE_DEPOSITS, PAUSE_DEPOSITS,
    /// POOL_LIMIT, LOCK_RATE, LOCK_FEE, LOCK_NO_POOL_LIMIT, EMERGENCY_LIST.
    function settingIds() external pure returns (bytes32[16] memory) {
        return [
            RATE,
            FEE,
            FEE_CONTRACT,
            FEE_RECIPIENT,
            PAYMASTER,
            APPROVER,
            GUARDIAN,
            SENTINEL,
            OWNER,
            CLOSE_DEPOSITS,
            PAUSE_DEPOSITS,
            POOL_LIMIT,
            LOCK_RATE,
            LOCK_FEE,
            LOCK_NO_POOL_LIMIT,
            EMERGENCY_LIST
        ];
    }

    // ---------------------------------------------------------------- types

    /// @notice Settings a vault is created with.
    /// @param rewardToken The token deposited and paid out.
    /// @param owner The owner (a multisig).
    /// @param guardian May pause, cancel pending lists, switch off the paymaster and cancel queued changes.
    /// @param sentinel The watcher: may pause, cancel pending lists and switch off the paymaster.
    /// @param paymaster Posts the daily lists.
    /// @param approver Co-signs every list.
    /// @param feeRecipient Receives deposit fees.
    /// @param feeContract Answers the fee on a deposit. May be zero.
    /// @param rateBps Daily rate, in basis points of the pool.
    /// @param feeBps Base deposit fee, in basis points.
    /// @param timelockDelay Wait for settings changes.
    /// @param emergencyTimeout Time without a list before the emergency can start.
    /// @param poolLimit Largest pool. `NO_POOL_LIMIT` = no limit.
    /// @param proofChecker Checks the proof of every list.
    /// @param programVKey Verification key of the list program.
    struct InitParams {
        address rewardToken;
        address owner;
        address guardian;
        address sentinel;
        address paymaster;
        address approver;
        address feeRecipient;
        address feeContract;
        uint16 rateBps;
        uint16 feeBps;
        uint64 timelockDelay;
        uint64 emergencyTimeout;
        uint256 poolLimit;
        address proofChecker;
        bytes32 programVKey;
    }

    /// @notice What the paymaster posts. The vault adds the chain, itself, the day and the parent list.
    /// @param root Merkle root of the running totals: one leaf per wallet, (wallet, total earned so far).
    /// @param addition Today's new money: the new grand total minus the previous one.
    /// @param emergencyRoot Merkle root of the emergency split: one leaf (index, wallet, shares) per NFT paid today.
    /// @param emergencyTotal Number of shares in the emergency split, at least 1.
    /// @param fileHash Hash of the public list file the proof was made from.
    /// @param snapshotBlock The block at midnight UTC at which owners were read.
    /// @param snapshotBlockHash Hash of that block.
    struct Post {
        bytes32 root;
        uint128 addition;
        bytes32 emergencyRoot;
        uint128 emergencyTotal;
        bytes32 fileHash;
        uint64 snapshotBlock;
        bytes32 snapshotBlockHash;
        uint128 allocatedAfter; // this vault's "allocated so far" after this list, proven by the stamp
    }

    /// @notice One vault's line in a night's master list.
    /// @param epoch The day of the line.
    /// @param parentRoot The root of the list it builds on (part of what the stamp proves).
    /// @param post The post.
    /// @param batchRoot The night's master list.
    /// @param path The Merkle path of this line in it.
    struct Line {
        uint64 epoch;
        bytes32 parentRoot;
        Post post;
        bytes32 batchRoot;
        bytes32[] path;
    }

    /// @notice A posted list, as kept in its slot.
    /// @param root Merkle root of the running totals.
    /// @param emergencyRoot Merkle root of the emergency split.
    /// @param allocatedAfter Total allocated so far, ever, including this list.
    /// @param epoch The day of the list.
    /// @param publishedAt When it was posted.
    /// @param emergencyTotal Number of shares in its emergency split.
    /// @param seq The list number this slot holds. A number is valid only in its own slot.
    struct List {
        bytes32 root;
        bytes32 emergencyRoot;
        uint128 allocatedAfter;
        uint64 epoch;
        uint64 publishedAt;
        uint128 emergencyTotal;
        uint64 seq;
    }

    /// @notice A queued settings change. `eta` 0 = nothing queued.
    struct Queued {
        bytes32 value;
        uint64 eta;
    }

    /// @notice A queued proof checker change. `eta` 0 = nothing queued.
    struct CheckerChange {
        address checker;
        bytes32 vkey;
        uint64 eta;
    }

    /// @notice A queued rescue of a token other than the reward token. `token` zero = ETH.
    struct Rescue {
        address token;
        address to;
        uint256 amount;
        uint64 eta;
    }

    // ---------------------------------------------------------------- storage: fixed at initialisation

    /// @notice The factory that created this vault.
    address public factory;
    /// @notice The token deposited and paid out.
    IERC20 public rewardToken;
    /// @notice Wait for settings changes.
    uint64 public timelockDelay;
    /// @notice Time without a list before the emergency can start.
    uint64 public emergencyTimeout;
    /// @notice When the vault was initialised.
    uint64 public initializedAt;

    // ---------------------------------------------------------------- storage: settings

    /// @notice The owner.
    address public owner;
    /// @notice A new owner waiting to accept. Zero = none.
    address public pendingOwner;
    /// @notice The guardian.
    address public guardian;
    /// @notice The watcher.
    address public sentinel;
    /// @notice The key that posts lists. Zero = switched off.
    address public paymaster;
    /// @notice The key that co-signs lists.
    address public approver;
    /// @notice Where deposit fees go.
    address public feeRecipient;
    /// @notice Answers the fee on a deposit. Zero = none, the base fee applies.
    address public feeContract;
    /// @notice Daily rate, in basis points of the pool.
    uint16 public rateBps;
    /// @notice Base deposit fee, in basis points: charged on stray money, and when the fee contract is blank or fails.
    uint16 public feeBps;
    /// @notice True once the rate is locked forever.
    bool public rateLocked;
    /// @notice True once the base fee and the fee contract are locked forever.
    bool public feeLocked;
    /// @notice True once "no pool limit" is locked forever.
    bool public noPoolLimitLocked;
    /// @notice True once deposits are closed forever.
    bool public depositsClosed;
    /// @notice Deposits are paused until this time.
    uint64 public depositsPausedUntil;
    /// @notice Goes up by one on every approver change. For readers only: the approver's signature is checked in the
    /// hub inside the same transaction, so an old signature can't be used again anyway.
    uint64 public approverEra;
    /// @notice A line from a night posted before this time can't be saved or claimed from. Set when a list is
    /// cancelled, when lines are cancelled, and when the approver changes (only saved lists survive these).
    uint64 public linesValidFrom;
    /// @notice The highest rate in force since the last saved list, while it differs from `rateBps`, so a rate
    /// cut can never make a valid list fail its cap. 0 = just `rateBps`.
    uint16 public capRateBps;
    /// @notice Largest pool. `NO_POOL_LIMIT` = no limit.
    uint256 public poolLimit;
    /// @notice Checks the proof of every list.
    IProofChecker public proofChecker;
    /// @notice Verification key of the list program.
    bytes32 public programVKey;

    /// @notice Queued settings changes, by setting id.
    mapping(bytes32 => Queued) public queued;
    /// @notice The queued proof checker change.
    CheckerChange public pendingChecker;
    /// @notice The queued rescue.
    Rescue public pendingRescue;

    // ---------------------------------------------------------------- storage: books

    /// @notice Counted money not yet allocated. Only a deposit or a bring-in adds to it.
    uint256 public pool;
    /// @notice Everything ever paid in, fees included: the running total a fee contract is told.
    uint256 public totalDeposited;
    /// @notice Total paid out by claims, ever.
    /// @dev Packed with the next three: every claim reads and writes this one slot.
    uint128 public paidEver;
    /// @notice Claims are paused until this time.
    uint64 public pauseEndsAt;
    /// @notice Number of the newest posted list. 0 = none.
    uint64 public head;
    /// @notice When the last pause started. 0 = never.
    uint64 public pausedAt;
    /// @notice Paid so far, per wallet.
    mapping(address => uint256) public paid;
    mapping(uint256 => List) private _ring;
    /// @notice Fingerprints of cancelled lists: keccak256(abi.encode(epoch, parentRoot, root)). A cancelled list
    /// can never be posted again.
    /// @dev Not the root alone: a day with no changes has its parent's root, and burning that root would block
    /// every later no-change list.
    mapping(bytes32 => bool) public burnedPost;

    // ---------------------------------------------------------------- storage: emergency

    /// @notice True once the emergency has started.
    bool public emergencyActive;
    /// @notice The day of the list the emergency split uses.
    uint64 public emergencyEpoch;
    /// @notice Emergency claims open at this time, and never while a change of the split is queued. The owner
    /// can always act first, so no one can claim early and lock the split.
    uint64 public emergencyOpensAt;
    /// @notice Merkle root of the emergency split.
    bytes32 public emergencyRoot;
    /// @notice Number of shares in the emergency split.
    uint128 public emergencyTotal;
    /// @notice The money split in the emergency.
    uint256 public emergencyPool;
    /// @notice Paid out by emergency claims so far.
    uint256 public emergencyPaid;
    /// @dev One bit per split line, not per wallet.
    BitMaps.BitMap private _emergencyClaimed;
    /// @dev When the rate was last cut.
    uint64 private _capRateAt;

    // ---------------------------------------------------------------- events

    /// @notice The vault was initialised by `factory`.
    event Initialized(address indexed factory, address indexed rewardToken, uint16 rateBps, uint16 feeBps);
    /// @notice `depositor` paid in `amount`, of which `fee` went to the fee recipient.
    event Deposited(address indexed depositor, uint256 amount, uint256 fee);
    /// @notice Money sent in directly was put on the books: `amount` in total, `fee` to the fee recipient.
    event BroughtIn(uint256 amount, uint256 fee);
    /// @notice A started emergency was called off: a newer valid list was saved during the wait.
    event EmergencyCalledOff(uint64 epoch, uint64 postedAt);
    /// @notice Every line posted so far that isn't saved was cancelled.
    event LinesCancelled(address indexed by);

    /// @notice List `seq` for day `epoch` was saved in this vault. `fileUri` is always empty; the night's file link is
    /// in the list hub's `NightPosted` event.
    event Published(uint64 indexed seq, uint64 indexed epoch, Post post, uint256 allocatedAfter, string fileUri);
    /// @notice Pending list `seq` was cancelled by `by`.
    event Cancelled(uint64 indexed seq, uint64 indexed epoch, bytes32 root, address indexed by);
    /// @notice `wallet` was paid `amount`, bringing its total paid to `totalPaid`. `submitter` sent the claim.
    event Claimed(address indexed wallet, uint256 amount, uint256 totalPaid, address submitter);
    /// @notice `by` switched off the paymaster.
    event PaymasterDisabled(address indexed by);
    /// @notice `by` paused claims until `until`.
    event Paused(address indexed by, uint64 until);
    /// @notice `by` ended the pause.
    event Unpaused(address indexed by);
    /// @notice `by` ended the deposit pause.
    event DepositsResumed(address indexed by);
    /// @notice A change of setting `id` to `value` was queued, to apply from `eta`.
    event ChangeQueued(bytes32 indexed id, bytes32 value, uint64 eta);
    /// @notice `by` cancelled the queued change of setting `id`.
    event ChangeCancelled(bytes32 indexed id, address indexed by);
    /// @notice Setting `id` was changed to `value`.
    event ChangeApplied(bytes32 indexed id, bytes32 value);
    /// @notice A proof checker change was queued, to apply from `eta`.
    event ProofCheckerQueued(address checker, bytes32 vkey, uint64 eta);
    /// @notice `by` cancelled the queued proof checker change.
    event ProofCheckerCancelled(address indexed by);
    /// @notice The proof checker was changed.
    event ProofCheckerApplied(address checker, bytes32 vkey);
    /// @notice `newOwner` accepted ownership.
    event OwnershipAccepted(address indexed newOwner);
    /// @notice A rescue was queued, to apply from `eta`.
    event RescueQueued(address token, address to, uint256 amount, uint64 eta);
    /// @notice `by` cancelled the queued rescue.
    event RescueCancelled(address indexed by);
    /// @notice `amount` of `token` was sent to `to`.
    event Rescued(address token, address to, uint256 amount);
    /// @notice The emergency started. `pool` is split by the list of day `epoch`.
    event EmergencyActivated(uint64 epoch, uint256 pool);
    /// @notice Line `index` of the emergency split paid `amount` to `wallet`.
    event EmergencyClaimed(uint256 indexed index, address indexed wallet, uint256 amount);

    // ---------------------------------------------------------------- errors

    /// @notice Only the owner may do this.
    error NotOwner();
    /// @notice Only the pending owner may accept.
    error NotPendingOwner();
    /// @notice Only the paymaster may post lists.
    error NotPaymaster();
    /// @notice Only the guardian or the watcher may do this.
    error NotStopper();
    /// @notice Only the owner or the guardian may do this.
    error NotOwnerOrGuardian();
    /// @notice An address is zero or not allowed.
    error ZeroAddress();
    /// @notice A value is outside its allowed range.
    error OutOfBounds();
    /// @notice One key would hold two roles.
    error RoleClash();
    /// @notice Deposits are not open.
    error DepositsNotOpen();
    /// @notice The emergency has started.
    error EmergencyIsActive();
    /// @notice The emergency has not started.
    error EmergencyNotActive();
    /// @notice The fee is above what the depositor accepted.
    error FeeAboveLimit(uint256 fee, uint16 maxFeeBps);
    /// @notice The vault received less than was sent.
    error ShortReceipt(uint256 expected, uint256 received);
    /// @notice An amount or root is zero.
    error ZeroAmount();
    /// @notice The deposit would take the pool over its limit. `room` is what still fits.
    error OverPoolLimit(uint256 room);
    /// @notice The emergency split is empty.
    error EmptySplit();
    /// @notice This list was cancelled and can never be posted again.
    error RootBurned();
    /// @notice A list for this day already exists.
    error ListExists(uint64 epoch);
    /// @notice The list adds more than today's budget.
    error OverBudget(uint256 addition, uint256 budget);
    /// @notice The approver's signature is not valid.
    error BadApproval();
    /// @notice No such list is kept.
    error NoList(uint64 seq);
    /// @notice The list is final; it can no longer be cancelled.
    error WindowOver(uint64 seq);
    /// @notice No list is final yet.
    error NoFinalList();
    /// @notice The Merkle proof is not valid.
    error InvalidProof();
    /// @notice The claim would pay more than the newest final list allocated.
    error ExceedsAllocated();
    /// @notice A claim may not pay the vault itself.
    error PaysVault();
    /// @notice Claims are paused.
    error ClaimsPaused();
    /// @notice Claims are already paused.
    error PauseActive();
    /// @notice The next pause is possible from `until`.
    error PauseCooldown(uint64 until);
    /// @notice Nothing is paused.
    error NotPaused();
    /// @notice Nothing is queued for this id.
    error NothingQueued(bytes32 id);
    /// @notice The wait is not over until `eta`.
    error TooEarly(uint64 eta);
    /// @notice This setting is locked.
    error SettingLocked(bytes32 id);
    /// @notice No such setting.
    error UnknownSetting(bytes32 id);
    /// @notice The guardian may not cancel a change of the guardian or the watcher.
    error GuardianCannotCancel(bytes32 id);
    /// @notice The reward token can never be rescued.
    error CannotRescueRewardToken();
    /// @notice An ETH transfer failed.
    error TransferFailed();
    /// @notice The emergency, or emergency claims, are not possible until `at`.
    error EmergencyTooEarly(uint64 at);
    /// @notice This emergency line was already paid.
    error AlreadyClaimed();
    /// @notice The emergency claim would pay more than the emergency pool.
    error ExceedsPool();

    // ---------------------------------------------------------------- modifiers

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner();
        _;
    }

    modifier onlyStopper() {
        if (msg.sender != guardian && msg.sender != sentinel) revert NotStopper();
        _;
    }

    // ---------------------------------------------------------------- constructor

    /// @dev The implementation is never used directly; only its clones are initialised.
    /// @param wait The settings wait and the list wait. Always 24 hours, except on Sepolia and local test chains,
    /// where it may be as short as 5 minutes.
    constructor(uint64 wait) {
        if (
            wait != 24 hours
                && (wait > 24 hours || wait < 5 minutes || (block.chainid != 11_155_111 && block.chainid != 31_337))
        ) {
            revert OutOfBounds();
        }
        CHALLENGE_PERIOD = wait;
        _disableInitializers();
    }

    // ================================================================ initialisation

    /// @notice Sets up a new clone. Called once, by the factory, in the transaction that creates it.
    /// @param p The vault's settings.
    function initialize(InitParams calldata p) external initializer {
        if (
            p.rewardToken == address(0) || p.owner == address(0) || p.guardian == address(0) || p.sentinel == address(0)
                || p.paymaster == address(0) || p.approver == address(0) || p.feeRecipient == address(0)
        ) revert ZeroAddress();
        if (p.rateBps == 0 || p.rateBps > MAX_RATE_BPS || p.feeBps > MAX_FEE_BPS) revert OutOfBounds();
        if (p.timelockDelay < CHALLENGE_PERIOD || p.timelockDelay > MAX_TIMELOCK) revert OutOfBounds();
        if (p.emergencyTimeout < MIN_EMERGENCY_TIMEOUT || p.emergencyTimeout > MAX_EMERGENCY_TIMEOUT) {
            revert OutOfBounds();
        }
        if (p.poolLimit == 0) revert OutOfBounds();
        _checkChecker(p.proofChecker);
        _checkNoClash(p.owner, address(0), p.guardian, p.sentinel, p.paymaster, p.approver);

        factory = msg.sender;
        rewardToken = IERC20(p.rewardToken);
        owner = p.owner;
        guardian = p.guardian;
        sentinel = p.sentinel;
        paymaster = p.paymaster;
        approver = p.approver;
        feeRecipient = p.feeRecipient;
        feeContract = p.feeContract;
        rateBps = p.rateBps;
        feeBps = p.feeBps;
        timelockDelay = p.timelockDelay;
        emergencyTimeout = p.emergencyTimeout;
        poolLimit = p.poolLimit;
        proofChecker = IProofChecker(p.proofChecker);
        programVKey = p.programVKey;
        initializedAt = uint64(block.timestamp);
        emit Initialized(msg.sender, p.rewardToken, p.rateBps, p.feeBps);
    }

    // ================================================================ views

    /// @notice Today's day number (UTC days since 1970).
    /// @return The current epoch.
    function currentEpoch() public view returns (uint64) {
        return uint64(block.timestamp / EPOCH);
    }

    /// @notice Allocated so far, ever, pending lists included.
    /// @return The total allocated.
    function allocatedEver() public view returns (uint256) {
        return _allocatedAt(head);
    }

    /// @notice What the vault owes: allocated and not yet claimed.
    /// @return The amount owed.
    function owed() public view returns (uint256) {
        return _allocatedAt(head) - paidEver;
    }

    /// @notice Reward tokens in the vault that are not on the books (sent in directly).
    /// @return The amount not on the books.
    function stray() public view returns (uint256) {
        uint256 counted = pool + owed() + (emergencyPool - emergencyPaid);
        uint256 bal = rewardToken.balanceOf(address(this));
        return bal > counted ? bal - counted : 0;
    }

    /// @notice One night's budget at today's pool and rate. A line may add this for EACH night since the newest saved
    /// list (see `_capOver`), so saving lists regularly keeps the cap tight.
    /// @return Today's budget.
    function budget() public view returns (uint256) {
        return pool * rateBps / 10_000;
    }

    /// @notice Whether claims are paused.
    /// @return True while paused.
    function isPaused() public view returns (bool) {
        return block.timestamp < pauseEndsAt;
    }

    /// @notice Whether deposits are open: only after the first list is final, and not while paused, closed or in
    /// the emergency.
    /// @return True if a deposit would be accepted now.
    function depositsOpen() public view returns (bool) {
        return !depositsClosed && !emergencyActive && block.timestamp >= depositsPausedUntil && newestFinal() != 0;
    }

    /// @notice The newest final list. At most two lists can be pending at once.
    /// @return seq Its number; 0 = none yet.
    function newestFinal() public view returns (uint64 seq) {
        seq = head;
        while (seq != 0 && block.timestamp < _ring[seq % RING].publishedAt + CHALLENGE_PERIOD) --seq;
    }

    /// @notice A kept list. Reverts if `seq` is not one of the kept lists.
    /// @param seq The list number.
    /// @return The list.
    function listOf(uint64 seq) external view returns (List memory) {
        return _kept(seq);
    }

    /// @dev List `seq` if it is live and its slot still holds it. Slots are reused (`seq % RING`); after a cancel,
    /// a slot that an older number maps to can hold the cancelled list, so "within the last 33" alone is not enough.
    function _kept(uint64 seq) private view returns (List storage l) {
        l = _ring[seq % RING];
        if (seq == 0 || seq > head || l.seq != seq) revert NoList(seq);
    }

    /// @notice Whether line `index` of the emergency split has been paid.
    /// @param index The line number.
    /// @return True if paid.
    function isEmergencyLineClaimed(uint256 index) external view returns (bool) {
        return _emergencyClaimed.get(index);
    }

    /// @notice The Merkle leaf of a running total.
    /// @param wallet The wallet.
    /// @param total Its total earned so far.
    /// @return The leaf.
    function totalLeaf(address wallet, uint256 total) public view returns (bytes32) {
        return keccak256(bytes.concat(keccak256(abi.encode(TOTAL_LEAF, block.chainid, address(this), wallet, total))));
    }

    /// @notice The Merkle leaf of one line of an emergency split.
    /// @param epoch The day of the list.
    /// @param index The line number.
    /// @param wallet The wallet paid.
    /// @param shares Its shares.
    /// @return The leaf.
    function emergencyLeaf(uint64 epoch, uint256 index, address wallet, uint256 shares) public view returns (bytes32) {
        return keccak256(
            bytes.concat(
                keccak256(abi.encode(EMERGENCY_LEAF, block.chainid, address(this), epoch, index, wallet, shares))
            )
        );
    }

    /// @notice The exact public values the proof must commit to. The vault builds them itself.
    /// @param epoch The day of the list.
    /// @param parentRoot The root of the previous list (zero for the first).
    /// @param p The post.
    /// @return The encoded public values.
    function proofPublicValues(uint64 epoch, bytes32 parentRoot, Post calldata p) public view returns (bytes memory) {
        return abi.encode(
            PROOF_TAG,
            block.chainid,
            address(this),
            epoch,
            parentRoot,
            p.root,
            p.addition,
            p.emergencyRoot,
            p.emergencyTotal,
            p.fileHash,
            p.allocatedAfter
        );
    }

    // ================================================================ deposits

    /// @notice Pay `amount` of the reward token into the pool. Needs an allowance.
    /// @param amount The amount, fee included.
    /// @param maxFeeBps The highest fee the depositor accepts. Reverts if the fee is higher.
    function deposit(uint256 amount, uint16 maxFeeBps) external nonReentrant {
        _deposit(amount, maxFeeBps);
    }

    /// @notice `deposit` with an EIP-2612 permit instead of an allowance.
    /// @param amount The amount, fee included.
    /// @param maxFeeBps The highest fee the depositor accepts.
    /// @param deadline The permit's deadline.
    /// @param v The permit signature's v.
    /// @param r The permit signature's r.
    /// @param s The permit signature's s.
    function depositWithPermit(uint256 amount, uint16 maxFeeBps, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external
        nonReentrant
    {
        // A front-run permit must not block the deposit; the allowance check in transferFrom still applies.
        try IERC20Permit(address(rewardToken)).permit(msg.sender, address(this), amount, deadline, v, r, s) {} catch {}
        _deposit(amount, maxFeeBps);
    }

    /// @dev The fee goes straight from the depositor to the fee recipient and never enters the vault.
    function _deposit(uint256 amount, uint16 maxFeeBps) private {
        if (!depositsOpen()) revert DepositsNotOpen();
        if (amount == 0) revert ZeroAmount();
        uint256 fee = quoteFee(msg.sender, amount);
        if (fee > _bps(amount, maxFeeBps)) revert FeeAboveLimit(fee, maxFeeBps);
        uint256 net = amount - fee;
        uint256 room = _room();
        if (net > room) revert OverPoolLimit(room);
        if (fee != 0) rewardToken.safeTransferFrom(msg.sender, feeRecipient, fee);
        uint256 before = rewardToken.balanceOf(address(this));
        rewardToken.safeTransferFrom(msg.sender, address(this), net);
        uint256 received = rewardToken.balanceOf(address(this)) - before;
        if (received != net) revert ShortReceipt(net, received);
        pool += net;
        totalDeposited += amount;
        emit Deposited(msg.sender, amount, fee);
    }

    /// @notice Put money that was sent in directly on the books, with the base fee (the sender is unknown, so the fee
    /// contract can't be asked). Anyone can call it.
    function bringIn() external nonReentrant {
        if (!depositsOpen()) revert DepositsNotOpen();
        uint256 s = stray();
        uint256 room = _room();
        if (s > room) s = room; // the rest waits for room under the pool limit
        if (s == 0) return;
        uint256 fee = _bps(s, feeBps);
        pool += s - fee;
        totalDeposited += s;
        if (fee != 0) rewardToken.safeTransfer(feeRecipient, fee);
        emit BroughtIn(s, fee);
    }

    /// @notice The fee a deposit pays now: the fee contract's answer, or the base fee if it is blank or fails. Never
    /// above the hard cap: an answer above it is refused, and no money moves.
    /// @param who The depositor.
    /// @param amount The amount, fee included.
    /// @return fee The fee, in token units.
    function quoteFee(address who, uint256 amount) public view returns (uint256 fee) {
        fee = _bps(amount, feeBps);
        if (feeContract != address(0)) {
            try IFeeContract(feeContract).feeFor(who, amount, totalDeposited) returns (uint256 f) {
                fee = f;
            } catch {} // no answer: the base fee stands
        }
        if (fee > _bps(amount, MAX_FEE_BPS)) revert OutOfBounds();
    }

    /// @dev Rounds up.
    function _bps(uint256 amount, uint256 bps) private pure returns (uint256) {
        return (amount * bps + 9_999) / 10_000;
    }

    function _room() private view returns (uint256) {
        if (poolLimit == NO_POOL_LIMIT) return NO_POOL_LIMIT;
        uint256 held = pool + owed();
        return poolLimit > held ? poolLimit - held : 0;
    }

    // ================================================================ daily list

    /// @notice Save this vault's line from a night's master list. Nothing is written into a vault at night; anyone
    /// can save a line (usually the first claimer of a night, or a keeper). The list's 24-hour stop window runs from
    /// when the night was posted, not from when the line is saved.
    /// @param l The line.
    function saveLine(Line calldata l) external nonReentrant {
        _saveLine(l);
    }

    function _saveLine(Line calldata l) private {
        Post calldata p = l.post;
        (,, uint64 postedAt,) = _night(l.batchRoot);
        bool undo = emergencyActive;
        // Only inside the emergency's wait, and only with a list that proves the vault wasn't really left off.
        if (undo && (block.timestamp >= emergencyOpensAt || block.timestamp >= uint256(postedAt) + emergencyTimeout)) {
            revert EmergencyIsActive();
        }
        // A line is saved only once its stop window is over (the one exception: calling off an emergency). A night
        // the watcher cancels in the hub can then never be saved, and the head is never pending while an older line
        // pays.
        if (!undo && block.timestamp < uint256(postedAt) + CHALLENGE_PERIOD) revert NoFinalList();
        if (p.root == bytes32(0)) revert ZeroAmount();
        if (p.emergencyRoot == bytes32(0) || p.emergencyTotal == 0) revert EmptySplit();

        uint64 h = head;
        uint64 headEpoch = h == 0 ? 0 : _ring[h % RING].epoch;
        if (h != 0 && headEpoch >= l.epoch) revert ListExists(l.epoch);
        if (burnedPost[_postKey(l.epoch, p.root)]) revert RootBurned();
        // Yesterday's list is here, so today's must build on it (checked wherever no night was skipped).
        if (l.epoch == headEpoch + 1 && l.parentRoot != _ring[h % RING].root) revert BadApproval();
        if (undo) _callOffEmergency(l.epoch, postedAt);

        uint256 before = _allocatedAt(h);
        if (p.allocatedAfter < before) revert OverBudget(p.allocatedAfter, before);
        uint256 increase = p.allocatedAfter - before;
        uint256 cap = _capOver(h == 0 ? 1 : l.epoch - headEpoch);
        if (increase > cap) revert OverBudget(increase, cap);
        _checkLine(l);

        uint64 seq = h + 1;
        _ring[seq % RING] = List({
            root: p.root,
            emergencyRoot: p.emergencyRoot,
            allocatedAfter: p.allocatedAfter,
            epoch: l.epoch,
            publishedAt: postedAt,
            emergencyTotal: p.emergencyTotal,
            seq: seq
        });
        head = seq;
        pool -= increase;
        if (postedAt > _capRateAt) capRateBps = 0; // only a night posted after the cut ends the old cap
        emit Published(seq, l.epoch, p, p.allocatedAfter, "");
    }

    /// @dev The most this vault's own rate allows over `nights` nights from its pool, as if a list came each night. The
    /// pool only grows between lists (deposits), so a valid line is never over this. The hard cap: however wrong a
    /// master list is, one line takes at most this from the pool (it grows with the nights since the newest saved
    /// list).
    function _capOver(uint256 nights) private view returns (uint256 cap) {
        uint256 rate = rateBps > capRateBps ? rateBps : capRateBps;
        uint256 left = pool;
        if (nights > MAX_CAP_NIGHTS) nights = MAX_CAP_NIGHTS;
        for (uint256 i; i < nights; ++i) {
            uint256 b = left * rate / 10_000;
            cap += b;
            left -= b;
        }
    }

    /// @dev Approver, night and stamp. The master list's root is what the approver signed AND what the stamp proves:
    /// the proof is built here from `batchRoot`, so a line from another stamp can't borrow this night's signature.
    /// @return postedAt When the night was posted.
    function _night(bytes32 batchRoot) private view returns (address, uint64, uint64, bool) {
        if (paymaster == address(0)) revert NotPaymaster();
        return IListHub(paymaster).nightOf(batchRoot);
    }

    function _checkLine(Line calldata l) private view returns (uint64 postedAt) {
        address signer;
        uint64 nightEpoch;
        bool nightCancelled;
        (signer, nightEpoch, postedAt, nightCancelled) = _night(l.batchRoot);
        if (signer != approver || nightEpoch != l.epoch || nightCancelled || postedAt <= linesValidFrom) {
            revert BadApproval(); // a night posted in the same block as the stop is also refused
        }
        proofChecker.verifyProof(
            programVKey, proofPublicValues(l.epoch, l.parentRoot, l.post), abi.encode(l.batchRoot, l.path)
        );
    }

    function _callOffEmergency(uint64 epoch, uint64 postedAt) private {
        // The emergency's day, root and total stay as they were; nothing reads them unless it's active, and the next
        // start overwrites them.
        pool = emergencyPool;
        emergencyPool = 0;
        emergencyActive = false;
        emergencyOpensAt = 0;
        emit EmergencyCalledOff(epoch, postedAt);
    }

    /// @notice Emergency stop: cancel a pending list, and every list built on it. Their money returns to the pool and
    /// their fingerprints can never be posted again.
    /// @param seq The first list to cancel.
    function cancel(uint64 seq) external onlyStopper {
        uint64 h = head;
        // through _kept, like every other reader: after a cancel, an old number's slot can hold the cancelled list
        if (block.timestamp >= _kept(seq).publishedAt + CHALLENGE_PERIOD) revert WindowOver(seq);
        uint256 restored = _allocatedAt(h) - _allocatedAt(seq - 1);
        for (uint64 s = seq; s <= h; ++s) {
            List storage l = _ring[s % RING];
            // Day + fingerprint, no parent: a line saved after skipped nights has a parent the vault never saw.
            burnedPost[_postKey(l.epoch, l.root)] = true;
            emit Cancelled(s, l.epoch, l.root, msg.sender);
        }
        head = seq - 1;
        pool += restored; // "allocated so far" rolls back to the parent's value
        linesValidFrom = uint64(block.timestamp); // and anything posted on top of it that isn't saved yet
    }

    /// @notice Emergency stop: cancel every line posted so far that isn't saved. As with a cancel, the next
    /// night's line carries every earned amount forward, so no wallet loses anything; save the last good line first to
    /// keep it claimable in the meantime.
    function cancelLines() external onlyStopper {
        linesValidFrom = uint64(block.timestamp);
        emit LinesCancelled(msg.sender);
    }

    /// @notice Emergency stop: switch off the paymaster key. A new one only through the timelock.
    function disablePaymaster() external onlyStopper {
        paymaster = address(0);
        emit PaymasterDisabled(msg.sender);
    }

    function _postKey(uint64 epoch, bytes32 root) private pure returns (bytes32) {
        return keccak256(abi.encode(epoch, root));
    }

    function _allocatedAt(uint64 seq) private view returns (uint256) {
        return seq == 0 ? 0 : _ring[seq % RING].allocatedAfter;
    }

    // ================================================================ claims

    /// @notice Pay `wallet` its total on final list `seq`, minus what it was already paid. Anyone can submit; the
    /// list decides who is paid. `seq` may be any final list still kept (the last 33), so if a newer list's file is
    /// withheld, the older lists still pay. An older list never pays more: totals only go up from list to list, and
    /// `paid` remembers what was paid.
    /// @param seq A final, kept list.
    /// @param wallet The wallet on the list.
    /// @param total Its total on that list.
    /// @param proof The Merkle proof of (wallet, total).
    /// @return amount The amount paid; 0 if there is nothing new to pay.
    function claim(uint64 seq, address wallet, uint256 total, bytes32[] calldata proof)
        external
        nonReentrant
        returns (uint256 amount)
    {
        _claimOpen(wallet);
        return _claim(seq, wallet, total, proof);
    }

    /// @notice Claim from a line of a final master list, saving it first if it's newer than the vault's newest
    /// list (the first claimer of a night pays that one extra write). An older final line pays without being saved, so
    /// if a newer list's file is withheld, older nights still pay. Same limits as `claim`.
    /// @param l The line.
    /// @param wallet The wallet.
    /// @param total Its running total on that line.
    /// @param proof The Merkle proof of `total` in the line's root.
    /// @return amount What was paid.
    function claimFromLine(Line calldata l, address wallet, uint256 total, bytes32[] calldata proof)
        external
        nonReentrant
        returns (uint256 amount)
    {
        _claimOpen(wallet);
        uint64 h = head;
        if (h == 0 || _ring[h % RING].epoch < l.epoch) {
            _saveLine(l);
            return _claim(head, wallet, total, proof);
        }
        if (burnedPost[_postKey(l.epoch, l.post.root)]) revert RootBurned();
        uint64 postedAt = _checkLine(l);
        if (block.timestamp < uint256(postedAt) + CHALLENGE_PERIOD) revert NoFinalList();
        uint64 newest = newestFinal();
        if (newest == 0) revert NoFinalList();
        return _pay(newest, l.post.root, wallet, total, proof);
    }

    function _claimOpen(address wallet) private view {
        if (isPaused()) revert ClaimsPaused();
        if (wallet == address(this)) revert PaysVault();
    }

    function _claim(uint64 seq, address wallet, uint256 total, bytes32[] calldata proof) private returns (uint256) {
        uint64 newest = newestFinal();
        if (newest == 0) revert NoFinalList();
        if (seq > newest) revert NoList(seq);
        return _pay(newest, _kept(seq).root, wallet, total, proof);
    }

    function _pay(uint64 newest, bytes32 root, address wallet, uint256 total, bytes32[] calldata proof)
        private
        returns (uint256 amount)
    {
        if (!MerkleProof.verifyCalldata(proof, root, totalLeaf(wallet, total))) revert InvalidProof();
        uint256 already = paid[wallet];
        if (total <= already) return 0;
        amount = total - already;
        uint256 newPaidEver = uint256(paidEver) + amount;
        // never more than allocated by the newest final list
        if (newPaidEver > _ring[newest % RING].allocatedAfter) revert ExceedsAllocated();
        paid[wallet] = total;
        paidEver = uint128(newPaidEver);
        rewardToken.safeTransfer(wallet, amount);
        emit Claimed(wallet, amount, total, msg.sender);
    }

    // ================================================================ pause

    /// @notice Emergency stop: pause all claims, emergency claims included, for up to 48 hours. One pause for the
    /// whole vault, whoever presses it.
    function pause() external onlyStopper {
        if (isPaused()) revert PauseActive();
        if (pausedAt != 0 && block.timestamp < pauseEndsAt + PAUSE_COOLDOWN) {
            revert PauseCooldown(pauseEndsAt + PAUSE_COOLDOWN);
        }
        pausedAt = uint64(block.timestamp);
        pauseEndsAt = uint64(block.timestamp) + PAUSE_WINDOW;
        emit Paused(msg.sender, pauseEndsAt);
    }

    /// @notice End the pause early.
    function unpause() external onlyOwner {
        if (!isPaused()) revert NotPaused();
        pauseEndsAt = uint64(block.timestamp);
        emit Unpaused(msg.sender);
    }

    /// @notice End a deposit pause early. It only opens; it never moves money.
    function resumeDeposits() external onlyOwner {
        if (block.timestamp >= depositsPausedUntil) revert NotPaused();
        depositsPausedUntil = uint64(block.timestamp);
        emit DepositsResumed(msg.sender);
    }

    // ================================================================ emergency

    /// @notice After `emergencyTimeout` with no new live list, anyone may start the emergency: the counted pool is
    /// split by the newest live list's emergency split. Only live lists move the clock; cancelled lists roll it
    /// back. Deposits stay closed while the emergency is active.
    function activateEmergency() external nonReentrant {
        if (emergencyActive) revert EmergencyIsActive();
        uint64 h = head;
        if (h == 0) revert NoList(0);
        List storage l = _ring[h % RING];
        uint64 at = l.publishedAt + emergencyTimeout;
        if (block.timestamp < at) revert EmergencyTooEarly(at);
        emergencyActive = true; // also closes deposits while active
        emergencyEpoch = l.epoch;
        emergencyOpensAt = uint64(block.timestamp) + timelockDelay;
        emergencyRoot = l.emergencyRoot;
        emergencyTotal = l.emergencyTotal;
        emergencyPool = pool;
        pool = 0;
        emit EmergencyActivated(l.epoch, emergencyPool);
    }

    /// @notice Pay one line of the emergency split to its wallet. Anyone can submit. Rounds down; the dust stays
    /// in the vault.
    /// @param index The line number.
    /// @param wallet The wallet on that line.
    /// @param shares Its shares.
    /// @param proof The Merkle proof of the line.
    function emergencyClaim(uint256 index, address wallet, uint256 shares, bytes32[] calldata proof)
        external
        nonReentrant
    {
        if (!emergencyActive) revert EmergencyNotActive();
        // closed until `emergencyOpensAt`, and while a split change is queued: until applied or cancelled, but never
        // longer than `timelockDelay` after it could be applied (a leftover or unapplied change can't shut claims for
        // ever)
        if (block.timestamp < emergencyOpensAt || block.timestamp < uint256(queued[EMERGENCY_LIST].eta) + timelockDelay)
        {
            revert EmergencyTooEarly(emergencyOpensAt);
        }
        if (isPaused()) revert ClaimsPaused();
        if (wallet == address(this)) revert PaysVault();
        if (_emergencyClaimed.get(index)) revert AlreadyClaimed();
        if (!MerkleProof.verifyCalldata(proof, emergencyRoot, emergencyLeaf(emergencyEpoch, index, wallet, shares))) {
            revert InvalidProof();
        }
        uint256 payout = shares * emergencyPool / emergencyTotal; // rounds down: dust stays in the vault
        // a claim paying 0 would still mark the line, and block that share after a split change
        if (payout == 0) revert ZeroAmount();
        if (emergencyPaid + payout > emergencyPool) revert ExceedsPool();
        _emergencyClaimed.set(index);
        emergencyPaid += payout;
        rewardToken.safeTransfer(wallet, payout);
        emit EmergencyClaimed(index, wallet, payout);
    }

    // ================================================================ timelocked settings

    /// @notice Queue a settings change. It can be applied after `timelockDelay`.
    /// @param id The setting id (see the constants above).
    /// @param value The new value: a number, or an address in the low 20 bytes.
    function queue(bytes32 id, bytes32 value) external onlyOwner {
        // A split change only during the emergency's wait, so once claims open nobody can shut them again by
        // queueing one
        if (id == EMERGENCY_LIST && block.timestamp >= emergencyOpensAt) revert OutOfBounds();
        _validate(id, value);
        uint64 eta = uint64(block.timestamp) + timelockDelay;
        queued[id] = Queued(value, eta);
        emit ChangeQueued(id, value, eta);
    }

    /// @notice Cancel a queued change. The owner may cancel any; the guardian may cancel any except a change of
    /// the guardian or the watcher.
    /// @param id The setting id.
    function cancelQueued(bytes32 id) external {
        if (msg.sender != owner) {
            if (msg.sender != guardian) revert NotOwnerOrGuardian();
            if (id == GUARDIAN || id == SENTINEL) revert GuardianCannotCancel(id);
        }
        if (queued[id].eta == 0) revert NothingQueued(id);
        delete queued[id];
        emit ChangeCancelled(id, msg.sender);
    }

    /// @notice Apply a queued change once its wait is over. It is checked again first.
    /// @param id The setting id.
    function applyChange(bytes32 id) external onlyOwner {
        Queued memory q = queued[id];
        if (q.eta == 0) revert NothingQueued(id);
        if (block.timestamp < q.eta) revert TooEarly(q.eta);
        _validate(id, q.value); // a lock or another role change may have landed since queueing
        delete queued[id];
        uint256 v = uint256(q.value);
        address a = address(uint160(v));
        if (id == RATE) {
            uint16 top = rateBps > capRateBps ? rateBps : capRateBps; // lines already posted were made at the old rate
            if (top > uint16(v)) {
                capRateBps = top;
                _capRateAt = uint64(block.timestamp);
            }
            rateBps = uint16(v);
        } else if (id == FEE) {
            feeBps = uint16(v);
        } else if (id == FEE_CONTRACT) {
            feeContract = a;
        } else if (id == FEE_RECIPIENT) {
            feeRecipient = a;
        } else if (id == PAYMASTER) {
            paymaster = a;
        } else if (id == APPROVER) {
            approver = a;
            ++approverEra;
            linesValidFrom = uint64(block.timestamp); // unsaved nights signed by the old approver can no longer be used
        } else if (id == GUARDIAN) {
            guardian = a;
        } else if (id == SENTINEL) {
            sentinel = a;
        } else if (id == OWNER) {
            pendingOwner = a; // two steps: the new owner must accept
        } else if (id == CLOSE_DEPOSITS) {
            depositsClosed = true;
        } else if (id == PAUSE_DEPOSITS) {
            depositsPausedUntil = uint64(block.timestamp + v * 1 days);
        } else if (id == POOL_LIMIT) {
            poolLimit = v;
        } else if (id == LOCK_RATE) {
            rateLocked = true;
            delete queued[RATE];
        } else if (id == LOCK_FEE) {
            feeLocked = true;
            delete queued[FEE];
            delete queued[FEE_CONTRACT];
        } else if (id == LOCK_NO_POOL_LIMIT) {
            noPoolLimitLocked = true;
            delete queued[POOL_LIMIT];
        } else if (id == EMERGENCY_LIST) {
            List storage l = _kept(uint64(v));
            emergencyEpoch = l.epoch;
            emergencyRoot = l.emergencyRoot;
            emergencyTotal = l.emergencyTotal;
        }
        emit ChangeApplied(id, q.value);
    }

    /// @notice The pending owner accepts ownership.
    function acceptOwnership() external {
        if (msg.sender != pendingOwner || msg.sender == address(0)) revert NotPendingOwner();
        _checkNoClash(msg.sender, address(0), guardian, sentinel, paymaster, approver);
        owner = msg.sender;
        pendingOwner = address(0);
        emit OwnershipAccepted(msg.sender);
    }

    function _validate(bytes32 id, bytes32 value) private view {
        uint256 v = uint256(value);
        address a = address(uint160(v));
        if (id == RATE) {
            if (rateLocked) revert SettingLocked(id);
            if (v == 0 || v > MAX_RATE_BPS) revert OutOfBounds();
        } else if (id == FEE) {
            if (feeLocked) revert SettingLocked(id);
            if (v > MAX_FEE_BPS) revert OutOfBounds();
        } else if (id == FEE_CONTRACT) {
            if (feeLocked) revert SettingLocked(id);
            if (v >> 160 != 0 || (a != address(0) && a.code.length == 0)) revert OutOfBounds();
        } else if (id == FEE_RECIPIENT) {
            if (a == address(0) || v >> 160 != 0) revert ZeroAddress();
        } else if (id == PAYMASTER || id == APPROVER || id == GUARDIAN || id == SENTINEL || id == OWNER) {
            if (a == address(0) || v >> 160 != 0) revert ZeroAddress();
            _checkNoClash(
                id == OWNER ? a : owner,
                id == OWNER ? address(0) : pendingOwner, // a pending owner counts as a role
                id == GUARDIAN ? a : guardian,
                id == SENTINEL ? a : sentinel,
                id == PAYMASTER ? a : paymaster,
                id == APPROVER ? a : approver
            );
        } else if (id == PAUSE_DEPOSITS) {
            if (v == 0 || v > MAX_DEPOSIT_PAUSE_DAYS) revert OutOfBounds();
        } else if (id == POOL_LIMIT) {
            if (noPoolLimitLocked) revert SettingLocked(id);
            if (v == 0) revert OutOfBounds();
        } else if (id == LOCK_RATE) {
            if (rateLocked) revert SettingLocked(id);
        } else if (id == LOCK_FEE) {
            if (feeLocked) revert SettingLocked(id);
            // Never lock onto a fee contract whose answer can't be read or is above the cap: one sample quote, the same
            // path a deposit takes, when queued and again when applied. The vault itself is the sample depositor (a
            // real address, so a contract that refuses address 0 still answers). A contract that reverts counts as the
            // base fee, which deposits accept. One sample can't prove every deposit works.
            quoteFee(address(this), LOCK_FEE_SAMPLE);
        } else if (id == LOCK_NO_POOL_LIMIT) {
            if (noPoolLimitLocked) revert SettingLocked(id);
            if (poolLimit != NO_POOL_LIMIT) revert OutOfBounds(); // only "no limit" can be locked
        } else if (id == EMERGENCY_LIST) {
            // only once the emergency is on, and before anyone was paid from it: no split is ever paid twice
            if (!emergencyActive || emergencyPaid != 0) revert OutOfBounds();
            if (v > newestFinal()) revert NoList(uint64(v));
            _kept(uint64(v));
        } else if (id != CLOSE_DEPOSITS) {
            revert UnknownSetting(id);
        }
    }

    /// @dev No key holds two roles. Zero (a switched-off paymaster, no pending owner) never clashes.
    function _checkNoClash(address o, address po, address g, address s, address p, address ap) private pure {
        address[6] memory r = [o, po, g, s, p, ap];
        for (uint256 i; i < 6; ++i) {
            if (r[i] == address(0)) continue;
            for (uint256 j = i + 1; j < 6; ++j) {
                if (r[i] == r[j]) revert RoleClash();
            }
        }
    }

    // ================================================================ proof checker (7 days, never removed)

    /// @notice Queue a new proof checker and program. Waits 7 days; the guardian can cancel. The check can never
    /// be removed.
    /// @param checker The new proof checker (a contract).
    /// @param vkey The new program's verification key.
    function queueProofChecker(address checker, bytes32 vkey) external onlyOwner {
        _checkChecker(checker);
        uint64 eta = uint64(block.timestamp) + PROOF_CHECKER_DELAY;
        pendingChecker = CheckerChange(checker, vkey, eta);
        emit ProofCheckerQueued(checker, vkey, eta);
    }

    /// @notice Cancel the queued proof checker change. Owner or guardian.
    function cancelProofChecker() external {
        if (msg.sender != owner && msg.sender != guardian) revert NotOwnerOrGuardian();
        if (pendingChecker.eta == 0) revert NothingQueued(keccak256("PROOF_CHECKER"));
        delete pendingChecker;
        emit ProofCheckerCancelled(msg.sender);
    }

    /// @notice Apply the queued proof checker change once its wait is over.
    function applyProofChecker() external onlyOwner {
        CheckerChange memory c = pendingChecker;
        if (c.eta == 0) revert NothingQueued(keccak256("PROOF_CHECKER"));
        if (block.timestamp < c.eta) revert TooEarly(c.eta);
        delete pendingChecker;
        proofChecker = IProofChecker(c.checker);
        programVKey = c.vkey;
        emit ProofCheckerApplied(c.checker, c.vkey);
    }

    function _checkChecker(address checker) private view {
        if (checker == address(0) || checker.code.length == 0) revert ZeroAddress();
    }

    // ================================================================ rescue (never the reward token)

    /// @notice Queue sending out a token other than the reward token (or ETH) that ended up in the vault.
    /// @param token The token; zero = ETH.
    /// @param to The receiver.
    /// @param amount The amount.
    function queueRescue(address token, address to, uint256 amount) external onlyOwner {
        if (token == address(rewardToken)) revert CannotRescueRewardToken();
        if (to == address(0)) revert ZeroAddress();
        uint64 eta = uint64(block.timestamp) + timelockDelay;
        pendingRescue = Rescue(token, to, amount, eta);
        emit RescueQueued(token, to, amount, eta);
    }

    /// @notice Cancel the queued rescue. Owner or guardian.
    function cancelRescue() external {
        if (msg.sender != owner && msg.sender != guardian) revert NotOwnerOrGuardian();
        if (pendingRescue.eta == 0) revert NothingQueued(keccak256("RESCUE"));
        delete pendingRescue;
        emit RescueCancelled(msg.sender);
    }

    /// @notice Apply the queued rescue once its wait is over.
    function applyRescue() external onlyOwner nonReentrant {
        Rescue memory r = pendingRescue;
        if (r.eta == 0) revert NothingQueued(keccak256("RESCUE"));
        if (block.timestamp < r.eta) revert TooEarly(r.eta);
        delete pendingRescue;
        if (r.token == address(0)) {
            (bool ok,) = r.to.call{value: r.amount}("");
            if (!ok) revert TransferFailed();
        } else {
            IERC20(r.token).safeTransfer(r.to, r.amount);
        }
        emit Rescued(r.token, r.to, r.amount);
    }

    // No receive() or fallback(): plain ETH transfers revert. Forced ETH can be rescued through the queue.
}

src/interfaces/IFeeContract.sol

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

/// @title IFeeContract
/// @author Displaid
/// @notice Answers the fee on a deposit. Read-only: it can never move or hold money. A fee contract should have no
/// owner and no settings: a new rule is a new contract, which a vault can only switch to through its 24-hour wait.
interface IFeeContract {
    /// @notice The fee on this deposit. The vault refuses an answer above its 10% cap.
    /// @param depositor Who is depositing.
    /// @param amount The amount, fee included, in token units.
    /// @param totalBefore Everything ever paid into the vault before this deposit, in token units.
    /// @return The fee, in token units.
    function feeFor(address depositor, uint256 amount, uint256 totalBefore) external view returns (uint256);
}

src/interfaces/IListHub.sol

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

/// @title IListHub
/// @notice What a vault asks the list hub (its paymaster) about a night's master list.
interface IListHub {
    /// @notice One night's record. Zeros = no such night.
    /// @param batchRoot The master list's root.
    /// @return signer The approver that signed it.
    /// @return epoch Its day.
    /// @return postedAt When it was posted.
    /// @return cancelled Whether the watcher cancelled the whole night.
    function nightOf(bytes32 batchRoot)
        external
        view
        returns (address signer, uint64 epoch, uint64 postedAt, bool cancelled);
}

src/interfaces/IProofChecker.sol

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

/// @title IProofChecker
/// @notice The proof check a vault calls before it accepts a list. Same shape as SP1's verifier contracts.
interface IProofChecker {
    /// @notice Reverts unless `proofBytes` is a valid proof for `programVKey` and exactly these public values.
    /// @param programVKey The verification key of the program.
    /// @param publicValues The values the program committed.
    /// @param proofBytes The proof.
    function verifyProof(bytes32 programVKey, bytes calldata publicValues, bytes calldata proofBytes) external view;
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.