Mental model
An autonomous on-chain agent should treat the language model as a planner, never as an authority to spend. A deterministic policy layer converts a proposal into a narrowly scoped authorization, checks the account nonce and chain, then signs an ERC-4337 UserOperation whose validation and execution are enforced by the account contract. Bundlers transport the operation; inclusion and finality are separate states, not synonyms for success.
Learning outcomes
- Trace an agent proposal through account policy, ERC-4337 validation, bundler inclusion, and transaction finality.
- Calculate the fee ceiling and explain which gas components a paymaster must budget.
- Identify how EIP-7702 delegation, replay, and transaction ordering change an agent's threat model.
Theory
An agent often starts with untrusted natural-language intent, such as “swap a small amount of token A for token B.” The model should produce a structured proposal: chain ID, account, target, function selector, token or native value, slippage bound, nonce, expiration, and maximum fee. A policy engine compares those fields with an allowlist and the account's current state. It rejects ambiguous calls, unbounded approvals, unexpected recipients, stale nonces, and fee quotes above the user or sponsor budget. The model can suggest; only the account's verified authorization path can commit.
ERC-4337 represents the request as a UserOperation. The sender account validates its signature and policy, the bundler simulates validation before accepting the operation into an alternate mempool, and the bundler later calls the EntryPoint to execute one or more operations. The operation carries a nonce, call data, signature, gas limits, fee caps, and optional paymaster data. The userOpHash binds the operation to a chain and EntryPoint so a signature cannot simply be replayed against a different deployment. See the ERC-4337 specification for the operation fields, validation flow, and paymaster interface.
EIP-7702 lets an externally owned account authorize delegated code. That can make an existing account programmable, but the authorization is powerful: delegated code can act with the account's authority. EIP-7702 does not create fine-grained permissions by itself. A wallet or account module still has to constrain target, calldata, value, nonce, and expiry, and to verify any initialization signature. A session key is safe only when the account validation code actually enforces its scope; hiding a key in an agent process is not a policy boundary. The EIP-7702 security considerations call out replay and broad delegate authority as wallet risks.
Operations also have protocol costs and adversarial ordering. Under EIP-1559, the effective gas price is bounded by the signed max fee and the sum of the base fee and priority fee. A paymaster may sponsor that cost, but sponsorship moves the budget to the paymaster; it does not make execution free. Competing transactions can alter a pool's price or consume a quote before an agent's operation executes. The Flash Boys 2.0 study describes how transaction ordering and front-running create economic incentives around public transaction flow. Slippage limits, expirations, replay protection, and a simulation are useful controls, but a simulation is only a snapshot of state and cannot promise the eventual ordering.
Worked example
Suppose an agent proposes a token swap with an estimated total of 180,000 gas units. The current base fee is 12 gwei and the operation offers a 2 gwei priority fee, while its max fee is 18 gwei. The effective price is min(18, 12 + 2) = 14 gwei, so the simple transaction-level estimate is 180,000 × 14 = 2,520,000 gwei, or 0.00252 ETH. If the policy reserves at most 200,000 gas at the 18 gwei fee cap, the hard ceiling is 0.0036 ETH. The account should reject a proposal that exceeds that ceiling even if the model predicts a favorable swap.
For an ERC-4337 operation, the estimate must include validation, call execution, pre-verification overhead, and any paymaster validation or post-operation work. Compare the operation's final actualGasCost with the reservation and reconcile it against the emitted UserOperationEvent. A bundler response that says “accepted” means the operation entered a transport path; it does not prove that it executed, that the call succeeded, or that the containing block is final.
Quantitative model
For a transaction-like operation, define the effective price and cost as:
Here, prices are in wei per gas, gas values are unitless execution units, and costs are in wei. G_billed must account for all applicable UserOperation gas components; G_limit is the policy's reserved upper bound. The reserve is a ceiling rather than a forecast. EIP-1559 fee fields and EntryPoint accounting should be evaluated together before enabling sponsorship.
Implementation pattern
This TypeScript pre-sign check rejects proposals outside a session policy. The same constraints must be enforced by the smart account during UserOperation validation; a client-side check alone can be bypassed by a compromised agent process.
typescripttype Proposal = {chainId: bigint;entryPoint: string;nonce: bigint;target: string;data: `0x${string}`;valueWei: bigint;gasBounds: {call: bigint;verification: bigint;preVerification: bigint;paymasterValidation: bigint;paymasterPostOp: bigint;};maxFeePerGasWei: bigint;expiresAt: number;};const sessionPolicy = {chainId: 1n,entryPoint: "0x0000000071727De22E5E9d8BAf0edAc6f37da032",nonce: 42n,target: "0x1111111111111111111111111111111111111111",selector: "0x38ed1739",maxValueWei: 0n,maxReservedFeeWei: 3_600_000_000_000_000n,};function authorizeProposal(p: Proposal, nowSeconds: number): void {if (p.chainId !== sessionPolicy.chainId) throw new Error("wrong chain");if (p.entryPoint.toLowerCase() !== sessionPolicy.entryPoint.toLowerCase()) {throw new Error("unrecognized EntryPoint");}if (p.nonce !== sessionPolicy.nonce) throw new Error("stale account nonce");if (p.target.toLowerCase() !== sessionPolicy.target.toLowerCase()) {throw new Error("target is outside session scope");}if (p.data.slice(0, 10) !== sessionPolicy.selector) throw new Error("selector denied");if (p.valueWei > sessionPolicy.maxValueWei) throw new Error("value exceeds limit");const totalGasLimit = Object.values(p.gasBounds).reduce((sum, limit) => sum + limit, 0n);if (totalGasLimit * p.maxFeePerGasWei > sessionPolicy.maxReservedFeeWei) {throw new Error("fee reservation exceeds sponsor budget");}if (p.expiresAt <= nowSeconds) throw new Error("proposal expired");}
Trade-offs
An account policy can limit losses without blocking every useful action, but each added capability expands the code and upgrade surface. A per-call allowlist is easier to audit than a general “execute arbitrary calldata” module; it is also less flexible when an application changes its router or token contracts. Bundling operations can amortize fixed transaction overhead, though a failure in one call may affect later calls depending on the account's execution mode. Sponsorship improves onboarding while giving the paymaster a denial-of-service and cost-control problem. Track accepted, rejected, expired, reverted, and finalized operations separately, along with gas per successful user outcome.
Failure modes and misconceptions
- Prompt injection becomes spending authority: the model can be manipulated into proposing a malicious recipient or approval. Enforce target, selector, amount, and allowance caps in account validation rather than relying on prompt instructions.
- A client retries an unknown operation: a timed-out bundler request may still be pending. Query by the operation hash and nonce before constructing another signed operation; otherwise the retry may collide or execute twice under a poorly scoped nonce policy.
- EIP-7702 delegate is over-privileged: a delegated implementation may reach arbitrary account assets. Audit the delegate and storage layout, require a signed initialization payload, and keep the wallet's recovery path independent of the agent.
- Simulation becomes stale: an AMM reserve or account balance can change between simulation and inclusion. Encode a deadline and minimum output in the signed call, then report a revert as a failed operation instead of asking the agent to silently retry at a worse price.
- Paymaster budget is drained: a public sponsorship rule can subsidize spam or expensive validation. Rate-limit by account and operation class, cap validation gas, and monitor the paymaster deposit and stake.
- Inclusion is mistaken for finality: a receipt can be reorganized. Keep pending and finalized states distinct and only trigger irreversible off-chain actions after the application's chosen confirmation rule.
Decision scenario
A wallet's agent proposes approve(maxUint256) for a new router. The bundler simulation succeeds and the paymaster estimate is within budget, but the router is not in the session's allowlist and the approval has no expiry. Reject the operation, require a reviewed router registration and a bounded allowance, then simulate and sign the narrower call. If a swap quote changes before inclusion, let its explicit slippage bound fail; do not have the language model broaden approval or increase the fee cap to make the transaction “work.”