Introduction

Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.

I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.

I also build and publish a variety of tools, libraries, and open-source projects.

AI agents and micropayments

Consider an AI agent tasked with research. It searches for sources through one service and retrieves documents from another. If a search costs 0.01 USDC and retrieving a document costs 0.02 USDC, research costs can reflect actual usage rather than a monthly subscription to each service. USDC is a stablecoin designed to track the value of the US dollar; here it serves as the unit of pricing and payment. These prices are illustrative, not the actual rates of any particular service.

With micropayments, processing overhead can outweigh the price itself. Recording every transfer on a blockchain incurs gas (transaction execution fees) each time. If the agent holds funds on a different chain from the one on which a service wants to receive payment, moving funds adds further overhead.

Allowing software to read a price, authorize payment and receive a result is a different problem from making repeated payments inexpensive. x402 embeds pricing and payment information in HTTP requests and responses. Circle Gateway treats USDC deposited across multiple chains in advance as an available balance and provides infrastructure for recording small payments against that balance in batches.

The original figures retain their Japanese labels.

AI agents and micropayments

Embedding payments in HTTP with x402

x402 exchanges payment terms between software requesting paid information and the server providing it. The buyer receives the price and authorizes payment; the seller checks the authorization and delivers the service. Rather than redirecting to a dedicated checkout page before calling an API, the parties exchange this information within HTTP requests and responses.

How x402 embeds payments in HTTP

Quoting a price and authorizing payment

When a buyer initially requests a resource, the seller returns HTTP 402 Payment Required. In x402 V2, the seller puts its accepted payment terms in the PAYMENT-REQUIRED header. The buyer selects a supported option, checks the amount and recipient, and constructs a payment authorization.

The buyer includes this information in PAYMENT-SIGNATURE and requests the same resource again. If the seller accepts payment, it returns the resource and PAYMENT-RESPONSE. Header values contain Base64-encoded JSON, but Base64 encoding is neither encryption nor proof of payment. The seller checks the terms and signature according to the chosen payment method.

The accepts field is an array of acceptable payment options. Each option specifies how and what the buyer will pay.

Field Meaning
scheme Payment scheme
network Network to use
asset Asset used for payment
amount Amount in the asset's smallest unit
payTo Seller's receiving address

For example, exact is a scheme for paying a specified amount. Selecting this option determines both the price and the payment method to authorize.

The legacy X-PAYMENT header and the V2 headers must be used with their corresponding protocol versions.

The buyer controlling the funds creates the authorization. They specify whose balance may be debited, how much may be paid to whom, and when the authorization is valid, then sign with their key. The recipient receives the authorization and signature; the private key remains with the buyer.

Gateway checks the selected terms against the signature and accepts only the specified payment amount. Creating a signature does not itself execute an onchain transfer, so the buyer can provide authorization without spending gas.

The authorization includes a nonce, a unique value identifying the payment that prevents a used authorization from being accepted as a separate payment. The network and verifying contract are bound to the signature, helping prevent reuse in a different payment context. Gateway uses a dedicated signing domain to identify payments from deposited balances. A signature made for ordinary USDC transfers cannot be repurposed simply by changing the header.

Here is an example of the decoded terms returned by a search API.

json
{
  "x402Version": 2,
  "resource": {
    "url": "<検索APIのURL>",
    "description": "検索結果の取得",
    "mimeType": "application/json"
  },
  "accepts": [{
    "scheme": "exact",
    "network": "eip155:5042002",
    "asset": "0x3600000000000000000000000000000000000000",
    "amount": "10000",
    "payTo": "<API提供者の受取先アドレス>",
    "maxTimeoutSeconds": 604900,
    "extra": {
      "name": "GatewayWalletBatched",
      "version": "1",
      "verifyingContract": "0x0077777d7EBA4688BDeF3E311b846F25870A19B9"
    }
  }]
}

The network is Arc Testnet and the asset is USDC on that network. An amount of 10000 represents 0.01 USDC, and payTo identifies the seller's receiving address. The name and verifying contract in extra specify the dedicated signing domain for payments from Gateway balances. The maxTimeoutSeconds value of 604900 is an example configured by the official server SDK, not a universal minimum validity period for every environment.

When the buyer selects this option, the authorization's to corresponds to the selected payTo, and its value to the selected amount. The buyer packages the authorization and signature while retaining the selected option and resource.

typescript
const selected = paymentRequired.accepts[0];
const paymentPayload = {
  x402Version: 2,
  resource: paymentRequired.resource,
  accepted: selected,
  payload: {
    authorization: {
      from: '<買い手のアドレス>',
      to: selected.payTo,
      value: selected.amount,
      validAfter: '<有効開始のUnix時刻>',
      validBefore: '<有効期限のUnix時刻>',
      nonce: '<この支払いを識別する32バイト値>',
    },
    signature: '<買い手がこの内容へ作った署名値>',
  },
};

The seller compares the fields in the returned accepted object against the options it originally offered. It passes the matching terms to Gateway so the authorization can be checked against the acceptance criteria. Payment proceeds when both the buyer's signed authorization and the seller's accepted terms match. HTTP carries the terms and payment information in their respective headers.

http
HTTP/1.1 402 Payment Required
PAYMENT-REQUIRED: <条件JSONをBase64化した値>

GET <要求したリソースのパス> HTTP/1.1
PAYMENT-SIGNATURE: <支払いJSONをBase64化した値>

HTTP/1.1 200 OK
PAYMENT-RESPONSE: <決済受付結果をBase64化した値>

The final successful response corresponds to retrieval of the resource and acceptance of payment by Gateway. When the seller can use its balance onchain depends on the batch confirmation process described below.

Price quotation and payment authorization

Facilitators and settlement methods

A seller can verify and execute payments itself or delegate these operations to a service known as a facilitator. The seller supplies the buyer's authorization and the payment terms set by the server, requesting verification and execution according to the selected settlement method.

With conventional onchain settlement, a transaction transferring USDC is submitted using the authorization. With Gateway, payment is accepted against a balance within Gateway, and multiple payments are recorded together later. The distinguishing feature of x402 is that the HTTP pricing exchange remains the same while the underlying payment method can vary. Adopting x402 alone does not make every payment free or cross-chain.

Facilitators and settlement methods

Circle Gateway for funds across multiple chains

Holding USDC on several chains can require redistributing funds to match where they will be spent. If a search service wants to receive funds on chain A and a document service on chain B, for example, a conventional arrangement involves preparing balances on both chains before use. Circle Gateway provides a combined view of funds deposited into contracts on supported chains and lets users choose where to use them.

Circle Gateway and balances across chains

Advance deposits and unified balances

First, the user deposits USDC through a deposit method on Gateway Wallet. Gateway tracks the deposit on its source chain and reflects the funds in the available balance after the required confirmations. Simply holding USDC in one's own wallet does not count toward this balance.

Suppose a user deposits 3 USDC on chain A and 2 USDC on chain B, and both deposits have been confirmed. Ignoring fees for this example, the user can choose where to spend funds from a combined balance of 5 USDC. The USDC itself remains in the respective holding contracts, and Gateway's ledger tracks balances by chain, asset, and depositor address. It does not mean that the same 5 USDC can be spent twice, once on each chain.

Preparing a unified balance in advance avoids waiting for source-chain deposit confirmations every time funds are transferred. Funds awaiting confirmation are tracked separately from available funds. Sending tokens directly to the Gateway Wallet contract using a regular ERC20 transfer does not credit the Gateway balance. Use the designated deposit method to register the funds.

Advance deposits and unified balances

Receiving funds on another chain

To receive deposited funds on another chain, the amount deducted on the source side must correspond to the amount credited on the destination side. The user signs a burn intent specifying the amount and destination, and the Gateway API checks the authorization and available balance. When the conditions are met, the API returns signed proof authorizing issuance on the destination chain, known as an attestation.

The destination Gateway Minter verifies the attestation and mints USDC to the specified recipient. Gateway submits the burn corresponding to the used attestation on the source chain, reducing the original USDC. Linking issuance to consumption of the source balance prevents the same funds from being used twice.

This mechanism reduces waiting at the point of use because source-chain deposits have already been confirmed. The time it takes the API to return an attestation is distinct from the time it takes the destination transaction to be recorded. API response speed alone does not measure the full deposit-to-withdrawal process.

Receiving funds on another chain

Micropayments through batching

With Gateway Nanopayments, buyers pay from balances deposited in advance. Instead of creating a USDC transfer transaction each time, they send Gateway a signed payment authorization. Gateway batches multiple authorizations and reflects the resulting balance changes in contracts, reducing the overhead of repeated small payments.

Batch settlement for micropayments

Individual transfers versus batched records

Consider paying 0.01 USDC for a search and 0.02 USDC to retrieve a document. With individual onchain transfers, both transfers are executed separately. Gas per transaction is not necessarily proportional to the payment amount, so execution costs can represent a larger fraction of smaller payments.

Batching collects authorized payments and calculates net balance changes for each participant. In this example, the buyer's balance decreases by 0.03 USDC, the search seller's balance increases by 0.01 USDC, and the document seller's balance increases by 0.02 USDC. These changes are recorded with other payments, sharing execution costs. Which payments are grouped together is determined during processing, so the two payments in this example will not necessarily appear in the same batch.

Signing costs the buyer no gas, but subsequent onchain processing still takes place. Deposits, withdrawals, and cross-chain transfers each have their own fee conditions. Any claim about transactions per second also requires measurement in the relevant environment.

Individual records versus batched settlement

Payment acceptance and when balances become spendable

On receiving the buyer's authorization, Gateway verifies the signature and balance and reserves the payment amount. The seller can confirm successful acceptance and return the API result. However, the credit reflected for the seller is a pending balance before batch confirmation.

Once Gateway submits the batch and onchain confirmation is complete, the funds are reflected in the seller's available balance. There can be an interval during which the buyer's available balance has fallen from 5 USDC to 4.97 USDC while the seller's withdrawable balance has not yet increased. By accepting this delay, the seller avoids waiting for batch completion before responding to every API call.

The vision of immediate availability described in the 2025 integration proposal should be distinguished from the mechanism actually provided. Separating API acceptance, the seller's pending balance, and the confirmed available balance makes it possible to determine where waiting is required.

Payment acceptance and balance availability

Calling APIs with x402 and Gateway

A research task using both a search API and a document API illustrates how price negotiation connects to balance management. Assume the buyer's agent has deposited 5 USDC into Gateway and both APIs support Gateway payments. For illustration, a search costs 0.01 USDC and retrieving a document costs 0.02 USDC.

When the agent requests the search API, the server returns 402 with the payment terms. Before signing, the agent's application evaluates the conditions.

Condition to check Application decision
API endpoint Is the URL permitted?
Network Does it match the intended payment network?
Recipient Is this an approved seller?
Individual amount Does it exceed the configured per-payment limit?
Total research spending Is it within the overall budget, including concurrent payments?

If the terms are permitted, the application authorizes the 0.01 USDC payment and retries the request with the signature. The search API passes the authorization and its own pricing terms to Gateway, confirms successful acceptance, and returns the search results.

The agent selects the required document from the search results and pays the document API 0.02 USDC using the same procedure. Total spending is 0.03 USDC, leaving an available balance of 4.97 USDC. Because the agent pays from a deposited Gateway balance, there is no separate transfer from the source chain on every API call.

The sellers reconcile their balance credits and can use the funds after batch confirmation. If they want to receive funds on another chain, they use Gateway's cross-chain transfer mechanism. The HTTP network, the balance authorizing payment, and the final withdrawal chain serve distinct purposes. Separating negotiation during API use from fund operations at withdrawal accommodates services with different receiving destinations.

API usage with x402 and Gateway

Implementation with a test API

The seller connects price negotiation to the paid operation, while the buyer prepares a Gateway balance and a signing mechanism. Circle's @circle-fin/x402-batching SDK brings these pieces together. The original article reports type checking against version 4.0.0.

The following is a minimal Arc Testnet setup. The original example's checks covered types, syntax, and HTTP responses not involving signatures, rather than transferring assets or signing payments. The code examples retain their original comments and illustrative strings.

Implementation with a test API

Seller pricing and payment acceptance

Insert Gateway middleware before the paid operation in an Express API. Pass the recipient and connection endpoint to the middleware. Setting a price on the paid route with gateway.require causes unpaid requests to receive a 402 response containing payment terms. For signed requests, the middleware requests acceptance from Gateway and proceeds to the API operation only if it succeeds.

typescript
import express from 'express';
import { isAddress } from 'viem';
import { createGatewayMiddleware } from '@circle-fin/x402-batching/server';

const sellerAddress = process.env.SELLER_ADDRESS;
if (!sellerAddress || !isAddress(sellerAddress)) {
  throw new Error('SELLER_ADDRESSに有効な受取先を指定してください');
}

const app = express();
const gateway = createGatewayMiddleware({
  sellerAddress,
  facilitatorUrl: 'https://gateway-api-testnet.circle.com',
});
app.get('/search', gateway.require('$0.01'), (_req, res) => {
  res.json({ result: '検索結果' });
});
app.listen(3000);

The recipient is the address at which the API provider receives funds. A price of 0.01 corresponds to 10000 in USDC's smallest unit. facilitatorUrl identifies the testnet Gateway API, and /v1/x402/settle handles payment acceptance. The server requests acceptance using the recipient and amount it defined.

Before starting the server, configure SELLER_ADDRESS with a test recipient.

Seller pricing and payment acceptance

Buyer balance checks and payment

The buyer configures GatewayClient with the target chain and signing key. Before paying, the buyer obtains balances using getBalances() and checks gateway.available. If the balance is insufficient, a deposit is needed first, but submitting a deposit does not mean the balance has been confirmed. Once ready, the buyer checks whether the target API supports Gateway and calls pay.

typescript
import { GatewayClient } from '@circle-fin/x402-batching/client';

const privateKey = process.env.PRIVATE_KEY;
const apiUrl = process.env.PAID_API_URL;
if (!privateKey || !/^0x[0-9a-fA-F]{64}$/.test(privateKey)) {
  throw new Error('PRIVATE_KEYの形式を確認してください');
}
if (!apiUrl) throw new Error('PAID_API_URLを指定してください');

const target = new URL(apiUrl);
if (!['http:', 'https:'].includes(target.protocol)) {
  throw new Error('HTTPまたはHTTPSのURLを指定してください');
}
const client = new GatewayClient({
  chain: 'arcTestnet',
  privateKey: privateKey as `0x${string}`,
});
const balances = await client.getBalances();
if (balances.gateway.available < 10000n) {
  throw new Error('0.01 USDCを支払う利用可能残高がありません');
}
const support = await client.supports(target.href);
if (!support.supported) throw new Error('Gateway非対応');
const { data, status } = await client.pay(target.href);
if (status < 200 || status >= 300) {
  throw new Error(`APIの応答を確認してください: ${status}`);
}
console.log(data);

pay combines receiving the price, signing the authorization, and resending the signed request. The caller checks the returned status and data. The code above checks whether the balance covers the illustrative 0.01 USDC search price. The acceptance checks and budget management described in the integration example must be implemented separately. The actual price quoted by the API must also be checked against the balance at payment time.

supports checks whether the target API supports Gateway payments. Price limits and recipient restrictions must be set separately; the minimal example above does not include them.

For production use, checks before signing should compare the quoted payment options with the permitted conditions in the integration example. The signing implementation supplied to BatchEvmScheme through signTypedData should sign only terms that pass these checks. These restrictions are part of application design; passing a request to GatewayClient's pay does not automatically enforce a budget.

Buyer balance checks and payment

Reconciling payments and results

If the connection drops after payment acceptance, the API result alone may fail to reach the buyer. The seller should retain a record that links the original payment with the requested resource.

Field to retain What it identifies
Requested resource The resource whose paid result should be returned
nonce Identifier for looking up the original payment
Payer Buyer who authorized payment
Amount Accepted price
network Network on which payment was accepted

Look up the payment ID using the nonce and check its status. If confirmation is pending, wait rather than creating another payment.

There is also a distinction between checking confirmed for accounting purposes and completed before subsequent onchain operations. The API must separately implement retrieval of results for payments that have already succeeded.

When a failure reason is available, distinguish rejection before acceptance from a possible earlier acceptance. A clear rejection for insufficient funds calls for replenishing the available balance; an expiry rejection calls for correcting the terms. By contrast, nonce_already_used indicates that the nonce was previously submitted. Look up the original payment before deciding whether to wait or retrieve its result. Immediately creating a new payment for the same resource with a fresh nonce risks paying twice.

If the looked-up payment has reached the terminal failed state, treat it as uncharged and do not deliver the paid resource for that payment. If confirmation is pending, continue querying; if completed, retrieve the already-paid result. If the lookup itself fails or the record cannot yet be found, treat the outcome as unknown and hold off on paying again rather than assuming no charge occurred. This is an application-level recovery policy for safely connecting API use and payment.

Reconciling payments and API results

Adoption considerations

This architecture is well suited to applications using many APIs in small increments. However, service availability, successful payment acceptance, and the ability to spend received funds onchain are separate conditions. Select a settlement method based on the required response time and when the funds must become available.

Adoption considerations

Fund control and operational dependencies

USDC deposited in Gateway is held in contracts, and fund movements rely on user authorizations. This is why the mechanism is described as non-custodial. In the normal low-latency path, however, Circle's API tracks balances and issues attestations for fund movements. Who authorizes the movement of funds and which services the system depends on operationally are separate considerations.

Standard Gateway provides a fallback path for when the API is unavailable: users can initiate recovery through a contract and withdraw after a delay. Nanopayments batch verification uses a TEE (trusted execution environment) to validate authorizations and sign aggregated results. Because the contract checks that signature, the protections around the execution environment and signing key are also important prerequisites to understand before adopting the system.

Fund control and operational dependencies

Why verification alone is not enough to deliver a service

Confirming that a signature is valid and a balance exists does not necessarily reserve funds for that payment. If another payment takes precedence after verification, the balance initially observed may no longer be available. A seller using Gateway should proceed with delivery based on successful settle, which secures the funds. Delivering a service on signature verification alone can result in payment failing later.

Wallet and fee requirements

General Gateway support and Nanopayments support are not identical. According to the official documentation cited by the original article, Nanopayments requires an EOA (externally owned account) that signs directly with a key and does not accept ERC1271, where signature validation is delegated to a contract. Check whether the wallet supports the selected payment method. Official documents differ regarding the minimum signature validity period, so check the value required by the SDK and endpoint being used.

Even if individual payments incur no gas cost for the payer, deposits, withdrawals, and cross-chain movements have separate costs. If the seller withdraws tiny amounts to another chain each time it receives a payment, those downstream costs also matter. Comparing the conditions under which the seller can use accumulated balances with those under which each payment must be recorded independently onchain clarifies which method to choose.

The application operating the agent should check the permitted conditions in the integration example before releasing a signature. It should enforce an overall task budget including concurrent payments and stop authorizing new ones when the limit is reached. The ability of software to read a price is separate from deciding whether the service is worth that price.

Wallet and fee requirements

Conclusion

x402 standardizes price quotation and payment exchange during API use, while Gateway supports spending deposited funds and aggregating payments. Combining the two makes it possible to purchase low-cost services on demand. When adopting the approach, distinguish the point at which the API returns a response from the point at which the seller can spend funds, and evaluate wallet, fee, and operational requirements.

The official x402 documentation describes the communication protocol for exchanging payment terms.

The official Gateway documentation describes unified balances and cross-chain fund movements.

The official Nanopayments documentation describes batch settlement and its integration SDK.