Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 8 min read

When an AI agent pays twice

In short With x402, an agent pays for an API call by signing a USDC payment. If the response is lost after the seller took the payment, the standard client signs a second, different payment on retry. On Base Sepolia,

In short

  • With x402, an agent pays for an API call by signing a USDC payment. If the response is lost after the seller took the payment, the standard client signs a second, different payment on retry.
  • On Base Sepolia, in 100 purchases where 30% of responses were lost, the standard client made 113 payments for 94 purchases. x402-once made 96 for 96.
  • The fix: save the signed payment before sending it, send the same one on a retry, and sign a new one only when the chain proves the old one can no longer be used.
  • The cost: if the seller will not serve a payment twice, you pay once and get no data. The package tells you, with the transaction, instead of paying again.

Written for: Developers building AI agents, or APIs, that pay or get paid per request.

An AI agent calls a paid API. The API answers with a price. The agent pays and gets the data. That is the whole idea of x402, a protocol that revives the old HTTP status code 402, β€œPayment Required”, so a program can pay for a request with stablecoins and no account.

Now picture the same thing on a bad network. The agent pays, the seller takes the money, and the response never arrives. The agent's HTTP library times out and the agent retries.

What does the agent pay the second time?

What actually happens

This is what the standard client does. I checked it in the official @x402/fetch package, and it matches several open reports (#3438, #4198, #4367).

One purchase, two settlements

1. client asks for /report              -> 402, price 0.01 USDC
2. client signs payment A (nonce a)     -> sends it
3. seller settles A on chain            -> response is lost
4. the app retries /report              -> 402 again
5. client signs payment B (nonce b)     -> seller settles B too

The payment is a signed message, an EIP-3009 authorization. It carries a random one-time number, a nonce. The standard client makes a new nonce every time it sees a 402. So the retry is a different payment, not the same payment sent again, and the chain has no reason to refuse it.

This is the same bug I wrote about in the first post of this series, with a twist. A card payment can be refunded. An on-chain transfer cannot be undone, and an agent can make thousands of calls without anyone watching.

The fix: the same signed payment, saved first

An idempotency key works because the same key means the same request. The x402 version of that is simple. The signed payment is the key. If the retry sends payment A again instead of signing B, the chain can only ever settle it once, because a nonce can be used only once. The package follows four rules.

1. Save before you send

The signed payment is written to a store before the request goes out. If the process dies one millisecond later, the payment is on record. A retry, even after a restart, finds it.

2. Send the same payment again

A retry before the deadline sends the saved payment unchanged. If the first attempt had settled, the chain refuses the repeat, and the seller either serves the answer again or refuses. Either way, no second charge.

3. Sign a new payment only when the old one is provably dead

Every payment has a deadline, validBefore. After it, the old payment can never settle. But β€œI think it expired” is not good enough. The package asks the token contract directly, with authorizationState, whether the payment was used. It reads the answer and the chain's own clock from the same block, and it waits a margin past the deadline. If the chain says β€œnever used”, a new payment is safe. If the chain says β€œused”, the money moved, and the package throws an error that tells you so. If it cannot tell, it signs nothing.

4. Fail closed

Every doubt ends in an error, not a second payment. A damaged record, a wrong-chain RPC, an answer that is not exactly what it should be, a clock that returns nonsense: all of them stop the call and sign nothing.

Using it

import { createPaidFetch, evmAuthorizationResolver } from 'x402-once';

const paidFetch = createPaidFetch({
  client, // your x402Client; it signs, this package never sees a key
  resolver: evmAuthorizationResolver({
    rpcUrls: { 'eip155:8453': ['https://rpc-one.example', 'https://rpc-two.example'] },
    minProviders: 2,
  }),
  limits: { networks: ['eip155:8453'], maxAmount: '1000000' }, // at most 1 USDC
});

const response = await paidFetch('https://api.example.com/report'); // used like fetch

What I measured

I did not want to claim this from unit tests alone, so I ran the real thing. Two environments: a local chain (anvil) with the official x402 seller and facilitator code and a USDC stand-in, and Base Sepolia, the public test network, with real test USDC and the public x402.org facilitator.

The seller sometimes drops the connection right after a payment settled, which is the case that matters. A proxy in front of the seller causes the failure, not a real outage. The buyer retries up to twice on a dropped connection or a server error, the way most agent code does. I ran the same wallet and the same fault schedule once with the standard client and once with x402-once, and counted the transfers on the chain. The chain is the judge, not either side's log.

Base Sepolia, 100 purchases per row, 30% of paid requests lose their response:

Seller Client Delivered Transfers on chain Items charged twice Wasted payments
plain standard 92/100 113 17 19
plain x402-once 77/100 96 0 0
replays a settled payment standard 89/100 109 14 16
replays a settled payment x402-once 95/100 95 0 0

Two smaller Base Sepolia runs of 20 purchases gave the same picture: the standard client wasted between 5 and 8 payments per row, and x402-once wasted none. On the local chain, 40 purchases cost the standard client 51 transfers and x402-once 40.

The honest part: a plain seller

Look at the second row. With a plain seller, x402-once delivered 77 of 100 and the standard client 92. The standard client got more data, and it got it by paying for the same item twice.

A β€œplain” seller is how the official seller middleware behaves today: it does not remember payments. When the lost response is followed by a retry with the same payment, the chain says β€œalready used”, and the seller has nothing to give. x402-once cannot get the data back without paying again, and it will not. What it does is tell you. Every item that was paid for and not delivered came back as a SettledWithoutDeliveryError, so you know what you paid for and can ask the seller for it. In a further 40-purchase run, all 8 purchases that came back this way named the transaction.

Another finding: the facilitator

Even with no faults at all, the public facilitator failed to settle 6 to 8 of every 100 payments, for both clients. In the run that recorded reasons, the errors were invalid_exact_evm_transaction_failed, mostly the facilitator's own transaction nonce being behind. This is not related to retries, but an agent should expect it. A failed settlement is a different problem from a lost response, and the package handles it the same way: nothing settled, so nothing is lost.

What the tests found, and what the reviewers found

Property tests, with random failures, clock jumps and retries, found a real bug in my first design. A payment that settled on chain but was never delivered was marked β€œsettled”, and under a derived key that means β€œthe next call is a new purchase”. The retry bought it again. That is why there is now a separate status for it, and why it is the most important state in the code.

I also had separate AI agents review the package, each starting fresh with no hints from me: a money-safety reviewer, a security reviewer, one trying to break it, one checking release readiness, a protocol auditor and a supply-chain auditor. These were AI reviewers, not human auditors, and I would still want a human security review of a package that moves money. They found things I had not:

  • The signed payment followed a redirect to another origin.
  • An edited or damaged record file could make the library sign again.
  • A slow process could overwrite another process's newer payment.
  • Errors printed the signed payment, so a logger would have captured it.
  • An RPC on the wrong chain was believed.
  • A buggy or hostile signer could get a different payee or amount saved and sent.

Each is fixed and has a test. To check that the tests actually bite, I broke the source in 70 small, deliberate ways, one at a time, and made sure a test failed every time. The first run missed one, which showed me a weak test, and I fixed that too.

What it does not do

  • It does not make a seller or a facilitator honest. If either settles one payment twice, the client cannot see it. That is a different open issue.
  • It is for one machine per store. The file store survives restarts and works for several processes on one machine. Several machines need a shared database store.
  • EVM only. EIP-3009 and Permit2 payments are inspected. Solana and other types are refused before anything is sent, unless you opt in. They have no protection.
  • The signed payment is a bearer instrument. Anyone who sees it before it expires can submit it themselves. They cannot change the payee or the amount, but the seller's facilitator would then find it used. So the package refuses plain http and redirects to other origins, and sellers should not log or cache the header.
  • The samples are small. One network, one public facilitator, failures injected by me, 100 purchases per row at most. The wasted-payment counts are solid. The delivery percentages are not.
  • You need a resolver you trust. β€œNever settled” is the one answer that can lead to a second payment, so it needs every one of your RPC providers to agree. Use two or more.

Try it

The package and the benchmark are on GitHub, and it installs with npm install x402-once. No wallet is needed to see the bug: the testing kit has a simulated seller that loses the response and counts the settlements.

Run it in a minute

import { createPaidFetch } from 'x402-once';
import { createSimulatedMerchant, createFakeClient, scriptedFaults } from 'x402-once/testing';

const seller = createSimulatedMerchant({ faults: scriptedFaults('drop-after-settle'), serveOnReplay: true });
const paidFetch = createPaidFetch({ client: createFakeClient('eip155:84532'), fetch: seller.fetch });

await paidFetch('https://seller.test/report').catch(() => 'response lost');
const retry = await paidFetch('https://seller.test/report');
console.log(retry.status, seller.settlementCount); // 200 1

Swap the paid fetch for the standard one and the last number is 2. x402-once is MIT licensed and has no runtime dependencies. If you build agents that pay for things, I would like to hear what failure you hit that this does not cover. If you run a seller, add the replay: your buyers will not pay twice for what you already delivered.

Originally published at https://mokshupadhyay.com/writing/when-an-ai-agent-pays-twice. This is part 3 of "Payments that stay correct". I write about keeping money correct when networks do something unexpected, and I maintain open-source payment libraries on GitHub.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.