Skip to content
Verified contractExactUNLICENSED

StrategyManager

Address0x84c8a1d31b82f2409786aa2f8eb6cec4d18b5454
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.26

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.26+commit.8a97fa7a
Language
solidity
Optimization
Yes, 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/StrategyManager.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 {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {Registry} from "./Registry.sol";
import {Executor} from "./Executor.sol";
import {ILogic} from "./interfaces/ILogic.sol";
import {ROUNDING_PER_ACT} from "./Rounding.sol";

/// @notice The front door: the one address every account calls and approves. `act` runs one
/// route; `collectFee` pays what Logic says the account owes, and does nothing when nothing is
/// owed. Immutable, no storage beyond three addresses and a transient lock.
///
/// A composite (a rebalance, a swap then a deposit) is several acts in one account batch, all or
/// nothing. Handing in a bound receipt is an exit, which no gate can stop; anything else asks
/// Logic's gate first. A new feature is a new tag in Logic plus a route the timelock adds.
///
/// Fees: `act` never pays the treasury. Every fee is taken by `collectFee`, never more than the
/// collection produced, always to the Registry's treasury (timelocked). Rates and rules live in
/// Logic.
contract StrategyManager is ReentrancyGuardTransient {
    using SafeERC20 for IERC20;

    Registry public immutable registry;
    ILogic public immutable logic;
    Executor public immutable executor;

    /// @dev The gas a withdrawal's report gets, exactly: the act refuses to start it with less, so
    /// no caller can starve it on purpose, and Logic can spend no more.
    uint256 public constant EXIT_REPORT_GAS = 150_000;

    /// @dev What one act carries between phases. Baselines are the Executor's balances before
    /// the pull, so resting balances stay out of reach and leftovers are exact. The report to
    /// Logic is filled as the act goes.
    struct Act {
        /// @dev The route's row and the Registry's `assetOf` for its token in and (on an entry)
        /// its token out: read once, handed to Logic.
        Registry.Route route;
        address assetIn;
        address assetOut;
        uint256 inBaseline;
        uint256 outBaseline;
        /// @dev What the venue was handed.
        uint256 legAmountIn;
        /// @dev The account's holding of token out before the act.
        uint256 outHeldBefore;
        /// @dev The Executor's token in after the venue call, and its token out at the sweep:
        /// read once, handed to the forward that follows.
        uint256 inHeld;
        uint256 outHeld;
        ILogic.ActReport r;
    }

    /// @dev One per act. `amountIn` is what the venue was handed; `output` what the account gained.
    event PositionEvent(
        address indexed account,
        bytes32 indexed routeId,
        address tokenIn,
        address tokenOut,
        uint256 amountIn,
        uint256 output
    );

    event ResidualForwarded(address indexed account, address indexed token, uint256 amount);
    event FeeCollected(address indexed account, address indexed token, uint256 amount);
    /// @dev Logic refused or failed a withdrawal's report; the withdrawal stands.
    event ReportFailed(address indexed account, bytes32 indexed routeId);

    error ZeroAddress();
    error LogicRegistryMismatch(address expected, address actual);
    error RouteNotRegistered(bytes32 id);
    error ExitExceedsHolding(uint256 amount, uint256 held);
    error ZeroAmount();
    error AmountMustBeZero();
    error NothingDelivered(uint256 amount);
    error ShortDelivery(uint256 requested, uint256 delivered);
    error BelowMinOutput(uint256 minOutput, uint256 actualOutput);
    error BaselineBreached(address token, uint256 baseline, uint256 held);
    error NothingToCollect();
    error CollectNeedsExitRoute(bytes32 id);
    error ReportNeedsGas(uint256 left, uint256 needed);
    error TreasuryIsOurs(address treasury);

    /// @dev Deploys its own Executor, so it is its only caller.
    constructor(Registry registry_, ILogic logic_) {
        if (address(registry_) == address(0) || address(logic_) == address(0)) revert ZeroAddress();
        if (logic_.registry() != address(registry_)) {
            revert LogicRegistryMismatch(address(registry_), logic_.registry());
        }
        registry = registry_;
        logic = logic_;
        executor = new Executor(registry_);
    }

    /// @notice Whether an act is in flight; the Executor refuses `sweep` while one is.
    function busy() external view returns (bool) {
        return _reentrancyGuardEntered();
    }

    /// @notice Runs one route. `amount` is pulled from `msg.sender` in the route's token in.
    /// `minOutput` bounds what the account gains of the route's token out; zero accepts any
    /// outcome. `params` go to Logic unchanged (a withdrawal's report carries none). No fee is
    /// ever taken here.
    function act(bytes32 routeId, uint256 amount, uint256 minOutput, bytes calldata params) external nonReentrant {
        Act memory a = _load(routeId);
        ILogic.ActReport memory r = a.r;
        if (!r.exit) logic.gate(r.account, routeId, a.route, a.assetOut);
        _baselines(a);
        _pull(a, amount);
        _run(a, params);
        _sweep(a);
        address tokenOut = a.route.tokenOut;
        if (r.gross != 0) executor.forward(tokenOut, r.account, r.gross, a.outHeld);
        if (tokenOut != address(0)) {
            uint256 held = IERC20(tokenOut).balanceOf(r.account);
            r.output = held > a.outHeldBefore ? held - a.outHeldBefore : 0;
            if (r.output < minOutput) revert BelowMinOutput(minOutput, r.output);
            // An entry's receipt is its token out, so this is the holding after.
            if (!r.exit && r.receipt != address(0)) r.holdingAfter = held;
        }
        _finish(a, params);
    }

    /// @notice Pays what Logic says `msg.sender` owes by redeeming receipts through an exit route;
    /// the rest of the proceeds comes back. Never more than the collection produces, always to the
    /// Registry's treasury. Does nothing when nothing is owed on a route that still names a
    /// position, so a batch that settles first never fails on it.
    function collectFee(bytes32 routeId, bytes calldata params) external nonReentrant {
        Act memory a = _load(routeId);
        ILogic.ActReport memory r = a.r;
        (address token, uint256 amount, uint256 receipts) =
            logic.collect(r.account, routeId, a.route, a.assetIn, params);
        // Nothing owed reads no balance: the baselines come after.
        if (amount == 0) return;
        if (!r.exit || a.route.tokenOut != token) revert CollectNeedsExitRoute(routeId);
        _baselines(a);
        r.collection = true;
        _pull(a, receipts);
        _run(a, params);
        _sweep(a);
        // A venue that pays nothing collects nothing: the receipts stay where they were.
        if (r.gross == 0) revert NothingToCollect();
        r.fee = amount < r.gross ? amount : r.gross;
        // A treasury set by mistake to one of our own contracts would trap the fee: refuse it.
        // Logic too: it has no way to send a token on.
        address treasury = registry.treasury();
        if (treasury == address(executor) || treasury == address(this) || treasury == address(logic)) {
            revert TreasuryIsOurs(treasury);
        }
        uint256 held = executor.forward(token, treasury, r.fee, a.outHeld);
        emit FeeCollected(r.account, token, r.fee);
        // Read after the fee's transfer: a scaled receipt may round a unit on it.
        uint256 rest = held > a.outBaseline ? held - a.outBaseline : 0;
        if (rest != 0) executor.forward(token, r.account, rest, held);
        r.output = _gain(IERC20(token), r.account, a.outHeldBefore);
        _finish(a, params);
    }

    // ---------------------------------------------------------------------
    // Load, pull, run
    // ---------------------------------------------------------------------

    /// @dev The route must exist. An exit (a bound receipt handed in) skips Logic's gate, so only
    /// a timelocked removal of the row can block it. The position is named here, once: the
    /// receipt handed in on an exit, the receipt produced on an entry, none on a plain route.
    /// The only Registry reads of the act: Logic gets this copy.
    function _load(bytes32 routeId) private view returns (Act memory a) {
        Registry.Route memory route = registry.getRoute(routeId);
        if (route.targets.length == 0) revert RouteNotRegistered(routeId);
        a.route = route;
        ILogic.ActReport memory r = a.r;
        r.account = msg.sender;
        r.routeId = routeId;
        r.tokenOut = route.tokenOut;
        if (route.tokenIn != address(0)) a.assetIn = registry.assetOf(route.tokenIn);
        r.exit = a.assetIn != address(0);
        if (r.exit) {
            r.receipt = route.tokenIn;
        } else {
            a.assetOut = registry.assetOf(route.tokenOut);
            if (a.assetOut != address(0)) r.receipt = route.tokenOut;
        }
    }

    /// @dev The Executor's balances before the pull, and the account's holding of token out.
    function _baselines(Act memory a) private view {
        Registry.Route memory route = a.route;
        ILogic.ActReport memory r = a.r;
        if (route.tokenIn != address(0)) a.inBaseline = IERC20(route.tokenIn).balanceOf(address(executor));
        if (route.tokenOut != address(0)) {
            a.outBaseline = IERC20(route.tokenOut).balanceOf(address(executor));
            a.outHeldBefore = IERC20(route.tokenOut).balanceOf(r.account);
            if (r.receipt == route.tokenOut) r.holdingBefore = a.outHeldBefore;
        }
    }

    /// @dev One pull into the Executor. Entries must deliver exactly (fee-on-transfer and
    /// rebasing fail closed). Exits must deliver something (scaled receipts deliver less) and
    /// never more than the account holds (Compound III would open a borrow).
    function _pull(Act memory a, uint256 amount) private {
        address tokenIn = a.route.tokenIn;
        if (tokenIn == address(0)) {
            if (amount != 0) revert AmountMustBeZero();
            return;
        }
        if (amount == 0) revert ZeroAmount();
        ILogic.ActReport memory r = a.r;

        IERC20 token = IERC20(tokenIn);
        if (r.exit) {
            r.holdingBefore = token.balanceOf(r.account);
            // A full exit is sized here, not when the batch was built: a figure fixed earlier can
            // be above the holding by the time it runs (interest rounding, a collection in front,
            // or anyone shrinking a Compound III balance with a zero transfer).
            if (amount == type(uint256).max) amount = r.holdingBefore;
            if (amount > r.holdingBefore) revert ExitExceedsHolding(amount, r.holdingBefore);
        }
        r.amountIn = amount;

        token.safeTransferFrom(r.account, address(executor), amount);

        uint256 afterPull = token.balanceOf(address(executor));
        if (afterPull <= a.inBaseline) revert NothingDelivered(amount);
        uint256 delivered = afterPull - a.inBaseline;
        if (!r.exit && delivered != amount) revert ShortDelivery(amount, delivered);
        // What the venue is handed: nonzero, the pull proved something arrived.
        a.legAmountIn = delivered;
        if (r.exit) r.holdingAfter = token.balanceOf(r.account);
    }

    /// @dev The venue call is built from what the Executor holds of token in above its baseline.
    /// Every call pays the Executor; the front door forwards the output.
    function _run(Act memory a, bytes calldata params) private {
        address tokenIn = a.route.tokenIn;
        ILogic.ActReport memory r = a.r;

        ILogic.Call[] memory calls = logic.plan(
            ILogic.Leg({
                account: r.account,
                executor: address(executor),
                routeId: r.routeId,
                amountIn: a.legAmountIn,
                route: a.route,
                assetIn: a.assetIn,
                assetOut: a.assetOut
            }),
            params
        );
        executor.run(a.route.targets, calls);

        if (tokenIn == address(0)) return;
        a.inHeld = IERC20(tokenIn).balanceOf(address(executor));
        uint256 left = a.inHeld > a.inBaseline ? a.inHeld - a.inBaseline : 0;
        if (r.exit) {
            // Receipts the venue handed back unspent did not leave the position: the sweep
            // returns them to the account.
            r.holdingAfter += left;
        } else if (r.receipt != address(0)) {
            // An entry into a bound receipt, paid in its own asset: what the venue consumed.
            r.consumed = left < a.legAmountIn ? a.legAmountIn - left : 0;
        }
    }

    // ---------------------------------------------------------------------
    // Settle
    // ---------------------------------------------------------------------

    /// @dev Token in above its baseline goes back to the account; token out above it is `gross`,
    /// which the caller forwards. A balance below its baseline (beyond scaled-receipt rounding)
    /// means the plan spent what was not the act's, and the act fails.
    function _sweep(Act memory a) private {
        address tokenIn = a.route.tokenIn;
        if (tokenIn != address(0)) {
            uint256 held = a.inHeld;
            if (held + ROUNDING_PER_ACT < a.inBaseline) revert BaselineBreached(tokenIn, a.inBaseline, held);
            if (held > a.inBaseline) {
                uint256 residual = held - a.inBaseline;
                executor.forward(tokenIn, a.r.account, residual, held);
                emit ResidualForwarded(a.r.account, tokenIn, residual);
            }
        }
        address tokenOut = a.route.tokenOut;
        if (tokenOut == address(0)) return;
        uint256 out = IERC20(tokenOut).balanceOf(address(executor));
        a.outHeld = out;
        if (out + ROUNDING_PER_ACT < a.outBaseline) revert BaselineBreached(tokenOut, a.outBaseline, out);
        if (out > a.outBaseline) a.r.gross = out - a.outBaseline;
    }

    /// @dev The event, then Logic's report: best effort for an exit that paid the account, so
    /// nothing after the venue call can stop a withdrawal; strict for everything else.
    function _finish(Act memory a, bytes calldata params) private {
        ILogic.ActReport memory r = a.r;
        emit PositionEvent(r.account, r.routeId, a.route.tokenIn, a.route.tokenOut, a.legAmountIn, r.output);
        // A withdrawal's report carries no `params` (only a move reads them), so no caller can
        // spend its fixed gas budget on copying them.
        if (r.exit && !r.collection && r.gross != 0) return _reportExit(r);
        r.params = params;
        logic.onAct(r);
    }

    /// @dev A withdrawal's report: exactly `EXIT_REPORT_GAS`, no return data copied, the outcome
    /// only logged. A caller who sent too little gas for it is refused and resends with more.
    function _reportExit(ILogic.ActReport memory r) private {
        bytes memory data = abi.encodeCall(ILogic.onAct, (r));
        address target = address(logic);
        uint256 needed = EXIT_REPORT_GAS + EXIT_REPORT_GAS / 63 + 5_000;
        if (gasleft() < needed) revert ReportNeedsGas(gasleft(), needed);
        bool ok;
        assembly ("memory-safe") {
            ok := call(EXIT_REPORT_GAS, target, 0, add(data, 0x20), mload(data), 0, 0)
        }
        if (!ok) emit ReportFailed(r.account, r.routeId);
    }

    /// @dev A balance that fell reads as no gain, never as a panic on the exit path.
    function _gain(IERC20 token, address who, uint256 before) private view returns (uint256) {
        uint256 now_ = token.balanceOf(who);
        return now_ > before ? now_ - before : 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/ReentrancyGuardTransient.sol

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

pragma solidity ^0.8.24;

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

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

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

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

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

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

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

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

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

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

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

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

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

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

pragma solidity ^0.8.24;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

lib/openzeppelin-contracts/contracts/utils/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/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 }
            }
        }
    }
}

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.