SolidityIn

Paymasters and sponsored gas

Lesson 36 of 40 · Account Abstraction

A paymaster is a contract that agrees to pay the gas for a user's operation. This lets apps sponsor fees for new users, who then do not need ETH before they can do anything, or lets users pay fees in a token such as a stablecoin.

In ERC-4337 the paymaster holds a deposit in the EntryPoint and checks each operation before agreeing to pay. If the checks pass, the EntryPoint takes the gas cost from that deposit. If the paymaster misjudges an operation, it loses money, so the checks matter.

Good paymasters apply policies: only certain apps or functions, a limit per user per day, or a signature from the app's server. Without such limits, anyone could drain the deposit by sending many expensive operations.

The example shows only the policy part, with an allowlist of target contracts and a daily spending limit per user. A real paymaster also implements the ERC-4337 interface and stakes funds in the EntryPoint, and developers usually start from a provider's or the reference implementation rather than writing one from scratch.

contract SponsorPolicy {
    address public owner = msg.sender;
    uint256 public dailyLimit = 0.01 ether;
    mapping(address => bool) public allowedTarget;
    mapping(address => mapping(uint256 => uint256)) public spent;   // user => day => wei

    modifier onlyOwner() {
        require(msg.sender == owner, "Not owner");
        _;
    }
    function deposit() external payable {}

    function setTarget(address target, bool ok) external onlyOwner {
        allowedTarget[target] = ok;
    }
    function canSponsor(address user, address target, uint256 maxCost) public view returns (bool) {
        if (!allowedTarget[target]) return false;
        return spent[user][block.timestamp / 1 days] + maxCost <= dailyLimit;
    }
    function charge(address user, address target, uint256 cost) external onlyOwner {
        require(canSponsor(user, target, cost), "Not sponsored");
        spent[user][block.timestamp / 1 days] += cost;
    }
}

Try it yourself

Add a global daily budget for all users together, and an event that is emitted on every charge. Then explain how an attacker could abuse a paymaster that has no per-user limit.

Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.

Quick check: Why must a paymaster check each operation before paying?