Skip to content
Verified contractExactMIT

AgentWallet

Address0x45494e2624f64aa6a93ea4fd79ec8f99cca3b7e7
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
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,441,346
Creation transaction
0xfab575ddb5…fadd53fcf4

src/AgentWallet.sol

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

interface IPermit2 {
    function approve(address token, address spender, uint160 amount, uint48 expiration) external;
    function allowance(address user, address token, address spender) external view returns (uint160, uint48, uint48);
}

interface IFeeSource {
    function feeFor(address walletOwner) external view returns (uint256 bps, address recipient);
}

/// @title AgentWallet
/// @notice A wallet an AI agent can operate, inside limits its owner sets and the contract enforces.
///
/// The agent key can only:
///   - call (target, function) pairs the owner listed, and send to recipients the owner listed;
///   - move out, per listed asset, at most `perTx` in one call and `cap` per window;
///   - use token approvals that exist only for the duration of one call;
///   - draw a small gas allowance to its own address;
///   - ask the owner to approve anything else (a proposal).
/// The agent can never approve, sign for the wallet, change the rules or touch an unlisted token directly.
/// The owner can do anything. The guardian can only freeze the agent and send everything back to the owner.
contract AgentWallet {
    // ---------------------------------------------------------------- constants

    address public constant ETH = address(0);
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
    uint256 public constant MAX_FEE_BPS = 25;
    uint256 public constant MAX_ASSETS = 12;
    uint256 public constant MAX_RULES = 64;
    uint256 public constant MAX_RECIPIENTS = 64;
    uint256 public constant PROPOSAL_TTL = 7 days;
    uint32 public constant MIN_PERIOD = 1 hours;
    uint32 public constant MAX_PERIOD = 30 days;

    bytes4 internal constant SEL_TRANSFER = 0xa9059cbb;
    bytes4 internal constant SEL_TRANSFER_FROM = 0x23b872dd;
    bytes4 internal constant SEL_APPROVE = 0x095ea7b3;
    bytes4 internal constant SEL_INCREASE_ALLOWANCE = 0x39509351;
    bytes4 internal constant SEL_SET_APPROVAL_FOR_ALL = 0xa22cb465;

    address public immutable factory;

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

    struct Limit {
        uint128 cap; // most that may be outstanding at once; it refills evenly over one period
        uint128 perTx; // most that may leave in one call (0 = no separate limit)
        uint128 spent; // outstanding as of `updatedAt`
        uint64 updatedAt;
        bool listed;
    }

    struct AssetLimit {
        address asset;
        uint128 cap;
        uint128 perTx;
    }

    struct Rule {
        address target;
        bytes4 selector;
    }

    struct Init {
        address agent;
        uint64 agentExpiry; // 0 = no expiry
        address guardian;
        uint32 period;
        uint128 gasAllowance;
        bool openTransfers;
        AssetLimit[] limits;
        Rule[] rules;
        address[] recipients;
    }

    struct Proposal {
        address target;
        uint64 createdAt;
        uint8 status; // 0 pending, 1 executed, 2 rejected, 3 cancelled
        bool viaPermit2;
        uint32 epoch; // requests made before the agent was stopped or replaced can no longer be approved
        address token;
        uint256 value;
        uint256 amount;
        bytes data;
    }

    struct AssetView {
        address asset;
        uint128 cap;
        uint128 perTx;
        uint128 spent;
        uint64 fullAt; // when the whole limit is available again (0 = now)
        uint256 balance;
    }

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

    address public owner;
    address public pendingOwner;
    address public agent;
    address public guardian;
    uint64 public agentExpiry;
    uint64 public createdBlock;
    uint32 public period;
    bool public frozen;
    bool public openTransfers;
    bool private _initialized;
    bool private _locked;

    mapping(address => Limit) public limits;
    address[] private _assets;

    bytes32[] private _rules;
    mapping(bytes32 => uint256) private _ruleIndex; // key => index + 1

    address[] private _recipients;
    mapping(address => uint256) private _recipientIndex; // recipient => index + 1

    uint128 public gasAllowance;
    uint128 public gasSpent;
    uint64 public gasUpdatedAt;
    uint32 public proposalEpoch;

    Proposal[] private _proposals;

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

    event Initialized(address indexed owner, address indexed agent);
    event Executed(address indexed target, bytes4 indexed selector, uint256 value, string note);
    event Spent(address indexed asset, uint256 amount, uint256 fee);
    event Refueled(uint256 amount);
    event Proposed(uint256 indexed id, address indexed target, bytes4 selector, uint256 value, address token, uint256 amount, string note);
    event ProposalApproved(uint256 indexed id);
    event ProposalRejected(uint256 indexed id);
    event ProposalCancelled(uint256 indexed id);
    event Frozen(address indexed by);
    event Unfrozen();
    event Panic(address indexed by);
    event AgentSet(address indexed agent, uint64 expiry);
    event GuardianSet(address indexed guardian);
    event LimitSet(address indexed asset, uint128 cap, uint128 perTx);
    event AssetRemoved(address indexed asset);
    event RuleSet(address indexed target, bytes4 indexed selector, bool allowed);
    event RecipientSet(address indexed recipient, bool allowed);
    event OpenTransfersSet(bool open);
    event PeriodSet(uint32 period);
    event GasAllowanceSet(uint128 amount);
    event Withdrawn(address indexed asset, address indexed to, uint256 amount);
    event OwnerExecuted(address indexed target, uint256 value, bytes4 selector);
    event OwnershipTransferStarted(address indexed to);
    event OwnershipTransferred(address indexed from, address indexed to);

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

    error NotOwner();
    error NotAgent();
    error NotAllowed();
    error IsFrozen();
    error AgentExpired();
    error Reentrancy();
    error AlreadyInitialized();
    error ZeroAddress();
    error BadPeriod();
    error BadCalldata();
    error BlockedSelector(bytes4 selector);
    error TargetNotAllowed(address target, bytes4 selector);
    error RecipientNotAllowed(address recipient);
    error AssetNotListed(address asset);
    error OverPerTx(address asset, uint256 amount, uint256 limit);
    error OverCap(address asset, uint256 amount, uint256 remaining);
    error OverGasAllowance(uint256 amount, uint256 remaining);
    error TooMany();
    error BadProposal();
    error TokenCallFailed(address token);
    error EthSendFailed();

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

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

    modifier onlyAgent() {
        if (msg.sender != agent) revert NotAgent();
        if (frozen) revert IsFrozen();
        if (agentExpiry != 0 && block.timestamp >= agentExpiry) revert AgentExpired();
        _;
    }

    modifier lock() {
        if (_locked) revert Reentrancy();
        _locked = true;
        _;
        _locked = false;
    }

    // ---------------------------------------------------------------- setup

    constructor() {
        factory = msg.sender;
        _initialized = true; // the implementation itself can never be set up
    }

    function initialize(address owner_, Init calldata init) external {
        if (_initialized) revert AlreadyInitialized();
        _initialized = true;
        if (owner_ == address(0)) revert ZeroAddress();
        owner = owner_;
        createdBlock = uint64(block.number);
        emit OwnershipTransferred(address(0), owner_);
        _setPeriod(init.period);
        _setAgent(init.agent, init.agentExpiry);
        guardian = init.guardian;
        emit GuardianSet(init.guardian);
        gasAllowance = init.gasAllowance;
        emit GasAllowanceSet(init.gasAllowance);
        openTransfers = init.openTransfers;
        emit OpenTransfersSet(init.openTransfers);
        _setLimit(ETH, 0, 0); // ETH is always measured; it stays unspendable until a limit is set
        for (uint256 i; i < init.limits.length; ++i) {
            _setLimit(init.limits[i].asset, init.limits[i].cap, init.limits[i].perTx);
        }
        for (uint256 i; i < init.rules.length; ++i) {
            _setRule(init.rules[i].target, init.rules[i].selector, true);
        }
        for (uint256 i; i < init.recipients.length; ++i) {
            _setRecipient(init.recipients[i], true);
        }
        emit Initialized(owner_, init.agent);
    }

    receive() external payable {}

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

    /// @notice Call an allowed target. Anything that leaves the wallet is counted against the limits.
    function execute(address target, uint256 value, bytes calldata data, string calldata note)
        external
        onlyAgent
        lock
        returns (bytes memory)
    {
        return _agentCall(target, value, data, address(0), 0, false, note);
    }

    /// @notice Same as `execute`, with `amount` of `token` approved to `target` for this call only.
    /// @param viaPermit2 approve through Permit2 (Uniswap Universal Router) instead of directly.
    function executeWithApproval(
        address target,
        uint256 value,
        bytes calldata data,
        address token,
        uint256 amount,
        bool viaPermit2,
        string calldata note
    ) external onlyAgent lock returns (bytes memory) {
        if (token == ETH) revert ZeroAddress();
        return _agentCall(target, value, data, token, amount, viaPermit2, note);
    }

    /// @notice Send gas money to the agent's own address, inside the gas allowance.
    function refuel(uint256 amount) external onlyAgent lock {
        uint256 level = _level(gasSpent, gasUpdatedAt, gasAllowance);
        uint256 left = gasAllowance > level ? gasAllowance - level : 0;
        if (amount > left) revert OverGasAllowance(amount, left);
        gasSpent = uint128(level + amount);
        gasUpdatedAt = uint64(block.timestamp);
        _sendEth(msg.sender, amount);
        emit Refueled(amount);
    }

    /// @notice Ask the owner to approve a call the limits do not allow.
    function propose(
        address target,
        uint256 value,
        bytes calldata data,
        address token,
        uint256 amount,
        bool viaPermit2,
        string calldata note
    ) external onlyAgent returns (uint256 id) {
        if (target == address(this) || target == address(0)) revert NotAllowed();
        id = _proposals.length;
        _proposals.push(
            Proposal({
                target: target,
                createdAt: uint64(block.timestamp),
                status: 0,
                viaPermit2: viaPermit2,
                epoch: proposalEpoch,
                token: token,
                value: value,
                amount: amount,
                data: data
            })
        );
        emit Proposed(id, target, _selector(data), value, token, amount, note);
    }

    function cancelProposal(uint256 id) external {
        if (msg.sender != agent && msg.sender != owner) revert NotAllowed();
        Proposal storage p = _proposals[id];
        if (p.status != 0) revert BadProposal();
        p.status = 3;
        emit ProposalCancelled(id);
    }

    // ---------------------------------------------------------------- stop

    /// @notice Stop the agent. The owner, the guardian and the agent itself can do this.
    function freeze() external {
        if (msg.sender != owner && msg.sender != guardian && msg.sender != agent) revert NotAllowed();
        _freeze();
    }

    /// @notice Stop the agent and send ETH plus the given tokens to the owner.
    /// The guardian can call this, and the funds can only go to the owner.
    function panic(address[] calldata tokens) external lock {
        if (msg.sender != owner && msg.sender != guardian) revert NotAllowed();
        _freeze();
        address to = owner;
        for (uint256 i; i < tokens.length; ++i) {
            address t = tokens[i];
            if (t == ETH) continue;
            (bool ok, bytes memory r) = t.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
            if (!ok || r.length < 32) continue;
            uint256 bal = abi.decode(r, (uint256));
            if (bal == 0) continue;
            // one broken token must not block the rest
            (ok,) = t.call(abi.encodeWithSelector(SEL_TRANSFER, to, bal));
            if (ok) emit Withdrawn(t, to, bal);
        }
        uint256 eth = address(this).balance;
        if (eth != 0) {
            (bool sent,) = to.call{value: eth}("");
            if (sent) emit Withdrawn(ETH, to, eth);
        }
        emit Panic(msg.sender);
    }

    function unfreeze() external onlyOwner {
        frozen = false;
        emit Unfrozen();
    }

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

    function approveProposal(uint256 id) external onlyOwner lock returns (bytes memory ret) {
        Proposal storage p = _proposals[id];
        if (p.status != 0 || p.epoch != proposalEpoch || block.timestamp > uint256(p.createdAt) + PROPOSAL_TTL) {
            revert BadProposal();
        }
        p.status = 1;
        address token = p.token;
        address target = p.target;
        bool viaPermit2 = p.viaPermit2;
        if (token != ETH) _grant(token, target, p.amount, viaPermit2);
        ret = _call(target, p.value, p.data);
        if (token != ETH) _revoke(token, target, viaPermit2);
        emit ProposalApproved(id);
    }

    function rejectProposal(uint256 id) external onlyOwner {
        Proposal storage p = _proposals[id];
        if (p.status != 0) revert BadProposal();
        p.status = 2;
        emit ProposalRejected(id);
    }

    function setAgent(address agent_, uint64 expiry) external onlyOwner {
        _setAgent(agent_, expiry);
    }

    function setGuardian(address guardian_) external onlyOwner {
        guardian = guardian_;
        emit GuardianSet(guardian_);
    }

    function setLimit(address asset, uint128 cap, uint128 perTx) external onlyOwner {
        _setLimit(asset, cap, perTx);
    }

    /// @notice Stop tracking an asset. The agent can then no longer spend it at all.
    function removeAsset(address asset) external onlyOwner {
        if (!limits[asset].listed) revert AssetNotListed(asset);
        if (asset == ETH) revert NotAllowed(); // set its limit to 0 instead
        delete limits[asset];
        uint256 n = _assets.length;
        for (uint256 i; i < n; ++i) {
            if (_assets[i] == asset) {
                _assets[i] = _assets[n - 1];
                _assets.pop();
                break;
            }
        }
        emit AssetRemoved(asset);
    }

    function setRule(address target, bytes4 selector, bool allowed) external onlyOwner {
        _setRule(target, selector, allowed);
    }

    function setRecipient(address recipient, bool allowed) external onlyOwner {
        _setRecipient(recipient, allowed);
    }

    function setOpenTransfers(bool open) external onlyOwner {
        openTransfers = open;
        emit OpenTransfersSet(open);
    }

    function setPeriod(uint32 period_) external onlyOwner {
        _setPeriod(period_);
    }

    function setGasAllowance(uint128 amount) external onlyOwner {
        gasAllowance = amount;
        emit GasAllowanceSet(amount);
    }

    function withdraw(address asset, uint256 amount, address to) external onlyOwner lock {
        if (to == address(0)) revert ZeroAddress();
        if (asset == ETH) _sendEth(to, amount);
        else _tokenCall(asset, abi.encodeWithSelector(SEL_TRANSFER, to, amount));
        emit Withdrawn(asset, to, amount);
    }

    /// @notice The owner can make any call from the wallet.
    function ownerExecute(address target, uint256 value, bytes calldata data)
        external
        onlyOwner
        lock
        returns (bytes memory ret)
    {
        if (target == address(this)) revert NotAllowed();
        ret = _call(target, value, data);
        emit OwnerExecuted(target, value, _selector(data));
    }

    /// @notice Several owner settings in one transaction.
    function multicall(bytes[] calldata calls) external onlyOwner {
        for (uint256 i; i < calls.length; ++i) {
            (bool ok, bytes memory ret) = address(this).delegatecall(calls[i]);
            if (!ok) _bubble(ret);
        }
    }

    function transferOwnership(address to) external onlyOwner {
        pendingOwner = to;
        emit OwnershipTransferStarted(to);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert NotAllowed();
        emit OwnershipTransferred(owner, msg.sender);
        owner = msg.sender;
        pendingOwner = address(0);
    }

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

    function assetsView() external view returns (AssetView[] memory out) {
        uint256 n = _assets.length;
        out = new AssetView[](n);
        for (uint256 i; i < n; ++i) {
            address a = _assets[i];
            Limit memory l = limits[a];
            uint256 level = _level(l.spent, l.updatedAt, l.cap);
            out[i] = AssetView({
                asset: a,
                cap: l.cap,
                perTx: l.perTx,
                spent: uint128(level),
                fullAt: level == 0 || l.cap == 0 ? 0 : uint64(block.timestamp + (level * period + l.cap - 1) / l.cap),
                balance: _balance(a)
            });
        }
    }

    /// @notice How much of `asset` the agent could still move out right now.
    function remaining(address asset) public view returns (uint256) {
        Limit memory l = limits[asset];
        if (!l.listed) return 0;
        uint256 level = _level(l.spent, l.updatedAt, l.cap);
        return level >= l.cap ? 0 : l.cap - level;
    }

    function gasRemaining() external view returns (uint256) {
        uint256 level = _level(gasSpent, gasUpdatedAt, gasAllowance);
        return level >= gasAllowance ? 0 : gasAllowance - level;
    }

    function rulesView() external view returns (Rule[] memory out) {
        uint256 n = _rules.length;
        out = new Rule[](n);
        for (uint256 i; i < n; ++i) {
            uint256 k = uint256(_rules[i]);
            out[i] = Rule({target: address(uint160(k >> 32)), selector: bytes4(uint32(k))});
        }
    }

    function recipientsView() external view returns (address[] memory) {
        return _recipients;
    }

    function isRuleAllowed(address target, bytes4 selector) public view returns (bool) {
        return _ruleIndex[_ruleKey(target, selector)] != 0;
    }

    function isRecipientAllowed(address recipient) public view returns (bool) {
        return _recipientIndex[recipient] != 0;
    }

    function proposalCount() external view returns (uint256) {
        return _proposals.length;
    }

    function getProposal(uint256 id) external view returns (Proposal memory) {
        return _proposals[id];
    }

    function agentActive() external view returns (bool) {
        return agent != address(0) && !frozen && (agentExpiry == 0 || block.timestamp < agentExpiry);
    }

    // ---------------------------------------------------------------- token receivers

    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return 0x150b7a02;
    }

    function onERC1155Received(address, address, uint256, uint256, bytes calldata) external pure returns (bytes4) {
        return 0xf23a6e61;
    }

    function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)
        external
        pure
        returns (bytes4)
    {
        return 0xbc197c81;
    }

    function supportsInterface(bytes4 id) external pure returns (bool) {
        return id == 0x01ffc9a7 || id == 0x150b7a02 || id == 0x4e2312e0;
    }

    // ---------------------------------------------------------------- internals: agent call

    function _agentCall(
        address target,
        uint256 value,
        bytes calldata data,
        address token,
        uint256 amount,
        bool viaPermit2,
        string calldata note
    ) private returns (bytes memory ret) {
        bytes4 selector = _checkCall(target, data);
        if (token != ETH && !limits[token].listed) revert AssetNotListed(token);

        uint256 n = _assets.length;
        uint256[] memory snap = new uint256[](n);
        for (uint256 i; i < n; ++i) {
            snap[i] = _balance(_assets[i]);
        }

        if (token != ETH) _grant(token, target, amount, viaPermit2);
        ret = _call(target, value, data);
        // what was sent counts in full even if the call hands some of it back
        uint256 used;
        if (token != ETH) {
            used = _used(token, target, amount, viaPermit2);
            _revoke(token, target, viaPermit2);
        }

        (uint256 bps, address feeTo) = _fee();
        for (uint256 i; i < n; ++i) {
            address asset = _assets[i];
            uint256 nowBal = _balance(asset);
            uint256 out = nowBal < snap[i] ? snap[i] - nowBal : 0;
            if (asset == ETH) {
                if (value > out) out = value;
            } else if (asset == token && used > out) {
                out = used;
            }
            snap[i] = 0;
            if (out == 0) continue;
            _consume(asset, out);
            uint256 fee = (out * bps) / 10_000;
            if (fee > nowBal) fee = nowBal;
            snap[i] = fee;
            emit Spent(asset, out, fee);
        }
        // fees are paid only after every asset has been measured
        if (bps != 0) {
            for (uint256 i; i < n; ++i) {
                uint256 fee = snap[i];
                if (fee == 0) continue;
                address asset = _assets[i];
                // a fee that cannot be delivered is skipped, it never blocks the agent
                if (asset == ETH) {
                    (bool ok,) = feeTo.call{value: fee, gas: 30_000}("");
                    ok;
                } else {
                    (bool ok,) = asset.call{gas: 100_000}(abi.encodeWithSelector(SEL_TRANSFER, feeTo, fee));
                    ok;
                }
            }
        }
        emit Executed(target, selector, value, note);
    }

    function _checkCall(address target, bytes calldata data) private view returns (bytes4 selector) {
        if (target == address(this) || target == address(0) || target == PERMIT2 || target == factory) {
            revert NotAllowed();
        }
        if (data.length == 0) {
            // plain ETH send
            if (!openTransfers && !isRecipientAllowed(target)) revert RecipientNotAllowed(target);
            return bytes4(0);
        }
        if (data.length < 4) revert BadCalldata();
        selector = bytes4(data[:4]);
        if (
            selector == SEL_APPROVE || selector == SEL_INCREASE_ALLOWANCE || selector == SEL_SET_APPROVAL_FOR_ALL
                || selector == SEL_TRANSFER_FROM
        ) revert BlockedSelector(selector);
        if (selector == SEL_TRANSFER) {
            // token send: the token must be listed, the recipient allowed
            if (!limits[target].listed) revert AssetNotListed(target);
            if (data.length < 68) revert BadCalldata();
            address to = address(uint160(uint256(bytes32(data[4:36]))));
            if (!openTransfers && !isRecipientAllowed(to)) revert RecipientNotAllowed(to);
            return selector;
        }
        if (!isRuleAllowed(target, selector)) revert TargetNotAllowed(target, selector);
    }

    function _consume(address asset, uint256 out) private {
        Limit storage l = limits[asset];
        if (l.perTx != 0 && out > l.perTx) revert OverPerTx(asset, out, l.perTx);
        uint256 level = _level(l.spent, l.updatedAt, l.cap);
        uint256 left = level >= l.cap ? 0 : l.cap - level;
        if (out > left) revert OverCap(asset, out, left);
        l.spent = uint128(level + out);
        l.updatedAt = uint64(block.timestamp);
    }

    /// What is still outstanding: spending drains back at `cap` per `period`, so the agent can never
    /// move more than `cap` at once, and never faster than one more `cap` per period after that.
    function _level(uint256 spent, uint256 since, uint256 cap) private view returns (uint256) {
        uint256 refilled = (cap * (block.timestamp - since)) / period;
        return spent > refilled ? spent - refilled : 0;
    }

    function _fee() private view returns (uint256 bps, address to) {
        // a broken or hostile fee source can cost gas, never funds beyond MAX_FEE_BPS, and never blocks a call
        (bool ok, bytes memory r) = factory.staticcall{gas: 60_000}(abi.encodeCall(IFeeSource.feeFor, (owner)));
        if (!ok || r.length != 64) return (0, address(0));
        (bps, to) = abi.decode(r, (uint256, address));
        if (to == address(0)) return (0, address(0));
        if (bps > MAX_FEE_BPS) bps = MAX_FEE_BPS;
    }

    // ---------------------------------------------------------------- internals: approvals

    function _grant(address token, address spender, uint256 amount, bool viaPermit2) private {
        if (viaPermit2) {
            if (amount > type(uint160).max) revert BadCalldata();
            _approve(token, PERMIT2, amount);
            IPermit2(PERMIT2).approve(token, spender, uint160(amount), uint48(block.timestamp));
        } else {
            _approve(token, spender, amount);
        }
    }

    /// How much of the one-call approval the target actually took.
    function _used(address token, address spender, uint256 amount, bool viaPermit2) private view returns (uint256) {
        uint256 rest;
        if (viaPermit2) {
            try IPermit2(PERMIT2).allowance(address(this), token, spender) returns (uint160 a, uint48, uint48) {
                rest = a;
            } catch {
                return 0;
            }
        } else {
            (bool ok, bytes memory r) = token.staticcall(abi.encodeWithSelector(0xdd62ed3e, address(this), spender));
            if (!ok || r.length < 32) return 0;
            rest = abi.decode(r, (uint256));
        }
        return amount > rest ? amount - rest : 0;
    }

    function _revoke(address token, address spender, bool viaPermit2) private {
        if (viaPermit2) {
            IPermit2(PERMIT2).approve(token, spender, 0, 0);
            _approve(token, PERMIT2, 0);
        } else {
            _approve(token, spender, 0);
        }
    }

    function _approve(address token, address spender, uint256 amount) private {
        bytes memory data = abi.encodeWithSelector(SEL_APPROVE, spender, amount);
        if (_tryTokenCall(token, data)) return;
        // tokens like USDT refuse to change a non-zero allowance
        _tokenCall(token, abi.encodeWithSelector(SEL_APPROVE, spender, 0));
        _tokenCall(token, data);
    }

    // ---------------------------------------------------------------- internals: settings

    function _setAgent(address agent_, uint64 expiry) private {
        if (agent_ == owner && agent_ != address(0)) revert NotAllowed();
        agent = agent_;
        agentExpiry = expiry;
        ++proposalEpoch;
        emit AgentSet(agent_, expiry);
    }

    function _setPeriod(uint32 period_) private {
        if (period_ < MIN_PERIOD || period_ > MAX_PERIOD) revert BadPeriod();
        period = period_;
        emit PeriodSet(period_);
    }

    function _setLimit(address asset, uint128 cap, uint128 perTx) private {
        Limit storage l = limits[asset];
        if (!l.listed) {
            if (_assets.length >= MAX_ASSETS) revert TooMany();
            if (asset != ETH) _balance(asset); // must answer balanceOf
            l.listed = true;
            _assets.push(asset);
        }
        l.cap = cap;
        l.perTx = perTx;
        emit LimitSet(asset, cap, perTx);
    }

    function _setRule(address target, bytes4 selector, bool allowed) private {
        if (target == address(0) || target == address(this) || target == PERMIT2) revert NotAllowed();
        bytes32 key = _ruleKey(target, selector);
        uint256 idx = _ruleIndex[key];
        if (allowed && idx == 0) {
            if (_rules.length >= MAX_RULES) revert TooMany();
            _rules.push(key);
            _ruleIndex[key] = _rules.length;
        } else if (!allowed && idx != 0) {
            bytes32 last = _rules[_rules.length - 1];
            _rules[idx - 1] = last;
            _ruleIndex[last] = idx;
            _rules.pop();
            delete _ruleIndex[key];
        }
        emit RuleSet(target, selector, allowed);
    }

    function _setRecipient(address recipient, bool allowed) private {
        if (recipient == address(0) || recipient == address(this)) revert NotAllowed();
        uint256 idx = _recipientIndex[recipient];
        if (allowed && idx == 0) {
            if (_recipients.length >= MAX_RECIPIENTS) revert TooMany();
            _recipients.push(recipient);
            _recipientIndex[recipient] = _recipients.length;
        } else if (!allowed && idx != 0) {
            address last = _recipients[_recipients.length - 1];
            _recipients[idx - 1] = last;
            _recipientIndex[last] = idx;
            _recipients.pop();
            delete _recipientIndex[recipient];
        }
        emit RecipientSet(recipient, allowed);
    }

    function _freeze() private {
        if (!frozen) {
            frozen = true;
            ++proposalEpoch;
            emit Frozen(msg.sender);
        }
    }

    // ---------------------------------------------------------------- internals: low level

    function _ruleKey(address target, bytes4 selector) private pure returns (bytes32) {
        return bytes32((uint256(uint160(target)) << 32) | uint256(uint32(selector)));
    }

    function _selector(bytes calldata data) private pure returns (bytes4) {
        return data.length >= 4 ? bytes4(data[:4]) : bytes4(0);
    }

    function _balance(address asset) private view returns (uint256) {
        if (asset == ETH) return address(this).balance;
        (bool ok, bytes memory r) = asset.staticcall(abi.encodeWithSelector(0x70a08231, address(this)));
        if (!ok || r.length < 32) revert TokenCallFailed(asset);
        return abi.decode(r, (uint256));
    }

    function _call(address target, uint256 value, bytes memory data) private returns (bytes memory ret) {
        bool ok;
        (ok, ret) = target.call{value: value}(data);
        if (!ok) _bubble(ret);
    }

    function _tryTokenCall(address token, bytes memory data) private returns (bool) {
        if (token.code.length == 0) return false;
        (bool ok, bytes memory r) = token.call(data);
        return ok && (r.length == 0 || (r.length >= 32 && abi.decode(r, (bool))));
    }

    function _tokenCall(address token, bytes memory data) private {
        if (!_tryTokenCall(token, data)) revert TokenCallFailed(token);
    }

    function _sendEth(address to, uint256 amount) private {
        (bool ok,) = to.call{value: amount}("");
        if (!ok) revert EthSendFailed();
    }

    function _bubble(bytes memory ret) private pure {
        assembly {
            revert(add(ret, 32), mload(ret))
        }
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.