Skip to content
Verified contractExactCC0-1.0

StateOracle

Address0x7746bcf2879afcee344cbbd830ab5c6d4b49a318
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.36

 

Same code

5 more contracts

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
No
EVM version
prague
License
CC0-1.0
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,084,351
Creation transaction
0x8742477aa8…305e928b3d

src/StateOracle.sol

// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.28;

import {IDAVerifier} from "./interfaces/IDAVerifier.sol";
import {IAdminVerifier} from "./interfaces/IAdminVerifier.sol";
import {Batch} from "./Batch.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Initializable} from "solady/utils/Initializable.sol";
import {AdminVerifierRegistry} from "./lib/AdminVerifierRegistry.sol";
import {DAVerifierRegistry} from "./lib/DAVerifierRegistry.sol";
import {StateOracleAccessControl} from "./StateOracleAccessControl.sol";

/// @title StateOracle
/// @author @fredo ([email protected])
/// @notice Manages assertion adopters and their assertions
/// @dev Provides functionality to register assertion adopters and manage their assertions

contract StateOracle is Batch, Initializable, StateOracleAccessControl {
    using AdminVerifierRegistry for mapping(IAdminVerifier adminVerifier => bool isRegistered);
    using DAVerifierRegistry for mapping(IDAVerifier daVerifier => bool isRegistered);

    /// @notice Number of blocks to wait before an assertion becomes active or inactive
    uint256 public immutable ASSERTION_TIMELOCK_BLOCKS;

    /// @notice Thrown when an unauthorized address attempts to register an assertion adopter
    error UnauthorizedRegistrant();
    /// @notice Thrown when attempting to transfer management to an invalid address
    error InvalidManagerTransferRequest();
    /// @notice Thrown when attempting to accept management when no transfer is pending
    error NoPendingManager();
    /// @notice Thrown when attempting to register an assertion adopter that is already registered
    error AssertionAdopterAlreadyRegistered();
    /// @notice Thrown when attempting to interact with an unregistered assertion adopter
    error AssertionAdopterNotRegistered();
    /// @notice Thrown when attempting to add an assertion that already exists
    error AssertionAlreadyExists();
    /// @notice Thrown when attempting to remove or modify a non-existent assertion
    error AssertionDoesNotExist();
    /// @notice Thrown when the DA verifier is not registered
    error DAVerifierNotRegistered();
    /// @notice Thrown when the provided DA proof is invalid
    /// @param daVerifier The DA verifier that rejected the proof
    error InvalidDAProof(IDAVerifier daVerifier);
    /// @notice Thrown when attempting to set an invalid assertion timelock value
    error InvalidAssertionTimelock();
    /// @notice Thrown when attempting to add more assertions than the maximum allowed
    error TooManyAssertions();
    /// @notice Thrown when attempting to remove or modify an already removed assertion
    error AssertionAlreadyRemoved();
    /// @notice Thrown when whitelist is enabled and caller is not whitelisted
    error NotWhitelisted();
    /// @notice Thrown when attempting to add an account that is already whitelisted
    error AlreadyWhitelisted(address account);
    /// @notice Thrown when attempting to remove an account that is not whitelisted
    error AccountNotWhitelisted(address account);
    /// @notice Thrown when attempting to enable an already enabled whitelist
    error WhitelistAlreadyEnabled();
    /// @notice Thrown when attempting to disable an already disabled whitelist
    error WhitelistAlreadyDisabled();

    /// @notice Struct containing assertion adopter data
    /// @param manager Address authorized to manage assertions
    /// @param assertions Mapping of assertion IDs to assertion windows, describing the assertion's lifecycle
    struct AssertionAdopter {
        address manager;
        address pendingManager;
        uint16 assertionCount;
        mapping(bytes32 assertionId => AssertionWindow assertionWindow) assertions;
    }

    /// @notice Struct containing the assertion time window
    /// @param activationBlock Block number when the assertion becomes active
    /// @param deactivationBlock Block number when the assertion becomes inactive
    struct AssertionWindow {
        uint256 activationBlock;
        uint256 deactivationBlock;
    }

    /// @notice Emitted when a new assertion adopter is registered
    /// @param contractAddress The address of the registered contract
    /// @param manager The address authorized to manage the contract's assertions
    /// @param adminVerifier The admin verifier used to register the assertion adopter
    event AssertionAdopterAdded(address indexed contractAddress, address indexed manager, IAdminVerifier adminVerifier);

    /// @notice Emitted when a manager transfer is requested
    /// @param contractAddress The address of the contract
    /// @param manager The address requesting the transfer
    /// @param newManager The address being requested to manage the contract
    event ManagerTransferRequested(
        address indexed contractAddress, address indexed manager, address indexed newManager
    );

    /// @notice Emitted when a manager transfer is accepted
    /// @param contractAddress The address of the contract
    /// @param newManager The address accepting the transfer
    event ManagerTransferred(address indexed contractAddress, address indexed newManager);

    /// @notice Emitted when a new assertion is added
    /// @param assertionAdopter The assertion adopter the assertion is associated with
    /// @param assertionId The unique identifier of the assertion
    /// @param activationBlock The block number when the assertion becomes active
    /// @param daVerifier The DA verifier used to verify the proof
    /// @param metadata The metadata used for verification
    /// @param proof The proof used for verification
    event AssertionAdded(
        address indexed assertionAdopter,
        bytes32 indexed assertionId,
        uint256 activationBlock,
        IDAVerifier indexed daVerifier,
        bytes metadata,
        bytes proof
    );

    /// @notice Emitted when an assertion is removed
    /// @param assertionAdopter The assertion adopter where the assertion is removed from
    /// @param assertionId The unique identifier of the removed assertion
    /// @param deactivationBlock The block number when the assertion is going to be inactive
    event AssertionRemoved(address indexed assertionAdopter, bytes32 indexed assertionId, uint256 deactivationBlock);

    /// @notice Emitted when a storage reset is requested for an assertion adopter
    /// @param adopter The assertion adopter whose side-store state should be reset
    /// @param storageKey The side-store key identifying the state to reset
    /// @param resetBlock The block number when the reset becomes eligible
    event StorageReset(address indexed adopter, bytes32 indexed storageKey, uint256 resetBlock);

    /// @notice Emitted when the whitelist is enabled
    event WhitelistEnabled();

    /// @notice Emitted when the whitelist is disabled
    event WhitelistDisabled();

    /// @notice Emitted when an account is added to the whitelist
    /// @param account The address added to the whitelist
    event AddedToWhitelist(address indexed account);

    /// @notice Emitted when an account is removed from the whitelist
    /// @param account The address removed from the whitelist
    event RemovedFromWhitelist(address indexed account);

    /// @notice Maps contract addresses to their assertion adopter data
    mapping(address => AssertionAdopter) public assertionAdopters;

    /// @notice The admin verification registry
    mapping(IAdminVerifier adminVerifier => bool isRegistered) public adminVerifiers;

    /// @notice The DA verification registry
    mapping(IDAVerifier daVerifier => bool isRegistered) public daVerifiers;

    /// @notice Mapping of whitelisted addresses
    mapping(address => bool) public whitelist;

    /// @notice Whether the whitelist is enabled
    bool public whitelistEnabled;

    /// @notice Maximum number of assertions per assertion adopter
    uint16 public maxAssertionsPerAA;

    /// @notice Ensures caller is the manager of the contract
    /// @param contractAddress The address of the contract being managed
    modifier onlyManager(address contractAddress) {
        _onlyManager(contractAddress);
        _;
    }

    /// @notice Ensures caller is whitelisted when whitelist is enabled
    modifier onlyWhitelisted() {
        _onlyWhitelisted();
        _;
    }

    /// @notice Internal function to ensure caller is whitelisted when whitelist is enabled
    function _onlyWhitelisted() internal view {
        require(!whitelistEnabled || whitelist[msg.sender], NotWhitelisted());
    }

    /// @notice Internal function to ensure caller is the manager of the contract
    /// @param contractAddress The address of the contract being managed
    function _onlyManager(address contractAddress) internal view {
        address manager = assertionAdopters[contractAddress].manager;
        require(manager != address(0), AssertionAdopterNotRegistered());
        require(manager == msg.sender, UnauthorizedManager());
    }

    /// @notice Initializes the contract with a timelock period
    /// @param assertionTimelockBlocks Number of blocks to wait before assertions become active/inactive
    constructor(uint256 assertionTimelockBlocks) Ownable(msg.sender) {
        require(assertionTimelockBlocks > 0, InvalidAssertionTimelock());
        ASSERTION_TIMELOCK_BLOCKS = assertionTimelockBlocks;
        renounceOwnership();
        _disableInitializers();
    }

    /// @notice Initializes the contract
    /// @param admin The address of the admin
    /// @param _adminVerifiers The admin verifiers to add
    /// @param _daVerifiers The DA verifiers to add
    /// @param _maxAssertionsPerAA Maximum number of assertions per assertion adopter
    function initialize(
        address admin,
        IAdminVerifier[] calldata _adminVerifiers,
        IDAVerifier[] calldata _daVerifiers,
        uint16 _maxAssertionsPerAA
    ) external initializer {
        _initialize(admin, _adminVerifiers, _daVerifiers, _maxAssertionsPerAA, true, new address[](0));
    }

    /// @notice Initializes the contract with an explicit whitelist configuration
    /// @param admin The address to set as the admin
    /// @param _adminVerifiers The admin verifiers to add
    /// @param _daVerifiers The DA verifiers to add
    /// @param _maxAssertionsPerAA Maximum number of assertions per assertion adopter
    /// @param _whitelistEnabled Whether whitelist checks are enabled initially
    /// @param _initialWhitelist Addresses to add to the initial whitelist
    function initializeWithWhitelist(
        address admin,
        IAdminVerifier[] calldata _adminVerifiers,
        IDAVerifier[] calldata _daVerifiers,
        uint16 _maxAssertionsPerAA,
        bool _whitelistEnabled,
        address[] calldata _initialWhitelist
    ) external initializer {
        _initialize(admin, _adminVerifiers, _daVerifiers, _maxAssertionsPerAA, _whitelistEnabled, _initialWhitelist);
    }

    function _initialize(
        address admin,
        IAdminVerifier[] memory _adminVerifiers,
        IDAVerifier[] memory _daVerifiers,
        uint16 _maxAssertionsPerAA,
        bool _whitelistEnabled,
        address[] memory _initialWhitelist
    ) internal {
        _initializeRoles(admin);

        whitelistEnabled = _whitelistEnabled;
        for (uint256 i = 0; i < _adminVerifiers.length; i++) {
            _addAdminVerifier(_adminVerifiers[i]);
        }
        for (uint256 i = 0; i < _daVerifiers.length; i++) {
            _addDAVerifier(_daVerifiers[i]);
        }
        for (uint256 i = 0; i < _initialWhitelist.length; i++) {
            _addToWhitelist(_initialWhitelist[i]);
        }
        _setMaxAssertionsPerAA(_maxAssertionsPerAA);
    }

    /// @notice Registers a new assertion adopter
    /// @param contractAddress The address of the contract to register
    /// @param adminVerifier The admin verifier to use
    /// @param data The data to pass to the admin verifier
    function registerAssertionAdopter(address contractAddress, IAdminVerifier adminVerifier, bytes calldata data)
        external
        onlyWhitelisted
    {
        require(adminVerifiers.isRegistered(adminVerifier), AdminVerifierRegistry.AdminVerifierNotRegistered());
        require(adminVerifier.verifyAdmin(contractAddress, msg.sender, data), UnauthorizedRegistrant());
        require(assertionAdopters[contractAddress].manager == address(0), AssertionAdopterAlreadyRegistered());
        assertionAdopters[contractAddress].manager = msg.sender;
        emit AssertionAdopterAdded(contractAddress, msg.sender, adminVerifier);
    }

    /// @notice Adds a new assertion for an assertion adopter
    /// @dev An assertion ID can be re-added once its previous deactivation block is reached.
    /// Each addition requires a valid DA proof and starts a new activation timelock.
    /// @param contractAddress The address of the assertion adopter
    /// @param assertionId The unique identifier for the assertion
    /// @param daVerifier The DA verifier to use for proof verification
    /// @param metadata Needed to verify the proof
    /// @param proof The data availability proof for the assertion
    function addAssertion(
        address contractAddress,
        bytes32 assertionId,
        IDAVerifier daVerifier,
        bytes calldata metadata,
        bytes calldata proof
    ) external onlyManager(contractAddress) onlyWhitelisted {
        AssertionWindow storage window = assertionAdopters[contractAddress].assertions[assertionId];
        require(
            window.activationBlock == 0 || (window.deactivationBlock != 0 && block.number >= window.deactivationBlock),
            AssertionAlreadyExists()
        );
        require(daVerifiers.isRegistered(daVerifier), DAVerifierNotRegistered());
        require(daVerifier.verifyDA(assertionId, metadata, proof), InvalidDAProof(daVerifier));
        require(assertionAdopters[contractAddress].assertionCount < maxAssertionsPerAA, TooManyAssertions());

        uint256 activationBlock = block.number + ASSERTION_TIMELOCK_BLOCKS;
        window.activationBlock = activationBlock;
        window.deactivationBlock = 0;
        assertionAdopters[contractAddress].assertionCount++;
        emit AssertionAdded(contractAddress, assertionId, activationBlock, daVerifier, metadata, proof);
    }

    /// @notice Requests a storage reset for an assertion adopter
    /// @param adopter The assertion adopter whose side-store state should be reset
    /// @param storageKey The side-store key identifying the state to reset
    function resetStorage(address adopter, bytes32 storageKey) external onlyManager(adopter) {
        emit StorageReset(adopter, storageKey, block.number + ASSERTION_TIMELOCK_BLOCKS);
    }

    /// @notice Removes an assertion from an assertion adopter
    /// @param contractAddress The address of the assertion adopter
    /// @param assertionId The unique identifier of the assertion to remove
    function removeAssertion(address contractAddress, bytes32 assertionId) external onlyManager(contractAddress) {
        _removeAssertion(contractAddress, assertionId);
    }

    /// @notice Removes an assertion from an assertion adopter by guardian
    /// @param contractAddress The address of the assertion adopter
    /// @param assertionId The unique identifier of the assertion to remove
    function removeAssertionByGuardian(address contractAddress, bytes32 assertionId) external onlyGuardian {
        _removeAssertion(contractAddress, assertionId);
    }

    /// @notice Enables the whitelist
    function enableWhitelist() external onlyGovernance {
        require(!whitelistEnabled, WhitelistAlreadyEnabled());
        whitelistEnabled = true;
        emit WhitelistEnabled();
    }

    /// @notice Disables the whitelist
    function disableWhitelist() external onlyGovernance {
        require(whitelistEnabled, WhitelistAlreadyDisabled());
        whitelistEnabled = false;
        emit WhitelistDisabled();
    }

    /// @notice Adds an account to the whitelist
    /// @param account The address to add
    function addToWhitelist(address account) external onlyOperator {
        _addToWhitelist(account);
    }

    function _addToWhitelist(address account) internal {
        require(!whitelist[account], AlreadyWhitelisted(account));
        whitelist[account] = true;
        emit AddedToWhitelist(account);
    }

    /// @notice Removes an account from the whitelist
    /// @param account The address to remove
    function removeFromWhitelist(address account) external onlyOperator {
        require(whitelist[account], AccountNotWhitelisted(account));
        whitelist[account] = false;
        emit RemovedFromWhitelist(account);
    }

    /// @notice Checks if an account is allowed to perform whitelisted actions
    /// @param account The address to check
    /// @return True if whitelist is disabled (everyone allowed) or account is whitelisted
    function isWhitelisted(address account) external view returns (bool) {
        return !whitelistEnabled || whitelist[account];
    }

    /// @notice Internal function to remove an assertion from an assertion adopter
    /// @param contractAddress The address of the assertion adopter
    /// @param assertionId The unique identifier of the assertion to remove
    function _removeAssertion(address contractAddress, bytes32 assertionId) internal {
        require(hasAssertion(contractAddress, assertionId), AssertionDoesNotExist());
        require(
            assertionAdopters[contractAddress].assertions[assertionId].deactivationBlock == 0, AssertionAlreadyRemoved()
        );
        uint256 deactivationBlock = block.number + ASSERTION_TIMELOCK_BLOCKS;
        assertionAdopters[contractAddress].assertions[assertionId].deactivationBlock = deactivationBlock;
        assertionAdopters[contractAddress].assertionCount--;
        emit AssertionRemoved(contractAddress, assertionId, deactivationBlock);
    }

    /// @notice Checks if an assertion is associated with an assertion adopter
    /// @dev Remains true after removal; it does not indicate current enforcement or re-add eligibility.
    /// @param contractAddress The address of the contract
    /// @param assertionId The unique identifier of the assertion
    /// @return isAssociated True if the assertion is associated with the adopter, false otherwise
    function hasAssertion(address contractAddress, bytes32 assertionId) public view returns (bool isAssociated) {
        return assertionAdopters[contractAddress].assertions[assertionId].activationBlock != 0;
    }

    /// @notice Gets the latest assertion window for a given assertion adopter and assertion
    /// @dev Returns 0 for both activationBlock and deactivationBlock if the assertion is not associated.
    /// A successful re-add replaces this window; earlier lifecycle history remains in events.
    /// @param contractAddress The address of the assertion adopter
    /// @param assertionId The unique identifier of the assertion
    /// @return activationBlock The block number when the assertion becomes active
    /// @return deactivationBlock The block number when the assertion becomes inactive
    function getAssertionWindow(address contractAddress, bytes32 assertionId)
        public
        view
        returns (uint256 activationBlock, uint256 deactivationBlock)
    {
        return (
            assertionAdopters[contractAddress].assertions[assertionId].activationBlock,
            assertionAdopters[contractAddress].assertions[assertionId].deactivationBlock
        );
    }

    /// @notice Gets the assertion count for a given assertion adopter
    /// @param contractAddress The address of the assertion adopter
    /// @return assertionCount The number of assertions associated with the adopter
    function getAssertionCount(address contractAddress) public view returns (uint16 assertionCount) {
        return assertionAdopters[contractAddress].assertionCount;
    }

    /// @notice Gets the manager address for a given assertion adopter
    /// @param contractAddress The address of the assertion adopter
    /// @return manager The manager address
    function getManager(address contractAddress) public view returns (address manager) {
        return assertionAdopters[contractAddress].manager;
    }

    /// @notice Gets the pending manager address for a given assertion adopter
    /// @param contractAddress The address of the assertion adopter
    /// @return pendingManager The pending manager address
    function getPendingManager(address contractAddress) public view returns (address pendingManager) {
        return assertionAdopters[contractAddress].pendingManager;
    }

    /// @notice Transfers the manager role to a new address
    /// @param contractAddress The address of the assertion adopter
    /// @param newManager The address to transfer the manager role to
    function transferManager(address contractAddress, address newManager) external onlyManager(contractAddress) {
        require(newManager != address(0), InvalidManagerTransferRequest());
        assertionAdopters[contractAddress].pendingManager = newManager;
        emit ManagerTransferRequested(contractAddress, msg.sender, newManager);
    }

    /// @notice Accepts a manager transfer request
    /// @param contractAddress The address of the assertion adopter
    function acceptManagerTransfer(address contractAddress) external {
        address pendingManager = assertionAdopters[contractAddress].pendingManager;
        require(pendingManager != address(0), NoPendingManager());
        require(pendingManager == msg.sender, UnauthorizedManager());
        _transferManager(contractAddress, msg.sender);
    }

    /// @notice Revokes the manager role from an assertion adopter by guardian
    /// @param contractAddress The address of the assertion adopter
    function revokeManager(address contractAddress) external onlyGuardian {
        require(assertionAdopters[contractAddress].manager != address(0), AssertionAdopterNotRegistered());
        _transferManager(contractAddress, address(0));
    }

    /// @notice Internal function to transfer the manager role
    /// @param contractAddress The address of the assertion adopter
    /// @param newManager The address to transfer the manager role to
    function _transferManager(address contractAddress, address newManager) internal {
        assertionAdopters[contractAddress].manager = newManager;
        assertionAdopters[contractAddress].pendingManager = address(0);
        emit ManagerTransferred(contractAddress, newManager);
    }

    /// @notice Adds an authorization module to the state oracle
    /// @param adminVerifier The admin verifier to add
    function addAdminVerifier(IAdminVerifier adminVerifier) external onlyGovernance {
        _addAdminVerifier(adminVerifier);
    }

    /// @notice Internal function to add an admin verifier
    /// @param adminVerifier The admin verifier to add
    function _addAdminVerifier(IAdminVerifier adminVerifier) internal {
        adminVerifiers.add(adminVerifier);
    }

    /// @notice Removes an authorization module from the state oracle
    /// @param adminVerifier The admin verifier to remove
    function removeAdminVerifier(IAdminVerifier adminVerifier) external onlyGovernance {
        adminVerifiers.remove(adminVerifier);
    }

    /// @notice Checks if an admin verifier is registered
    /// @param adminVerifier The admin verifier to check
    /// @return isRegistered True if the admin verifier is registered, false otherwise
    function isAdminVerifierRegistered(IAdminVerifier adminVerifier) public view returns (bool isRegistered) {
        return adminVerifiers.isRegistered(adminVerifier);
    }

    /// @notice Adds a DA verifier to the registry
    /// @param daVerifier The DA verifier to add
    function addDAVerifier(IDAVerifier daVerifier) external onlyGovernance {
        _addDAVerifier(daVerifier);
    }

    /// @notice Internal function to add a DA verifier
    /// @param daVerifier The DA verifier to add
    function _addDAVerifier(IDAVerifier daVerifier) internal {
        daVerifiers.add(daVerifier);
    }

    /// @notice Removes a DA verifier from the registry
    /// @param daVerifier The DA verifier to remove
    function removeDAVerifier(IDAVerifier daVerifier) external onlyGovernance {
        daVerifiers.remove(daVerifier);
    }

    /// @notice Checks if a DA verifier is registered
    /// @param daVerifier The DA verifier to check
    /// @return isRegistered True if the DA verifier is registered, false otherwise
    function isDAVerifierRegistered(IDAVerifier daVerifier) public view returns (bool isRegistered) {
        return daVerifiers.isRegistered(daVerifier);
    }

    /// @notice Sets the maximum number of assertions per assertion adopter
    /// @param _maxAssertionsPerAA The maximum number of assertions per assertion adopter
    function setMaxAssertionsPerAA(uint16 _maxAssertionsPerAA) external onlyGovernance {
        _setMaxAssertionsPerAA(_maxAssertionsPerAA);
    }

    function _setMaxAssertionsPerAA(uint16 _maxAssertionsPerAA) internal {
        maxAssertionsPerAA = _maxAssertionsPerAA;
    }
}

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

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {IERC165, ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

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/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.
 */
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/introspection/ERC165.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

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

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

pragma solidity >=0.4.16;

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

lib/solady/src/utils/Initializable.sol

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

/// @notice Initializable mixin for the upgradeable contracts.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Initializable.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/proxy/utils/Initializable.sol)
abstract contract Initializable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

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

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

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

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

    /// @dev `keccak256(bytes("Initialized(uint64)"))`.
    bytes32 private constant _INITIALIZED_EVENT_SIGNATURE =
        0xc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2;

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

    /// @dev The default initializable slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_INITIALIZABLE_SLOT")))))`.
    ///
    /// Bits Layout:
    /// - [0]     `initializing`
    /// - [1..64] `initializedVersion`
    bytes32 private constant _INITIALIZABLE_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffbf601132;

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

    constructor() {
        // Construction time check to ensure that `_initializableSlot()` is not
        // overridden to zero. Will be optimized away if there is no revert.
        require(_initializableSlot() != bytes32(0));
    }

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

    /// @dev Override to return a non-zero custom storage slot if required.
    function _initializableSlot() internal pure virtual returns (bytes32) {
        return _INITIALIZABLE_SLOT;
    }

    /// @dev Guards an initializer function so that it can be invoked at most once.
    ///
    /// You can guard a function with `onlyInitializing` such that it can be called
    /// through a function guarded with `initializer`.
    ///
    /// This is similar to `reinitializer(1)`, except that in the context of a constructor,
    /// an `initializer` guarded function can be invoked multiple times.
    /// This can be useful during testing and is not expected to be used in production.
    ///
    /// Emits an {Initialized} event.
    modifier initializer() virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            let i := sload(s)
            // Set `initializing` to 1, `initializedVersion` to 1.
            sstore(s, 3)
            // If `!(initializing == 0 && initializedVersion == 0)`.
            if i {
                // If `!(address(this).code.length == 0 && initializedVersion == 1)`.
                if iszero(lt(extcodesize(address()), eq(shr(1, i), 1))) {
                    mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
                    revert(0x1c, 0x04)
                }
                s := shl(shl(255, i), s) // Skip initializing if `initializing == 1`.
            }
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            if s {
                // Set `initializing` to 0, `initializedVersion` to 1.
                sstore(s, 2)
                // Emit the {Initialized} event.
                mstore(0x20, 1)
                log1(0x20, 0x20, _INITIALIZED_EVENT_SIGNATURE)
            }
        }
    }

    /// @dev Guards a reinitializer function so that it can be invoked at most once.
    ///
    /// You can guard a function with `onlyInitializing` such that it can be called
    /// through a function guarded with `reinitializer`.
    ///
    /// Emits an {Initialized} event.
    modifier reinitializer(uint64 version) virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            // Clean upper bits, and shift left by 1 to make space for the initializing bit.
            version := shl(1, and(version, 0xffffffffffffffff))
            let i := sload(s)
            // If `initializing == 1 || initializedVersion >= version`.
            if iszero(lt(and(i, 1), lt(i, version))) {
                mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
                revert(0x1c, 0x04)
            }
            // Set `initializing` to 1, `initializedVersion` to `version`.
            sstore(s, or(1, version))
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            // Set `initializing` to 0, `initializedVersion` to `version`.
            sstore(s, version)
            // Emit the {Initialized} event.
            mstore(0x20, shr(1, version))
            log1(0x20, 0x20, _INITIALIZED_EVENT_SIGNATURE)
        }
    }

    /// @dev Guards a function such that it can only be called in the scope
    /// of a function guarded with `initializer` or `reinitializer`.
    modifier onlyInitializing() virtual {
        _checkInitializing();
        _;
    }

    /// @dev Reverts if the contract is not initializing.
    function _checkInitializing() internal view virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(and(1, sload(s))) {
                mstore(0x00, 0xd7e6bcf8) // `NotInitializing()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Locks any future initializations by setting the initialized version to `2**64 - 1`.
    ///
    /// Calling this in the constructor will prevent the contract from being initialized
    /// or reinitialized. It is recommended to use this to lock implementation contracts
    /// that are designed to be called through proxies.
    ///
    /// Emits an {Initialized} event the first time it is successfully called.
    function _disableInitializers() internal virtual {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            let i := sload(s)
            if and(i, 1) {
                mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
                revert(0x1c, 0x04)
            }
            let uint64max := 0xffffffffffffffff
            if iszero(eq(shr(1, i), uint64max)) {
                // Set `initializing` to 0, `initializedVersion` to `2**64 - 1`.
                sstore(s, shl(1, uint64max))
                // Emit the {Initialized} event.
                mstore(0x20, uint64max)
                log1(0x20, 0x20, _INITIALIZED_EVENT_SIGNATURE)
            }
        }
    }

    /// @dev Returns the highest version that has been initialized.
    function _getInitializedVersion() internal view virtual returns (uint64 version) {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            version := shr(1, sload(s))
        }
    }

    /// @dev Returns whether the contract is currently initializing.
    function _isInitializing() internal view virtual returns (bool result) {
        bytes32 s = _initializableSlot();
        /// @solidity memory-safe-assembly
        assembly {
            result := and(1, sload(s))
        }
    }
}

src/Batch.sol

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.22;

import {IBatch} from "./interfaces/IBatch.sol";

/// @title Batch
/// @notice See the documentation in {IBatch}.
/// @dev Forked from: https://github.com/sablier-labs/v2-core/blob/b88ead3d7dd483f7107d56320ca01e4122e00d92/src/abstracts/Batch.sol
abstract contract Batch is IBatch {
    /// @notice Thrown when an unexpected error occurs during a batch call.
    /// @param result The result of the failed batch call.
    error BatchError(bytes result);

    /// @inheritdoc IBatch
    /// @dev The `msg.value` should not be used on any method called in the batch.
    function batch(bytes[] calldata calls) external override {
        uint256 count = calls.length;

        for (uint256 i = 0; i < count; ++i) {
            (bool success, bytes memory result) = address(this).delegatecall(calls[i]);
            if (!success) {
                revert BatchError(result);
            }
        }
    }
}

src/StateOracleAccessControl.sol

// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.28;

import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";

/// @title StateOracleAccessControl
/// @author @fredo ([email protected])
/// @notice Base contract providing role-based access control for StateOracle
/// @dev Implements a five-tier role hierarchy with owner/DEFAULT_ADMIN_ROLE invariant
/// @dev Invariant: owner() always has DEFAULT_ADMIN_ROLE exclusively (1:1 coupling)
///
/// @dev Role Hierarchy:
/// ```
///                              owner() (Cold Multisig)
///                                       ║
///                          (1:1 coupling - INVARIANT)
///                                       ║
///                               DEFAULT_ADMIN_ROLE
///                                       │
///                ┌──────────────────────┼──────────────────────┐
///                │                      │                      │
///          GOVERNANCE_ROLE        GUARDIAN_ADMIN        OPERATOR_ADMIN
///                │                      │                      │
///                │                GUARDIAN_ROLE         OPERATOR_ROLE
///                │                      │                      │
///                ▼                      ▼                      ▼
///    ┌────────────────────┐ ┌────────────────────┐ ┌────────────────────┐
///    │  Protocol Admin    │ │  Emergency Actions │ │  Whitelist Mgmt    │
///    ├────────────────────┤ ├────────────────────┤ ├────────────────────┤
///    │ • enableWhitelist  │ │ • removeAssertion  │ │ • addToWhitelist   │
///    │ • disableWhitelist │ │   ByGuardian       │ │ • removeFrom       │
///    │ • addAdminVerifier │ │ • revokeManager    │ │   Whitelist        │
///    │ • removeAdmin      │ │                    │ │                    │
///    │   Verifier         │ │                    │ │                    │
///    │ • setMaxAssertions │ │                    │ │                    │
///    │   PerAA            │ │                    │ │                    │
///    └────────────────────┘ └────────────────────┘ └────────────────────┘
/// ```
///
/// @dev Security Features:
/// - owner() and DEFAULT_ADMIN_ROLE are permanently coupled (cannot be broken)
/// - DEFAULT_ADMIN_ROLE cannot be granted to any address except owner()
/// - DEFAULT_ADMIN_ROLE cannot be revoked from owner()
/// - Owner cannot renounce DEFAULT_ADMIN_ROLE through renounceRole()
/// - renounceOwnership() maintains invariant by granting role to address(0)
/// - All role transfers are atomic to prevent invariant violations
abstract contract StateOracleAccessControl is Ownable2Step, AccessControl {
    /// @notice Role for governance operations (protocol administration)
    /// @dev Managed by DEFAULT_ADMIN_ROLE (owner)
    bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");

    /// @notice Role for guardian admins who can manage guardian access
    bytes32 public constant GUARDIAN_ADMIN_ROLE = keccak256("GUARDIAN_ADMIN_ROLE");

    /// @notice Role for guardians who can take emergency defensive actions
    bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE");

    /// @notice Role for operator admins who can manage operator access
    bytes32 public constant OPERATOR_ADMIN_ROLE = keccak256("OPERATOR_ADMIN_ROLE");

    /// @notice Role for operators who can manage day-to-day operations like whitelist management
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");

    /// @notice Thrown when an unauthorized address attempts to manage assertions
    error UnauthorizedManager();

    /// @notice Thrown when attempting to grant DEFAULT_ADMIN_ROLE to non-owner
    error CannotGrantDefaultAdminRole();

    /// @notice Thrown when attempting to revoke owner's DEFAULT_ADMIN_ROLE
    error CannotRevokeOwnerDefaultAdminRole();

    /// @notice Thrown when owner attempts to renounce DEFAULT_ADMIN_ROLE
    error CannotRenounceOwnerDefaultAdminRole();

    /// @notice Modifier to restrict access to governance role
    modifier onlyGovernance() {
        _checkRole(GOVERNANCE_ROLE);
        _;
    }

    /// @notice Modifier to restrict access to guardian role
    modifier onlyGuardian() {
        _checkRole(GUARDIAN_ROLE);
        _;
    }

    /// @notice Modifier to restrict access to operator role
    modifier onlyOperator() {
        _checkRole(OPERATOR_ROLE);
        _;
    }

    /// @notice Returns all roles in the system
    /// @dev DEFAULT_ADMIN_ROLE is not included as it's coupled with ownership
    /// @return roles Array of all role identifiers
    function _getAllRoles() internal pure returns (bytes32[] memory roles) {
        roles = new bytes32[](5);
        roles[0] = GOVERNANCE_ROLE;
        roles[1] = GUARDIAN_ADMIN_ROLE;
        roles[2] = OPERATOR_ADMIN_ROLE;
        roles[3] = GUARDIAN_ROLE;
        roles[4] = OPERATOR_ROLE;
        return roles;
    }

    /// @notice Initialize the role hierarchy and grant initial roles
    /// @dev Internal function called during contract initialization
    /// @dev Sets up the complete role hierarchy with proper admin relationships
    /// @dev Initially grants all admin roles to the admin address (can be delegated later)
    /// @param admin The address to set as owner and grant initial roles to
    function _initializeRoles(address admin) internal {
        // _transferOwnership grants DEFAULT_ADMIN_ROLE to admin automatically
        _transferOwnership(admin);

        // Set up role hierarchy
        // DEFAULT_ADMIN_ROLE (owner) is the admin of all other roles
        _setRoleAdmin(GOVERNANCE_ROLE, DEFAULT_ADMIN_ROLE);
        _setRoleAdmin(GUARDIAN_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
        _setRoleAdmin(OPERATOR_ADMIN_ROLE, DEFAULT_ADMIN_ROLE);
        _setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ADMIN_ROLE);
        _setRoleAdmin(OPERATOR_ROLE, OPERATOR_ADMIN_ROLE);

        // Grant all delegatable roles to admin
        bytes32[] memory roles = _getAllRoles();
        for (uint256 i = 0; i < roles.length; i++) {
            _grantRole(roles[i], admin);
        }
    }

    /// @notice Grants the governance role to an address
    /// @dev Only callable by owner (who has DEFAULT_ADMIN_ROLE)
    /// @dev Governance role can manage protocol parameters (whitelist, verifiers, etc.)
    /// @param governance The address to grant the governance role to
    function grantGovernanceRole(address governance) external onlyOwner {
        _grantRole(GOVERNANCE_ROLE, governance);
    }

    /// @notice Revokes the governance role from an address
    /// @dev Only callable by owner (who has DEFAULT_ADMIN_ROLE)
    /// @param governance The address to revoke the governance role from
    function revokeGovernanceRole(address governance) external onlyOwner {
        _revokeRole(GOVERNANCE_ROLE, governance);
    }

    /// @notice Grants the guardian admin role to an address
    /// @dev Only callable by owner (who has DEFAULT_ADMIN_ROLE)
    /// @dev Guardian admins can manage the guardian role (grant/revoke guardians)
    /// @param guardianAdmin The address to grant the guardian admin role to
    function grantGuardianAdminRole(address guardianAdmin) external onlyOwner {
        _grantRole(GUARDIAN_ADMIN_ROLE, guardianAdmin);
    }

    /// @notice Revokes the guardian admin role from an address
    /// @dev Only callable by owner (who has DEFAULT_ADMIN_ROLE)
    /// @param guardianAdmin The address to revoke the guardian admin role from
    function revokeGuardianAdminRole(address guardianAdmin) external onlyOwner {
        _revokeRole(GUARDIAN_ADMIN_ROLE, guardianAdmin);
    }

    /// @notice Grants the guardian role to an address
    /// @dev Only callable by guardian admins
    /// @dev Guardians can perform emergency defensive actions (remove assertions, revoke managers)
    /// @param guardian The address to grant the guardian role to
    function grantGuardianRole(address guardian) external onlyRole(GUARDIAN_ADMIN_ROLE) {
        _grantRole(GUARDIAN_ROLE, guardian);
    }

    /// @notice Revokes the guardian role from an address
    /// @dev Only callable by guardian admins
    /// @param guardian The address to revoke the guardian role from
    function revokeGuardianRole(address guardian) external onlyRole(GUARDIAN_ADMIN_ROLE) {
        _revokeRole(GUARDIAN_ROLE, guardian);
    }

    /// @notice Grants the operator admin role to an address
    /// @dev Only callable by owner (who has DEFAULT_ADMIN_ROLE)
    /// @dev Operator admins can manage the operator role (grant/revoke operators)
    /// @param operatorAdmin The address to grant the operator admin role to
    function grantOperatorAdminRole(address operatorAdmin) external onlyOwner {
        _grantRole(OPERATOR_ADMIN_ROLE, operatorAdmin);
    }

    /// @notice Revokes the operator admin role from an address
    /// @dev Only callable by owner (who has DEFAULT_ADMIN_ROLE)
    /// @param operatorAdmin The address to revoke the operator admin role from
    function revokeOperatorAdminRole(address operatorAdmin) external onlyOwner {
        _revokeRole(OPERATOR_ADMIN_ROLE, operatorAdmin);
    }

    /// @notice Grants the operator role to an address
    /// @dev Only callable by operator admins
    /// @dev Operators can manage the whitelist (add/remove addresses)
    /// @param operator The address to grant the operator role to
    function grantOperatorRole(address operator) external onlyRole(OPERATOR_ADMIN_ROLE) {
        _grantRole(OPERATOR_ROLE, operator);
    }

    /// @notice Revokes the operator role from an address
    /// @dev Only callable by operator admins
    /// @param operator The address to revoke the operator role from
    function revokeOperatorRole(address operator) external onlyRole(OPERATOR_ADMIN_ROLE) {
        _revokeRole(OPERATOR_ROLE, operator);
    }

    /// @notice Override _transferOwnership to also transfer DEFAULT_ADMIN_ROLE atomically
    /// @dev Internal function called by transferOwnership() and renounceOwnership()
    /// @dev Transfers DEFAULT_ADMIN_ROLE BEFORE changing ownership to maintain invariant
    /// @dev Also transfers any delegatable roles that the old owner had
    /// @dev Handles address(0) case for renounceOwnership() to maintain invariant
    /// @param newOwner The address of the new owner (can be address(0) when renouncing)
    function _transferOwnership(address newOwner) internal virtual override {
        address oldOwner = owner();

        // Transfer DEFAULT_ADMIN_ROLE BEFORE ownership transfer (maintain 1:1 invariant)
        // Always transfer role, even to address(0) (maintains invariant when renouncing)
        if (oldOwner != address(0)) {
            _revokeRole(DEFAULT_ADMIN_ROLE, oldOwner);

            // Transfer any delegatable roles the old owner has to the new owner
            bytes32[] memory roles = _getAllRoles();
            for (uint256 i = 0; i < roles.length; i++) {
                if (hasRole(roles[i], oldOwner)) {
                    _revokeRole(roles[i], oldOwner);
                    if (newOwner != address(0)) {
                        _grantRole(roles[i], newOwner);
                    }
                }
            }
        }

        // Grant DEFAULT_ADMIN_ROLE to newOwner unconditionally (even if address(0))
        _grantRole(DEFAULT_ADMIN_ROLE, newOwner);

        super._transferOwnership(newOwner);
    }

    /// @notice Override grantRole to prevent granting DEFAULT_ADMIN_ROLE to anyone
    /// @dev Maintains invariant: only owner() can have DEFAULT_ADMIN_ROLE
    /// @dev DEFAULT_ADMIN_ROLE can only be transferred via ownership transfer
    /// @param role The role to grant
    /// @param account The account to grant the role to
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        require(role != DEFAULT_ADMIN_ROLE, CannotGrantDefaultAdminRole());
        super.grantRole(role, account);
    }

    /// @notice Override revokeRole to prevent revoking DEFAULT_ADMIN_ROLE from owner
    /// @dev Maintains invariant: owner() must always have DEFAULT_ADMIN_ROLE
    /// @dev Allows revoking DEFAULT_ADMIN_ROLE from non-owners (e.g., during ownership transfer)
    /// @param role The role to revoke
    /// @param account The account to revoke the role from
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        require(role != DEFAULT_ADMIN_ROLE || account != owner(), CannotRevokeOwnerDefaultAdminRole());
        super.revokeRole(role, account);
    }

    /// @notice Override renounceRole to prevent owner from renouncing DEFAULT_ADMIN_ROLE
    /// @dev Maintains invariant: owner() must keep DEFAULT_ADMIN_ROLE
    /// @dev Owner must use renounceOwnership() instead to give up both owner and role atomically
    /// @param role The role to renounce
    /// @param callerConfirmation Must be msg.sender (OpenZeppelin safety check)
    function renounceRole(bytes32 role, address callerConfirmation) public virtual override {
        require(role != DEFAULT_ADMIN_ROLE || callerConfirmation != owner(), CannotRenounceOwnerDefaultAdminRole());
        super.renounceRole(role, callerConfirmation);
    }
}

src/interfaces/IAdminVerifier.sol

// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.28;

interface IAdminVerifier {
    function verifyAdmin(address contractAddress, address requester, bytes calldata data) external view returns (bool);
}

src/interfaces/IBatch.sol

// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.22;

/// @notice This contract implements logic to batch call any function.
interface IBatch {
    /// @notice Allows batched call to self, `this` contract.
    /// @param calls An array of inputs for each call.
    function batch(bytes[] calldata calls) external;
}

src/interfaces/IDAVerifier.sol

// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.28;

interface IDAVerifier {
    /// @notice Error thrown when a proof is invalid
    error InvalidProof();

    /// @notice Verifies a data availability proof for an assertion
    /// @param assertionId The unique identifier of the assertion
    /// @param metadata The metadata of the assertion, needed to verify the proof
    /// @param proof The proof proving data availability
    /// @return verified True if the proof is valid, false otherwise
    function verifyDA(bytes32 assertionId, bytes calldata metadata, bytes calldata proof)
        external
        view
        returns (bool verified);
}

src/lib/AdminVerifierRegistry.sol

// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.28;

import {IAdminVerifier} from "../interfaces/IAdminVerifier.sol";

/// @title AdminVerifierRegistry
/// @author @fredo ([email protected])
/// @notice Manages the registration of admin verifiers
library AdminVerifierRegistry {
    /// @notice Thrown when attempting to add an admin verifier that is already registered
    error AdminVerifierAlreadyRegistered();
    /// @notice Thrown when attempting to remove an unregistered admin verifier
    error AdminVerifierNotRegistered();

    /// @notice Emitted when an admin verifier is added
    /// @param adminVerifier The admin verifier that was added
    event AdminVerifierAdded(IAdminVerifier adminVerifier);

    /// @notice Emitted when an admin verifier is removed
    /// @param adminVerifier The admin verifier that was removed
    event AdminVerifierRemoved(IAdminVerifier adminVerifier);

    /// @notice Checks if an admin verifier is registered
    /// @param adminVerifiers The mapping of admin verifiers to their registration status
    /// @param adminVerifier The admin verifier to check
    /// @return isRegistered True if the admin verifier is registered, false otherwise
    function isRegistered(mapping(IAdminVerifier => bool) storage adminVerifiers, IAdminVerifier adminVerifier)
        internal
        view
        returns (bool)
    {
        return adminVerifiers[adminVerifier];
    }

    /// @notice Adds an admin verifier to the registry
    /// @param adminVerifiers The mapping of admin verifiers to their registration status
    /// @param adminVerifier The admin verifier to add
    /// @dev Throws an error if the admin verifier is already registered
    function add(mapping(IAdminVerifier => bool) storage adminVerifiers, IAdminVerifier adminVerifier) internal {
        require(!isRegistered(adminVerifiers, adminVerifier), AdminVerifierAlreadyRegistered());
        adminVerifiers[adminVerifier] = true;
        emit AdminVerifierAdded(adminVerifier);
    }

    /// @notice Removes an admin verifier from the registry
    /// @param adminVerifiers The mapping of admin verifiers to their registration status
    /// @param adminVerifier The admin verifier to remove
    /// @dev Throws an error if the admin verifier is not registered
    function remove(mapping(IAdminVerifier => bool) storage adminVerifiers, IAdminVerifier adminVerifier) internal {
        require(isRegistered(adminVerifiers, adminVerifier), AdminVerifierNotRegistered());
        adminVerifiers[adminVerifier] = false;
        emit AdminVerifierRemoved(adminVerifier);
    }
}

src/lib/DAVerifierRegistry.sol

// SPDX-License-Identifier: CC0-1.0
pragma solidity ^0.8.28;

import {IDAVerifier} from "../interfaces/IDAVerifier.sol";

/// @title DAVerifierRegistry
/// @author @fredo ([email protected])
/// @notice Manages the registration of DA verifiers
library DAVerifierRegistry {
    /// @notice Thrown when attempting to add a DA verifier that is already registered
    error DAVerifierAlreadyRegistered();
    /// @notice Thrown when attempting to remove an unregistered DA verifier
    error DAVerifierNotRegistered();

    /// @notice Emitted when a DA verifier is added
    /// @param daVerifier The DA verifier that was added
    event DAVerifierAdded(IDAVerifier daVerifier);

    /// @notice Emitted when a DA verifier is removed
    /// @param daVerifier The DA verifier that was removed
    event DAVerifierRemoved(IDAVerifier daVerifier);

    /// @notice Checks if a DA verifier is registered
    /// @param daVerifiers The mapping of DA verifiers to their registration status
    /// @param daVerifier The DA verifier to check
    /// @return isRegistered True if the DA verifier is registered, false otherwise
    function isRegistered(mapping(IDAVerifier => bool) storage daVerifiers, IDAVerifier daVerifier)
        internal
        view
        returns (bool)
    {
        return daVerifiers[daVerifier];
    }

    /// @notice Adds a DA verifier to the registry
    /// @param daVerifiers The mapping of DA verifiers to their registration status
    /// @param daVerifier The DA verifier to add
    /// @dev Throws an error if the DA verifier is already registered
    function add(mapping(IDAVerifier => bool) storage daVerifiers, IDAVerifier daVerifier) internal {
        require(!isRegistered(daVerifiers, daVerifier), DAVerifierAlreadyRegistered());
        daVerifiers[daVerifier] = true;
        emit DAVerifierAdded(daVerifier);
    }

    /// @notice Removes a DA verifier from the registry
    /// @param daVerifiers The mapping of DA verifiers to their registration status
    /// @param daVerifier The DA verifier to remove
    /// @dev Throws an error if the DA verifier is not registered
    function remove(mapping(IDAVerifier => bool) storage daVerifiers, IDAVerifier daVerifier) internal {
        require(isRegistered(daVerifiers, daVerifier), DAVerifierNotRegistered());
        daVerifiers[daVerifier] = false;
        emit DAVerifierRemoved(daVerifier);
    }
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.