Back to blog
Agentic Infrastructure12 min read

How ERC-4337 Paymasters Actually Work

What an ERC-4337 paymaster does, how validatePaymasterUserOp and postOp work, the four sponsorship models, and what breaks in production. Includes agent gas budgets.

Parth Chaudhary
How ERC-4337 Paymasters Actually Work

An ERC-4337 paymaster is a smart contract that agrees to pay gas for a user operation, so the user or agent sending it does not need to hold the chain's native token. The EntryPoint contract asks the paymaster to approve each operation before execution and charges the gas to the paymaster's deposit afterwards. That makes gasless transactions possible.

Gas fees are the first wall most Web3 users hit: native tokens mean an exchange, an off-ramp and a balance to manage, and none of that is product. A paymaster moves that cost into infrastructure. Below: the full paymaster lifecycle, a Solidity sketch of the two main paymaster designs, the four sponsorship models, what breaks in production, and how a paymaster becomes an AI agent's gas budget.

Key takeaways

  • A paymaster is a contract with a deposit in the EntryPoint. It approves user operations in validatePaymasterUserOp and, if it asks for one, gets a postOp callback with the actual gas cost.
  • A verifying paymaster sponsors whatever its off-chain signer approves. An ERC-20 paymaster lets the user pay gas in a token and settles that charge in postOp.
  • Most production failures are operational, not cryptographic: an empty deposit, bundler throttling, token price moves and sponsorship abuse.
  • For AI agents, the paymaster policy is the gas budget. Restricting which accounts can draw on it keeps a misbehaving agent from draining a treasury.

What Gasless Transactions Actually Mean

Gasless transactions do not eliminate gas costs. They change where the cost is paid.

In a standard transaction, the user pays gas directly. In a gasless model, the application or infrastructure layer sponsors the cost.

In production, this means:

  • Users interact without holding native tokens
  • Transactions can be initiated immediately after onboarding
  • Application-controlled transaction flows replace user-driven approvals

Gasless transactions are not a pricing feature. They are an infrastructure capability that removes a dependency from the user journey.

Why Gasless Execution Requires New Infrastructure

The traditional Ethereum transaction model is built around Externally Owned Accounts. EOAs require the account holder to sign transactions and pay gas directly. The format does not support flexible third-party gas sponsorship.

Gasless execution requires:

  • Programmable accounts
  • Abstraction of transaction validation and execution

This is what account abstraction provides. Smart accounts add a programmable execution layer that lets gas payment logic separate from the user (see how EOAs and smart accounts differ). That separation is the foundation for gasless transactions in production.

ERC-4337 Paymasters: The Mechanism

An ERC-4337 paymaster is a smart contract that sponsors gas for users or applications. It operates within the account abstraction flow alongside smart accounts and bundlers.

A paymaster is registered with the EntryPoint contract and is responsible for:

  • Validating whether a transaction should be sponsored, via the validatePaymasterUserOp method
  • Applying rules for gas payment
  • Covering the execution cost when conditions are met
  • Optionally running post-execution logic via the postOp method

Instead of requiring users to hold ETH, the paymaster funds the transaction during execution. The paymaster's address and any policy data are passed in the paymasterAndData field of the UserOperation.

Two operational details matter here. First, a paymaster keeps a deposit in the EntryPoint, and the deposit is what pays for gas. Some paymasters also lock a stake, which bundler rules (ERC-7562) require before a paymaster may read its own storage during validation or return a context for postOp. The stake ties the paymaster's reputation to locked capital, which is how bundlers stop one bad paymaster from flooding the shared mempool. Second, the EntryPoint version matters: v0.6 and v0.7 differ in how paymasterAndData is encoded and how post-op gas accounting works, which affects how integrations are configured. In v0.7, paymasterAndData carries the paymaster address, its own verification gas limit and its postOp gas limit before any custom data.

The paymaster lifecycle, step by step

  1. The wallet builds a UserOperation and fills the paymaster fields, usually by calling a paymaster service. ERC-7677 standardizes this with pm_getPaymasterStubData and pm_getPaymasterData.
  2. The bundler simulates the operation and submits it to the EntryPoint.
  3. In the validation phase, the EntryPoint calls validatePaymasterUserOp on the paymaster. The paymaster checks its rules (a signature from its off-chain signer, a token allowance, a policy) and returns a context and validity window.
  4. The account's call executes.
  5. If the paymaster returned a non-empty context, the EntryPoint calls postOp with the actual gas cost. This is where an ERC-20 paymaster collects the user's token payment.
  6. The gas is deducted from the paymaster's deposit held in the EntryPoint.

The stub call in step 1 exists because gas estimation needs paymaster data of a realistic size before the final, signed paymaster data can be produced. The wallet estimates with the stub, then asks for the real data once the gas limits are fixed.

From the user's perspective, the transaction completes without holding native tokens. From the system's perspective, execution stays controlled and auditable.

Verifying paymaster vs ERC-20 paymaster

Almost every production paymaster is a variation on one of two designs. Simplified examples using EntryPoint v0.7 interfaces, the version Abstraxn's paymaster targets. Both leave out access control setup, deposits and gas limit checks, so neither is production code.

A verifying paymaster sponsors any operation its off-chain signer has approved. The paymaster service decides off-chain (is this account allowed, is the policy satisfied) and signs a hash of the operation together with a validUntil and validAfter window. On-chain, the contract only checks that signature. The signed hash cannot be the userOpHash itself, because that hash covers paymasterAndData, which contains the signature. So the paymaster hashes the operation's other fields plus the chain ID, its own address and the window.

// Verifying paymaster. Simplified, not production code (EntryPoint v0.7).
function validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32 /* userOpHash */, uint256 /* maxCost */)
    external returns (bytes memory context, uint256 validationData)
{
    require(msg.sender == address(entryPoint), "only EntryPoint");
    // paymasterAndData = paymaster (20) | verificationGas (16) | postOpGas (16) | validUntil, validAfter (64) | signature
    (uint48 validUntil, uint48 validAfter) = abi.decode(userOp.paymasterAndData[52:116], (uint48, uint48));
    bytes calldata signature = userOp.paymasterAndData[116:];
    // getHash: the userOp fields without the paymaster signature, plus chainid, address(this) and the window
    bytes32 hash = MessageHashUtils.toEthSignedMessageHash(getHash(userOp, validUntil, validAfter));
    bool sigFailed = ECDSA.recover(hash, signature) != verifyingSigner;
    // validationData packs sigFailed (low 160 bits), validUntil (next 48) and validAfter (top 48)
    validationData = (sigFailed ? 1 : 0) | (uint256(validUntil) << 160) | (uint256(validAfter) << 208);
    return ("", validationData); // empty context: no postOp call
}

Note what the contract does not do: it does not revert on a bad signature. Returning sigFailed lets the EntryPoint and bundler reject the operation cleanly, and the validity window lets the EntryPoint refuse stale approvals without the paymaster reading the clock itself.

An ERC-20 paymaster lets the user pay for gas in a token. During validation it checks that the sender has approved and holds enough tokens to cover the worst-case cost at a known price. It returns a context so that postOp runs, and charges the token amount for the gas actually used.

// ERC-20 paymaster. Simplified, not production code (EntryPoint v0.7).
function validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32, uint256 maxCost)
    external returns (bytes memory context, uint256 validationData)
{
    require(msg.sender == address(entryPoint), "only EntryPoint");
    // cachedPrice lives in this contract's storage (tokens per 1e18 wei), so the paymaster must be staked
    uint256 maxTokenCost = (maxCost * cachedPrice * MARKUP) / (1e18 * 100);
    require(token.allowance(userOp.sender, address(this)) >= maxTokenCost, "allowance");
    require(token.balanceOf(userOp.sender) >= maxTokenCost, "balance");
    return (abi.encode(userOp.sender, cachedPrice), 0); // non-empty context: postOp will run
}
 
function postOp(PostOpMode, bytes calldata context, uint256 actualGasCost, uint256 actualUserOpFeePerGas) external {
    require(msg.sender == address(entryPoint), "only EntryPoint");
    (address sender, uint256 price) = abi.decode(context, (address, uint256));
    uint256 tokenCost = ((actualGasCost + POST_OP_GAS * actualUserOpFeePerGas) * price) / 1e18;
    token.safeTransferFrom(sender, address(this), tokenCost);
}

The markup is the paymaster's buffer against price moves between validation and settlement. actualGasCost does not include the gas postOp itself burns, so the sketch adds an estimate priced at actualUserOpFeePerGas. Some designs move the risk earlier by transferring the maximum token amount during validation and refunding the difference in postOp.

Four Paymaster Models You Will See in Production

Paymasters support multiple transaction models depending on application requirements.

Full gas sponsorship. The application covers all transaction costs. Configured as an unconditional sponsorship policy on the paymaster.

Conditional sponsorship. Gas is sponsored based on predefined rules: first transaction free, specific actions sponsored, daily caps per user, allowlisted contract calls. These rules usually live in the paymaster service that signs for a verifying paymaster, or in the paymaster contract itself.

Token-based gas payment. Users pay fees in application-specific tokens instead of native assets. The paymaster handles the conversion and execution. ERC-20 paymasters fall in this bucket and typically use postOp to settle the user's token payment after execution.

Subscription-based execution. Applications sponsor transactions for users on a subscription model. Gas costs are managed as part of product pricing rather than per-transaction.

What breaks in production

Gasless execution has to behave deterministically, and the failure modes are mostly operational. These are the ones that show up first.

  • Deposit runs dry: sponsorship silently stops. Monitor the EntryPoint deposit and alert well before it reaches zero, because the wallet usually sees only a generic validation failure.
  • Stake and reputation: paymasters that access storage need stake. Bundlers throttle paymasters whose operations fail validation, so a buggy policy can degrade sponsorship for every user, not just the one with a bad operation.
  • ERC-20 settlement risk: the token charge happens after execution, so price moves or revoked allowances are the paymaster's loss to price in. In v0.7, if postOp reverts, the account's call is reverted but the paymaster still pays the gas.
  • Sponsorship abuse: an unconditional policy is a faucet. Rate-limit per account and restrict sponsorship to the accounts or contracts you intend to serve, which covers most of how to stop a paymaster from being drained.
  • Simulation vs reality: an operation that passes simulation can still fail on-chain if state changes between simulation and inclusion. Validation that depends on balances or prices is the usual culprit, so keep it to the minimum the bundler rules allow.

Cost control sits across all five: every paymaster needs a policy that answers who can trigger sponsored transactions, which actions are sponsored, and when.

Paymasters for AI agents

An AI agent that transacts on-chain hits the same wall as a new user: it needs native gas before it can do anything. A paymaster removes that, and its policy becomes the agent's gas budget. Sponsorship can be limited to approved wallets, so an agent outside the policy gets no sponsored gas. The practical pattern is one smart account per agent: add the agent's account to the sponsorship policy when you deploy it, remove it when you retire or suspend it, and the agent loses access to sponsored gas with it. Because every sponsored operation is charged to the paymaster's deposit, the deposit balance becomes your real-time view of what your agents are spending on gas.

Keep the gas budget and the spending budget separate. The paymaster bounds what an agent spends on gas, not the value it moves. Limits on value belong in the account's own policy, which is the subject of a mandate that cannot be overspent. The other half of the path is the bundler, which packages the agent's user operations and submits them to the EntryPoint; how ERC-4337 bundlers work covers that side.

Running a sponsorship policy for a fleet of agents

Once several agents draw on the same paymaster, the policy becomes an operations job. The practices below follow from how ERC-4337 validates and charges sponsored operations.

Give every agent its own smart account. The EntryPoint sees the sender address and nothing else, so agents sharing one account are indistinguishable on-chain. Separate accounts give you attribution (each operation names the agent that sent it), revocation (you can cut off one agent without touching the rest) and a smaller blast radius (a compromised or looping agent can only burn the sponsorship its own account is allowed).

Onboard and offboard through the wallet list. Onboarding means putting the agent's smart-account address, the userOp sender, on the allowlist when you deploy it. Not the owner EOA: the paymaster matches its wallet list against the sender of each user operation, which is the smart account. Offboarding means removing it, or blocklisting it if the paymaster is open to everyone else. On Abstraxn's paymaster, this is the dashboard's wallet restriction setting: an allowlist or a blocklist of wallets. Offboarding stops sponsorship, not the account. An agent whose account holds native gas can still pay for its own operations, so drain or lock that balance too if you need a full stop.

Know what removal does to in-flight operations. Removing an agent's smart account from the sponsorship policy stops new sponsored operations immediately. Paymaster data that was already signed stays valid for its validity window, about 10 minutes by default, so an operation the agent had already prepared can still land. For agent fleets, set a short validUntilMinutes so a revocation takes effect almost at once.

Monitor the deposit and alert early. The EntryPoint holds one deposit per paymaster (read with balanceOf, topped up with depositTo, withdrawn with withdrawTo), not one per agent, and an empty deposit fails every agent's operations at once. On Abstraxn, the dashboard's Gas Tank shows the paymaster deposit available for sponsorship, and the gas sponsorship settings let you configure low-credit thresholds and notifications, so set the threshold to leave time for a top-up at your peak burn rate.

Log every sponsored operation. Because the deposit is shared and the Agent Kit SDK has no deposit API, per-agent gas spend attribution has to come from your own logging. From each UserOperationEvent, store the userOpHash, sender, paymaster address, success flag, actualGasCost and actualGasUsed, together with the chain ID, block timestamp and your internal agent ID. Summing actualGasCost per sender reconciles against the fall in the deposit. Operations whose execution reverted are still charged, so count them too.

Paymasters in Onboarding and the Wider Stack

Gas fees create a dependency that delays onboarding. With gasless execution, users do not need to pre-fund wallets, transactions can occur immediately after signup, and onboarding stays inside the application. Combined with embedded wallets and authentication-based access, wallet creation becomes part of onboarding and blockchain interaction becomes application-native.

Paymasters are one layer in that architecture, not a standalone solution. Gasless transactions in production also need smart accounts for programmable execution, bundlers for transaction processing, wallet provisioning and authentication-integrated onboarding.

How Abstraxn Implements Paymaster Infrastructure

Abstraxn runs Paymaster v2 alongside its bundler, relayer and ERC-4337 smart account integrations. It has two modes: sponsor mode, where the paymaster pays native gas, and token mode, where an ERC-20 fee is deducted from the sender during the same UserOperation. The documented flow has five steps.

  1. Fund gas sponsorship. In the Abstraxn dashboard, open Gas sponsorship and add a budget in crypto or fiat. It is tracked as USD gas credit, and both modes draw from it. The Gas Tank shows the balance available for sponsorship, and deposit history and gas usage history show top-ups and consumption.
  2. Set controls. Configure low-credit thresholds, notification settings, and whether sponsorship is enabled.
  3. Create a paymaster and set its policy. Choose whether sponsor mode and token mode are enabled, set how many minutes generated paymaster data stays valid (about 10 by default; keep it short for agent fleets), and pick a wallet restriction: none, an allowlist of approved wallets, or a blocklist. The list matches smart-account addresses, the sender of each user operation. Token mode also requires a treasury wallet, which receives the token fees, and a constant fee charged per operation. Then copy the paymaster API key from View details.
  4. Create the paymaster client. Point viem's createPaymasterClient at the Paymaster v2 endpoint for your chain, using that API key.
  5. Send the UserOperation. Pass the client and a paymasterContext to sendUserOperation on your bundler client.
import { http } from "viem";
import { createPaymasterClient } from "viem/account-abstraction";
 
const CHAIN_ID = 80002; // Polygon Amoy testnet
const API_KEY = "<YOUR_PAYMASTER_API_KEY>";
 
const paymasterClient = createPaymasterClient({
  transport: http(`https://paymaster.abstraxn.com/api/v2/${CHAIN_ID}/?apikey=${API_KEY}`),
});
 
const hash = await bundlerClient.sendUserOperation({
  account: kernelAccount, // your smart account
  calls: [{ to: TARGET_CONTRACT, value: 0n, data: TARGET_CALLDATA }],
  paymaster: paymasterClient,
  paymasterContext: { mode: "sponsor" },
});

For token mode, set the mode to "token" and pass a tokenAddress. Add an ERC-20 approve for the paymaster contract to calls before the real action, because the fee is deducted inside the same UserOperation. The treasury and constant fee come from the dashboard configuration, not the request, and the request is rejected if token mode is not configured there. The Paymaster integration guide has the full token-mode example, and the docs list the supported networks, including Ethereum, Base, BNB Smart Chain and Polygon.

Closing

Gasless transactions are not a surface feature. They are the result of changes in execution architecture.

A paymaster is a small contract with two hooks, a deposit and a policy. validatePaymasterUserOp decides what gets sponsored, postOp settles what was used, and the deposit and stake make the arrangement credible to bundlers. Everything hard about running one in production lives around those hooks: keeping the deposit funded, keeping validation simple enough to pass bundler rules, pricing token risk, and writing a policy that is not a faucet.

For teams building production systems, and increasingly for teams deploying AI agents, gasless transactions are a shift toward infrastructure-driven execution. When integrated correctly, they let applications deliver blockchain functionality without exposing users to underlying operational complexity.

Frequently asked questions

What is a paymaster in ERC-4337?

A contract that pays gas for user operations it approves, so the sender does not need native tokens.

Who pays the gas in a gasless transaction?

The paymaster, from its deposit in the EntryPoint contract. The app or service running it covers that cost, or recovers it in another token.

What is the difference between a verifying paymaster and an ERC-20 paymaster?

A verifying paymaster sponsors operations its off-chain signer approves. An ERC-20 paymaster lets the user pay gas in a token and collects it in postOp.

Do paymasters need to stake?

A paymaster keeps a deposit in the EntryPoint to pay gas. Staking is required when it accesses storage or context in ways the bundler rules restrict.

Can an AI agent use a paymaster?

Yes. The agent's smart account sends user operations like any other account, and the paymaster policy acts as the agent's gas budget.

What is ERC-7677?

A wallet standard for requesting paymaster data from a paymaster service, using pm_getPaymasterStubData and pm_getPaymasterData.

About the Author

Parth Chaudhary

Parth Chaudhary

Solution Architect

Parth Chaudhary is a Solution Architect at Abstraxn. He works at the intersection of account abstraction and agentic AI infrastructure, on wallets, paymasters, agent identity, and the policy guardrails that keep autonomous agents inside their limits. Find out more at abstraxn.com or spin up an agent at dashboard.abstraxn.com.