Skip to content
Verified contractExactMIT

CuratorRegistry

Address0x602955ca091559e83fcf4858a81bc58d0942a784
Balance

0 ETH

 

Transactions

2

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,359,870
Creation transaction
0x6f6320fcc9…da08c779da

27 files

src/CuratorRegistry.sol

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

import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";

import {AgentVault} from "./AgentVault.sol";
import {ICauseCatalog} from "./interfaces/ICauseCatalog.sol";
import {ICauseRegistry} from "./interfaces/ICauseRegistry.sol";
import {ICuratorRegistry} from "./interfaces/ICuratorRegistry.sol";
import {IEpochGovernor} from "./interfaces/IEpochGovernor.sol";
import {ITokenProfileRegistry} from "./interfaces/ITokenProfileRegistry.sol";
import {IERC8004IdentityRegistry} from "./interfaces/external/IERC8004IdentityRegistry.sol";
import {IEndaomentOrgFundFactory} from "./interfaces/external/IEndaomentOrgFundFactory.sol";
import {LabelLib} from "./libraries/LabelLib.sol";

/// @title CuratorRegistry
/// @notice One curator agent per cause category: its ERC-8004 identity (owned by this contract),
///         its signer (a 1Claw HSM key), its `AgentVault`, and its ENS label under
///         `agent.<parent>`. Agents submit weekly curations for the next epoch, which
///         `EpochGovernor` reads to build ballots.
/// @dev The registry is the source of truth; ERC-8004 is the public identity layer (a Draft
///      standard behind an upgradeable proxy), so nothing here depends on its state after
///      registration. A curation applies to exactly one epoch and can be replaced until that epoch
///      starts, so an agent can never reshape a running epoch's ballot. During the epoch the owner
///      can only drop it (`voidCurations`), for picks that are never served; ballots already
///      prepared keep their options.
contract CuratorRegistry is ICuratorRegistry, Ownable2Step, IERC721Receiver {
    /// @inheritdoc ICuratorRegistry
    uint8 public constant MAX_PICKS = 32;
    /// @inheritdoc ICuratorRegistry
    uint16 public constant MAX_WEIGHT = 10_000;

    uint16 internal constant REGION_SLOTS = 16;
    /// @dev Category masks are 64 bits wide.
    uint8 internal constant MAX_CATEGORIES = 64;
    /// @dev Regions in the taxonomy (`packages/sdk/src/catalog.ts`).
    uint8 public constant REGION_COUNT = 8;

    IERC8004IdentityRegistry public immutable identityRegistry;
    ICauseCatalog public immutable catalog;
    ICauseRegistry public immutable causeRegistry;
    IEndaomentOrgFundFactory public immutable endaomentFactory;
    IERC20 public immutable usdc;
    /// @inheritdoc ICuratorRegistry
    bytes32 public immutable agentsNode;

    IEpochGovernor public governor;

    mapping(uint8 categoryBit => Agent) internal _agents;
    mapping(bytes32 labelhash => uint8) internal _categoryPlusOneByLabel;
    mapping(bytes32 node => uint8) internal _categoryPlusOneByNode;
    mapping(uint16 bucket => mapping(uint256 epoch => Curation)) internal _curations;

    /// @param initialOwner The platform.
    /// @param identityRegistry_ ERC-8004 Identity Registry.
    /// @param profileRegistry Token profile registry (for the parent node; the label `agent` must be
    ///        reserved there so no token can take it).
    constructor(
        address initialOwner,
        IERC8004IdentityRegistry identityRegistry_,
        ICauseCatalog catalog_,
        ICauseRegistry causeRegistry_,
        IEndaomentOrgFundFactory endaomentFactory_,
        IERC20 usdc_,
        ITokenProfileRegistry profileRegistry
    ) Ownable(initialOwner) {
        if (
            address(identityRegistry_) == address(0) || address(catalog_) == address(0)
                || address(causeRegistry_) == address(0) || address(endaomentFactory_) == address(0)
                || address(usdc_) == address(0) || address(profileRegistry) == address(0)
        ) revert ZeroAddress();
        identityRegistry = identityRegistry_;
        catalog = catalog_;
        causeRegistry = causeRegistry_;
        endaomentFactory = endaomentFactory_;
        usdc = usdc_;
        agentsNode = keccak256(abi.encodePacked(profileRegistry.parentNode(), keccak256("agent")));
    }

    // ------------------------------------------------------------------ admin

    /// @notice Sets the epoch governor whose clock curations follow. Once.
    function setGovernor(IEpochGovernor governor_) external onlyOwner {
        if (address(governor) != address(0)) revert GovernorAlreadySet();
        if (address(governor_) == address(0)) revert ZeroAddress();
        governor = governor_;
        emit GovernorSet(address(governor_));
    }

    /// @inheritdoc ICuratorRegistry
    function registerAgent(
        uint8 categoryBit,
        string calldata label,
        address signer,
        string calldata agentURI,
        string calldata description
    ) external onlyOwner returns (uint256 agentId, address vault) {
        if (categoryBit >= MAX_CATEGORIES) {
            revert InvalidCategory(categoryBit);
        }
        if (signer == address(0)) revert ZeroAddress();
        Agent storage a = _agents[categoryBit];
        if (a.vault != address(0)) revert AgentExists(categoryBit);
        bytes32 labelhash = LabelLib.validate(label);
        if (_categoryPlusOneByLabel[labelhash] != 0) revert LabelTaken(labelhash);

        vault = address(
            new AgentVault{salt: bytes32(uint256(categoryBit))}(
                this, categoryBit, usdc, catalog, causeRegistry, endaomentFactory
            )
        );

        IERC8004IdentityRegistry.MetadataEntry[] memory meta =
            new IERC8004IdentityRegistry.MetadataEntry[](2);
        meta[0] = IERC8004IdentityRegistry.MetadataEntry(
            "varada.category", abi.encodePacked(categoryBit)
        );
        meta[1] = IERC8004IdentityRegistry.MetadataEntry("varada.vault", abi.encodePacked(vault));
        agentId = identityRegistry.register(agentURI, meta);

        a.agentId = agentId;
        a.signer = signer;
        a.vault = vault;
        a.active = true;
        a.labelhash = labelhash;
        a.label = label;
        a.description = description;
        _categoryPlusOneByLabel[labelhash] = categoryBit + 1;
        _categoryPlusOneByNode[keccak256(abi.encodePacked(agentsNode, labelhash))] = categoryBit + 1;
        emit AgentRegistered(categoryBit, agentId, label, signer, vault);
    }

    function setSigner(uint8 categoryBit, address signer) external onlyOwner {
        if (signer == address(0)) revert ZeroAddress();
        _agent(categoryBit).signer = signer;
        emit SignerSet(categoryBit, signer);
    }

    /// @notice Pauses or resumes an agent. A paused agent cannot submit, and its curations are
    ///         ignored by the governor (ballots fall back to rotation) for every epoch while it
    ///         is paused. To drop one epoch's picks only, use `voidCurations`.
    function setActive(uint8 categoryBit, bool active) external onlyOwner {
        _agent(categoryBit).active = active;
        emit ActiveSet(categoryBit, active);
    }

    /// @inheritdoc ICuratorRegistry
    function voidCurations(uint256 epoch, uint16[] calldata buckets) external onlyOwner {
        for (uint256 i; i < buckets.length; ++i) {
            delete _curations[buckets[i]][epoch];
            emit CurationVoided(buckets[i], epoch);
        }
    }

    function setAgentURI(uint8 categoryBit, string calldata agentURI) external onlyOwner {
        identityRegistry.setAgentURI(_agent(categoryBit).agentId, agentURI);
        emit AgentURISet(categoryBit, agentURI);
    }

    function setDescription(uint8 categoryBit, string calldata description) external onlyOwner {
        _agent(categoryBit).description = description;
        emit DescriptionSet(categoryBit, description);
    }

    /// @notice Links the agent's vault as its ERC-8004 agent wallet. `signature` is the agent
    ///         signer's EIP-712 signature of `AgentWalletSet(agentId, vault, owner = this, deadline)`
    ///         in the Identity Registry's domain; the vault validates it by ERC-1271, and only for
    ///         the Identity Registry during this call.
    function linkAgentWallet(uint8 categoryBit, uint256 deadline, bytes calldata signature)
        external
        onlyOwner
    {
        Agent storage a = _agent(categoryBit);
        AgentVault vault = AgentVault(a.vault);
        vault.setWalletLinkVerifier(address(identityRegistry));
        identityRegistry.setAgentWallet(a.agentId, address(vault), deadline, signature);
        vault.setWalletLinkVerifier(address(0));
        emit AgentWalletLinked(categoryBit, a.vault);
    }

    // ------------------------------------------------------------------ agents

    /// @inheritdoc ICuratorRegistry
    function submitCurations(
        uint8 categoryBit,
        uint256 epoch,
        uint32 catalogVersion,
        bytes32 reportRef,
        CurationInput[] calldata curations
    ) external {
        Agent storage a = _agent(categoryBit);
        if (msg.sender != a.signer) revert NotSigner(categoryBit, msg.sender);
        if (!a.active) revert AgentInactive(categoryBit);
        if (epoch != currentEpoch() + 1) revert NotNextEpoch(epoch);
        if (catalogVersion == 0 || catalogVersion > catalog.latestVersion()) {
            revert InvalidCuration();
        }

        uint256 seen;
        for (uint256 i; i < curations.length; ++i) {
            CurationInput calldata c = curations[i];
            if (c.regionBit >= REGION_COUNT) revert InvalidRegion(c.regionBit);
            if ((seen >> c.regionBit) & 1 == 1) revert InvalidCuration();
            seen |= uint256(1) << c.regionBit;
            if (c.count > MAX_PICKS || c.weight > MAX_WEIGHT) revert InvalidCuration();
            if ((c.count == 0) != (c.picksRoot == bytes32(0))) revert InvalidCuration();

            uint16 bucket = uint16(categoryBit) * REGION_SLOTS + c.regionBit;
            _curations[bucket][epoch] = Curation(c.picksRoot, c.count, c.weight, catalogVersion);
            emit CurationSet(bucket, epoch, c.picksRoot, c.count, c.weight, catalogVersion);
        }
        emit CurationsSubmitted(categoryBit, epoch, catalogVersion, reportRef);
    }

    // ------------------------------------------------------------------ views

    /// @inheritdoc ICuratorRegistry
    function agentOf(uint8 categoryBit) external view returns (Agent memory) {
        return _agents[categoryBit];
    }

    /// @inheritdoc ICuratorRegistry
    function isRegistered(uint8 categoryBit) external view returns (bool) {
        return _agents[categoryBit].vault != address(0);
    }

    /// @inheritdoc ICuratorRegistry
    function signerOf(uint8 categoryBit) external view returns (address) {
        return _agents[categoryBit].signer;
    }

    /// @inheritdoc ICuratorRegistry
    function categoryOfLabelhash(bytes32 labelhash) external view returns (bool, uint8) {
        uint8 c = _categoryPlusOneByLabel[labelhash];
        return c == 0 ? (false, 0) : (true, c - 1);
    }

    /// @inheritdoc ICuratorRegistry
    function categoryOfNode(bytes32 node) external view returns (bool, uint8) {
        uint8 c = _categoryPlusOneByNode[node];
        return c == 0 ? (false, 0) : (true, c - 1);
    }

    /// @inheritdoc ICuratorRegistry
    function curationOf(uint16 bucket, uint256 epoch) external view returns (Curation memory) {
        return _curations[bucket][epoch];
    }

    /// @inheritdoc ICuratorRegistry
    function curationsFor(uint256 epoch, uint32 catalogVersion, uint16[] calldata buckets)
        external
        view
        returns (Curation[] memory out)
    {
        out = new Curation[](buckets.length);
        for (uint256 i; i < buckets.length; ++i) {
            uint16 bucket = buckets[i];
            // forge-lint: disable-next-line(unsafe-typecast)
            uint8 categoryBit = uint8(bucket / REGION_SLOTS);
            if (!_agents[categoryBit].active) continue;
            Curation storage c = _curations[bucket][epoch];
            if (c.count == 0 || c.weight == 0 || c.catalogVersion != catalogVersion) continue;
            out[i] = c;
        }
    }

    /// @inheritdoc ICuratorRegistry
    function currentEpoch() public view returns (uint256) {
        if (address(governor) == address(0)) revert GovernorNotSet();
        return governor.currentEpoch();
    }

    /// @inheritdoc IERC721Receiver
    /// @dev Accepts only the agent identities this contract registers.
    function onERC721Received(address, address, uint256, bytes calldata)
        external
        view
        returns (bytes4)
    {
        if (msg.sender != address(identityRegistry)) revert ZeroAddress();
        return IERC721Receiver.onERC721Received.selector;
    }

    function _agent(uint8 categoryBit) internal view returns (Agent storage a) {
        a = _agents[categoryBit];
        if (a.vault == address(0)) revert UnknownAgent(categoryBit);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * The initial owner is set to the address provided by the deployer. This can
 * later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        return _pendingOwner;
    }

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     *
     * Setting `newOwner` to the zero address is allowed; this can be used to cancel an initiated ownership transfer.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

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

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

pragma solidity >=0.5.0;

/**
 * @dev Interface of the ERC-1271 standard signature validation method for
 * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
 */
interface IERC1271 {
    /**
     * @dev Should return whether the signature provided is valid for the provided data
     * @param hash      Hash of the data to be signed
     * @param signature Signature byte array associated with `hash`
     */
    function isValidSignature(bytes32 hash, bytes calldata signature) external view returns (bytes4 magicValue);
}

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

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

pragma solidity >=0.6.2;

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

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

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

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

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

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

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

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

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

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

pragma solidity >=0.4.16;

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

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

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

pragma solidity >=0.4.16;

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

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

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

pragma solidity >=0.6.2;

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

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

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

pragma solidity >=0.4.16;

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

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

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

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

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

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

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

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

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

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

pragma solidity >=0.6.2;

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

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

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

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

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol

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

pragma solidity >=0.5.0;

/**
 * @title ERC-721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC-721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 *
 * IMPORTANT: Deprecated in favor of accessing `msg.sender` and `msg.data` directly. This contract, along with its
 * `_msgSender`, `_msgData` and `_contextSuffixLength` functions, will be removed in v6.0, where contracts read
 * `msg.sender` and `msg.data` directly. Contracts that override `_msgSender`/`_msgData` (e.g. to support
 * meta-transactions) will lose that extension point; plan the migration before upgrading.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

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

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

pragma solidity ^0.8.20;

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

/**
 * @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].
 *
 * IMPORTANT: Deprecated. This storage-based reentrancy guard will be removed and replaced
 * by the {ReentrancyGuardTransient} variant in v6.0.
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuard {
    using StorageSlot for bytes32;

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

    // 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;

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

    constructor() {
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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();
    }

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().getUint256Slot().value = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _reentrancyGuardStorageSlot().getUint256Slot().value = 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 _reentrancyGuardStorageSlot().getUint256Slot().value == ENTERED;
    }

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

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

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

pragma solidity ^0.8.20;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

pragma solidity >=0.4.16;

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

src/AgentVault.sol

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

import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";

import {ICauseCatalog} from "./interfaces/ICauseCatalog.sol";
import {ICauseRegistry} from "./interfaces/ICauseRegistry.sol";
import {ICuratorRegistry} from "./interfaces/ICuratorRegistry.sol";
import {IEndaomentOrg} from "./interfaces/external/IEndaomentOrg.sol";
import {IEndaomentOrgFundFactory} from "./interfaces/external/IEndaomentOrgFundFactory.sol";

interface IOwned {
    function owner() external view returns (address);
}

/// @title AgentVault
/// @notice USDC donation vault of one curator agent. Anyone can donate; only the agent's signer can
///         give, and only to an unblocked catalogue org inside one of the agent's own cause buckets,
///         through the Endaoment factory. There is no withdrawal and no arbitrary call.
/// @dev Deployed by `CuratorRegistry`; the platform (the registry's owner) sets the per-epoch cap
///      and can pause. Credit is opt-in: `donate(amount, true)` names the donor in `Donated`; plain
///      transfers (including x402 settlements) only add to the balance.
contract AgentVault is IERC1271, ReentrancyGuard {
    using SafeERC20 for IERC20;

    uint16 internal constant REGION_SLOTS = 16;
    bytes4 internal constant ERC1271_MAGIC = 0x1626ba7e;
    /// @dev Transient slot: the address allowed to check a signature, set only during
    ///      `CuratorRegistry.linkAgentWallet`. keccak256("varada.AgentVault.walletLinkVerifier")
    bytes32 internal constant _LINK_VERIFIER_SLOT =
        0xec5aff2c0d8b3f7adff65d7eccf95d703e57e5454f4948c3f8d8f9f24c5e08b4;

    ICuratorRegistry public immutable curators;
    uint8 public immutable categoryBit;
    IERC20 public immutable usdc;
    ICauseCatalog public immutable catalog;
    ICauseRegistry public immutable causeRegistry;
    IEndaomentOrgFundFactory public immutable endaomentFactory;

    /// @notice Largest total the agent may give in one epoch (USDC, 6 decimals). Zero: no gifts.
    uint256 public maxGivePerEpoch;
    bool public paused;
    mapping(uint256 epoch => uint256) public givenIn;

    event Donated(address indexed from, uint256 amount, bool credit);
    event Given(
        uint256 indexed epoch,
        uint8 indexed regionBit,
        bytes32 indexed orgId,
        address org,
        uint256 amount
    );
    event MaxGivePerEpochSet(uint256 amount);
    event PausedSet(bool paused);

    error NotSigner(address caller);
    error NotPlatform(address caller);
    error NotCurators(address caller);
    error AgentInactive();
    error Paused();
    error ZeroAmount();
    error InvalidRegion(uint8 regionBit);
    error NotInBucket(bytes32 orgId);
    error OrgBlocked(bytes32 orgId);
    error EpochCapExceeded(uint256 epoch, uint256 requested, uint256 remaining);
    error OrgAddressMismatch(bytes32 orgId, address expected, address actual);
    error AllowanceNotCleared(address spender);

    constructor(
        ICuratorRegistry curators_,
        uint8 categoryBit_,
        IERC20 usdc_,
        ICauseCatalog catalog_,
        ICauseRegistry causeRegistry_,
        IEndaomentOrgFundFactory endaomentFactory_
    ) {
        curators = curators_;
        categoryBit = categoryBit_;
        usdc = usdc_;
        catalog = catalog_;
        causeRegistry = causeRegistry_;
        endaomentFactory = endaomentFactory_;
    }

    modifier onlyPlatform() {
        if (msg.sender != IOwned(address(curators)).owner()) revert NotPlatform(msg.sender);
        _;
    }

    // ------------------------------------------------------------------ donors

    /// @notice Donates `amount` USDC (approve first). `credit` opts in to being named.
    function donate(uint256 amount, bool credit) external nonReentrant {
        if (amount == 0) revert ZeroAmount();
        usdc.safeTransferFrom(msg.sender, address(this), amount);
        emit Donated(msg.sender, amount, credit);
    }

    // ------------------------------------------------------------------ agent

    /// @notice Gives `amount` USDC to catalogue org `orgId`, entry `catalogIndex` of the bucket
    ///         `(categoryBit, regionBit)` in the latest catalogue version.
    function give(
        uint8 regionBit,
        bytes32 orgId,
        uint32 catalogIndex,
        bytes32[] calldata proof,
        uint256 amount
    ) external nonReentrant returns (address org) {
        ICuratorRegistry.Agent memory agent = curators.agentOf(categoryBit);
        if (msg.sender != agent.signer) revert NotSigner(msg.sender);
        if (!agent.active) revert AgentInactive();
        if (paused) revert Paused();
        if (amount == 0) revert ZeroAmount();
        if (regionBit >= REGION_SLOTS) revert InvalidRegion(regionBit);

        uint16 bucket = uint16(categoryBit) * REGION_SLOTS + regionBit;
        uint32 version = catalog.latestVersion();
        if (version == 0 || !catalog.verify(version, bucket, catalogIndex, orgId, proof)) {
            revert NotInBucket(orgId);
        }
        if (causeRegistry.isBlocked(keccak256(abi.encode(orgId)))) revert OrgBlocked(orgId);

        uint256 epoch = curators.currentEpoch();
        uint256 used = givenIn[epoch];
        if (used + amount > maxGivePerEpoch) {
            revert EpochCapExceeded(
                epoch, amount, maxGivePerEpoch > used ? maxGivePerEpoch - used : 0
            );
        }
        givenIn[epoch] = used + amount;

        org = endaomentFactory.computeOrgAddress(orgId);
        if (org.code.length == 0) {
            usdc.forceApprove(address(endaomentFactory), amount);
            address deployed = endaomentFactory.deployOrgAndDonate(orgId, amount);
            if (deployed != org) revert OrgAddressMismatch(orgId, org, deployed);
            _requireCleared(address(endaomentFactory));
        } else {
            usdc.forceApprove(org, amount);
            IEndaomentOrg(org).donate(amount);
            _requireCleared(org);
        }
        emit Given(epoch, regionBit, orgId, org, amount);
    }

    /// @inheritdoc IERC1271
    /// @dev Valid only for the ERC-8004 wallet link: the caller must be the verifier that
    ///      `CuratorRegistry.linkAgentWallet` set for this transaction, the vault must not be
    ///      paused, and the agent's current signer must have signed `hash`. Any other caller
    ///      (a token checking a permit, for example) gets the invalid value.
    function isValidSignature(bytes32 hash, bytes calldata signature)
        external
        view
        returns (bytes4)
    {
        address verifier;
        assembly ("memory-safe") {
            verifier := tload(_LINK_VERIFIER_SLOT)
        }
        if (verifier == address(0) || msg.sender != verifier || paused) return 0xffffffff;
        (address recovered, ECDSA.RecoverError err,) = ECDSA.tryRecover(hash, signature);
        if (
            err == ECDSA.RecoverError.NoError && recovered != address(0)
                && recovered == curators.signerOf(categoryBit)
        ) return ERC1271_MAGIC;
        return 0xffffffff;
    }

    /// @notice Sets the one address allowed to check a signature for the rest of this transaction.
    ///         Zero closes it. Only the curator registry, around its wallet-link call.
    function setWalletLinkVerifier(address verifier) external {
        if (msg.sender != address(curators)) revert NotCurators(msg.sender);
        assembly ("memory-safe") {
            tstore(_LINK_VERIFIER_SLOT, verifier)
        }
    }

    // ------------------------------------------------------------------ platform

    function setMaxGivePerEpoch(uint256 amount) external onlyPlatform {
        maxGivePerEpoch = amount;
        emit MaxGivePerEpochSet(amount);
    }

    function setPaused(bool paused_) external onlyPlatform {
        paused = paused_;
        emit PausedSet(paused_);
    }

    function _requireCleared(address spender) private {
        if (usdc.allowance(address(this), spender) != 0) {
            usdc.forceApprove(spender, 0);
            if (usdc.allowance(address(this), spender) != 0) revert AllowanceNotCleared(spender);
        }
    }
}

src/interfaces/ICauseCatalog.sol

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

/// @title ICauseCatalog
/// @notice Versioned Merkle commitment to every eligible nonprofit, grouped into buckets of
///         `category x region`. A leaf is `(uint16 bucket, uint32 index, bytes32 orgId)` hashed as
///         an OpenZeppelin standard Merkle tree leaf; entries of a bucket are numbered
///         `0..bucketSize-1` in ascending orgId order. An org appears once in every bucket it
///         belongs to.
/// @dev `bucket = categoryBit * REGION_SLOTS + regionBit`. A focus is a pair of masks
///      (`uint64` categories, `uint16` regions); its pool is the concatenation, in ascending
///      bucket order, of every non-empty bucket inside it.
interface ICauseCatalog {
    /// @notice Emitted when a catalogue version is published. It applies to epochs starting
    ///         after `setAt`.
    event CatalogVersionSet(
        uint32 indexed version, bytes32 root, bytes32 swarmRef, uint256 entries, uint64 setAt
    );

    error ZeroRoot();
    error InvalidBucketCount(uint256 count);
    error UnknownVersion(uint32 version);
    error PoolIndexOutOfRange(uint256 poolIndex, uint256 poolSize);

    /// @notice Region slots per category in the bucket layout.
    function REGION_SLOTS() external view returns (uint16);

    /// @notice Publishes a new catalogue version. Owner only.
    /// @param root Merkle root of the catalogue.
    /// @param bucketSizes Entries per bucket; length a multiple of `REGION_SLOTS`, at most
    ///        `64 * REGION_SLOTS`.
    /// @param swarmRef Swarm reference of the published snapshot (files and full tree).
    function setVersion(bytes32 root, uint32[] calldata bucketSizes, bytes32 swarmRef)
        external
        returns (uint32 version);

    /// @notice Latest version (zero before the first).
    function latestVersion() external view returns (uint32);

    /// @notice Latest version set strictly before `timestamp` (zero if none).
    function versionAt(uint256 timestamp) external view returns (uint32);

    function rootOf(uint32 version) external view returns (bytes32);
    function swarmRefOf(uint32 version) external view returns (bytes32);
    function setAtOf(uint32 version) external view returns (uint64);
    function bucketSizesOf(uint32 version) external view returns (uint32[] memory);

    /// @notice Whether `bucket` lies inside the focus `(categoryMask, regionMask)`.
    function inFocus(uint16 bucket, uint64 categoryMask, uint16 regionMask)
        external
        pure
        returns (bool);

    /// @notice Non-empty buckets of a focus with their sizes, in ascending bucket order.
    function focusBuckets(uint32 version, uint64 categoryMask, uint16 regionMask)
        external
        view
        returns (uint16[] memory buckets, uint32[] memory sizes);

    /// @notice Number of entries in a focus pool.
    function poolSize(uint32 version, uint64 categoryMask, uint16 regionMask)
        external
        view
        returns (uint256);

    /// @notice Bucket and in-bucket index of entry `poolIndex` of a focus pool.
    function locate(uint32 version, uint64 categoryMask, uint16 regionMask, uint256 poolIndex)
        external
        view
        returns (uint16 bucket, uint32 index);

    /// @notice Whether `(bucket, index, orgId)` is an entry of `version`.
    function verify(
        uint32 version,
        uint16 bucket,
        uint32 index,
        bytes32 orgId,
        bytes32[] calldata proof
    ) external view returns (bool);

    /// @notice Leaf hash of an entry (OpenZeppelin standard Merkle tree encoding).
    function leafHash(uint16 bucket, uint32 index, bytes32 orgId) external pure returns (bytes32);
}

src/interfaces/ICauseRegistry.sol

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

/// @title ICauseRegistry
/// @notice Allowlist of nonprofit causes eligible to receive funds.
interface ICauseRegistry {
    /// @notice A registered cause.
    /// @param orgId Endaoment org id: bytes32 of the EIN digits (no hyphen), left-aligned.
    /// @param orgAddress CREATE2 address of the Endaoment org entity (may not be deployed yet).
    /// @param metadataURI Cause metadata URI.
    /// @param active Whether the cause can currently be voted for and paid.
    struct Cause {
        bytes32 orgId;
        address orgAddress;
        string metadataURI;
        bool active;
    }

    /// @notice Emitted when a cause is added.
    event CauseAdded(bytes32 indexed causeId, address payout);
    /// @dev `payout` in CauseAdded/PayoutUpdated is the org's CREATE2 address.

    /// @notice Emitted when a cause is deactivated.
    event CauseDeactivated(bytes32 indexed causeId);

    /// @notice Emitted when a cause's payout address changes.
    event PayoutUpdated(bytes32 indexed causeId, address oldPayout, address newPayout);

    /// @notice Emitted when an account is allowed or disallowed to materialize causes.
    event MaterializerSet(address indexed account, bool allowed);

    /// @notice Emitted when a catalogue org is written to the registry on demand (as active).
    event CauseMaterialized(bytes32 indexed causeId, bytes32 indexed orgId, address payout);

    error NotMaterializer(address caller);
    error CauseAlreadyExists(bytes32 causeId);
    error CauseNotFound(bytes32 causeId);
    error ZeroPayout();
    error ZeroOrgId();

    /// @notice Adds a cause. `causeId` is the keccak256 of the nonprofit's organization id string.
    ///         `orgAddress` is the org's CREATE2 address (factory.computeOrgAddress(orgId)).
    function addCause(
        bytes32 causeId,
        bytes32 orgId,
        address orgAddress,
        string calldata metadataURI
    ) external;

    /// @notice Deactivates a cause.
    function deactivateCause(bytes32 causeId) external;

    /// @notice Records `orgId` as a deactivated cause whether or not it was ever added, so a
    ///         catalogue org that must not receive funds can never be drawn, pinned or
    ///         materialized. Owner only. Returns its cause id.
    function blockOrg(bytes32 orgId) external returns (bytes32 causeId);

    /// @notice Allows or disallows `account` (the epoch governor) to materialize causes.
    function setMaterializer(address account, bool allowed) external;

    /// @notice Writes catalogue org `orgId` as an active cause with its factory-computed address,
    ///         unless a cause with its id already exists (active or not), which is left untouched.
    ///         Materializers only. Returns the cause id, `keccak256(abi.encode(orgId))`.
    function materialize(bytes32 orgId) external returns (bytes32 causeId);

    /// @notice Whether `causeId` was ever added, materialized or blocked.
    function exists(bytes32 causeId) external view returns (bool);

    /// @notice Whether `causeId` exists and is deactivated (blocked from ballots and payouts).
    function isBlocked(bytes32 causeId) external view returns (bool);

    /// @notice Whether `account` may materialize causes.
    function isMaterializer(address account) external view returns (bool);

    /// @notice Changes a cause's org address (for example if the org was re-derived).
    function updatePayout(bytes32 causeId, address newPayout) external;

    /// @notice Returns a cause.
    function getCause(bytes32 causeId) external view returns (Cause memory);

    /// @notice Endaoment org id and org address of a cause, without its metadata string. Reverts
    ///         `CauseNotFound` for an unknown cause (deactivated causes still resolve).
    function orgOf(bytes32 causeId) external view returns (bytes32 orgId, address orgAddress);

    /// @notice Whether `causeId` exists and is active.
    function isActive(bytes32 causeId) external view returns (bool);

    /// @notice Number of causes ever added.
    function causeCount() external view returns (uint256);

    /// @notice Cause id at `index` in insertion order.
    function causeIdAt(uint256 index) external view returns (bytes32);
}

src/interfaces/ICuratorRegistry.sol

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

/// @title ICuratorRegistry
/// @notice One curator agent per cause category, named `<label>.agent.<parent>`. Each week an
///         agent submits, for the next epoch, per region: a Merkle root of up to `MAX_PICKS` ranked
///         catalogue picks and an urgency weight. `EpochGovernor` reads them to build ballots.
/// @dev A pick leaf is the OpenZeppelin standard-tree leaf of
///      `(uint8 rank, uint32 catalogIndex, bytes32 orgId)`; ranks run `0..count-1`. Picks are not
///      checked on submission: the governor skips any pick whose catalogue entry is not that org.
interface ICuratorRegistry {
    struct Agent {
        uint256 agentId;
        address signer;
        address vault;
        bool active;
        bytes32 labelhash;
        string label;
        string description;
    }

    struct Curation {
        bytes32 picksRoot;
        uint8 count;
        uint16 weight;
        uint32 catalogVersion;
    }

    struct CurationInput {
        uint8 regionBit;
        bytes32 picksRoot;
        uint8 count;
        uint16 weight;
    }

    event AgentRegistered(
        uint8 indexed categoryBit,
        uint256 indexed agentId,
        string label,
        address signer,
        address vault
    );
    event SignerSet(uint8 indexed categoryBit, address signer);
    event ActiveSet(uint8 indexed categoryBit, bool active);
    event AgentURISet(uint8 indexed categoryBit, string agentURI);
    event DescriptionSet(uint8 indexed categoryBit, string description);
    event AgentWalletLinked(uint8 indexed categoryBit, address wallet);
    event GovernorSet(address governor);
    /// @notice One per region in a weekly submission; `reportRef` is the Swarm reference of the
    ///         full report (picks with scores, reasons, sources, and the newsletter).
    event CurationSet(
        uint16 indexed bucket,
        uint256 indexed epoch,
        bytes32 picksRoot,
        uint8 count,
        uint16 weight,
        uint32 catalogVersion
    );
    event CurationsSubmitted(
        uint8 indexed categoryBit, uint256 indexed epoch, uint32 catalogVersion, bytes32 reportRef
    );
    /// @notice The owner dropped `bucket`'s curation for `epoch` (`voidCurations`).
    event CurationVoided(uint16 indexed bucket, uint256 indexed epoch);

    error ZeroAddress();
    error UnknownAgent(uint8 categoryBit);
    error AgentExists(uint8 categoryBit);
    error LabelTaken(bytes32 labelhash);
    error InvalidCategory(uint8 categoryBit);
    error InvalidRegion(uint8 regionBit);
    error NotSigner(uint8 categoryBit, address caller);
    error AgentInactive(uint8 categoryBit);
    error NotNextEpoch(uint256 epoch);
    error InvalidCuration();
    error GovernorAlreadySet();
    error GovernorNotSet();

    function MAX_PICKS() external view returns (uint8);
    function MAX_WEIGHT() external view returns (uint16);

    function registerAgent(
        uint8 categoryBit,
        string calldata label,
        address signer,
        string calldata agentURI,
        string calldata description
    ) external returns (uint256 agentId, address vault);

    function submitCurations(
        uint8 categoryBit,
        uint256 epoch,
        uint32 catalogVersion,
        bytes32 reportRef,
        CurationInput[] calldata curations
    ) external;

    /// @notice Owner only. Deletes the curations of `buckets` for `epoch`, so ballots and rounds of
    ///         that epoch not yet prepared skip them and fill with rotation. For picks committed
    ///         but never served, or a bad root: unlike pausing the agent, it touches one epoch
    ///         only, so the agent stays active and can submit the next epoch's picks. Only the next
    ///         epoch's curation can be submitted again.
    function voidCurations(uint256 epoch, uint16[] calldata buckets) external;

    function agentOf(uint8 categoryBit) external view returns (Agent memory);
    function isRegistered(uint8 categoryBit) external view returns (bool);
    function signerOf(uint8 categoryBit) external view returns (address);
    function categoryOfLabelhash(bytes32 labelhash)
        external
        view
        returns (bool found, uint8 categoryBit);
    function categoryOfNode(bytes32 node) external view returns (bool found, uint8 categoryBit);
    /// @notice Namehash of `agent.<parent>`.
    function agentsNode() external view returns (bytes32);

    function curationOf(uint16 bucket, uint256 epoch) external view returns (Curation memory);

    /// @notice Usable curations of `buckets` for `epoch` under `catalogVersion`: zeroed for a bucket
    ///         with no agent, an inactive agent, nothing submitted (or voided), or another catalogue
    ///         version.
    function curationsFor(uint256 epoch, uint32 catalogVersion, uint16[] calldata buckets)
        external
        view
        returns (Curation[] memory);

    function currentEpoch() external view returns (uint256);
}

src/interfaces/IEpochGovernor.sol

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

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

/// @title IEpochGovernor
/// @notice Weekly epochs in which token holders choose the cause receiving the cause pool.
/// @dev Each epoch of a token is a poll on the pluggable voting scheme. Its ballot is prepared at
///      the start of the epoch from the token's cause focus (fixed at launch) and the cause
///      catalogue version in effect at that time:
///      - up to `PINNED_MAX` causes pinned by the token's controller (its "shortlist"), each proven
///        to be a catalogue entry inside the focus;
///      - then curator agents' picks for the focus buckets, when published;
///      - the rest filled by rotation: draw `k` is pool entry
///        `keccak256(abi.encode(token, epoch, version, k)) % poolSize`, skipping blocked causes and
///        repeats, so over time every charity in the focus reaches a ballot. When the pool is not
///        larger than the free slots, the whole pool is taken in order.
///      Ballot size: the owner sets a protocol cap (`ballotSizeCap`, `MIN_OPTIONS..MAX_OPTIONS`,
///      `MAX_OPTIONS` by default) and a token's controller may choose its own size
///      (`setBallotSize`, zero to follow the cap). An epoch gets
///      `min(choice or cap, cap, scheme.MAX_OPTIONS())`. Pins and the size follow one timing rule:
///      both are read when the epoch's ballot is prepared, so a change applies to the current
///      epoch while its ballot is unprepared (nobody can vote before that) and otherwise from the
///      next epoch. A prepared ballot keeps its size (`ballotSizeFor`) and its option count
///      (`ballotCommitment`), which closing and finalizing use. Smaller ballots cost voters less:
///      the scheme packs three counters per encrypted tally word, so a ballot costs
///      `ceil(size / 3)` word updates and multiples of 3 waste no counter.
///      Anyone may prepare a ballot by supplying the entries and Merkle proofs for exactly those
///      draws (`prepareBallot`); the filler has no choice in what is drawn.
///      Voters do not call the governor: they call
///      `IVotingScheme.castBallot(address(governor), token, epoch, ballot)` on the scheme the epoch
///      was opened with, which calls back `authorizeBallot` so the governor can check eligibility
///      and return the voter's weight. Ballots are accepted only once the epoch is opened (by
///      `prepareBallot` or `openEpoch`), and their option index refers to the ballot order of
///      `BallotPrepared`. The governor stores only a commitment to that ballot
///      (`ballotCommitment`); finalizing an epoch with ballots takes the org ids back. Weight is
///      the voter's lowest vote checkpoint over the hold window
///      `[holdFromFor(token, epoch), snapshotFor(token, epoch)]`, in whole tokens. The snapshot is
///      `snapshotOf(epoch)` (the second before the epoch starts), except in the epoch a token
///      launches in, which predates the token and uses its `launchSnapshotOf` instead. The window
///      is `holdWindow()` (by default the whole previous epoch), so a position held only around
///      the public snapshot carries no weight. A token's launch epoch and the epoch after it start
///      the window at `launchSnapshotOf - min(launchSnapshotDelay, launch epoch end -
///      launchSnapshotOf) / 2` instead, the later half of the launch delay (fixed when the token
///      registered). Ballots are accepted only in the last `votingWindow()` of an epoch
///      (`votingOpensAt`); weights are fixed at the snapshot before the epoch starts, so trading
///      during the epoch's first phase cannot change that epoch's weights. The voter and weight are public; the choice
///      is as private as the scheme makes it.
interface IEpochGovernor {
    /// @notice A pinned cause: catalogue entry `(bucket, index, orgId)` and its Merkle proof
    ///         against the latest catalogue version.
    struct Pin {
        bytes32 orgId;
        uint16 bucket;
        uint32 index;
        bytes32[] proof;
    }

    /// @notice The catalogue entry at a rotation draw's pool index, with its Merkle proof. The
    ///         bucket and index are derived by the governor.
    struct Draw {
        bytes32 orgId;
        bytes32[] proof;
    }

    /// @notice A curated pick (bucket and rank derived by the governor): the pick leaf
    ///         `(rank, catalogIndex, pickOrgId)` with its proof against the agent's picks root, and
    ///         the catalogue entry actually at `(bucket, catalogIndex)` with its catalogue proof
    ///         (ignored when the index is past the bucket). The pick counts only when both orgs match.
    struct CuratedDraw {
        uint32 catalogIndex;
        bytes32 pickOrgId;
        bytes32[] pickProof;
        bytes32 entryOrgId;
        bytes32[] entryProof;
    }

    /// @notice Emitted when a vote is cast. `voteRef` is opaque so private schemes can replace it.
    event VoteCast(address indexed token, uint256 indexed epoch, bytes32 voteRef);

    /// @notice Emitted when an epoch is finalized with its winning cause.
    event EpochFinalized(address indexed token, uint256 indexed epoch, bytes32 causeId);

    /// @notice Emitted when an epoch's poll is opened with its frozen options.
    event EpochOpened(address indexed token, uint256 indexed epoch, bytes32[] options);

    /// @notice Emitted when a token registered in the epoch it was created in gets a launch
    ///         snapshot, at which the weights of that epoch are read.
    event LaunchSnapshotSet(address indexed token, uint256 indexed epoch, uint256 snapshot);

    /// @notice Emitted when an epoch's poll is closed and the tally requested.
    event EpochClosed(address indexed token, uint256 indexed epoch);

    /// @notice Emitted when an epoch with no ballots falls back to the default cause.
    event NoVoteFallbackApplied(address indexed token, uint256 indexed epoch, bytes32 causeId);

    /// @notice Emitted when an epoch with ballots falls back to the default cause because no
    ///         valid final tally arrived within `tallyGrace` after the epoch ended.
    event TallyTimeoutFallbackApplied(
        address indexed token, uint256 indexed epoch, bytes32 causeId
    );

    /// @notice Emitted when closing an epoch could not request the tally from its scheme (for
    ///         example because the scheme no longer lists this governor). `closeEpoch` may be
    ///         retried; otherwise the epoch falls back to the default cause after `tallyGrace`.
    event EpochCloseFailed(address indexed token, uint256 indexed epoch);

    /// @notice Emitted with every token shortlist change: the epoch from which `causes` apply.
    event ShortlistScheduled(
        address indexed token, uint256 indexed effectiveFrom, bytes32[] causes
    );

    /// @notice Emitted when an epoch's ballot is fixed: the options' catalogue org ids in ballot
    ///         order (cause id = `keccak256(orgId)`). `pinned` options come first, then curated
    ///         picks, then the rotation draws. This log is the only record of the org ids: the
    ///         governor keeps `ballotCommitment`, and `finalizeEpoch` of an epoch with ballots takes
    ///         them back. With fewer than `MIN_OPTIONS` options the epoch is not opened and finalizes
    ///         to the default cause.
    event BallotPrepared(
        address indexed token,
        uint256 indexed epoch,
        uint32 catalogVersion,
        uint256 poolSize,
        uint8 pinned,
        bytes32[] orgIds
    );

    event SchemeUpdated(address indexed scheme);
    /// @notice The epoch schedule changed: from epoch `startEpoch` (starting at `startTime`)
    ///         epochs last `length` seconds, ballots are accepted in the last `votingWindow`
    ///         seconds of each, and weights look back `holdWindow` seconds from the snapshot. Takes
    ///         effect from the next epoch, except before the first token registers, when it
    ///         re-anchors epoch zero (`startEpoch` 0).
    event EpochScheduleSet(
        uint256 startEpoch,
        uint256 startTime,
        uint256 length,
        uint256 votingWindow,
        uint256 holdWindow
    );
    /// @notice `tallyGrace` changed (applies immediately).
    event TallyGraceSet(uint256 grace);
    /// @notice `launchSnapshotDelay` changed (applies to tokens registered afterwards).
    event LaunchSnapshotDelaySet(uint256 delay);
    /// @notice `curationGrace` changed.
    event CurationGraceSet(uint256 grace);
    event CuratorRegistrySet(address curators);
    /// @notice No longer emitted (`requestCurationSkip` reverts); kept for indexers.
    event CurationSkipRequested(address indexed token, uint256 indexed epoch, uint256 skipAt);
    /// @notice Curated phase of a ballot: `drawn` picks checked, `included` of them on the ballot.
    event CuratedPicksUsed(
        address indexed token, uint256 indexed epoch, uint8 drawn, uint8 included
    );
    event FactorySet(address indexed factory);
    event DefaultCauseSet(bytes32 indexed causeId);
    event ShortlistSet(address indexed token, bytes32[] causes);
    /// @notice The protocol's largest ballot size changed. Also emitted at deployment.
    event BallotSizeCapSet(uint8 cap);
    /// @notice A token's controller chose its ballot size (zero: follow `ballotSizeCap`), applying
    ///         from epoch `effectiveFrom` (the current one when its ballot is not prepared yet).
    event BallotSizeSet(address indexed token, uint8 size, uint256 effectiveFrom);

    error NotFactory();
    error NotScheme(address caller);
    error NotController(address token, address caller);
    error TokenNotRegistered(address token);
    error EpochNotEnded(uint256 epoch);
    error EpochNotCurrent(uint256 epoch);
    /// @notice A ballot before the epoch's voting window opened at `opensAt`.
    error VotingNotOpen(uint256 epoch, uint256 opensAt);
    /// @notice A duration outside `[min, max]`.
    error DurationOutOfRange(uint256 value, uint256 min, uint256 max);
    error EpochNotOpened(address token, uint256 epoch);
    error EpochAlreadyOpened(address token, uint256 epoch);
    error EpochAlreadyClosed(address token, uint256 epoch);
    error EpochAlreadyFinalized(address token, uint256 epoch);
    error TallyNotFinal(address token, uint256 epoch);
    error InvalidTally(address token, uint256 epoch);
    /// @notice `finalizeEpoch` options do not match the ballot commitment.
    error BallotMismatch(address token, uint256 epoch);
    error InactiveCause(bytes32 causeId);
    error InvalidShortlist();
    error NoShortlist(address token);
    error NotInCatalog(bytes32 orgId);
    error OutOfFocus(bytes32 orgId, uint16 bucket);
    error BallotAlreadyPrepared(address token, uint256 epoch);
    /// @notice The ballot needs more draws than were supplied; `needed` is the next draw index.
    error IncompleteBallot(address token, uint256 epoch, uint256 needed);
    error TooManyDraws(uint256 supplied, uint256 used);
    error InvalidDraw(uint256 k);
    error PoolTooSmall(address token, uint256 poolSize);
    error IncompleteCuratedBallot(address token, uint256 epoch, uint256 needed);
    error TooManyCuratedDraws(uint256 supplied, uint256 used);
    error InvalidCuratedDraw(uint256 k);
    error CuratorRegistryAlreadySet();
    error CurationSkipAlreadyRequested(address token, uint256 epoch);
    /// @notice Published curations can no longer be skipped (`requestCurationSkip`).
    error CurationSkipDisabled(address token, uint256 epoch);
    error InvalidVote();
    error AlreadyVoted(address voter);
    error NoVotes(address token, uint256 epoch);
    error ZeroAddress();
    error FactoryAlreadySet();
    error InsufficientGas();
    /// @notice A ballot size outside `MIN_OPTIONS..MAX_OPTIONS` (zero is allowed for a token).
    error BallotSizeOutOfRange(uint256 size);
    /// @notice More pins than the token's current ballot size holds.
    error ShortlistTooLong(uint256 pins, uint256 size);

    // ------------------------------------------------------------------ constants / config

    /// @notice Shortest value of any owner-set duration (epoch, voting window, hold window,
    ///         graces).
    function MIN_DURATION() external view returns (uint256);

    /// @notice Longest value of any owner-set duration.
    function MAX_DURATION() external view returns (uint256);

    /// @notice Length in seconds of the current epoch (7 days by default). The length of any
    ///         epoch is `epochScheduleFor(epoch)`.
    function epochLength() external view returns (uint256);

    /// @notice Seconds at the end of the current epoch during which ballots are accepted (the
    ///         whole epoch by default). The remaining first part of the epoch is the trading phase.
    function votingWindow() external view returns (uint256);

    /// @notice Length of the hold window ending at the current epoch's snapshot (7 days by
    ///         default).
    function holdWindow() external view returns (uint256);

    /// @notice `(length, votingWindow, holdWindow)` in force for `epoch`. For the epoch after the
    ///         current one this is the schedule that will apply to it, including a pending change.
    function epochScheduleFor(uint256 epoch)
        external
        view
        returns (uint256 length, uint256 votingWindow, uint256 holdWindow);

    /// @notice Timestamp from which ballots of `epoch` are accepted: its end minus its voting
    ///         window. Ballots are accepted until the epoch ends.
    function votingOpensAt(uint256 epoch) external view returns (uint256);

    /// @notice Sets the epoch length, the voting window and the hold window, from the next epoch
    ///         (epochs already started keep their schedule). Before the first token registers it
    ///         applies at once, so the very first cycle can be short. Owner only.
    /// @param length Epoch length, `MIN_DURATION..MAX_DURATION`.
    /// @param votingWindow_ Final part of the epoch that accepts ballots, `MIN_DURATION..length`.
    /// @param holdWindow_ Hold window of the epochs' weights, `MIN_DURATION..MAX_DURATION`.
    function setEpochSchedule(uint256 length, uint256 votingWindow_, uint256 holdWindow_) external;

    /// @notice Sets `tallyGrace`. Owner only; applies at once.
    function setTallyGrace(uint256 grace) external;

    /// @notice Sets `launchSnapshotDelay`. Owner only; applies to tokens registered afterwards.
    function setLaunchSnapshotDelay(uint256 delay) external;

    /// @notice Sets `curationGrace`. Owner only.
    function setCurationGrace(uint256 grace) external;

    /// @notice Hard ceiling of every ballot size (further capped by the scheme's `MAX_OPTIONS`).
    function MAX_OPTIONS() external view returns (uint8);

    /// @notice Smallest ballot that opens a poll; also the smallest focus pool a token may launch
    ///         with.
    function MIN_OPTIONS() external view returns (uint8);

    /// @notice Largest number of causes a controller may pin.
    function PINNED_MAX() external view returns (uint8);

    /// @notice Rotation gives up after `DRAW_FACTOR` draws per free slot (repeats are skipped).
    function DRAW_FACTOR() external view returns (uint256);

    /// @notice Ballot size for epochs prepared now of a token that chose none:
    ///         `min(ballotSizeCap, scheme.MAX_OPTIONS())`. A token's own size is `ballotSizeFor`.
    function ballotSize() external view returns (uint256);

    /// @notice Protocol ballot size cap (`MIN_OPTIONS..MAX_OPTIONS`, owner-set, `MAX_OPTIONS` by
    ///         default). It bounds every token's ballot.
    function ballotSizeCap() external view returns (uint8);

    /// @notice The ballot size `token`'s controller chose (zero: follow `ballotSizeCap`). It may
    ///         exceed the cap, which then applies; the size in force is `ballotSizeFor`.
    function ballotSizeChoiceOf(address token) external view returns (uint8);

    /// @notice Ballot size of `token`'s `epoch`: the size it was prepared with, or for an
    ///         unprepared epoch the size it would get if prepared now,
    ///         `min(choice or ballotSizeCap, ballotSizeCap, scheme.MAX_OPTIONS())`. The ballot may
    ///         hold fewer options (`ballotCommitment`) when the pool is small.
    function ballotSizeFor(address token, uint256 epoch) external view returns (uint256);

    /// @notice Cause catalogue that ballots draw from.
    function catalog() external view returns (address);

    /// @notice Seconds after an epoch ends during which its final tally may still arrive; past
    ///         it, an epoch without a valid final tally finalizes to the default cause.
    function tallyGrace() external view returns (uint256);

    /// @notice Longest wait after a token's registration before its launch snapshot (shorter when
    ///         the launch epoch ends sooner: then halfway to its end).
    function launchSnapshotDelay() external view returns (uint256);

    /// @notice Former grace of `requestCurationSkip`. Kept for compatibility: a ballot with
    ///         usable curator picks now always needs its curated draws. Picks committed but
    ///         never served are dropped by the curator registry owner (`voidCurations`).
    function curationGrace() external view returns (uint256);

    /// @notice Timestamp at which epoch 0 starts.
    function epochZeroStart() external view returns (uint256);

    /// @notice Index of the current epoch.
    function currentEpoch() external view returns (uint256);

    /// @notice Start timestamp of `epoch`.
    function epochStart(uint256 epoch) external view returns (uint256);

    /// @notice Timestamp at which voting weights for `epoch` are read (the second before it starts,
    ///         so before the epoch's trading phase).
    function snapshotOf(uint256 epoch) external view returns (uint256);

    /// @notice Timestamp at which `token`'s voting weights for `epoch` are read: `snapshotOf(epoch)`,
    ///         or the token's launch snapshot in the epoch it launched in.
    function snapshotFor(address token, uint256 epoch) external view returns (uint256);

    /// @notice Launch snapshot of a token created in the epoch it was registered in (zero when the
    ///         token had supply at that epoch's snapshot and uses the regular one).
    function launchSnapshotOf(address token) external view returns (uint256);

    /// @notice Start of `token`'s hold window for `epoch`: weights are the lowest vote checkpoint
    ///         over `[holdFromFor, snapshotFor]`.
    function holdFromFor(address token, uint256 epoch) external view returns (uint256);

    /// @notice Voting scheme used for epochs opened from now on.
    function scheme() external view returns (address);

    /// @notice Cause that wins an epoch in which nobody voted (zero means no fallback).
    function defaultCause() external view returns (bytes32);

    /// @notice The token's pinned causes in effect for the current epoch.
    function shortlistOf(address token) external view returns (bytes32[] memory);
    /// @notice Pinned causes in effect for `epoch`. Exact for the current and later epochs; for a
    ///         prepared epoch its `BallotPrepared` options are authoritative.
    function shortlistFor(address token, uint256 epoch) external view returns (bytes32[] memory);
    /// @notice The token's pinned causes scheduled for a later epoch, and that epoch (zero when
    ///         nothing is scheduled). An empty list with a non-zero epoch schedules removing all pins.
    function pendingShortlistOf(address token)
        external
        view
        returns (bytes32[] memory causes, uint256 effectiveFrom);
    /// @notice Catalogue org ids of the pins in effect for `epoch`.
    function shortlistOrgIdsFor(address token, uint256 epoch)
        external
        view
        returns (bytes32[] memory);
    /// @notice Catalogue version and focus pool size an epoch's ballot draws from (the version in
    ///         effect at the epoch's start).
    function poolOf(address token, uint256 epoch)
        external
        view
        returns (uint32 version, uint256 poolSize);
    /// @notice Pool index of rotation draw `k` (see the contract notes).
    function drawIndex(address token, uint256 epoch, uint32 version, uint256 k, uint256 poolSize)
        external
        pure
        returns (uint256);

    // ------------------------------------------------------------------ admin

    /// @notice Registers a token for voting. Callable by the factory only, after the token's focus
    ///         is set; reverts `PoolTooSmall` unless the latest catalogue gives its focus at least
    ///         `MIN_OPTIONS` entries.
    function registerToken(address token) external;

    /// @notice Sets a token's pinned causes (0..PINNED_MAX distinct, unblocked catalogue entries
    ///         inside its focus, no more than its current ballot size) from the next epoch, or
    ///         from the current one if its ballot is not prepared yet. Callable by the token's
    ///         profile controller only. If the size is lowered later, a ballot takes only the
    ///         first `size` unblocked pins.
    function setShortlist(address token, Pin[] calldata pins) external;

    /// @notice Sets a token's ballot size: `MIN_OPTIONS..MAX_OPTIONS`, or zero to follow
    ///         `ballotSizeCap`. A choice above the cap gets the cap. Applies from the next epoch, or
    ///         from the current one if its ballot is not prepared yet (the pins' rule). Callable by
    ///         the token's profile controller only, like `setShortlist`.
    function setBallotSize(address token, uint8 size) external;

    /// @notice Sets the protocol ballot size cap (`MIN_OPTIONS..MAX_OPTIONS`). Owner only. It
    ///         bounds every token, including those that chose more, from each token's next
    ///         unprepared ballot; prepared ballots keep their size.
    function setBallotSizeCap(uint8 cap) external;

    // ------------------------------------------------------------------ lifecycle

    /// @notice Prepares and opens the current epoch's ballot for `token` (see the contract
    ///         notes). Permissionless. `draws` must be exactly the entries the rotation consumes.
    function prepareBallot(address token, uint256 epoch, Draw[] calldata draws) external;
    /// @notice `prepareBallot` with curated draws: the picks the curated phase consumes, in order,
    ///         then the rotation draws. Needed whenever the token's focus buckets have usable
    ///         curations for the epoch and its catalogue version: `prepareBallot` and `openEpoch`
    ///         (no curated draws) then revert `IncompleteCuratedBallot`, at any time.
    function prepareCuratedBallot(
        address token,
        uint256 epoch,
        CuratedDraw[] calldata curated,
        Draw[] calldata draws
    ) external;
    /// @notice Disabled: always reverts `CurationSkipDisabled`. Published curations cannot be
    ///         skipped; the curator registry owner voids picks nobody can get (`voidCurations`).
    function requestCurationSkip(address token, uint256 epoch) external;
    /// @notice Always 0 (`requestCurationSkip` is disabled). Kept for compatibility.
    function curationSkipAt(address token, uint256 epoch) external view returns (uint256);
    /// @notice Sets the curator registry. Owner only, once.
    function setCuratorRegistry(ICuratorRegistry curators_) external;
    /// @notice `prepareBallot` with no draws: works when the ballot needs none (empty pool, or
    ///         pins fill it). Permissionless. Ballots are rejected until the epoch is opened.
    function openEpoch(address token, uint256 epoch) external;

    /// @notice Closes an ended epoch's poll and asks the scheme for the tally. Permissionless. If
    ///         the scheme rejects the request the epoch is still marked closed (`EpochCloseFailed`)
    ///         and the call may be retried.
    function closeEpoch(address token, uint256 epoch) external;

    /// @notice Stores the winning cause of an ended epoch from the scheme's final tally, or the
    ///         default cause when nobody voted or when no valid final tally arrived within
    ///         `tallyGrace` of the epoch's end. Permissionless. Applying a tally needs the
    ///         ballot's org ids in order (`BallotPrepared`), checked against `ballotCommitment`
    ///         (`BallotMismatch` otherwise); without one they are ignored and may be empty.
    function finalizeEpoch(address token, uint256 epoch, bytes32[] calldata orgIds) external;

    // ------------------------------------------------------------------ epoch views

    /// @notice Whether the epoch's ballot has been prepared.
    function isPrepared(address token, uint256 epoch) external view returns (bool);
    /// @notice Commitment to the epoch's ballot, `keccak256(abi.encodePacked(orgIds))` over the
    ///         options' org ids in ballot order, and the option count (both zero if not prepared).
    ///         The org ids themselves are in `BallotPrepared`.
    function ballotCommitment(address token, uint256 epoch)
        external
        view
        returns (bytes32 commitment, uint8 optionCount);

    /// @notice Scheme the epoch was opened with (zero if not opened).
    function epochScheme(address token, uint256 epoch) external view returns (address);

    function isOpened(address token, uint256 epoch) external view returns (bool);
    function isClosed(address token, uint256 epoch) external view returns (bool);

    /// @notice Whether the last `closeEpoch` attempt failed to request the tally.
    function closeFailed(address token, uint256 epoch) external view returns (bool);

    /// @notice Whether the epoch has been finalized.
    function isFinalized(address token, uint256 epoch) external view returns (bool);

    /// @notice Winning cause of a finalized epoch (zero if not finalized).
    function winningCause(address token, uint256 epoch) external view returns (bytes32);

    /// @notice Final weight counted for a cause in a finalized epoch (zero when the cause was not on
    ///         the ballot or the epoch fell back to the default cause).
    function tally(address token, uint256 epoch, bytes32 causeId) external view returns (uint256);

    /// @notice Whether `voter` cast a ballot in the epoch.
    function hasVoted(address token, uint256 epoch, address voter) external view returns (bool);

    /// @notice Number of ballots authorized in the epoch.
    function voterCount(address token, uint256 epoch) external view returns (uint256);

    /// @notice Voting weight of `account` in `epoch`: its lowest vote checkpoint over
    ///         `[holdFromFor(token, epoch), snapshotFor(token, epoch)]`, in whole tokens (zero
    ///         while the snapshot is still in the future).
    function weightOf(address token, uint256 epoch, address account) external view returns (uint64);

    /// @notice Reads at most `maxReads` more vote checkpoints of `account`'s hold window for
    ///         `epoch` and caches the progress, so a ballot over a window with very many
    ///         checkpoints fits in a block. Anyone may call it; it never changes a weight.
    /// @return done Whether the whole window has been read.
    function advanceHoldScan(address token, uint256 epoch, address account, uint256 maxReads)
        external
        returns (bool done);
}

src/interfaces/ITokenProfileRegistry.sol

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

/// @title ITokenProfileRegistry
/// @notice Per-token profile written at launch: the ENS label under the Varada parent name, the
///         accounts allowed to edit records, ENS text records and the logo reference. The factory
///         registers; the controller (initially the creator) edits and may delegate to an editor;
///         the takeover governor can replace the controller. Every name serves the one site
///         contenthash set by the owner: no profile can point its subname at another site.
interface ITokenProfileRegistry {
    struct Profile {
        address controller;
        uint48 registeredAt;
        bool suppressed;
        address editor;
        bytes32 labelhash;
        bytes32 logoRef;
        string label;
    }

    struct Reservation {
        bool reserved;
        /// @dev Creator allowed to claim the reserved label; zero means nobody.
        address allowedCreator;
    }

    event TokenRegistered(
        address indexed token,
        bytes32 indexed labelhash,
        string label,
        address controller,
        bytes32 logoRef
    );
    event ControllerChanged(
        address indexed token, address indexed previousController, address indexed newController
    );
    event EditorChanged(address indexed token, address indexed editor);
    event TextChanged(address indexed token, string indexed indexedKey, string key, string value);
    event LogoChanged(address indexed token, bytes32 logoRef);
    event SuppressionChanged(address indexed token, bool suppressed);
    event GovernorChanged(address indexed governor);
    event DefaultContenthashChanged(bytes hash);
    event PlatformAddressChanged(address indexed platformAddress);
    event ParentTextChanged(string indexed indexedKey, string key, string value);
    event ReservationChanged(bytes32 indexed labelhash, bool reserved, address allowedCreator);

    /// @notice Emitted once per token when its cause focus is fixed at launch.
    event FocusSet(address indexed token, uint64 categoryMask, uint16 regionMask);

    error NotFactory();
    error FocusAlreadySet(address token);
    error ZeroFocus();
    error NotController(address token, address caller);
    error NotControllerOrEditor(address token, address caller);
    error NotGovernor();
    error NotRegistered(address token);
    error AlreadyRegistered(address token);
    error LabelTaken(bytes32 labelhash, address token);
    error LabelReserved(bytes32 labelhash);
    error EditorIsController();
    error ContenthashTooLong(uint256 length);
    error ZeroAddress();
    error ZeroParentNode();

    // ------------------------------------------------------------------ factory

    /// @notice Registers a launched token under `label`. Factory only.
    /// @return node ENS node of `<label>.<parent>`.
    function register(address token, string calldata label, address controller, bytes32 logoRef)
        external
        returns (bytes32 node);

    // ------------------------------------------------------------------ controller / governor

    /// @notice Transfers control. The controller may pass zero to renounce; the governor must pass
    ///         a non-zero account. Always clears the editor.
    function setController(address token, address newController) external;

    /// @notice Appoints (or clears, with zero) an editor who may edit records only.
    function setEditor(address token, address editor) external;

    // ------------------------------------------------------------------ controller or editor

    function setLogoRef(address token, bytes32 logoRef) external;
    function setText(address token, string calldata key, string calldata value) external;

    // ------------------------------------------------------------------ owner

    function setGovernor(address governor) external;
    /// @notice Sets the site contenthash served for the parent name and every registered subname.
    function setDefaultContenthash(bytes calldata hash) external;
    function setPlatformAddress(address platformAddress) external;
    function setParentText(string calldata key, string calldata value) external;
    function setReservation(bytes32 labelhash, bool reserved, address allowedCreator) external;
    function setSuppressed(address token, bool suppressed) external;

    // ------------------------------------------------------------------ views

    function factory() external view returns (address);
    function governor() external view returns (address);
    function parentNode() external view returns (bytes32);
    function defaultContenthash() external view returns (bytes memory);
    function platformAddress() external view returns (address);
    function parentText(string calldata key) external view returns (string memory);
    function isRegistered(address token) external view returns (bool);

    /// @notice Fixes a registered token's cause focus: the catalogue categories and regions its
    ///         ballots draw from. Factory only, once; both masks must be non-zero (all bits set
    ///         means "any").
    function setFocus(address token, uint64 categoryMask, uint16 regionMask) external;

    /// @notice Cause focus of a token (zero masks if never set).
    function focusOf(address token) external view returns (uint64 categoryMask, uint16 regionMask);
    function getProfile(address token) external view returns (Profile memory);
    function labelOf(address token) external view returns (string memory);
    function labelhashOf(address token) external view returns (bytes32);
    function nodeOf(address token) external view returns (bytes32);
    function controllerOf(address token) external view returns (address);
    function editorOf(address token) external view returns (address);
    function logoRefOf(address token) external view returns (bytes32);
    function registeredAtOf(address token) external view returns (uint48);
    function isSuppressed(address token) external view returns (bool);
    function text(address token, string calldata key) external view returns (string memory);
    function tokenByLabelhash(bytes32 labelhash) external view returns (address);
    function tokenByNode(bytes32 node) external view returns (address);
    function reservationOf(bytes32 labelhash) external view returns (Reservation memory);
    function MAX_CONTENTHASH_LENGTH() external view returns (uint256);
}

src/interfaces/external/IERC8004IdentityRegistry.sol

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

/// @title IERC8004IdentityRegistry
/// @notice The parts of the ERC-8004 (Trustless Agents, Draft) Identity Registry Varada uses, as
///         deployed on Ethereum mainnet at `0x8004A169FB4a3325136EB29fA0ceB6D2e539a432` (an
///         upgradeable proxy of `IdentityRegistryUpgradeable`, ERC-721 "AgentIdentity").
/// @dev `register` mints with `_safeMint`, so a contract owner must accept ERC-721 transfers.
///      `setAgentWallet` checks an EIP-712 signature over
///      `AgentWalletSet(uint256 agentId,address newWallet,address owner,uint256 deadline)` in the
///      domain `ERC8004IdentityRegistry`/`1`, by ECDSA or else ERC-1271 on `newWallet`; the deadline
///      may be at most 5 minutes ahead. The wallet is cleared when the token is transferred.
interface IERC8004IdentityRegistry {
    struct MetadataEntry {
        string metadataKey;
        bytes metadataValue;
    }

    event Registered(uint256 indexed agentId, string agentURI, address indexed owner);

    function register(string memory agentURI, MetadataEntry[] memory metadata)
        external
        returns (uint256 agentId);

    function setAgentURI(uint256 agentId, string calldata newURI) external;

    function setMetadata(uint256 agentId, string memory metadataKey, bytes memory metadataValue)
        external;

    function getMetadata(uint256 agentId, string memory metadataKey)
        external
        view
        returns (bytes memory);

    function setAgentWallet(
        uint256 agentId,
        address newWallet,
        uint256 deadline,
        bytes calldata signature
    ) external;

    function getAgentWallet(uint256 agentId) external view returns (address);

    function ownerOf(uint256 agentId) external view returns (address);

    function tokenURI(uint256 agentId) external view returns (string memory);
}

src/interfaces/external/IEndaomentOrg.sol

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

/// @notice Minimal view of an Endaoment org entity.
interface IEndaomentOrg {
    /// @notice Pulls `amount` of the base token (USDC) from the caller; allowance spender is the org.
    function donate(uint256 amount) external;

    function orgId() external view returns (bytes32);

    function baseToken() external view returns (address);
}

src/interfaces/external/IEndaomentOrgFundFactory.sol

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

/// @notice Minimal view of the Endaoment OrgFundFactory (Ethereum mainnet).
interface IEndaomentOrgFundFactory {
    /// @notice CREATE2 address of the org for `orgId`, whether or not it is deployed.
    function computeOrgAddress(bytes32 orgId) external view returns (address);

    /// @notice Deploys the org (reverts if already deployed), pulls `amount` USDC from the caller
    ///         (allowance spender is the factory) and credits the org.
    function deployOrgAndDonate(bytes32 orgId, uint256 amount) external returns (address org);

    function registry() external view returns (address);

    function baseToken() external view returns (address);
}

src/libraries/LabelLib.sol

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

/// @title LabelLib
/// @notice Validation for the ENS label a token is registered under (`<label>.varada.eth`).
/// @dev Accepted labels are a strict subset of ENSIP-15 normalized names: 3 to 63 bytes of
///      `[a-z0-9-]`, no leading or trailing hyphen and no hyphens at both positions 3 and 4
///      (the `xn--` punycode slot). Because only lowercase ASCII is accepted, a client that
///      normalizes `PEPE.varada.eth` to `pepe.varada.eth` always lands on the stored label, and
///      the DNS wire format (63-byte labels) is never exceeded.
library LabelLib {
    /// @notice Shortest accepted label.
    uint256 internal constant MIN_LENGTH = 3;
    /// @notice Longest accepted label (DNS wire-format limit).
    uint256 internal constant MAX_LENGTH = 63;

    error InvalidLabel(string label);

    /// @notice Reverts unless `label` is valid; returns its labelhash (`keccak256(label)`).
    function validate(string memory label) internal pure returns (bytes32) {
        if (!isValid(label)) revert InvalidLabel(label);
        return keccak256(bytes(label));
    }

    /// @notice Whether `label` satisfies every rule.
    function isValid(string memory label) internal pure returns (bool) {
        bytes memory b = bytes(label);
        uint256 len = b.length;
        if (len < MIN_LENGTH || len > MAX_LENGTH) return false;
        if (b[0] == "-" || b[len - 1] == "-") return false;
        if (len >= 4 && b[2] == "-" && b[3] == "-") return false;
        for (uint256 i; i < len; ++i) {
            bytes1 c = b[i];
            bool ok = (c >= "a" && c <= "z") || (c >= "0" && c <= "9") || c == "-";
            if (!ok) return false;
        }
        return true;
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v4-core/=lib/v4-core/",
    "@uniswap/v4-periphery/=lib/v4-periphery/",
    "v4-core/=lib/v4-core/src/",
    "v4-periphery/=lib/v4-periphery/src/",
    "solmate/=lib/v4-core/lib/solmate/",
    "permit2/=lib/v4-periphery/lib/permit2/",
    "@fhevm/solidity/=node_modules/@fhevm/solidity/",
    "encrypted-types/=node_modules/encrypted-types/",
    "@ensdomains/=lib/v4-core/node_modules/@ensdomains/",
    "ds-test/=lib/v4-core/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/v4-periphery/lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/v4-core/node_modules/hardhat/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.