Skip to content
Verified contractExactMIT

GaslessAccount

Address0xf933e0ddf3fc3db3b10c580aab06fa7f3fc6f180
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.24

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.24+commit.e11b9ed9
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,501,614
Creation transaction
0x30cf9d483a…984c8c1090

src/GaslessAccount.sol

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

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

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

/// @title GaslessAccount
/// @notice Implementation contract executed via EIP-7702 delegation to a user EOA.
///         When the relayer calls execute() with an intent carrying the
///         owner(=EOA) signature, it runs the batch calls (e.g. USDT.transfer)
///         and settles the gas cost in USDT.
///
/// @dev    Since it executes in a delegated context:
///         - address(this) == user EOA
///         - msg.sender of every external call == user EOA (no USDT approve needed)
///         - storage such as nonce is stored in the EOA account (independent per user)
///         - FEE_REGISTRY is immutable (embedded in code) so it is read correctly even in delegated execution
contract GaslessAccount {
    /// @notice Fee policy singleton. Fixed at deployment.
    FeeRegistry public immutable FEE_REGISTRY;

    /// @notice Replay-protection nonce (stored in EOA storage).
    uint256 public nonce;

    struct Call {
        address target;   // Call target (e.g. USDT)
        uint256 value;    // ETH to send (usually 0)
        bytes   data;     // calldata (e.g. transfer(recipient, amount))
    }

    struct Intent {
        Call[]  calls;     // List of calls to execute
        address feeToken;  // Fee token (USDT)
        uint256 maxFee;    // Maximum fee allowed by the user (USDT 6dp) — cap including markup
        uint256 nonce;     // Must match the current contract nonce
        uint256 deadline;  // Expiration time (block.timestamp)
    }

    bytes32 private constant _CALL_TYPEHASH =
        keccak256("Call(address target,uint256 value,bytes data)");
    bytes32 private constant _INTENT_TYPEHASH = keccak256(
        "Intent(Call[] calls,address feeToken,uint256 maxFee,uint256 nonce,uint256 deadline)Call(address target,uint256 value,bytes data)"
    );
    bytes32 private constant _EIP712_DOMAIN_TYPEHASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    event Executed(address indexed owner, uint256 indexed nonce, uint256 feeCharged);

    error Expired();
    error BadNonce();
    error BadSignature();
    error FeeExceedsMax(uint256 fee, uint256 maxFee);
    error CallFailed(uint256 index, bytes ret);
    error FeeTransferFailed();

    constructor(FeeRegistry feeRegistry) {
        FEE_REGISTRY = feeRegistry;
    }

    /// @notice Called by the relayer. Verify owner signature -> run batch -> settle gas cost in USDT.
    /// @param intent The intent signed by the user via EIP-712
    /// @param signature owner(=EOA) signature
    function execute(Intent calldata intent, bytes calldata signature) external {
        uint256 gasStart = gasleft();

        if (block.timestamp > intent.deadline) revert Expired();
        if (intent.nonce != nonce) revert BadNonce();

        // Verify signer == address(this)(=EOA owner)
        bytes32 digest = _hashIntent(intent);
        if (_recover(digest, signature) != address(this)) revert BadSignature();

        unchecked { nonce = intent.nonce + 1; } // effects before interactions

        // 1) Run the main calls (e.g. USDT.transfer(recipient, amount))
        uint256 len = intent.calls.length;
        for (uint256 i; i < len; ++i) {
            Call calldata c = intent.calls[i];
            (bool ok, bytes memory ret) = c.target.call{value: c.value}(c.data);
            if (!ok) revert CallFailed(i, ret);
        }

        // 2) Settle gas cost: measured gas + registry overheads -> USDT (including markup).
        //    A first intent (nonce == 0) rides in the same transaction as the EIP-7702
        //    authorization, whose intrinsic 25k gas is invisible to the measurement above,
        //    so the registry adds `authOverhead` for it.
        FeeRegistry reg = FEE_REGISTRY;
        uint256 measuredGas = gasStart - gasleft();
        uint256 fee = reg.quoteFeeFor(measuredGas, tx.gasprice, intent.nonce == 0);
        if (fee > intent.maxFee) revert FeeExceedsMax(fee, intent.maxFee);

        if (fee > 0) {
            _safeTransfer(intent.feeToken, reg.feeCollector(), fee);
        }

        emit Executed(address(this), intent.nonce, fee);
    }

    // ---------------------------------------------------------------------
    // EIP-712
    // ---------------------------------------------------------------------

    /// @dev Compute the domain separator on every call: verifyingContract = address(this) = EOA,
    ///      chainId = block.chainid -> blocks replay across chains/accounts.
    function _domainSeparator() internal view returns (bytes32) {
        return keccak256(abi.encode(
            _EIP712_DOMAIN_TYPEHASH,
            keccak256(bytes("GaslessAccount")),
            keccak256(bytes("1")),
            block.chainid,
            address(this)
        ));
    }

    function _hashIntent(Intent calldata intent) internal view returns (bytes32) {
        uint256 len = intent.calls.length;
        bytes32[] memory callHashes = new bytes32[](len);
        for (uint256 i; i < len; ++i) {
            callHashes[i] = keccak256(abi.encode(
                _CALL_TYPEHASH,
                intent.calls[i].target,
                intent.calls[i].value,
                keccak256(intent.calls[i].data)
            ));
        }
        bytes32 structHash = keccak256(abi.encode(
            _INTENT_TYPEHASH,
            keccak256(abi.encodePacked(callHashes)),
            intent.feeToken,
            intent.maxFee,
            intent.nonce,
            intent.deadline
        ));
        return keccak256(abi.encodePacked("\x19\x01", _domainSeparator(), structHash));
    }

    /// @dev Exposes the EIP-712 digest for external inspection (client debugging).
    function intentDigest(Intent calldata intent) external view returns (bytes32) {
        return _hashIntent(intent);
    }

    /// @dev Safely handles non-standard tokens like USDT whose transfer does not return a bool.
    ///      Passes only when success(ok) + (no return data || return value true).
    function _safeTransfer(address token, address to, uint256 amount) internal {
        (bool ok, bytes memory ret) = token.call(
            abi.encodeWithSelector(IERC20.transfer.selector, to, amount)
        );
        if (!ok || (ret.length != 0 && !abi.decode(ret, (bool)))) revert FeeTransferFailed();
    }

    // ---------------------------------------------------------------------
    // ECDSA recover (equivalent to OpenZeppelin ECDSA; prevents malleability)
    // ---------------------------------------------------------------------
    function _recover(bytes32 digest, bytes calldata sig) internal pure returns (address) {
        if (sig.length != 65) revert BadSignature();
        bytes32 r;
        bytes32 s;
        uint8 v;
        assembly {
            r := calldataload(sig.offset)
            s := calldataload(add(sig.offset, 32))
            v := byte(0, calldataload(add(sig.offset, 64)))
        }
        // Check s upper bound (prevents signature malleability)
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            revert BadSignature();
        }
        if (v != 27 && v != 28) revert BadSignature();
        address signer = ecrecover(digest, v, r, s);
        if (signer == address(0)) revert BadSignature();
        return signer;
    }

    receive() external payable {}
}

src/FeeRegistry.sol

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

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

/// @title FeeRegistry
/// @notice Singleton contract that holds the gas fee policy.
///         GaslessAccount (delegated to an EOA) references this address as an
///         immutable, reading the markup/exchange rate/collector/overhead at
///         execution time to compute the USDT fee.
/// @dev    When the owner changes the policy on-chain, it takes effect
///         immediately for all users.
///         The exchange rate has two modes:
///         - Oracle mode: computed automatically from Chainlink ETH/USD
///           (+ optional USDT/USD) feeds (recommended)
///         - Manual mode: when ethUsdFeed == address(0), uses the
///           owner-configured value (`manualUsdtPerEth`)
contract FeeRegistry {
    address public owner;

    /// @notice Margin charged on top of the gas cost (basis points, 10000 = 100%).
    ///         e.g. 1000 = +10%, 2000 = +20%.
    uint256 public markupBps;

    /// @notice Address that receives the fee (relayer hot wallet or treasury).
    address public feeCollector;

    /// @notice Fixed overhead not captured by the execute() gas measurement
    ///         (intrinsic gas, calldata, and everything after `gasleft()` is read:
    ///         the oracle read and the fee transfer itself). Tuned by the owner.
    /// @dev    Measured at ~75,000 on mainnet. Excludes the EIP-7702 authorization,
    ///         which is charged separately via {authOverhead}.
    uint256 public fixedOverhead;

    /// @notice Extra overhead charged on a first intent (nonce == 0), covering the
    ///         EIP-7702 authorization the relayer bundles to delegate the EOA.
    /// @dev    The authorization is intrinsic to the transaction and therefore invisible
    ///         to the delegate's own gas measurement. Charging it on every transfer would
    ///         overcharge already-delegated users by the same amount, so it is applied
    ///         only when the intent's nonce is 0.
    ///
    ///         Measured at ~27,000 on mainnet: `PER_EMPTY_ACCOUNT_COST` (25,000) plus
    ///         ~2,000 of first-intent-only gas that also falls outside the measured window.
    ///
    ///         The nonce==0 test is a proxy for "this transaction carried an authorization".
    ///         It is exact when the relayer bundles delegation with the first intent, which
    ///         is what the SDK does. A user who delegates in a separate transaction is
    ///         overcharged once by this amount; a user who re-delegates later (nonce > 0)
    ///         is undercharged once, and the relayer absorbs it. Both are bounded by the
    ///         user-signed `maxFee`, and both are visible to the user at signing time.
    uint256 public authOverhead;

    // --- Exchange rate (oracle) ---
    /// @notice Chainlink ETH/USD feed. If address(0), Manual mode.
    AggregatorV3Interface public ethUsdFeed;
    /// @notice (Optional) Chainlink USDT/USD feed. If address(0), assumes USDT=$1.
    AggregatorV3Interface public usdtUsdFeed;
    /// @notice Allowed feed response freshness (seconds). Reverts as stale if exceeded.
    uint256 public maxStaleness;
    /// @notice Manual mode exchange rate: USDT amount (6dp) per 1 ETH (1e18 wei).
    ///         e.g. for ETH=$3000, 3000 * 1e6.
    uint256 public manualUsdtPerEth;

    /// @notice Markup cap (hard cap for user protection). Even the owner cannot exceed this value.
    uint256 public constant MAX_MARKUP_BPS = 5000; // +50%

    /// @notice Overhead caps (hard caps for user protection). The owner cannot exceed these.
    uint256 public constant MAX_FIXED_OVERHEAD = 200_000;
    uint256 public constant MAX_AUTH_OVERHEAD = 50_000;

    /// @notice Output scale based on USDT decimals (6).
    uint256 private constant USDT_SCALE = 1e6;

    event PolicyUpdated(uint256 markupBps, address feeCollector, uint256 fixedOverhead, uint256 authOverhead);
    event OracleUpdated(address ethUsdFeed, address usdtUsdFeed, uint256 maxStaleness, uint256 manualUsdtPerEth);
    event OwnerTransferred(address indexed from, address indexed to);

    error NotOwner();
    error MarkupTooHigh();
    error OverheadTooHigh();
    error ZeroAddress();
    error StalePrice();
    error InvalidPrice();

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

    constructor(
        uint256 _markupBps,
        address _feeCollector,
        uint256 _fixedOverhead,
        uint256 _authOverhead,
        address _ethUsdFeed,
        address _usdtUsdFeed,
        uint256 _maxStaleness,
        uint256 _manualUsdtPerEth
    ) {
        if (_markupBps > MAX_MARKUP_BPS) revert MarkupTooHigh();
        if (_fixedOverhead > MAX_FIXED_OVERHEAD || _authOverhead > MAX_AUTH_OVERHEAD) revert OverheadTooHigh();
        if (_feeCollector == address(0)) revert ZeroAddress();
        owner = msg.sender;
        markupBps = _markupBps;
        feeCollector = _feeCollector;
        fixedOverhead = _fixedOverhead;
        authOverhead = _authOverhead;
        ethUsdFeed = AggregatorV3Interface(_ethUsdFeed);
        usdtUsdFeed = AggregatorV3Interface(_usdtUsdFeed);
        maxStaleness = _maxStaleness;
        manualUsdtPerEth = _manualUsdtPerEth;
        emit PolicyUpdated(_markupBps, _feeCollector, _fixedOverhead, _authOverhead);
        emit OracleUpdated(_ethUsdFeed, _usdtUsdFeed, _maxStaleness, _manualUsdtPerEth);
    }

    // -----------------------------------------------------------------------
    // Owner configuration
    // -----------------------------------------------------------------------

    /// @notice Update markup/collector/overheads.
    function setPolicy(uint256 _markupBps, address _feeCollector, uint256 _fixedOverhead, uint256 _authOverhead)
        external
        onlyOwner
    {
        if (_markupBps > MAX_MARKUP_BPS) revert MarkupTooHigh();
        if (_fixedOverhead > MAX_FIXED_OVERHEAD || _authOverhead > MAX_AUTH_OVERHEAD) revert OverheadTooHigh();
        if (_feeCollector == address(0)) revert ZeroAddress();
        markupBps = _markupBps;
        feeCollector = _feeCollector;
        fixedOverhead = _fixedOverhead;
        authOverhead = _authOverhead;
        emit PolicyUpdated(_markupBps, _feeCollector, _fixedOverhead, _authOverhead);
    }

    /// @notice Update oracle configuration / Manual exchange rate.
    function setOracle(
        address _ethUsdFeed,
        address _usdtUsdFeed,
        uint256 _maxStaleness,
        uint256 _manualUsdtPerEth
    ) external onlyOwner {
        ethUsdFeed = AggregatorV3Interface(_ethUsdFeed);
        usdtUsdFeed = AggregatorV3Interface(_usdtUsdFeed);
        maxStaleness = _maxStaleness;
        manualUsdtPerEth = _manualUsdtPerEth;
        emit OracleUpdated(_ethUsdFeed, _usdtUsdFeed, _maxStaleness, _manualUsdtPerEth);
    }

    /// @notice Quickly update only the Manual mode exchange rate (called frequently by the oracle bot).
    function setManualUsdtPerEth(uint256 _manualUsdtPerEth) external onlyOwner {
        manualUsdtPerEth = _manualUsdtPerEth;
        emit OracleUpdated(address(ethUsdFeed), address(usdtUsdFeed), maxStaleness, _manualUsdtPerEth);
    }

    function transferOwnership(address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        emit OwnerTransferred(owner, to);
        owner = to;
    }

    // -----------------------------------------------------------------------
    // Exchange rate / fee calculation
    // -----------------------------------------------------------------------

    /// @notice Currently applied exchange rate: USDT amount (6dp) per 1 ETH (1e18 wei).
    /// @dev    In Oracle mode, computed from Chainlink feeds; otherwise returns manualUsdtPerEth.
    function currentUsdtPerEth() public view returns (uint256) {
        if (address(ethUsdFeed) == address(0)) {
            return manualUsdtPerEth; // Manual mode
        }

        uint256 ethUsd = _readFeed(ethUsdFeed);     // ETH price (ethDec scale)
        uint8 ethDec = ethUsdFeed.decimals();

        // usdtPerEth = (ethPriceUsd / usdtPriceUsd) * 1e6
        if (address(usdtUsdFeed) == address(0)) {
            // Assume USDT = $1:  usdtPerEth = ethUsd * 1e6 / 10^ethDec
            return (ethUsd * USDT_SCALE) / (10 ** ethDec);
        } else {
            uint256 usdtUsd = _readFeed(usdtUsdFeed);
            uint8 usdtDec = usdtUsdFeed.decimals();
            // = ethUsd/10^ethDec / (usdtUsd/10^usdtDec) * 1e6
            // = ethUsd * 10^usdtDec * 1e6 / (10^ethDec * usdtUsd)
            return (ethUsd * (10 ** usdtDec) * USDT_SCALE) / ((10 ** ethDec) * usdtUsd);
        }
    }

    function _readFeed(AggregatorV3Interface feed) internal view returns (uint256) {
        (, int256 answer,, uint256 updatedAt,) = feed.latestRoundData();
        if (answer <= 0) revert InvalidPrice();
        if (block.timestamp - updatedAt > maxStaleness) revert StalePrice();
        return uint256(answer);
    }

    /// @notice Convert gas usage (cost in wei) into a USDT fee (including markup).
    /// @param gasUsed            Total gas to charge for (overheads already included)
    /// @param effectiveGasPrice  tx.gasprice (wei)
    /// @return fee USDT fee (6 decimals)
    function quoteFee(uint256 gasUsed, uint256 effectiveGasPrice) public view returns (uint256 fee) {
        uint256 rate = currentUsdtPerEth();                       // USDT(6dp) per 1 ETH
        uint256 gasCostWei = gasUsed * effectiveGasPrice;         // wei
        uint256 baseUsdt = (gasCostWei * rate) / 1e18;            // USDT(6dp)
        fee = (baseUsdt * (10000 + markupBps)) / 10000;           // + markup
    }

    /// @notice Quote a fee from the gas a delegate measured itself, adding the overheads
    ///         it cannot observe. Delegates should call this rather than {quoteFee}, so
    ///         the overhead policy stays here and one external call does the whole job.
    /// @param measuredGas  Gas measured inside the delegate (excludes intrinsic/calldata/fee transfer)
    /// @param effectiveGasPrice  tx.gasprice (wei)
    /// @param firstIntent  True when the intent's nonce is 0, i.e. the transaction also
    ///                     carried the EIP-7702 authorization that delegated the EOA.
    function quoteFeeFor(uint256 measuredGas, uint256 effectiveGasPrice, bool firstIntent)
        external
        view
        returns (uint256 fee)
    {
        uint256 gasUsed = measuredGas + fixedOverhead;
        if (firstIntent) gasUsed += authOverhead;
        return quoteFee(gasUsed, effectiveGasPrice);
    }
}

src/interfaces/AggregatorV3Interface.sol

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

/// @notice Minimal interface for the Chainlink price feed.
interface AggregatorV3Interface {
    function decimals() external view returns (uint8);

    function latestRoundData()
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "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.