Skip to content
Verified contractExactUNLICENSED

Executor

Address0x14a5a3d1b7aaa89d3c08d15895c42c8b5b9ba2ed
Balance

0 ETH

 

Transactions

0

 

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
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,399,527
Creation transaction
0x3c8271ea26…ff6a9fc2f1

src/Executor.sol

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

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Registry} from "./Registry.sol";
import {ILogic} from "./interfaces/ILogic.sol";
import {ROUNDING_PER_TRANSFER} from "./Rounding.sol";

/// @dev The one thing the Executor asks of its front door: whether an act is in flight.
interface IActLock {
    function busy() external view returns (bool);
}

/// @notice Makes every external call, and nobody approves it. Holds tokens during one act and
/// nothing between acts. Takes orders from the front door only (which deploys it) and calls
/// only the route's targets. What it calls them with is Logic's plan; a bad plan can reach
/// nothing but the act's own funds, because nothing else is here.
///
/// Only `_tokenCall` and `_allowanceOf` bound what a token can charge: a gas stipend and a
/// fixed 32-byte return window. A venue call in `run` gets all gas; it copies no success
/// returndata and caps a failure payload. The `balanceOf` in `forward` and every call in
/// `sweep` are ordinary calls.
contract Executor {
    using SafeERC20 for IERC20;

    address public immutable frontDoor;
    Registry public immutable registry;

    /// @dev Stipend for an approval. A real `approve` that writes a new allowance costs about 25k
    /// on mainnet today and about 119k on Ethereum Sepolia since its October 2026 upgrade
    /// repriced new storage. This contract never changes, so the bound leaves room for further
    /// repricing; it still caps what a hostile token can burn.
    uint256 private constant TOKEN_CALL_GAS = 500_000;

    /// @dev Stipend for returning leftovers. Receipts that settle rewards on transfer cost two to
    /// three times an approval.
    uint256 private constant FORWARD_GAS = 1_000_000;

    /// @dev Cap on the revert payload carried out of a failed venue call.
    uint256 private constant VENUE_ERROR_BYTES = 256;

    event Swept(address indexed token, address indexed to, uint256 amount);

    error OnlyFrontDoor(address caller);
    error NotGovernance(address caller);
    error TargetNotInRoute(address target);
    error VenueCallFailed(bytes truncatedReturndata);
    error AllowanceNotRevoked(address token, address spender);
    error SweepDuringAct();
    error SweepExceedsHeld(uint256 held, uint256 requested);
    error DeliveryFailed(address token, address to, uint256 amount);
    error ZeroAddress();

    modifier onlyFrontDoor() {
        if (msg.sender != frontDoor) revert OnlyFrontDoor(msg.sender);
        _;
    }

    constructor(Registry registry_) {
        if (address(registry_) == address(0)) revert ZeroAddress();
        frontDoor = msg.sender;
        registry = registry_;
    }

    /// @notice One leg's calls, in order. Each target must be in the route. An allowance, if
    /// any, is granted exact before the call, revoked after, and checked to be zero.
    function run(address[] calldata allowedTargets, ILogic.Call[] calldata calls) external onlyFrontDoor {
        for (uint256 i = 0; i < calls.length; i++) {
            ILogic.Call calldata c = calls[i];
            if (!_isAllowed(allowedTargets, c.target)) revert TargetNotInRoute(c.target);

            bool approves = c.approveToken != address(0);
            if (approves) _bestEffortApprove(IERC20(c.approveToken), c.target, c.approveAmount);

            _callVenue(c.target, c.data);

            // Launch venues pull the exact grant, so the allowance is already zero: revoke only
            // what is left. A token that cannot answer reads as allowed, so this fails closed.
            if (approves && _allowanceOf(c.approveToken, c.target) != 0) {
                _bestEffortApprove(IERC20(c.approveToken), c.target, 0);
                if (_allowanceOf(c.approveToken, c.target) != 0) revert AllowanceNotRevoked(c.approveToken, c.target);
            }
        }
    }

    /// @notice Delivers a leftover, an output or a fee. Strict: a delivery that does not happen
    /// fails the act, so nothing of an account's ever rests here. The transfer goes through
    /// `_tokenCall`; the `balanceOf` after it is an ordinary call. What the token says is not enough:
    /// the balance must have moved by what was sent, give or take the one unit a scaled-balance
    /// receipt rounds. `before` is the front door's own last read of this contract's balance of
    /// `token` (nothing ran since); `held` is the read after, so the next delivery starts from it.
    function forward(address token, address to, uint256 amount, uint256 before)
        external
        onlyFrontDoor
        returns (uint256 held)
    {
        if (token.code.length == 0) revert DeliveryFailed(token, to, amount);
        bool ok = _tokenCall(token, abi.encodeCall(IERC20.transfer, (to, amount)), FORWARD_GAS);
        held = IERC20(token).balanceOf(address(this));
        if (!ok || held > before || before - held + ROUNDING_PER_TRANSFER < amount) {
            revert DeliveryFailed(token, to, amount);
        }
    }

    /// @notice Governance rescue for tokens sent here by mistake. Refused while an act is in
    /// flight, and every act ends holding nothing, so no position is ever reachable.
    function sweep(address token, address to, uint256 amount) external {
        if (!registry.hasRole(registry.GOVERNANCE_ROLE(), msg.sender)) revert NotGovernance(msg.sender);
        if (to == address(0)) revert ZeroAddress();
        if (IActLock(frontDoor).busy()) revert SweepDuringAct();
        uint256 held = IERC20(token).balanceOf(address(this));
        if (amount > held) revert SweepExceedsHeld(held, amount);
        IERC20(token).safeTransfer(to, amount);
        emit Swept(token, to, amount);
    }

    /// @dev Bounded allowance read. A token that cannot answer counts as still allowed, so the
    /// revoke check fails closed.
    function _allowanceOf(address token, address spender) private view returns (uint256 allowed) {
        bytes memory payload = abi.encodeCall(IERC20.allowance, (address(this), spender));
        uint256 stipend = TOKEN_CALL_GAS;
        bool ok;
        assembly ("memory-safe") {
            let out := mload(0x40)
            mstore(out, 0)
            ok := staticcall(stipend, token, add(payload, 0x20), mload(payload), out, 0x20)
            allowed := mload(out)
            if iszero(eq(returndatasize(), 0x20)) { ok := 0 }
        }
        if (!ok) return type(uint256).max;
    }

    function _isAllowed(address[] calldata allowedTargets, address target) private pure returns (bool) {
        for (uint256 i = 0; i < allowedTargets.length; i++) {
            if (allowedTargets[i] == target) return true;
        }
        return false;
    }

    /// @dev Assembly so no success returndata is copied (a hostile venue could size it from the
    /// gas it got). Failure carries at most `VENUE_ERROR_BYTES`. A codeless target fails.
    function _callVenue(address venue, bytes calldata venueCalldata) private {
        bool ok;
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            calldatacopy(ptr, venueCalldata.offset, venueCalldata.length)
            ok := call(gas(), venue, 0, ptr, venueCalldata.length, 0, 0)
            // Only an empty success can come from an address with no code.
            if and(ok, iszero(returndatasize())) { if iszero(extcodesize(venue)) { ok := 0 } }
        }
        if (!ok) {
            bytes memory truncated = new bytes(VENUE_ERROR_BYTES);
            assembly ("memory-safe") {
                let size := returndatasize()
                if gt(size, VENUE_ERROR_BYTES) { size := VENUE_ERROR_BYTES }
                returndatacopy(add(truncated, 0x20), 0, size)
                mstore(truncated, size)
            }
            revert VenueCallFailed(truncated);
        }
    }

    /// @dev `forceApprove` without the revert: USDT rejects non-zero to non-zero, so zero first.
    function _bestEffortApprove(IERC20 token, address spender, uint256 amount) private {
        if (_tokenCall(address(token), abi.encodeCall(IERC20.approve, (spender, amount)), TOKEN_CALL_GAS)) return;
        if (_tokenCall(address(token), abi.encodeCall(IERC20.approve, (spender, 0)), TOKEN_CALL_GAS)) {
            _tokenCall(address(token), abi.encodeCall(IERC20.approve, (spender, amount)), TOKEN_CALL_GAS);
        }
    }

    /// @dev The one way to call a token this contract must survive: gas stipend, 32-byte return
    /// window, raw success check (empty return is the USDT shape), and no code means no success.
    function _tokenCall(address token, bytes memory payload, uint256 stipend) private returns (bool ok) {
        assembly ("memory-safe") {
            let out := mload(0x40)
            mstore(out, 0)
            ok := call(stipend, token, 0, add(payload, 0x20), mload(payload), out, 0x20)
            if ok {
                switch returndatasize()
                // Only an empty success can come from an address with no code.
                case 0 { if iszero(extcodesize(token)) { ok := 0 } }
                case 32 { ok := eq(mload(out), 1) }
                default { ok := 0 }
            }
        }
    }
}

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

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {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 ERC165
    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).
     *
     * Emits a {RoleRevoked} event if the calling account had `role` and this call successfully revoked it.
     *
     * 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/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 {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
import {IERC20Metadata} from "../../../interfaces/IERC20Metadata.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/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);
}

src/Registry.sol

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

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

/// @notice What the timelock approved: routes, the receipt table, the treasury, and the
/// roles. Immutable code holding data only. A route is in the catalog or it is not; being in
/// it is the approval, since the timelock is the only writer.
///
/// A route is four facts: token in, token out, the targets the Executor may call, and a `tag`
/// naming the call shape (defined in Logic). The front door reads the rest from the receipt
/// table: handing in a bound receipt is an exit, producing one is an entry. A route with no
/// tokens is "call the venue". Ids are the hash of the definition.
///
/// One asset per receipt, bound once and never rebound (Logic's fee clock prices a receipt in
/// that unit). A receipt is never an asset and an asset is never a receipt. A receipt is bound
/// before any route names it: a token a route has named can never be bound, so a binding never
/// changes what an existing route means.
contract Registry is AccessControl {
    /// @dev Either token may be zero: a claim pulls nothing, a bridge yields nothing here, and a
    /// route with neither just calls the venue.
    struct Route {
        address tokenIn;
        address tokenOut;
        address[] targets;
        bytes32 tag;
    }

    /// @dev Fast, restrict-only. Used by Logic (pause, close).
    bytes32 public constant EMERGENCY_ROLE = keccak256("EMERGENCY_ROLE");

    /// @dev Admin of `EMERGENCY_ROLE` and of itself, never of `TIMELOCK_ROLE`. Used by `sweep`.
    bytes32 public constant GOVERNANCE_ROLE = keccak256("GOVERNANCE_ROLE");

    /// @dev A `TimelockController`; administers itself. The only writer of this catalog.
    bytes32 public constant TIMELOCK_ROLE = keccak256("TIMELOCK_ROLE");

    mapping(bytes32 id => Route data) private _routes;

    /// @dev The asset a receipt is bought with and paid out in; zero for a non-receipt.
    mapping(address receipt => address asset) public assetOf;

    /// @dev Tokens named as an asset, so they can never become receipts.
    mapping(address token => bool) public isAsset;

    /// @dev Tokens any route has ever named, in or out; never cleared, so they can never become
    /// receipts.
    mapping(address token => bool) public isNamed;

    /// @dev Where every fee goes. Set at construction, changed only by the timelock, never zero.
    address public treasury;

    /// @dev OZ tracks members but not counts; the last-holder guard needs one.
    mapping(bytes32 role => uint256 count) private _roleMemberCount;

    event RouteAdded(
        bytes32 indexed id, address indexed tokenIn, address indexed tokenOut, address[] targets, bytes32 tag
    );
    event RouteRemoved(bytes32 indexed id);
    event ReceiptBound(address indexed receipt, address indexed asset);
    event TreasurySet(address indexed treasury);

    error RouteAlreadyAdded(bytes32 id);
    error RouteNotFound(bytes32 id);
    error ZeroAddress();
    error TreasuryIsRegistry();
    error RouteTokensMustDiffer(address token);
    error RouteNeedsTargets();
    error TokenIsAReceipt(address token, address asset);
    error TokenIsAnAsset(address token);
    error TokenAlreadyNamed(address token);
    error ReceiptAlreadyBound(address receipt, address asset);
    error ReceiptAssetMismatch(address receipt, address bound, address given);
    error RoleRenouncementDisabled();
    error LastRoleHolder(bytes32 role);
    error RolesMustBeDistinct();

    constructor(address governance_, address emergency_, address timelock_, address treasury_) {
        if (governance_ == address(0) || emergency_ == address(0) || timelock_ == address(0)) {
            revert ZeroAddress();
        }
        if (governance_ == emergency_ || governance_ == timelock_ || emergency_ == timelock_) {
            revert RolesMustBeDistinct();
        }

        _setRoleAdmin(GOVERNANCE_ROLE, GOVERNANCE_ROLE);
        _setRoleAdmin(EMERGENCY_ROLE, GOVERNANCE_ROLE);
        _setRoleAdmin(TIMELOCK_ROLE, TIMELOCK_ROLE);

        _grantRole(GOVERNANCE_ROLE, governance_);
        _grantRole(EMERGENCY_ROLE, emergency_);
        _grantRole(TIMELOCK_ROLE, timelock_);
        _setTreasury(treasury_);
    }

    /// @notice The route's id is its definition hashed.
    function routeId(Route calldata route) public pure returns (bytes32) {
        return keccak256(abi.encode(route.tokenIn, route.tokenOut, route.targets, route.tag));
    }

    /// @notice The full row; an unknown id returns an empty route.
    function getRoute(bytes32 id) external view returns (Route memory) {
        return _routes[id];
    }

    /// @notice Whether `id` is in the catalog (every route has targets).
    function isRoute(bytes32 id) public view returns (bool) {
        return _routes[id].targets.length != 0;
    }

    /// @notice Fixes the asset a receipt is bought with and paid out in. Once, for good, and
    /// before any route names the receipt: a later binding would turn a gated entry handing the
    /// token in into an ungated exit.
    function bindReceipt(address receipt, address asset) external onlyRole(TIMELOCK_ROLE) {
        if (receipt == address(0) || asset == address(0)) revert ZeroAddress();
        if (receipt == asset) revert RouteTokensMustDiffer(receipt);
        if (assetOf[receipt] != address(0)) revert ReceiptAlreadyBound(receipt, assetOf[receipt]);
        if (isAsset[receipt]) revert TokenIsAnAsset(receipt);
        if (isNamed[receipt]) revert TokenAlreadyNamed(receipt);
        if (assetOf[asset] != address(0)) revert TokenIsAReceipt(asset, assetOf[asset]);

        assetOf[receipt] = asset;
        isAsset[asset] = true;
        emit ReceiptBound(receipt, asset);
    }

    /// @notice Adds a route. Rows are never edited: to change one, remove it and add the new
    /// definition. Whether the targets answer the tag's call shape is the checklist's job; a
    /// mismatch fails closed at the first act.
    function addRoute(Route calldata route) external onlyRole(TIMELOCK_ROLE) returns (bytes32 id) {
        _validateShape(route);
        id = routeId(route);
        if (isRoute(id)) revert RouteAlreadyAdded(id);
        _routes[id] = route;
        if (route.tokenIn != address(0)) isNamed[route.tokenIn] = true;
        if (route.tokenOut != address(0)) isNamed[route.tokenOut] = true;
        emit RouteAdded(id, route.tokenIn, route.tokenOut, route.targets, route.tag);
    }

    /// @notice Removes a route. Timelocked, so the deliberate way to retire a venue: exits
    /// through the row stop with it (the root key can still leave at the venue). The fast stop
    /// for entries is Logic's `closeRoute`.
    function removeRoute(bytes32 id) external onlyRole(TIMELOCK_ROLE) {
        if (!isRoute(id)) revert RouteNotFound(id);
        delete _routes[id];
        emit RouteRemoved(id);
    }

    /// @notice Moves where fees go from now on. Timelocked, so everyone sees the new address
    /// during the delay; a lost key or a blocklisted address is replaced without a new front door.
    function setTreasury(address treasury_) external onlyRole(TIMELOCK_ROLE) {
        _setTreasury(treasury_);
    }

    /// @notice Disabled. Hand over a self-administered tier in two steps: the holder grants the
    /// new address, then the new holder revokes the old one. The revoke proves the new holder can
    /// act; until it, the old holder can still revoke a wrong grant.
    function renounceRole(bytes32, address) public pure override {
        revert RoleRenouncementDisabled();
    }

    /// @notice Rejects `address(0)`, which would slip past the last-holder guard, and an account
    /// that holds another tier: the three tiers stay three addresses, as at construction. To move
    /// an address to another tier, revoke its tier first (the only holder of a self-administered
    /// tier hands it over first: the last-holder guard refuses its revoke).
    function grantRole(bytes32 role, address account) public override onlyRole(getRoleAdmin(role)) {
        if (account == address(0)) revert ZeroAddress();
        if (
            (role != GOVERNANCE_ROLE && hasRole(GOVERNANCE_ROLE, account))
                || (role != EMERGENCY_ROLE && hasRole(EMERGENCY_ROLE, account))
                || (role != TIMELOCK_ROLE && hasRole(TIMELOCK_ROLE, account))
        ) revert RolesMustBeDistinct();
        _grantRole(role, account);
    }

    /// @notice The last holder of a self-administering tier cannot be revoked. EMERGENCY is
    /// unguarded on purpose: governance can always mint a replacement.
    function revokeRole(bytes32 role, address account) public override onlyRole(getRoleAdmin(role)) {
        bool selfAdministered = getRoleAdmin(role) == role;
        if (selfAdministered && hasRole(role, account) && _roleMemberCount[role] == 1) {
            revert LastRoleHolder(role);
        }
        _revokeRole(role, account);
    }

    function getRoleMemberCountOf(bytes32 role) public view returns (uint256) {
        return _roleMemberCount[role];
    }

    /// @dev Counts move only on an actual change.
    function _grantRole(bytes32 role, address account) internal override returns (bool granted) {
        granted = super._grantRole(role, account);
        if (granted) ++_roleMemberCount[role];
    }

    function _revokeRole(bytes32 role, address account) internal override returns (bool revoked) {
        revoked = super._revokeRole(role, account);
        if (revoked) --_roleMemberCount[role];
    }

    function _setTreasury(address treasury_) private {
        if (treasury_ == address(0)) revert ZeroAddress();
        // The Registry moves no tokens, so fees sent here would stay here.
        if (treasury_ == address(this)) revert TreasuryIsRegistry();
        treasury = treasury_;
        emit TreasurySet(treasury_);
    }

    /// @dev Tokens differ unless both are absent; at least one target; and a bound receipt on
    /// either side pairs with its own asset. Two unbound tokens are a plain route (no position).
    function _validateShape(Route calldata route) private view {
        if (route.tokenIn == route.tokenOut && route.tokenIn != address(0)) {
            revert RouteTokensMustDiffer(route.tokenIn);
        }
        if (route.targets.length == 0) revert RouteNeedsTargets();
        for (uint256 i = 0; i < route.targets.length; i++) {
            if (route.targets[i] == address(0)) revert ZeroAddress();
        }
        _requireAgrees(route.tokenIn, route.tokenOut);
        _requireAgrees(route.tokenOut, route.tokenIn);
    }

    /// @dev If `receipt` is bound, `other` must be its asset.
    function _requireAgrees(address receipt, address other) private view {
        address asset = assetOf[receipt];
        if (asset != address(0) && other != asset) revert ReceiptAssetMismatch(receipt, asset, other);
    }
}

src/Rounding.sol

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

/// @dev The rounding allowances, in one place. A scaled-balance receipt (Aave's aTokens,
/// Compound III) stores a scaled amount and shows `scaled × index`, so a transfer of it can land
/// one unit short of what was asked.

/// @dev One transfer: what the Executor's `forward` allows between the amount sent and the
/// balance that moved.
uint256 constant ROUNDING_PER_TRANSFER = 1;

/// @dev One act, two hops: the pull into the Executor and the venue's own burn. What the front
/// door allows below the Executor's baselines, and what Logic allows between the account and
/// the venue.
uint256 constant ROUNDING_PER_ACT = 2 * ROUNDING_PER_TRANSFER;

src/interfaces/ILogic.sol

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

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

/// @notice What the front door asks of Logic. `gate`, `plan` and `collect` are views: Logic
/// decides, the front door and the Executor act, so a hostile Logic can only answer badly.
/// `onAct` is the one call that lets Logic write: its own records of what just happened.
///
/// The front door reads the route and its receipt table entries once per act and hands Logic
/// its copy. Logic checks the copy against the route's id and the catalog; the
/// table entries it takes as given, so a direct caller that passes wrong ones only gets a wrong
/// answer to its own question.
interface ILogic {
    /// @dev One call the Executor will make. `approveToken == address(0)` means no allowance;
    /// otherwise exactly `approveAmount` is approved to `target` before the call and revoked after.
    struct Call {
        address target;
        bytes data;
        address approveToken;
        uint256 approveAmount;
    }

    /// @dev The act being planned. `amountIn` is what the Executor holds of the route's token in
    /// (delivered, not requested). Every call pays the Executor; the front door forwards the
    /// output to the account. `route` is the Registry's row for `routeId`; `assetIn` and
    /// `assetOut` are the Registry's `assetOf` for its token in and, on an entry, its token out
    /// (zero for a token that is not a bound receipt, and `assetOut` zero on an exit).
    struct Leg {
        address account;
        address executor;
        bytes32 routeId;
        uint256 amountIn;
        Registry.Route route;
        address assetIn;
        address assetOut;
    }

    /// @dev What the front door reports after every act and every collection. `receipt` is the
    /// bound receipt of the position: handed in on an exit or a collection, produced on an entry,
    /// zero for a route with no position. A collection is always an exit. Holdings are the
    /// account's, before and after; a collection's `holdingAfter` counts what the venue handed
    /// back unspent. `gross` is the output on the Executor, `fee` what went to the treasury,
    /// `output` what reached the account. `params` are the caller's bytes, forwarded unchanged,
    /// except on a withdrawal's report, which carries none.
    struct ActReport {
        address account;
        bytes32 routeId;
        bool collection;
        bool exit;
        address receipt;
        uint256 amountIn;
        address tokenOut;
        uint256 gross;
        uint256 fee;
        uint256 output;
        uint256 consumed;
        uint256 holdingBefore;
        uint256 holdingAfter;
        bytes params;
    }

    /// @notice Reverts if `account` may not enter through `routeId` now. Never asked for exits.
    /// `route` is the Registry's row for `routeId`, `assetOut` the Registry's `assetOf` for its
    /// token out.
    function gate(address account, bytes32 routeId, Registry.Route calldata route, address assetOut) external view;

    /// @notice The calls that carry out one act, built from the route's `tag`.
    function plan(Leg calldata leg, bytes calldata params) external view returns (Call[] memory calls);

    /// @notice What `account` owes right now, and how to pay it through `routeId`, an exit route:
    /// `amount` of `token` to the treasury, raised by redeeming `receiptsToRedeem` through it.
    /// `route` is the Registry's row for `routeId`, `assetIn` the Registry's `assetOf` for its
    /// token in.
    function collect(
        address account,
        bytes32 routeId,
        Registry.Route calldata route,
        address assetIn,
        bytes calldata params
    ) external view returns (address token, uint256 amount, uint256 receiptsToRedeem);

    /// @notice Called by the front door after every act and every collection. After an exit that
    /// paid the account something, with exactly the front door's `EXIT_REPORT_GAS`, and the exit
    /// stands whatever happens. After anything else (an entry, a collection, an exit that paid the
    /// account nothing, such as a move), strictly: a failing report fails the call.
    function onAct(ActReport calldata report) external;

    /// @notice The Registry this Logic reads; the front door refuses a mismatch.
    function registry() external view returns (address);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "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/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.