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.
The original Mermaid diagrams are retained; some labels remain in Japanese.
This article introduces x402.
What is x402?
x402 is an open payment protocol that uses the HTTP 402 Payment Required status code.
The protocol provides a mechanism for charging for access to APIs and content directly through HTTP. A key feature is that payments can be made programmatically without requiring conventional account or session management.
Official website:
Official documentation:
Key features
x402 has the following features.
- A standard protocol based on the HTTP 402 status code It can be integrated into existing HTTP workflows.
- Programmatic payments without user accounts Direct wallet-based payments are possible.
- Multi-network and multi-token support The protocol can accommodate different blockchain networks and tokens.
- Well suited to AI agents Its design supports machine-to-machine payments.
Main components
The following sections describe the main participants in the x402 protocol and their roles.
Client
The Client is the entity requesting access to a paid resource. It is also referred to as the buyer.
The Client's main responsibilities are as follows.
- Send requests Send HTTP requests to the resource server.
- Process payment requirements
Extract payment details from the
402 Payment Requiredresponse. - Create a payload Construct a valid payment payload based on the supplied requirements.
- Retry the request
Retry the request with the signed payload in the
PAYMENT-SIGNATUREheader.
The Client does not require CSV storage or conventional authentication token management for the payment protocol itself. Interactions take place through stateless HTTP requests. This allows buyers, including AI agents, to perform transactions without creating an account or managing conventional login credentials.
Server
The Server is a resource provider that requires payment for access to a service. It is also referred to as the seller.
The Server's main responsibilities are as follows.
- Define payment requirements
Provide the required payment details in a
402 Payment Requiredresponse. - Verify the payload Verify the payment payload locally or through a Facilitator service.
- Settle the transaction Execute settlement once the payment has been verified.
- Deliver the resource
Following successful payment, return the requested resource and a
PAYMENT-RESPONSEheader.
The Server does not need to maintain a conventional client account or session for the payment itself. Verification and settlement are handled for each request.
Facilitator
The Facilitator is an optional but recommended service that simplifies payment verification and settlement between the Client (buyer) and Server (seller).
The Facilitator's main responsibilities are as follows.
- Verify payments Check whether the payment payload submitted by the Client satisfies the Server's requirements.
- Process settlement Submit verified payments to the blockchain and monitor confirmation.
- Return results Return verification and settlement results to the Server to help it decide how to respond to the Client's request.
Benefits of using a Facilitator include the following.
- Reduced operational overhead The Server does not need to interact directly with blockchain nodes.
- Protocol consistency A standardized verification and settlement flow can be used across services.
- Fast integration Services can accept payments without specialized blockchain development expertise.
A Facilitator is not a custodian of the Client's funds. It verifies and executes on-chain transactions based on signed payment payloads supplied by the Client.
Wallet
A Wallet plays an important role for both buyers and sellers.
Its functions for buyers are as follows.
- Hold crypto assets
- Sign payment payloads
- Programmatically authorize on-chain payments
Its functions for sellers are as follows.
- Receive payments in crypto assets
- Specify payment recipient addresses in server configuration
Wallet addresses serve as identifiers for sending, receiving, and verifying payments. They also act as unique identifiers within the protocol, although a wallet address alone does not establish the real-world identity of an individual or organization.
Coinbase Wallet API is recommended in the referenced materials for programmatic payments and secure key management.
Bazaar
Bazaar is a service discovery feature that provides an API-searchable directory of services. It is also called the Discovery Layer.
It helps developers and AI agents discover and integrate x402-compatible API endpoints.
Bazaar provides the following functionality.
- For buyers Programmatically discover available x402-compatible services and understand their functionality, pricing, and schemas.
- For sellers Make x402-compatible services discoverable by a global audience of developers and AI agents.
- For AI agents Dynamically discover services that were not integrated in advance, then query, search, pay for, and use them.
Bazaar operates as follows.
The system exposes a simple /list endpoint that returns x402-compatible services registered with the CDP Facilitator.
Services opt in automatically when they use the CDP Facilitator and enable the Bazaar extension.
At the time of writing, Bazaar was in an early development stage, and its functionality and APIs could change in response to feedback and further development.
Problems addressed by x402
The following sections describe the problems x402 aims to solve.
High fees in traditional payment systems
Traditional payment systems such as credit cards and payment processors can charge fees of several percent or more, sometimes around 10%, depending on the service. When charging small amounts per API request, fees may exceed the transaction value.
x402 can substantially reduce payment costs by using cryptocurrencies. Payments can be settled for network fees alone when no additional facilitator or service fees apply.
Complexity of account and session management
Conventional payment systems often require creating user accounts, managing authentication credentials, and maintaining sessions. These mechanisms are not always well suited to machine-to-machine payments.
x402 supports direct wallet-based payments. This eliminates the need for conventional account creation and login in the payment flow.
Limited support for micropayments
Traditional payment systems often do not handle very small payments efficiently. Minimum fees can make transactions worth only a few to a few dozen yen economically impractical.
x402 can take advantage of cryptocurrency payment mechanisms to support micropayments. For example, a service could charge a few yen for each request.
Challenges integrating AI agents
Traditional payment systems are often designed around human interaction. They may not be well suited to autonomous payments initiated by AI agents.
x402 is designed with programmatic payments in mind. AI agents can automatically access APIs and complete authorized payments.
Architecture and operation
This section describes the architecture and operational flow of x402.
Main components
x402 comprises the following three main components.
Client (buyer)
The client seeking access to a resource. It has wallet functionality and initiates payments.
Server (seller)
The server providing an API or content. It returns a 402 response to request payment.
Facilitator (payment intermediary)
The service responsible for payment verification and settlement.
It provides two endpoints: /verify and /settle.
Payment flow
The x402 payment flow proceeds as follows.
sequenceDiagram
participant Client as Client (買い手)
participant Server as Server (売り手)
participant Facilitator as Facilitator (仲介者)
Client->>Server: リソースをリクエスト
Server->>Client: 402 Payment Required<br/>(支払い指示を含む)
Client->>Client: 支払いペイロードを準備
Client->>Server: 支払い情報と共にリクエスト
Server->>Facilitator: /verify (支払い検証)
Facilitator->>Server: 検証結果
Server->>Facilitator: /settle (決済確定)
Facilitator->>Server: 決済結果
Server->>Client: リソースを提供
Here is the detailed flow.
Step 1: Request the resource
The Client accesses a protected resource.
GET /api/protected-resource HTTP/1.1
Host: example.comStep 2: Return the 402 response
The Server returns the 402 Payment Required status code and payment instructions.
HTTP/1.1 402 Payment Required
Content-Type: application/json
{
"payment_required": true,
"amount": "0.001",
"currency": "ETH",
"recipient": "0x1234...",
"facilitator_url": "https://facilitator.example.com"
}Step 3: Initiate payment
The Client uses its wallet to prepare the payment authorization. It retries the request with the payment information.
GET /api/protected-resource HTTP/1.1
Host: example.com
X-Payment-Proof: {"tx_hash": "0xabcd...", "signature": "..."}Step 4: Verify payment
The Server calls the Facilitator's /verify endpoint to verify the payment.
POST /verify HTTP/1.1
Host: facilitator.example.com
Content-Type: application/json
{
"payment_proof": {"tx_hash": "0xabcd...", "signature": "..."},
"expected_amount": "0.001",
"expected_recipient": "0x1234..."
}Step 5: Settle payment
After successful verification, the Server calls /settle to settle the payment.
POST /settle HTTP/1.1
Host: facilitator.example.com
Content-Type: application/json
{
"payment_id": "payment_123",
"confirmation": true
}Step 6: Deliver the resource
After settlement, the Server delivers the resource.
HTTP/1.1 200 OK
Content-Type: application/json
{
"data": "Protected resource content"
}Role of the Facilitator
The Facilitator is an important component of the payment protocol.
Its main roles are as follows.
- Payment verification Check transaction validity, payment amount, and recipient.
- Settlement Validate and settle authorized payments while applying the scheme's replay-protection mechanisms.
- Abstract network differences Support different blockchain networks.
Blockchain payment implementation flow
This section illustrates a blockchain-based payment flow in the context of x402. The direct transaction-proof approach below is a conceptual example, distinct from the standard exact-scheme flow in which a client signs an authorization and the Facilitator submits settlement.
Overall flow (including the blockchain)
The following is the illustrative end-to-end payment flow including the blockchain layer.
sequenceDiagram
participant Client as Client (Buyer)
participant Wallet as Wallet
participant Blockchain as Blockchain Network
participant Server as Server (Seller)
participant Facilitator as Facilitator
Client->>Server: リソースをリクエスト
Server->>Client: 402 Payment Required<br/>(amount, recipient, network)
Note over Client,Wallet: 支払い準備
Client->>Wallet: トランザクション作成依頼
Wallet->>Wallet: トランザクション署名
Wallet->>Blockchain: トランザクション送信
Note over Blockchain: ブロックチェーン処理
Blockchain->>Blockchain: トランザクション検証
Blockchain->>Blockchain: ブロックに含める
Blockchain-->>Wallet: トランザクションハッシュ
Note over Client,Server: 支払い証明の提出
Wallet->>Client: tx_hash, signature
Client->>Server: リクエスト + Payment Proof
Note over Server,Facilitator: 検証プロセス
Server->>Facilitator: /verify (tx_hash, expected amount/recipient)
Facilitator->>Blockchain: トランザクション情報取得
Blockchain-->>Facilitator: トランザクション詳細
Facilitator->>Facilitator: 金額・受取人・ステータス検証
Facilitator-->>Server: 検証結果 (valid: true)
Note over Server,Facilitator: 決済確定
Server->>Facilitator: /settle (payment_id)
Facilitator->>Facilitator: 決済記録を保存
Facilitator-->>Server: 決済完了
Server->>Client: リソース提供
Creating and submitting a transaction
In this illustrative flow, after receiving a 402 response, the Client uses its wallet to create a blockchain transaction.
Step 1: Prepare transaction parameters
Prepare the transaction parameters using information from the 402 response.
const paymentInfo = {
amount: '0.001', // ETH
recipient: '0x1234567890abcdef...',
network: 'base', // Or 'ethereum', 'polygon', etc.
currency: 'ETH'
};Step 2: Create a transaction with a wallet
Use a wallet SDK to create and sign a transaction.
import { createWalletClient, http } from 'viem';
import { base } from 'viem/chains';
const walletClient = createWalletClient({
chain: base,
transport: http()
});
// Create the transaction
const hash = await walletClient.sendTransaction({
to: paymentInfo.recipient,
value: parseEther(paymentInfo.amount)
});
console.log('Transaction Hash:', hash);
// Example: 0xabcdef1234567890...Step 3: Processing on the blockchain network
In a conventional blockchain transaction flow, the transaction is recorded as follows.
-
Add to the mempool The submitted transaction may first enter the mempool (a pool of unconfirmed transactions), depending on the network's architecture.
-
Validation by the network Network validators or sequencers verify transaction validity, depending on the network. Checks include signature validity, the sender's balance, and the ability to pay gas fees.
-
Block inclusion A validated transaction is included in a new block. In this example, Base (Layer 2) produces new blocks approximately every two seconds.
-
Confirmation When a block is added to the chain, the transaction receives confirmation; this does not necessarily mean irreversible finality. Layer 2 networks can provide fast initial confirmations, while Ethereum mainnet can take minutes for multiple confirmations. Final settlement guarantees differ by network.
Facilitator verification process
In this transaction-proof example, the Facilitator retrieves transaction information directly from the blockchain and verifies it.
Step 1: Retrieve transaction information
The Facilitator retrieves transaction information from the blockchain through an RPC node.
import { createPublicClient, http } from 'viem';
import { base } from 'viem/chains';
const publicClient = createPublicClient({
chain: base,
transport: http()
});
// Retrieve transaction information
const transaction = await publicClient.getTransaction({
hash: paymentProof.tx_hash
});
console.log('Transaction Details:', {
from: transaction.from,
to: transaction.to,
value: transaction.value,
blockNumber: transaction.blockNumber
});Step 2: Check verification criteria
The Facilitator checks the following criteria.
function verifyPayment(transaction, expectedParams) {
// 1. Check the recipient address
if (transaction.to !== expectedParams.recipient) {
return { valid: false, reason: 'Recipient mismatch' };
}
// 2. Check the payment amount
const actualAmount = formatEther(transaction.value);
if (actualAmount < expectedParams.amount) {
return { valid: false, reason: 'Insufficient amount' };
}
// 3. Check transaction status
const receipt = await publicClient.getTransactionReceipt({
hash: transaction.hash
});
if (receipt.status !== 'success') {
return { valid: false, reason: 'Transaction failed' };
}
// 4. Check whether there are sufficient confirmations
const currentBlock = await publicClient.getBlockNumber();
const confirmations = currentBlock - receipt.blockNumber;
if (confirmations < REQUIRED_CONFIRMATIONS) {
return { valid: false, reason: 'Insufficient confirmations' };
}
// All checks passed
return { valid: true };
}Step 3: Prevent payment reuse
In this example, the Facilitator records transaction hashes to prevent the same hash from being accepted more than once.
// Save the settlement record in the database
async function settlePay(txHash: string, serverId: string) {
// Check whether the transaction hash has already been used
const existing = await db.settlements.findOne({ txHash });
if (existing) {
throw new Error('Transaction already settled');
}
// Create a new settlement record
await db.settlements.create({
txHash,
serverId,
settledAt: new Date(),
status: 'completed'
});
}Networks and confirmation times
Confirmation times and costs differ by blockchain network. The following figures are illustrative estimates from the original article, not guaranteed fees or finality times.
| Network | Block production time | Suggested confirmations | Confirmation time | Estimated gas fee |
|---|---|---|---|---|
| Ethereum | Approx. 12 seconds | 6–12 blocks | 1–2 minutes | High ($1–10) |
| Base | Approx. 2 seconds | 1–3 blocks | Several seconds to 10 seconds | Very low (less than $0.01) |
| Polygon | Approx. 2 seconds | 128 blocks | Approx. 4 minutes | Low ($0.01–0.1) |
| Arbitrum | Approx. 0.25 seconds | 1–5 blocks | Several seconds | Low ($0.01–0.1) |
Suggested networks
For micropayments, Layer 2 networks such as Base, Arbitrum, and Optimism are worth considering. Their potentially low gas costs and fast initial confirmations can make them suitable for small per-request charges.
Handling transaction failures
The following examples illustrate how transaction failures can be handled.
Case 1: Insufficient funds for gas
try {
const hash = await walletClient.sendTransaction({
to: paymentInfo.recipient,
value: parseEther(paymentInfo.amount)
});
} catch (error) {
if (error.message.includes('insufficient funds')) {
// Notify the user of the insufficient balance
console.error('Insufficient balance for gas fees');
}
}Case 2: Transaction revert
When a smart contract is involved, the transaction may revert if its conditions are not satisfied.
const receipt = await publicClient.getTransactionReceipt({
hash: txHash
});
if (receipt.status === 'reverted') {
// Retrieve the revert reason
const reason = await publicClient.getTransactionRevertReason({
hash: txHash
});
console.error('Transaction reverted:', reason);
}Case 3: Network delays
When the network is congested, transaction confirmation may take longer. In this case, the Client periodically polls the transaction status.
async function waitForConfirmation(txHash: string, maxWaitTime: number = 60000) {
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
const receipt = await publicClient.getTransactionReceipt({
hash: txHash
});
if (receipt && receipt.status === 'success') {
return receipt;
}
// Wait two seconds before retrying
await new Promise(resolve => setTimeout(resolve, 2000));
}
throw new Error('Transaction confirmation timeout');
}Integration with ERC standards
Combining x402 with existing ERC standards can enable more advanced payment experiences.
ERC-3009: Transfer with Authorization
ERC3009 defines a mechanism for token transfers authorized by EIP712 signatures.
Key features
- Atomic transfers Whereas ERC2612 (Permit) grants an allowance, ERC3009 executes the transfer itself. The transfer completes in a single call.
- Random nonces It uses a random 32-byte nonce rather than a sequential nonce. This allows thousands of independent authorizations to be generated in parallel without sequential nonce conflicts.
- Gasless transactions for users Users can transfer tokens without holding ETH for gas. Another address, such as a relayer, pays the gas fee.
Using ERC3009 with x402
ERC3009 can substantially simplify the x402 payment flow.
sequenceDiagram
participant Client as Client (Buyer)
participant Server as Server (Seller)
participant Relayer as Gas Relayer
participant USDC as USDC Contract (ERC-3009)
participant Blockchain as Blockchain
Client->>Server: リソースをリクエスト
Server->>Client: 402 Payment Required<br/>(amount, recipient)
Note over Client: オフチェーン署名
Client->>Client: EIP-712署名を作成<br/>(transferWithAuthorization)
Client->>Server: リクエスト + Signature
Note over Server,Relayer: サーバーがガス代を負担
Server->>Relayer: 署名を転送
Relayer->>USDC: transferWithAuthorization(signature)
USDC->>Blockchain: トランザクション実行
Blockchain-->>USDC: 確定
USDC-->>Relayer: 成功
Relayer-->>Server: 成功
Server->>Client: リソース提供
Implementation example
import { encodeFunctionData, keccak256, toHex } from 'viem';
// EIP-712 domain definition
const domain = {
name: 'USD Coin',
version: '2',
chainId: 8453, // Base
verifyingContract: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913' // USDC on Base
};
// TransferWithAuthorization type definition
const types = {
TransferWithAuthorization: [
{ name: 'from', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'validAfter', type: 'uint256' },
{ name: 'validBefore', type: 'uint256' },
{ name: 'nonce', type: 'bytes32' }
]
};
// Client: Create a signature
async function createTransferAuthorization(
from: string,
to: string,
value: bigint,
validAfter: number,
validBefore: number
) {
// Generate a random nonce
const nonce = keccak256(toHex(Date.now()));
const message = {
from,
to,
value,
validAfter,
validBefore,
nonce
};
// Create an EIP-712 signature
const signature = await walletClient.signTypedData({
domain,
types,
primaryType: 'TransferWithAuthorization',
message
});
return { message, signature, nonce };
}
// Server: Verify and execute the signature
async function executeTransferWithAuthorization(
message: any,
signature: string
) {
const usdcContract = '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
// Split into r, s, and v
const r = signature.slice(0, 66);
const s = '0x' + signature.slice(66, 130);
const v = parseInt(signature.slice(130, 132), 16);
// Call transferWithAuthorization
const data = encodeFunctionData({
abi: usdcABI,
functionName: 'transferWithAuthorization',
args: [
message.from,
message.to,
message.value,
message.validAfter,
message.validBefore,
message.nonce,
v,
r,
s
]
});
// The relayer pays gas and submits the transaction
const txHash = await relayerClient.sendTransaction({
to: usdcContract,
data
});
return txHash;
}Benefits
- Users do not need to hold ETH Users can make x402 payments while holding only USDC.
- Server-managed gas fees The server can cover gas costs to improve the user experience.
- Parallel processing Random nonces allow multiple AI agents to generate signatures concurrently without sequential nonce conflicts.
ERC2612: Permit (gasless ERC20 approvals)
ERC2612 is a standard for signature-based ERC20 token approvals without requiring the owner to submit an approval transaction.
Key features
- Signature-based approvals
Grant approval through an EIP712 signature instead of an
approve()transaction. - No gas fee for the approving user The user does not need to pay gas for a separate approval transaction.
- Broad adoption Permit mechanisms have been adopted by many ERC20 tokens, including DAI, UNI, and COMP; implementations may differ.
Using ERC2612 with x402
ERC2612 can simplify smart contract-based payment flows.
// User: Create a permit
async function createPermit(
owner: string,
spender: string,
value: bigint,
deadline: number
) {
const nonce = await tokenContract.read.nonces([owner]);
const domain = {
name: 'Dai Stablecoin',
version: '1',
chainId: 8453,
verifyingContract: daiAddress
};
const types = {
Permit: [
{ name: 'owner', type: 'address' },
{ name: 'spender', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'deadline', type: 'uint256' }
]
};
const message = { owner, spender, value, nonce, deadline };
const signature = await walletClient.signTypedData({
domain,
types,
primaryType: 'Permit',
message
});
return { message, signature };
}
// Server: Execute the permit and transfer tokens
async function executePermitAndTransfer(
permit: any,
signature: string
) {
const { v, r, s } = splitSignature(signature);
// 1. Grant approval with Permit
await tokenContract.write.permit([
permit.owner,
permit.spender,
permit.value,
permit.deadline,
v,
r,
s
]);
// 2. Transfer tokens with transferFrom
await tokenContract.write.transferFrom([
permit.owner,
permit.spender,
permit.value
]);
}ERC8004: Trustless Agents (a standard for AI agents)
ERC8004 is a standard designed to support trustless interactions between AI agents.
Key features
ERC8004 defines three on-chain registries.
- Identity Registry Uses ERC721 (NFTs) to give each agent a universal, portable, censorship-resistant on-chain identity.
- Reputation Registry Creates a persistent on-chain audit trail of feedback about agent performance. Serves as a source of raw data for off-chain reputation scoring systems.
- Validation Registry Supports task validation through cryptoeconomic staking or cryptographic attestations using TEEs (Trusted Execution Environments) or zero-knowledge proofs.
Using ERC8004 with x402
Combining ERC8004 and x402 can support an AI agent payment ecosystem with verifiable trust signals.
sequenceDiagram
participant AIAgent as AI Agent
participant IdentityNFT as Identity Registry (ERC-721)
participant ReputationReg as Reputation Registry
participant x402Server as x402 API Server
participant ValidationReg as Validation Registry
Note over AIAgent,IdentityNFT: エージェント登録
AIAgent->>IdentityNFT: registerAgent()
IdentityNFT-->>AIAgent: Agent NFT #123
Note over AIAgent,x402Server: x402決済フロー
AIAgent->>x402Server: リクエスト + Agent ID #123
x402Server->>IdentityNFT: verifyAgent(#123)
IdentityNFT-->>x402Server: 有効なエージェント
x402Server->>ReputationReg: getReputation(#123)
ReputationReg-->>x402Server: Score: 95/100
x402Server->>AIAgent: 402 Payment Required
AIAgent->>AIAgent: ERC-3009署名作成
AIAgent->>x402Server: リクエスト + Payment Signature
x402Server->>x402Server: 支払い検証・決済
x402Server->>AIAgent: API Response
Note over AIAgent,ValidationReg: タスク完了の記録
x402Server->>ValidationReg: recordCompletion(#123, task_id)
ValidationReg->>ReputationReg: updateReputation(#123, +1)
Implementation example
// Register an AI agent
async function registerAIAgent(
agentMetadata: {
name: string;
description: string;
capabilities: string[];
}
) {
const identityRegistry = '0x...'; // ERC-8004 Identity Registry
// Mint an agent NFT
const txHash = await identityContract.write.registerAgent([
agentMetadata.name,
agentMetadata.description,
JSON.stringify(agentMetadata.capabilities)
]);
const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash });
const agentId = receipt.logs[0].topics[1]; // NFT Token ID
return agentId;
}
// x402 server: Verify the agent
async function verifyAgent(agentId: bigint) {
// 1. Check agent existence in the Identity Registry
const owner = await identityContract.read.ownerOf([agentId]);
if (!owner) {
throw new Error('Invalid agent ID');
}
// 2. Retrieve feedback from the Reputation Registry
const reputation = await reputationContract.read.getReputation([agentId]);
if (reputation.score < MINIMUM_REPUTATION_SCORE) {
throw new Error('Agent reputation too low');
}
// 3. Check previous transaction history
const history = await reputationContract.read.getHistory([agentId]);
return {
agentId,
owner,
reputation: reputation.score,
totalTransactions: history.length,
verified: true
};
}
// Record feedback after completing the task
async function recordTaskCompletion(
agentId: bigint,
taskId: string,
success: boolean
) {
// Record task completion in the Validation Registry
await validationContract.write.recordCompletion([
agentId,
taskId,
success,
Date.now()
]);
// Update the Reputation Registry
const scoreChange = success ? 1 : -2;
await reputationContract.write.updateReputation([agentId, scoreChange]);
}Benefits
- Visible trust signals An agent's recorded track record can be examined on-chain.
- Fraud prevention Applications can reject transactions with agents whose reputation falls below a chosen threshold.
- Long-term incentives Building a positive track record can help agents gain more opportunities to transact.
ERC1363: Payable Tokens (integrating payments and callbacks)
ERC1363 is a standard that allows a token transfer and a contract function call to occur together.
Key features
- transferAndCall / transferFromAndCall Calls a function on the recipient contract as part of the token transfer. An on-chain payment and the associated on-chain service logic can complete in one transaction.
- approveAndCall Executes a contract callback as part of granting an allowance. Two steps can be combined into one transaction.
Mechanism and flow
ERC1363 extends ERC20 with callback functionality.
Interface definitions
interface IERC1363 {
function transferAndCall(address to, uint256 value) external returns (bool);
function transferAndCall(address to, uint256 value, bytes memory data) external returns (bool);
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
function transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool);
function approveAndCall(address spender, uint256 value) external returns (bool);
function approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool);
}
interface IERC1363Receiver {
function onTransferReceived(
address operator,
address from,
uint256 value,
bytes memory data
) external returns (bytes4);
}
interface IERC1363Spender {
function onApprovalReceived(
address owner,
uint256 value,
bytes memory data
) external returns (bytes4);
}Execution flow
-
Processing transferAndCall
- The client calls
transferAndCall(to, value, data). - The token contract executes
transfer()to transfer tokens. - After a successful transfer, it calls the recipient's
onTransferReceived()callback. - The operation succeeds if the callback returns the correct selector (
0x88a7ca5c).
- The client calls
-
Processing approveAndCall
- The client calls
approveAndCall(spender, value, data). - The token contract executes
approve()to grant an allowance. - After a successful approval, it calls the spender's
onApprovalReceived()callback. - The operation succeeds if the callback returns the correct selector (
0x7b04a2d0).
- The client calls
Callback verification
The receiving or spending contract must implement the relevant IERC1363Receiver or IERC1363Spender interface.
If the required callback is not implemented correctly, the transaction reverts.
// Example recipient implementation
contract PayableReceiver is IERC1363Receiver {
function onTransferReceived(
address operator,
address from,
uint256 value,
bytes memory data
) external override returns (bytes4) {
// Execute the operation
// ...
// Return the selector indicating success
return IERC1363Receiver.onTransferReceived.selector;
}
}Comparison with ERC20
| Feature | ERC20 | ERC1363 |
|---|---|---|
| Transactions | Two (approve + transferFrom, if approval is needed) | One (transferAndCall) |
| Callback | No | Yes (onTransferReceived) |
| Gas fees | Higher for two separate transactions | Potentially lower (one transaction) |
| Atomicity | Not across two separate transactions | Guaranteed for the transfer and callback |
Using ERC1363 with x402
ERC1363 can combine payment and on-chain service execution in a single transaction. Access to an off-chain HTTP API would still require a separate integration.
sequenceDiagram
participant Client as Client
participant Token as ERC-1363 Token (USDC)
participant x402Server as x402 API Server
Client->>Token: transferAndCall(x402Server, amount, apiParams)
Token->>Token: トークン送金処理
Token->>x402Server: onTransferReceived(from, amount, apiParams)
x402Server->>x402Server: API処理実行
x402Server-->>Token: 成功
Token-->>Client: API結果を返却
Implementation example
// x402 server integration: Implement an ERC-1363 receiver
contract X402APIServer is IERC1363Receiver {
// Handle a transferAndCall callback
function onTransferReceived(
address operator,
address from,
uint256 value,
bytes calldata data
) external override returns (bytes4) {
// API parameters are encoded in data
(string memory apiEndpoint, bytes memory params) = abi.decode(
data,
(string, bytes)
);
// Verify the payment amount
require(value >= getAPIPrice(apiEndpoint), 'Insufficient payment');
// Execute service logic
bytes memory result = executeAPI(apiEndpoint, params);
// Return success
return IERC1363Receiver.onTransferReceived.selector;
}
function executeAPI(
string memory endpoint,
bytes memory params
) internal returns (bytes memory) {
// Implement service logic
if (keccak256(bytes(endpoint)) == keccak256('generate-image')) {
return generateImage(params);
}
// ...
}
}
// Client: Combine payment and service invocation with transferAndCall
const erc1363Token = '0x...'; // ERC-1363-compatible token
const x402Server = '0x...';
// Encode API parameters
const apiParams = encodeFunctionData({
abi: apiABI,
functionName: 'encodeParams',
args: ['generate-image', { prompt: 'An image of a cat', style: 'realistic' }]
});
// Payment and service invocation in one transaction
const txHash = await walletClient.writeContract({
address: erc1363Token,
abi: erc1363ABI,
functionName: 'transferAndCall',
args: [
x402Server,
parseUnits('0.1', 6), // 0.1 USDC
apiParams
]
});Benefits
- Fewer transactions Combine two steps into one transaction, potentially saving gas.
- Atomicity The on-chain payment and callback execute together, reverting the entire transaction if either fails.
- Improved user experience Users can authorize the payment and on-chain operation with a single transaction signature.
ERC2771: Meta Transactions (a standard for gasless transactions)
ERC2771 is a standard for enabling gasless transactions for users through a Trusted Forwarder.
Key features
- Trusted Forwarder A relayer submits a message signed by the user on their behalf. The relayer pays the gas fee.
- Meta-transactions Users can execute transactions without holding ETH for gas.
- Compatibility Existing smart contracts can support this approach with minimal changes.
Mechanism and flow
ERC2771 uses the Trusted Forwarder pattern to enable meta-transactions.
Architecture
User (signs only) → Trusted Forwarder → Relayer (pays gas) → Target ContractMain components
-
Trusted Forwarder
- Verifies the user's signature.
- Coordinates the forwarded transaction with the relayer.
- Manages nonces to prevent replay attacks.
-
Relayer
- Submits the transaction through the Forwarder.
- Uses its own ETH to pay the gas fee.
- Submits the transaction to the blockchain.
-
ERC2771Context (target contract)
- Overrides the
_msgSender()function. - Returns the actual signer rather than
msg.senderfor a call from the trusted forwarder.
- Overrides the
How _msgSender() works
abstract contract ERC2771Context {
address private immutable _trustedForwarder;
constructor(address trustedForwarder) {
_trustedForwarder = trustedForwarder;
}
function isTrustedForwarder(address forwarder) public view returns (bool) {
return forwarder == _trustedForwarder;
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender) && msg.data.length >= 20) {
// The final 20 bytes of msg.data contain the actual sender address
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
sender = msg.sender;
}
}
}Message format
The Forwarder appends the actual sender address (20 bytes) to the original msg.data.
[Original calldata] + [Actual sender address (20 bytes)]Nonce management
contract MinimalForwarder {
mapping(address => uint256) private _nonces;
function getNonce(address from) public view returns (uint256) {
return _nonces[from];
}
function verify(
ForwardRequest calldata req,
bytes calldata signature
) public view returns (bool) {
address signer = _recoverSigner(req, signature);
return _nonces[req.from] == req.nonce && signer == req.from;
}
function execute(
ForwardRequest calldata req,
bytes calldata signature
) public payable returns (bool, bytes memory) {
require(verify(req, signature), 'Invalid signature');
_nonces[req.from]++;
// Call the target contract
(bool success, bytes memory returndata) = req.to.call{
gas: req.gas,
value: req.value
}(abi.encodePacked(req.data, req.from));
return (success, returndata);
}
}Security considerations
- Trust in the Trusted Forwarder: Use a trusted implementation of the Forwarder contract.
- Replay protection: Nonce management prevents the same signature from being used multiple times.
- Signature verification: EIP712 signatures can be used to prevent tampering with the signed request.
Using ERC2771 with x402
ERC2771 can enable users to make x402-related payments without holding ETH for gas.
sequenceDiagram
participant Client as Client (ETHなし)
participant Forwarder as Trusted Forwarder
participant Relayer as Gas Relayer
participant x402Server as x402 API Server
participant Blockchain as Blockchain
Client->>Client: メタトランザクションを作成・署名
Client->>Forwarder: 署名付きメッセージ送信
Note over Forwarder,Relayer: リレイヤーがガス代負担
Forwarder->>Relayer: トランザクション実行依頼
Relayer->>Blockchain: トランザクション送信(ガス代支払い)
Blockchain->>x402Server: execute(from=Client, data=...)
x402Server->>x402Server: API処理実行
x402Server-->>Blockchain: 成功
Blockchain-->>Client: API結果
Implementation example
// Client: Create a meta-transaction
async function createMetaTransaction(
from: string,
to: string,
data: string
) {
const forwarder = '0x...'; // Trusted Forwarder
const nonce = await forwarderContract.read.getNonce([from]);
const message = {
from,
to,
value: 0n,
gas: 1000000n,
nonce,
data
};
// Create an EIP-712 signature
const signature = await walletClient.signTypedData({
domain: {
name: 'MinimalForwarder',
version: '0.0.1',
chainId: 8453,
verifyingContract: forwarder
},
types: {
ForwardRequest: [
{ name: 'from', type: 'address' },
{ name: 'to', type: 'address' },
{ name: 'value', type: 'uint256' },
{ name: 'gas', type: 'uint256' },
{ name: 'nonce', type: 'uint256' },
{ name: 'data', type: 'bytes' }
]
},
primaryType: 'ForwardRequest',
message
});
return { message, signature };
}
// Relayer: Execute the meta-transaction
async function executeMetaTransaction(
request: any,
signature: string
) {
const forwarder = '0x...';
// The relayer pays gas and submits the transaction
const txHash = await relayerClient.writeContract({
address: forwarder,
abi: forwarderABI,
functionName: 'execute',
args: [request, signature]
});
return txHash;
}
// x402 server integration: Support ERC-2771
contract X402Server is ERC2771Context {
constructor(address trustedForwarder)
ERC2771Context(trustedForwarder)
{}
function processAPI(bytes calldata params) external {
// _msgSender() returns the actual sender (the client)
address actualSender = _msgSender();
// Execute service logic
// ...
}
}Benefits
- No ETH required for user gas fees Users can make x402 payments with USDC when a relayer covers gas.
- Easier onboarding New users do not need to purchase ETH for these transactions.
- Server control over the user experience The server can cover gas fees to improve the user experience.
ERC7677: Paymaster Web Service (abstracting gas payments)
ERC7677 standardizes how clients obtain paymaster data to enable gas sponsorship.
Key features
- Paymaster integration Works with ERC4337 account abstraction to support gas sponsorship.
- HTTP API based Paymaster services can be accessed through an HTTP API.
- Flexible gas payment options Supports arrangements such as paying fees in ERC20 tokens or having the server cover the full gas cost.
Mechanism and flow
ERC7677 defines an API for Paymaster services built on ERC4337 account abstraction.
ERC4337 UserOperation structure
struct UserOperation {
address sender; // Smart account address
uint256 nonce; // Replay protection
bytes initCode; // Account creation code (first operation only)
bytes callData; // Function call to execute
uint256 callGasLimit; // Gas limit for execution
uint256 verificationGasLimit; // Gas limit for verification
uint256 preVerificationGas; // Gas to compensate the bundler
uint256 maxFeePerGas; // Maximum fee per gas
uint256 maxPriorityFeePerGas; // Maximum priority fee per gas
bytes paymasterAndData; // Paymaster information
bytes signature; // User signature
}Paymaster lifecycle
-
Preparation phase (pm_getPaymasterStubData)
- The client creates an unsigned UserOperation.
- It sends an RPC request to the Paymaster service.
- The Paymaster returns stub (temporary)
paymasterAndData.
-
Signing preparation phase
- The client prepares the UserOperation for signing.
- Stub data allows the client to estimate gas requirements before obtaining final paymaster data.
-
Finalization phase (pm_getPaymasterData)
- The client submits the prepared UserOperation to the Paymaster service.
- The Paymaster returns the final
paymasterAndData. - This can include the Paymaster signature. The account signs the final UserOperation after the relevant fields are finalized.
-
Execution phase (validatePaymasterUserOp)
- The EntryPoint contract calls the Paymaster's
validatePaymasterUserOp. - The Paymaster approves gas sponsorship if its conditions are satisfied.
- The EntryPoint contract calls the Paymaster's
-
Settlement phase (postOp)
- After transaction execution,
postOpmay be called. - It records the actual gas consumption and performs any necessary settlement.
- After transaction execution,
RPC API methods
// pm_getPaymasterStubData: Obtain stub data
{
"jsonrpc": "2.0",
"id": 1,
"method": "pm_getPaymasterStubData",
"params": [{
"sender": "0x...",
"nonce": "0x1",
"callData": "0x...",
"callGasLimit": "0x100000",
"verificationGasLimit": "0x100000",
"preVerificationGas": "0x5000",
"maxFeePerGas": "0x3b9aca00",
"maxPriorityFeePerGas": "0x3b9aca00"
}, "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789"] // EntryPoint address
}
// Response
{
"result": {
"paymasterAndData": "0x...",
"preVerificationGas": "0x6000", // Adjusted value
"verificationGasLimit": "0x120000", // Adjusted value
"callGasLimit": "0x110000" // Adjusted value
}
}
// pm_getPaymasterData: Obtain final data
{
"jsonrpc": "2.0",
"id": 2,
"method": "pm_getPaymasterData",
"params": [{
// Complete UserOperation (illustrative request)
"sender": "0x...",
...
"signature": "0x..."
}, "0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789"]
}Paymaster contract implementation
interface IPaymaster {
function validatePaymasterUserOp(
UserOperation calldata userOp,
bytes32 userOpHash,
uint256 maxCost
) external returns (bytes memory context, uint256 validationData);
function postOp(
PostOpMode mode,
bytes calldata context,
uint256 actualGasCost
) external;
}
enum PostOpMode {
opSucceeded, // Success
opReverted, // Operation reverted
postOpReverted // postOp itself reverted
}Types of sponsorship
-
Full sponsorship
- The Paymaster covers the full gas fee.
- The user pays no gas fee.
-
ERC20 token payments
- The user pays the gas cost in an ERC20 token such as USDC.
- The Paymaster pays the network fee in ETH and may convert the tokens to recover its costs.
-
Credit-based model
- The user purchases credits in advance.
- The Paymaster deducts the cost from the credits.
Benefits of this mechanism
- A fully gas-abstracted experience: Users do not need to manage ETH for gas.
- Flexible business models: The server can cover gas fees, sell credits, or accept ERC20 payments.
- Standardized API: A common HTTP API makes it easier to switch between compatible Paymaster services.
- ERC4337 integration: The approach works with the account abstraction standard and its growing ecosystem.
Using ERC7677 with x402
ERC7677 can help users access x402-related services without managing gas payments directly.
sequenceDiagram
participant Client as Client
participant Bundler as Bundler (ERC-4337)
participant Paymaster as Paymaster Service
participant EntryPoint as EntryPoint Contract
participant x402Server as x402 API Server
Client->>Client: UserOperationを作成
Client->>Paymaster: pm_getPaymasterStubData(userOp)
Paymaster-->>Client: paymasterData
Client->>Client: UserOpに署名
Client->>Bundler: eth_sendUserOperation(userOp)
Bundler->>Paymaster: pm_getPaymasterData(userOp)
Paymaster->>Paymaster: ガス代負担を承認
Paymaster-->>Bundler: sponsorshipData
Bundler->>EntryPoint: handleOps([userOp])
EntryPoint->>Paymaster: validatePaymasterUserOp(userOp)
Paymaster-->>EntryPoint: 承認
EntryPoint->>x402Server: API実行
x402Server-->>EntryPoint: 成功
Note over Paymaster: Paymasterがガス代を支払う
EntryPoint->>Paymaster: postOp(actualGasCost)
EntryPoint-->>Client: API結果
Implementation example
// Client: Create a UserOperation using a Paymaster service
async function createSponsoredUserOp(
sender: string,
callData: string
) {
const paymasterUrl = 'https://paymaster.example.com/rpc';
// Step 1: Obtain Paymaster stub data
const stubData = await fetch(paymasterUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'pm_getPaymasterStubData',
params: [{
sender,
nonce: '0x1',
callData,
callGasLimit: '0x100000',
verificationGasLimit: '0x100000',
preVerificationGas: '0x5000',
maxFeePerGas: '0x3b9aca00',
maxPriorityFeePerGas: '0x3b9aca00'
}]
})
});
const { result: paymasterData } = await stubData.json();
// Step 2: Create and sign the UserOperation
const userOp = {
sender,
nonce: '0x1',
callData,
callGasLimit: '0x100000',
verificationGasLimit: '0x100000',
preVerificationGas: '0x5000',
maxFeePerGas: '0x3b9aca00',
maxPriorityFeePerGas: '0x3b9aca00',
...paymasterData,
signature: '0x' // Sign later
};
// Add the signature
userOp.signature = await signUserOp(userOp);
// Step 3: Submit to the Bundler
const txHash = await fetch(bundlerUrl, {
method: 'POST',
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'eth_sendUserOperation',
params: [userOp, entryPointAddress]
})
});
return txHash;
}
// Paymaster: Implement gas sponsorship
contract X402Paymaster is IPaymaster {
mapping(address => uint256) public credits;
// Purchase credits
function purchaseCredits() external payable {
credits[msg.sender] += msg.value;
}
// Determine whether to sponsor gas
function validatePaymasterUserOp(
UserOperation calldata userOp,
bytes32 userOpHash,
uint256 maxCost
) external override returns (bytes memory context, uint256 validationData) {
address sender = userOp.sender;
// Check credit balance
require(credits[sender] >= maxCost, 'Insufficient credits');
// Deduct credits
credits[sender] -= maxCost;
return ('', 0);
}
// Settle gas costs
function postOp(
PostOpMode mode,
bytes calldata context,
uint256 actualGasCost
) external override {
// Record the actual gas cost
// Refund excess credits if necessary
}
}Benefits
- A fully gas-abstracted experience Users do not need to manage gas payments directly.
- Flexible business models The server can cover gas fees, sell credits, or accept ERC20 payments.
- ERC4337 integration The approach integrates with the account abstraction standard and can evolve alongside its ecosystem.
ERC1337: Recurring Payments (subscription payments)
ERC1337 is a proposal for recurring payments on the blockchain.
Key features
- Automated recurring payments Once the user grants authorization, recurring payments can be executed automatically by a transaction submitter.
- Cancellation Users can cancel their subscriptions at any time.
Mechanism and flow
ERC1337 describes a mechanism for managing recurring payments on-chain.
Subscription structure
struct Subscription {
address subscriber; // Payer
address provider; // Recipient
address token; // Payment token (ERC20)
uint256 amount; // Amount per payment
uint256 interval; // Payment interval (in seconds)
uint256 lastPayment; // Time of the last payment
uint256 startTime; // Subscription start time
bool active; // Whether the subscription is active
}Execution flow
-
Create a subscription
- The user calls
subscribe(provider, token, amount, interval). - The user authorizes recurring payments with the token's
approve()function. - A Subscription struct is created.
- The user calls
-
Execute a recurring payment
- Anyone can call
executePayment(subscriptionId). - The contract checks the following conditions:
- Whether the subscription is active
- Whether
block.timestamp >= lastPayment + interval(whether payment is due) - Whether the user has a sufficient balance
- If the conditions are satisfied, the contract executes the payment using
transferFrom(). - It updates
lastPayment.
- Anyone can call
-
Cancel the subscription
- The subscriber calls
cancel(subscriptionId). - The
activeflag is set tofalse. - Subsequent payments are no longer executed.
- The subscriber calls
Implementation details
contract SubscriptionManager {
mapping(bytes32 => Subscription) public subscriptions;
event SubscriptionCreated(bytes32 indexed subId, address indexed subscriber, address indexed provider);
event PaymentExecuted(bytes32 indexed subId, uint256 amount, uint256 timestamp);
event SubscriptionCancelled(bytes32 indexed subId);
function subscribe(
address provider,
address token,
uint256 amount,
uint256 interval
) external returns (bytes32) {
bytes32 subId = keccak256(
abi.encodePacked(msg.sender, provider, token, block.timestamp)
);
subscriptions[subId] = Subscription({
subscriber: msg.sender,
provider: provider,
token: token,
amount: amount,
interval: interval,
lastPayment: block.timestamp,
startTime: block.timestamp,
active: true
});
emit SubscriptionCreated(subId, msg.sender, provider);
return subId;
}
function executePayment(bytes32 subId) external {
Subscription storage sub = subscriptions[subId];
require(sub.active, 'Subscription not active');
require(
block.timestamp >= sub.lastPayment + sub.interval,
'Too early'
);
// Transfer tokens
IERC20(sub.token).transferFrom(
sub.subscriber,
sub.provider,
sub.amount
);
sub.lastPayment = block.timestamp;
emit PaymentExecuted(subId, sub.amount, block.timestamp);
}
function cancel(bytes32 subId) external {
Subscription storage sub = subscriptions[subId];
require(sub.subscriber == msg.sender, 'Not subscriber');
sub.active = false;
emit SubscriptionCancelled(subId);
}
// Retrieve subscription information
function getSubscription(bytes32 subId) external view returns (Subscription memory) {
return subscriptions[subId];
}
// Retrieve the next payment due date
function getNextPaymentDue(bytes32 subId) external view returns (uint256) {
Subscription memory sub = subscriptions[subId];
return sub.lastPayment + sub.interval;
}
}Automating execution
Blockchains do not execute scheduled transactions on their own, so recurring payments can be implemented using the following approaches:
-
Keeper network (such as Chainlink Automation)
- Off-chain keepers periodically check whether payment is due.
- When payment is due, a keeper calls
executePayment().
-
Incentivized execution
- Allow anyone to call
executePayment(). - Add a mechanism that pays a fee to the executor.
- Allow anyone to call
function executePaymentWithReward(bytes32 subId) external {
Subscription storage sub = subscriptions[subId];
// Normal payment processing
IERC20(sub.token).transferFrom(sub.subscriber, sub.provider, sub.amount);
// Pay a reward to the executor
uint256 reward = sub.amount / 100; // 1% reward
IERC20(sub.token).transferFrom(sub.subscriber, msg.sender, reward);
sub.lastPayment = block.timestamp;
}Benefits of this mechanism
- SaaS business models: Implement monthly API charges or subscription models, bringing familiar Web2 revenue models to Web3.
- Automation: Users no longer need to manually pay each month. Once authorized, recurring payments can continue automatically.
- Transparency: All payment history is recorded on-chain and can be inspected at any time.
- User control: Users can cancel subscriptions at any time without the provider's consent.
Using ERC1337 with x402
This approach can support monthly API usage fees and recurring billing models.
// Subscription contract
contract X402Subscription {
struct Subscription {
address subscriber;
address provider;
uint256 amount;
uint256 interval; // Payment interval (seconds)
uint256 lastPayment;
bool active;
}
mapping(bytes32 => Subscription) public subscriptions;
// Create subscription
function subscribe(
address provider,
uint256 amount,
uint256 interval
) external {
bytes32 subId = keccak256(
abi.encodePacked(msg.sender, provider, block.timestamp)
);
subscriptions[subId] = Subscription({
subscriber: msg.sender,
provider: provider,
amount: amount,
interval: interval,
lastPayment: block.timestamp,
active: true
});
}
// Execute recurring payment
function executePayment(bytes32 subId) external {
Subscription storage sub = subscriptions[subId];
require(sub.active, 'Subscription not active');
require(
block.timestamp >= sub.lastPayment + sub.interval,
'Too early'
);
// Transfer tokens
IERC20(usdcToken).transferFrom(sub.subscriber, sub.provider, sub.amount);
sub.lastPayment = block.timestamp;
}
// Cancel subscription
function cancel(bytes32 subId) external {
require(subscriptions[subId].subscriber == msg.sender, 'Not subscriber');
subscriptions[subId].active = false;
}
}Benefits
- SaaS business models Implement monthly API billing and subscription models.
- Automation Users no longer need to pay manually each month.
ERC-7857: Intelligent NFTs for AI Agents
ERC7857 is an NFT standard proposed specifically for AI agents.
Key features
- AI model ownership Represent an AI agent's intelligence, personality, and training data through an NFT.
- Encrypted data storage Store AI state while protecting its privacy.
- Transferability AI agents represented by NFTs can be sold and transferred.
Mechanism and flow
ERC7857 aims to make an AI agent's intelligence ownable and transferable as an NFT.
Illustrative iNFT (Intelligent NFT) metadata structure
{
"name": "AI Agent #123",
"description": "GPT-4-based image generation agent",
"image": "ipfs://QmXxx.../avatar.png",
"intelligence": {
"modelType": "gpt-4",
"modelUri": "ipfs://QmYyyy.../model.enc",
"encryption": "AES-256-GCM",
"decryptionKey": "encrypted_with_owner_pubkey",
"capabilities": [
"image-generation",
"text-to-image",
"style-transfer"
],
"personality": {
"tone": "professional",
"language": "en",
"customization": "ipfs://QmZzzz.../personality.json"
},
"trainingData": {
"dataset": "private-dataset-v1",
"fineTuneUri": "ipfs://QmWwww.../finetune.enc",
"version": "1.2.3"
}
},
"performance": {
"accuracy": 0.95,
"speed": "fast",
"costPerRequest": "0.01 USDC"
}
}Encryption and access control
-
Owner-only access
- AI model weights are encrypted and stored on IPFS.
- The decryption key is encrypted using the NFT owner's public key.
- The owner can recover the decryption key using the corresponding private key and use the model.
-
Processing a transfer
- When the NFT is transferred, the decryption key is re-encrypted using the new owner's public key.
- The design aims to prevent the former owner from accessing the model thereafter; it cannot erase copies already obtained by that owner.
Illustrative interface definition
interface IERC7857 {
// Mint an iNFT
function mintAgent(
address to,
string memory modelUri,
bytes memory encryptedKey,
string memory metadata
) external returns (uint256 tokenId);
// Retrieve the model URI
function getModelUri(uint256 tokenId) external view returns (string memory);
// Retrieve the encrypted decryption key
function getEncryptedKey(uint256 tokenId) external view returns (bytes memory);
// Owner only: Update the decryption key during a transfer
function updateEncryptedKey(uint256 tokenId, bytes memory newEncryptedKey) external;
}Lifecycle
-
Creation (Mint)
- Train an AI model.
- Encrypt the model and upload it to IPFS.
- Encrypt the decryption key using the owner's public key.
- Mint the iNFT.
-
Usage
- The NFT owner decrypts the encrypted key.
- Retrieve the model from IPFS and decrypt it.
- Run the AI agent.
-
Transfer
- Transfer the NFT to its new owner.
- In this illustrative design, the
_afterTokenTransferhook coordinates re-encryption of the decryption key using the new owner's public key.
Implementation example
contract IntelligentNFT is ERC721, IERC7857 {
struct AgentData {
string modelUri; // Encrypted model URI
bytes encryptedKey; // Decryption key encrypted with the owner's public key
string metadata; // Metadata URI
uint256 createdAt; // Creation timestamp
}
mapping(uint256 => AgentData) private _agents;
uint256 private _tokenIdCounter;
function mintAgent(
address to,
string memory modelUri,
bytes memory encryptedKey,
string memory metadata
) external override returns (uint256) {
uint256 tokenId = _tokenIdCounter++;
_agents[tokenId] = AgentData({
modelUri: modelUri,
encryptedKey: encryptedKey,
metadata: metadata,
createdAt: block.timestamp
});
_safeMint(to, tokenId);
return tokenId;
}
function getModelUri(uint256 tokenId) external view override returns (string memory) {
require(_exists(tokenId), 'Token does not exist');
return _agents[tokenId].modelUri;
}
function getEncryptedKey(uint256 tokenId) external view override returns (bytes memory) {
require(ownerOf(tokenId) == msg.sender, 'Not owner');
return _agents[tokenId].encryptedKey;
}
function updateEncryptedKey(uint256 tokenId, bytes memory newEncryptedKey) external override {
require(ownerOf(tokenId) == msg.sender, 'Not owner');
_agents[tokenId].encryptedKey = newEncryptedKey;
}
}Benefits of this mechanism
- Clear representation of AI ownership: Treat an AI agent's intelligence as an asset that can be owned and transferred. This can help protect independently trained models.
- Privacy protection: Encryption can protect model weights and training data by limiting access to authorized parties.
- Marketplace: High-performing AI agents can be bought and sold through NFT marketplaces, supporting monetization for AI developers.
- Integration with x402: Use the NFT as an AI agent identifier and present it during payment to support identity verification.
Using ERC7857 with x402
Use the NFT as an AI agent identifier and present it during x402 payments.
// Mint an AI agent NFT
async function mintIntelligentNFT(
agentMetadata: {
name: string;
modelUri: string; // Encrypted AI model URI
capabilities: string[];
}
) {
const nftContract = '0x...'; // ERC-7857 contract
const txHash = await walletClient.writeContract({
address: nftContract,
abi: erc7857ABI,
functionName: 'mintAgent',
args: [
agentMetadata.name,
agentMetadata.modelUri,
JSON.stringify(agentMetadata.capabilities)
]
});
return txHash;
}ERC6551: Token Bound Accounts (NFT wallets)
ERC6551 is a standard that allows NFTs to have their own smart contract accounts.
Key features
- Wallets associated with NFTs An Ethereum account address can be derived for an individual NFT.
- Asset ownership An account bound to an NFT can hold ETH, ERC20 tokens, other NFTs, and more.
- Transaction history The associated account's on-chain history can be recorded.
Mechanism and flow
ERC6551 links an NFT to a dedicated smart contract wallet known as a Token Bound Account (TBA).
Architecture
ERC-721 NFT → Token Bound Account (TBA) → Assets (ETH, ERC20, NFTs, etc.)Main components
-
Registry
- Provides a common entry point for creating and locating Token Bound Accounts.
- Creates a TBA using
createAccount(). - Computes the TBA address using
account().
-
Implementation (implementation contract)
- Implements the actual TBA logic.
- Executes transactions using
execute(). - In this example, only the NFT owner can control the account.
-
Token Bound Account(TBA)
- A proxy contract with an address derived from an NFT and the account configuration.
- Can hold assets.
- Is controlled by the NFT owner in the example implementation.
Address calculation
The TBA address is computed deterministically from the following parameters:
function account(
address implementation,
uint256 chainId,
address tokenContract,
uint256 tokenId,
uint256 salt
) public view returns (address) {
bytes32 hash = keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
salt,
keccak256(
abi.encodePacked(
implementation,
chainId,
tokenContract,
tokenId
)
)
)
);
return address(uint160(uint256(hash)));
}With the same NFT, implementation, salt, registry, and other relevant parameters, this calculation always produces the same TBA address.
Lifecycle
-
Create a TBA
- Call
Registry.createAccount(). - Create a proxy for the Implementation using ERC1167 (Minimal Proxy).
- Deploy the proxy contract.
- Call
-
Deposit assets
- Anyone can send ETH or tokens to the TBA address.
- The TBA holds the assets.
-
Execute transactions
- The NFT owner calls
TBA.execute(to, value, data)in this illustrative interface. - The TBA calls the specified contract.
- The NFT owner pays the gas fee in this example.
- The NFT owner calls
-
Transfer the NFT
- When the NFT is transferred, control of an owner-controlled TBA passes to the new owner.
- The new owner can control the assets held in the TBA without moving each asset separately.
Registry implementation example
contract ERC6551Registry {
event AccountCreated(
address account,
address implementation,
uint256 chainId,
address tokenContract,
uint256 tokenId,
uint256 salt
);
function createAccount(
address implementation,
uint256 chainId,
address tokenContract,
uint256 tokenId,
uint256 salt,
bytes calldata initData
) external returns (address) {
bytes memory code = _creationCode(implementation, chainId, tokenContract, tokenId, salt);
address _account = Create2.computeAddress(
bytes32(salt),
keccak256(code)
);
if (_account.code.length != 0) {
return _account;
}
_account = Create2.deploy(0, bytes32(salt), code);
if (initData.length != 0) {
(bool success, ) = _account.call(initData);
require(success, 'Initialization failed');
}
emit AccountCreated(_account, implementation, chainId, tokenContract, tokenId, salt);
return _account;
}
function account(
address implementation,
uint256 chainId,
address tokenContract,
uint256 tokenId,
uint256 salt
) external view returns (address) {
bytes32 bytecodeHash = keccak256(
_creationCode(implementation, chainId, tokenContract, tokenId, salt)
);
return Create2.computeAddress(bytes32(salt), bytecodeHash);
}
}Implementation contract example
contract TokenBoundAccount {
function execute(
address to,
uint256 value,
bytes calldata data,
uint8 operation
) external payable returns (bytes memory) {
require(_isValidSigner(msg.sender), 'Invalid signer');
if (operation == 0) {
// Call
(bool success, bytes memory result) = to.call{value: value}(data);
require(success, 'Call failed');
return result;
} else if (operation == 1) {
// DelegateCall
(bool success, bytes memory result) = to.delegatecall(data);
require(success, 'Delegatecall failed');
return result;
}
revert('Invalid operation');
}
function _isValidSigner(address signer) internal view returns (bool) {
// Retrieve the NFT owner
(uint256 chainId, address tokenContract, uint256 tokenId) = _token();
if (chainId != block.chainid) return false;
return IERC721(tokenContract).ownerOf(tokenId) == signer;
}
function _token() internal view returns (uint256, address, uint256) {
bytes memory footer = new bytes(0x60);
assembly {
extcodecopy(address(), add(footer, 0x20), 0x4d, 0x60)
}
return abi.decode(footer, (uint256, address, uint256));
}
}Benefits of this mechanism
- Assets associated with an NFT: A token-bound account functions as a wallet holding ETH, ERC20 tokens, and other NFTs. Game items and revenue can be associated directly with an NFT.
- Unified ownership: Control of the NFT and the assets in its owner-controlled account can move together when the NFT is transferred.
- Transaction history: The TBA's transaction history is recorded on-chain, making it possible to trace the NFT's associated activity.
- Backward compatibility: This approach can be applied to existing ERC721 NFTs without creating a new NFT contract.
ERC7857 + ERC6551: Integrating AI agent NFTs with wallets
Combining ERC7857 (AI agent NFTs) with ERC6551 (Token Bound Accounts) enables an AI agent to have an associated wallet and make payments when granted suitable execution authority.
sequenceDiagram
participant Owner as オーナー
participant AgentNFT as AI Agent NFT (ERC-7857)
participant TBA as Token Bound Account (ERC-6551)
participant x402API as x402 API
participant USDC as USDC Contract
Note over Owner,AgentNFT: AI Agent NFTをミント
Owner->>AgentNFT: mintAgent(metadata)
AgentNFT-->>Owner: Agent NFT #123
Note over Owner,TBA: Token Bound Accountを作成
Owner->>TBA: createAccount(AgentNFT, #123)
TBA-->>Owner: TBA Address: 0xABC...
Note over Owner,TBA: TBAにUSDCを送金
Owner->>USDC: transfer(TBA, 10 USDC)
Note over AgentNFT,x402API: AIエージェントが自律的に支払い
AgentNFT->>x402API: GET /api/generate-image
x402API-->>AgentNFT: 402 (amount: 0.1 USDC)
AgentNFT->>TBA: executePayment(x402API, 0.1 USDC)
TBA->>USDC: transfer(x402API, 0.1 USDC)
USDC-->>TBA: 成功
TBA->>x402API: POST /api/generate-image
x402API-->>TBA: 画像データ
TBA-->>AgentNFT: 画像データ
Implementation example
// Create a Token Bound Account
async function createTokenBoundAccount(
nftContract: string,
tokenId: bigint
) {
const registryAddress = '0x...'; // ERC-6551 Registry
const txHash = await walletClient.writeContract({
address: registryAddress,
abi: erc6551RegistryABI,
functionName: 'createAccount',
args: [
implementationAddress, // TBA implementation contract
8453n, // chainId (Base)
nftContract,
tokenId,
0n, // salt
'0x' // initData
]
});
// Compute the TBA address
const tbaAddress = await registryContract.read.account([
implementationAddress,
8453n,
nftContract,
tokenId,
0n
]);
return tbaAddress;
}
// x402 payment using an AI agent NFT and TBA
class AIAgentWithWallet {
private nftId: bigint;
private tbaAddress: string;
async payAndExecuteAPI(apiUrl: string, params: any) {
// Step 1: Request API pricing
const response = await fetch(apiUrl, {
method: 'POST',
body: JSON.stringify(params)
});
if (response.status === 402) {
const paymentInfo = await response.json();
// Step 2: Pay from the Token Bound Account
const txHash = await publicClient.writeContract({
address: this.tbaAddress,
abi: tbaABI,
functionName: 'execute',
args: [
usdcAddress,
0n,
encodeFunctionData({
abi: erc20ABI,
functionName: 'transfer',
args: [paymentInfo.recipient, parseUnits(paymentInfo.amount, 6)]
}),
0 // call operation
],
account: this.getNFTOwner() // The NFT owner signs
});
// Step 3: Submit proof of payment and call the API
const apiResponse = await fetch(apiUrl, {
method: 'POST',
headers: {
'X-Payment-Hash': txHash,
'X-Agent-NFT': this.nftId.toString()
},
body: JSON.stringify(params)
});
return await apiResponse.json();
}
}
}Benefits
- Combine AI agent identity and assets The NFT acts as an identity, and the TBA acts as a wallet.
- Owner control The NFT owner can control the agent's assets and actions through the account's authorization logic.
- Transaction history The agent's on-chain transactions can be recorded.
ERC7579: Modular Smart Accounts (modular extensions)
ERC7579 is a standard for modular smart accounts.
Key features
- Pluggable modules Add modules such as Validators, Executors, and Fallback Handlers.
- Interoperability Share compatible modules across different providers.
- ERC4337 compatibility Integrates with account abstraction.
Mechanism and flow
ERC7579 standardizes how modules can be installed and uninstalled in smart accounts.
Module types
The following sections describe three module types from ERC7579 (the standard also defines Hooks):
-
Validator
- Validates UserOperation signatures.
- Can support multiple validation methods, including ECDSA, passkeys, and multisig.
- Implements the
validateUserOp()function.
-
Executor
- Executes transactions on behalf of the smart account.
- Can be used for automated actions and batch processing.
- Uses the account's execution interface to request execution.
-
Fallback Handler
- Handles function calls not directly supported by the smart account.
- Enables additional functionality.
- Handles calls routed through the account's fallback mechanism.
Interface definitions
interface IERC7579Account {
function installModule(
uint256 moduleTypeId,
address module,
bytes calldata initData
) external;
function uninstallModule(
uint256 moduleTypeId,
address module,
bytes calldata deInitData
) external;
function isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
) external view returns (bool);
function execute(
address target,
uint256 value,
bytes calldata data
) external;
function executeBatch(
address[] calldata targets,
uint256[] calldata values,
bytes[] calldata datas
) external;
}
interface IModule {
function onInstall(bytes calldata data) external;
function onUninstall(bytes calldata data) external;
function isModuleType(uint256 typeId) external view returns (bool);
function isInitialized(address smartAccount) external view returns (bool);
}Module lifecycle
-
Installation
- Call
installModule(moduleTypeId, moduleAddress, initData). - The module's
onInstall(initData)function is executed. - The module is registered in the account's state.
- Call
-
Usage
- Validator module: Invoked when validating a UserOperation.
- Executor module: Requests execution through the account.
- Fallback module: Invoked for calls routed to the fallback handler.
-
Uninstallation
- Call
uninstallModule(moduleTypeId, moduleAddress, deInitData). - The module's
onUninstall(deInitData)function is executed. - Cleanup is performed.
- Call
Validator module implementation example
contract ECDSAValidator is IValidator {
mapping(address => address) public owners;
function onInstall(bytes calldata data) external override {
address owner = abi.decode(data, (address));
owners[msg.sender] = owner;
}
function onUninstall(bytes calldata data) external override {
delete owners[msg.sender];
}
function validateUserOp(
UserOperation calldata userOp,
bytes32 userOpHash
) external view override returns (uint256 validationData) {
address owner = owners[msg.sender];
bytes32 hash = userOpHash.toEthSignedMessageHash();
address recovered = hash.recover(userOp.signature);
if (recovered == owner) {
return 0; // Success
}
return 1; // Failure
}
function isModuleType(uint256 typeId) external pure override returns (bool) {
return typeId == 1; // Validator type
}
}Executor module implementation example
contract ScheduledExecutor is IExecutor {
struct ScheduledTask {
address target;
uint256 value;
bytes data;
uint256 executeAfter;
bool executed;
}
mapping(address => ScheduledTask[]) public tasks;
function scheduleTask(
address target,
uint256 value,
bytes calldata data,
uint256 delay
) external {
tasks[msg.sender].push(ScheduledTask({
target: target,
value: value,
data: data,
executeAfter: block.timestamp + delay,
executed: false
}));
}
function executeScheduledTask(uint256 taskId) external {
ScheduledTask storage task = tasks[msg.sender][taskId];
require(!task.executed, 'Already executed');
require(block.timestamp >= task.executeAfter, 'Too early');
task.executed = true;
IERC7579Account(msg.sender).execute(task.target, task.value, task.data);
}
function isModuleType(uint256 typeId) external pure override returns (bool) {
return typeId == 2; // Executor type
}
}Example of combining modules
// Install multiple modules in a smart account
smartAccount.installModule(1, ecdsaValidator, abi.encode(ownerAddress));
smartAccount.installModule(1, passkeyValidator, abi.encode(passkeyData));
smartAccount.installModule(2, scheduledExecutor, '');
smartAccount.installModule(2, x402PaymentExecutor, '');
smartAccount.installModule(3, erc1271Fallback, '');Benefits of this mechanism
- Flexible extensions: Add features such as x402 payments, recurring payments, and multisig as modules without replacing the existing smart account.
- Interoperability: Compatible modules can be shared across providers such as Safe, Biconomy, and ZeroDev. A module developed once can be used by multiple compatible smart accounts.
- Upgradeability: Modules can be added and removed. A vulnerable module can be removed and replaced with a newer version, subject to the account's authorization rules.
- Separation of responsibilities: Each module handles specific functionality, improving code maintainability and auditability.
Using ERC7579 with x402
An x402 payment module can be added to an AI agent's smart account.
// x402 payment module
contract X402PaymentModule is IExecutor {
function executeX402Payment(
address apiServer,
uint256 amount,
bytes calldata apiParams
) external returns (bytes memory) {
// Transfer USDC
IERC20(usdcToken).transfer(apiServer, amount);
// Invoke the API
(bool success, bytes memory result) = apiServer.call(apiParams);
require(success, 'API call failed');
return result;
}
// Implement the ERC-7579 Executor interface
function onInstall(bytes calldata data) external override {}
function onUninstall(bytes calldata data) external override {}
function isModuleType(uint256 typeId) external pure override returns (bool) {
return typeId == 2; // Executor module
}
}
// Install the module
async function installX402Module(
smartAccountAddress: string,
moduleAddress: string
) {
const txHash = await walletClient.writeContract({
address: smartAccountAddress,
abi: erc7579ABI,
functionName: 'installModule',
args: [
2n, // Executor module type
moduleAddress,
'0x' // init data
]
});
return txHash;
}Benefits
- Flexible extensions Add x402 payment functionality as a module.
- Upgradeability Modules can be added and removed.
ERC5169: Client Script URI (miniDApp integration)
ERC5169 is a standard for associating client scripts with tokens.
Key features
- scriptURI function Retrieve client script URIs from the token contract.
- miniDApp Host small DApps designed for a particular token.
- TokenScript Provide a token-specific user interface in compatible wallets.
Mechanism and flow
ERC5169 associates client-side scripts (such as JavaScript and HTML) with token contracts so compatible wallets and DApps can retrieve and execute them.
Interface definitions
interface IERC5169 {
event ScriptUpdate(string[] newScriptURI);
function scriptURI() external view returns (string[] memory);
function setScriptURI(string[] memory newScriptURI) external;
}scriptURI format
// Multiple script URIs can be returned
[
"ipfs://QmXxxx.../script.js", // IPFS
"https://example.com/token-script.js", // HTTP/HTTPS
"ar://abcd1234.../app.html" // Arweave
]Execution flow
-
Register the scripts
- The authorized token contract operator calls
setScriptURI(). - Set the list of script URIs.
- The
ScriptUpdateevent is emitted.
- The authorized token contract operator calls
-
Retrieve scripts in the wallet
- The wallet detects the token.
- Call
scriptURI()to retrieve the script URIs. - Download the scripts from the URIs.
-
Execute and render
- Verify the scripts using mechanisms such as hash or signature verification.
- Execute them in a sandboxed environment.
- Display the token-specific UI.
Security verification
The following approaches can help ensure script safety:
-
Use immutable URIs
- Use content-addressable storage such as IPFS.
- The content hash associated with the URI allows modifications to be detected.
-
Signature verification (illustrative EIP3668-related approach)
- The script provider signs the script.
- The wallet verifies the signature before executing the script.
-
Sandboxed execution
- Execute the script in an iframe and restrict access to the parent page.
- Apply a Content Security Policy (CSP).
miniDApp implementation example
contract X402APIToken is ERC20, IERC5169 {
string[] private _scriptURIs;
event ScriptUpdate(string[] newScriptURI);
constructor() ERC20('X402 API Credit', 'X402') {
_scriptURIs = new string[](2);
_scriptURIs[0] = 'ipfs://QmXxxx.../x402-ui.html';
_scriptURIs[1] = 'ipfs://QmYyyy.../x402-script.js';
}
function scriptURI() external view override returns (string[] memory) {
return _scriptURIs;
}
function setScriptURI(string[] memory newScriptURI) external override onlyOwner {
_scriptURIs = newScriptURI;
emit ScriptUpdate(newScriptURI);
}
}Client-side implementation
// Wallet: Retrieve scriptURI and load the script
async function loadTokenScript(tokenAddress: string) {
// Step 1: Retrieve scriptURI
const scriptURIs = await publicClient.readContract({
address: tokenAddress,
abi: erc5169ABI,
functionName: 'scriptURI'
});
if (!scriptURIs || scriptURIs.length === 0) {
console.log('No scripts available for this token');
return;
}
// Step 2: Retrieve the script from IPFS
const response = await fetch(scriptURIs[0]);
const scriptContent = await response.text();
// Step 3: Security verification
const isSecure = await verifyScriptSecurity(scriptContent, scriptURIs[0]);
if (!isSecure) {
console.error('Script security verification failed');
return;
}
// Step 4: Execute in a sandbox
const iframe = document.createElement('iframe');
iframe.sandbox = 'allow-scripts allow-same-origin';
iframe.srcdoc = scriptContent;
document.body.appendChild(iframe);
}
// Security verification
async function verifyScriptSecurity(
content: string,
uri: string
): Promise<boolean> {
// For an IPFS URI, verify the content hash
if (uri.startsWith('ipfs://')) {
const expectedHash = uri.replace('ipfs://', '').split('/')[0];
const actualHash = await calculateHash(content);
return expectedHash === actualHash;
}
// For an HTTPS URI, verify the signature (illustrative EIP-3668-related approach)
// ...
return true;
}TokenScript example
<!-- x402-ui.html -->
<!DOCTYPE html>
<html>
<head>
<title>X402 API Credit</title>
<script src="https://cdn.jsdelivr.net/npm/viem"></script>
</head>
<body>
<h1>X402 API Credit Manager</h1>
<div>
<h2>Balance</h2>
<p id="balance">Loading...</p>
</div>
<div>
<h2>Purchase Credits</h2>
<input type="number" id="amount" placeholder="Amount (USDC)">
<button onclick="purchaseCredits()">Buy</button>
</div>
<script>
// Retrieve the token contract address
const tokenAddress = window.parent.tokenAddress;
// Retrieve the balance
async function loadBalance() {
const balance = await readContract({
address: tokenAddress,
abi: erc20ABI,
functionName: 'balanceOf',
args: [window.ethereum.selectedAddress]
});
document.getElementById('balance').textContent = balance.toString();
}
// Purchase credits
async function purchaseCredits() {
const amount = document.getElementById('amount').value;
await writeContract({
address: tokenAddress,
abi: x402ABI,
functionName: 'purchaseCredits',
args: [parseUnits(amount, 6)]
});
await loadBalance();
}
loadBalance();
</script>
</body>
</html>Benefits of this mechanism
- Token-specific UI: Provide a dedicated interface for accessing x402 APIs, allowing users to purchase and manage API access directly in a compatible wallet.
- Wallet integration: If major wallets such as MetaMask and Trust Wallet support ERC5169, they can display a token-specific UI when the token is viewed.
- Dynamic functionality: Updating scripts with
setScriptURI()can extend client-side functionality without upgrading the token contract itself. - Improved user experience: Users can interact with tokens through a visual interface without extensive technical knowledge, lowering barriers to Web3 adoption.
Using ERC5169 with x402
Associate a miniDApp with an x402 API token to provide a user-friendly interface.
// Implement scriptURI in the x402 API token
contract X402APIToken is ERC20, IERC5169 {
string private _scriptURI;
constructor() ERC20('X402 API Credit', 'X402') {
_scriptURI = 'ipfs://QmXxxxxxx'; // IPFS URI of the miniDApp
}
function scriptURI() external view override returns (string[] memory) {
string[] memory uris = new string[](1);
uris[0] = _scriptURI;
return uris;
}
function setScriptURI(string[] memory newScriptURI) external onlyOwner {
_scriptURI = newScriptURI[0];
}
}
// Client: Load the miniDApp using scriptURI
async function loadMiniDApp(tokenAddress: string) {
const scriptURIs = await publicClient.readContract({
address: tokenAddress,
abi: erc5169ABI,
functionName: 'scriptURI'
});
// Load the miniDApp from IPFS
const response = await fetch(scriptURIs[0]);
const miniDAppCode = await response.text();
// Execute the miniDApp after security verification
// ...
}Benefits
- Token-specific UI Provide a dedicated interface for accessing x402 APIs.
- Wallet integration Display an API access interface within a compatible wallet.
Other related ERC standards
ERC-4337: Account Abstraction
Use smart contract wallets to implement more flexible payment flows. These can provide advanced features such as batch processing and gas sponsorship.
ERC-1271: Standard Signature Validation
Allows smart contract wallets to validate signatures. Can be used to authorize payments through multisig wallets and DAOs.
Use cases
The following sections describe specific use cases for x402.
Per-request API billing
Traditional API services commonly offer fixed monthly fees or usage-based billing plans. With x402, providers can charge for individual requests.
For example, an image generation API could charge 10 yen per request. Users pay only for what they need, while providers can set prices flexibly.
Autonomous payments by AI agents
When an AI agent needs to call multiple APIs to perform a task, humans have traditionally had to obtain and configure API keys in advance.
With x402, an AI agent can discover the APIs it needs, make authorized payments, and use the services. Participating services can offer access without requiring conventional account creation or API key management.
Content paywalls
Readers can be charged each time they access content such as an article or video.
Under conventional subscription models, users may have to pay a monthly fee even if they want to read only one article. x402 can support small payments for individual articles.
Monetizing microservices
In a microservice architecture, providers can charge for calls between services.
When multiple teams within an organization provide APIs to each other, this can make resource usage visible and help allocate costs appropriately.
Reselling API functionality and proxy services
Wrap existing APIs to build proxy services that provide additional value.
For example, a service could integrate multiple AI APIs and charge per request. The proxy can receive payment through x402 and forward payments to backend API providers.
Implementation ideas using AI agents
Combining x402 and ERC8004 can support an ecosystem in which AI agents make authorized payments autonomously.
This section introduces practical implementation ideas and code examples.
Autonomous API access agent
An AI agent autonomously discovers APIs, makes payments, and completes a task.
Use cases
- Call multiple AI APIs to create a data analysis report
- Combine image generation and translation APIs to create multilingual visual content
- Use weather and traffic APIs to recommend an optimal travel route
Implementation flow
sequenceDiagram
participant User as ユーザー
participant AIAgent as AI Agent
participant IdentityReg as Identity Registry
participant x402API as x402 API (画像生成)
participant USDC as USDC Contract
participant ReputationReg as Reputation Registry
User->>AIAgent: タスク依頼「猫の画像を生成して」
Note over AIAgent,IdentityReg: 初回のみ:エージェント登録
AIAgent->>IdentityReg: registerAgent()
IdentityReg-->>AIAgent: Agent NFT #456
Note over AIAgent,x402API: API発見と価格確認
AIAgent->>x402API: GET /api/generate-image
x402API-->>AIAgent: 402 Payment Required (amount: 0.1 USDC)
Note over AIAgent: 予算チェック
AIAgent->>AIAgent: タスク価値評価:0.1 USDC
AIAgent->>AIAgent: 予算確認:OK
Note over AIAgent,USDC: ガスレス決済(ERC-3009)
AIAgent->>AIAgent: EIP-712署名作成
AIAgent->>x402API: POST /api/generate-image<br/>+ Payment Signature + Agent ID #456
Note over x402API: エージェント検証
x402API->>IdentityReg: verifyAgent(#456)
IdentityReg-->>x402API: 有効
x402API->>ReputationReg: getReputation(#456)
ReputationReg-->>x402API: Score: 85/100
Note over x402API,USDC: 決済実行
x402API->>USDC: transferWithAuthorization(signature)
USDC-->>x402API: 成功
Note over x402API: 画像生成
x402API->>x402API: 画像生成処理
x402API-->>AIAgent: 画像データ
Note over AIAgent,ReputationReg: レピュテーション更新
x402API->>ReputationReg: recordCompletion(#456, task_id, true)
ReputationReg->>ReputationReg: updateScore(#456, +1)
AIAgent-->>User: 生成した猫の画像
Detailed explanation of the sequence diagram
This sequence diagram illustrates the overall flow in which an AI agent autonomously accesses APIs using x402.
1. Agent registration phase (first time only)
The AI agent first registers itself in the Identity Registry.
Calling registerAgent() in the illustrative implementation issues an NFT identifying the agent (#456 in this example).
This NFT serves as a reference to the agent's registered identity.
2. API discovery and price check phase
The AI agent sends a request to the API endpoint (GET /api/generate-image) needed to execute the task.
The API returns the 402 Payment Required status code and specifies the required payment amount (0.1 USDC).
This allows the agent to determine the cost in advance.
3. Budget check phase
The agent evaluates the value of the task and checks whether it can execute it within the previously configured budget. If the budget is insufficient, the task is aborted. This autonomous decision helps the agent avoid exceeding its budget.
4. Gasless payment phase
The agent uses ERC3009 (transferWithAuthorization) to authorize a payment without paying gas directly.
It creates an EIP712 signature and sends it with the API request.
The signed payment authorization includes fields such as the amount, recipient, nonce, and validity window. The agent ID can be supplied separately in the request.
5. Agent verification phase
The API checks the supplied agent ID (#456) against the Identity Registry. It also retrieves the agent's reputation score (85/100 in this example) using data from the Reputation Registry. An application may deny API access to agents with low scores.
6. Payment execution phase
The API or its relayer uses the signature supplied by the agent to call transferWithAuthorization() on the USDC contract.
If the authorization is valid and the other transfer conditions are met, USDC is transferred from the agent's wallet to the API's receiving address.
The agent does not have to submit the on-chain transaction itself, so it can make the payment without directly paying gas.
7. Task execution phase
Once settlement is complete, the API generates the image and returns the result to the agent.
8. Reputation update phase
After successful task completion, the API records feedback through the Reputation Registry. In this example's scoring system, the score of agent #456 increases by +1. The score can be used as a trust signal for future API interactions.
Multi-agent collaboration system
Multiple AI agents divide responsibilities to complete a large task.
Use cases
- Translation, proofreading, and layout agents collaborate to produce multilingual documents
- Data collection, analysis, and report generation agents collaborate to produce a business report
- Speech recognition, summarization, and question-answering agents collaborate to prepare meeting minutes
Implementation flow
sequenceDiagram
participant User as ユーザー
participant CoordinatorAgent as コーディネーター Agent #100
participant TranslationAgent as 翻訳 Agent #101
participant ProofreadAgent as 校正 Agent #102
participant x402Translation as x402 翻訳API
participant x402Proofread as x402 校正API
participant USDC as USDC Contract
participant ReputationReg as Reputation Registry
User->>CoordinatorAgent: タスク依頼「英語論文を日本語に翻訳して校正」
Note over CoordinatorAgent: タスク分解
CoordinatorAgent->>CoordinatorAgent: サブタスク1: 翻訳<br/>サブタスク2: 校正
Note over CoordinatorAgent,TranslationAgent: サブタスク1の委託
CoordinatorAgent->>TranslationAgent: 翻訳依頼
TranslationAgent->>x402Translation: GET /api/translate
x402Translation-->>TranslationAgent: 402 (amount: 0.5 USDC)
TranslationAgent->>TranslationAgent: EIP-712署名作成
TranslationAgent->>x402Translation: POST + Signature + Agent ID #101
x402Translation->>USDC: transferWithAuthorization()
USDC-->>x402Translation: 成功
x402Translation-->>TranslationAgent: 翻訳結果
x402Translation->>ReputationReg: recordCompletion(#101, +1)
TranslationAgent-->>CoordinatorAgent: 翻訳完了
Note over CoordinatorAgent,ProofreadAgent: サブタスク2の委託
CoordinatorAgent->>ProofreadAgent: 校正依頼
ProofreadAgent->>x402Proofread: GET /api/proofread
x402Proofread-->>ProofreadAgent: 402 (amount: 0.3 USDC)
ProofreadAgent->>ProofreadAgent: EIP-712署名作成
ProofreadAgent->>x402Proofread: POST + Signature + Agent ID #102
x402Proofread->>USDC: transferWithAuthorization()
USDC-->>x402Proofread: 成功
x402Proofread-->>ProofreadAgent: 校正結果
x402Proofread->>ReputationReg: recordCompletion(#102, +1)
ProofreadAgent-->>CoordinatorAgent: 校正完了
Note over CoordinatorAgent: タスク統合
CoordinatorAgent->>ReputationReg: recordCompletion(#100, +1)
CoordinatorAgent-->>User: 最終成果物(翻訳+校正済み論文)
Detailed explanation of the sequence diagram
This sequence diagram shows how multiple AI agents collaborate to complete a large task.
1. Task acceptance and decomposition phase
The coordinator agent (#100) receives a request from the user to translate an English paper into Japanese and proofread it. The coordinator decomposes the task into two subtasks: translation and proofreading. A specialized agent is assigned to each subtask.
2. Execute subtask 1 (translation agent)
The coordinator delegates the subtask to the translation agent (#101).
The translation agent sends a request to the x402 translation API and receives 402 Payment Required with a price of 0.5 USDC.
It creates an EIP712 signature and sends a request to the API with the payment information.
The translation API executes settlement through the USDC contract and returns the translation.
After the task is completed, feedback is recorded through the Reputation Registry, and the translation agent's (#101) example score increases by +1.
3. Execute subtask 2 (proofreading agent)
After translation is complete, the coordinator delegates the next subtask to the proofreading agent (#102).
The proofreading agent sends a request to the x402 proofreading API and receives 402 Payment Required with a price of 0.3 USDC.
It makes a payment using the same process as the translation agent and obtains the proofreading result.
After the task is completed, the proofreading agent's (#102) example score increases by +1.
4. Combine results and complete the task
The coordinator combines the translation and proofreading results to produce the final deliverable. Task completion feedback is also recorded for the coordinator through the Reputation Registry, increasing its example score by +1. The final deliverable (the translated and proofread paper) is returned to the user.
Benefits of multi-agent collaboration
- Division of responsibilities: Each agent specializes in a particular task and processes it efficiently.
- Parallel execution: Independent subtasks can run in parallel to reduce overall processing time. This example runs sequentially, but independent work can be parallelized.
- Scalability: Adding agents allows the system to handle more complex tasks.
- Reputation management: Each agent has an independent score, making trust signals visible.
Comparison with traditional payment systems
The following table summarizes the differences between x402 and traditional payment systems.
| Item | Traditional payment systems | x402 |
|---|---|---|
| Fees | Approximately 3–10% in the original comparison | Network fees, potentially below 1% of the payment (additional service fees may apply) |
| Integration complexity | High (account management, authentication, and session management) | Low for the payment protocol itself (integrated into HTTP requests) |
| Micropayment support | Difficult when fees exceed the transaction amount | Supported (well suited to small payments) |
| Machine-to-machine payments | Often requires additional integration | Supported (programmatic payments) |
| Account management | Typically required | Not required by the protocol itself |
| Payment speed | Instant to several days | Blockchain-dependent (seconds to minutes for confirmation in the original examples) |
| Privacy | Often requires personal information | Wallet-based identifiers; on-chain activity may be public |
| International transfers | Can involve exchange-rate costs and high fees | Can be used across borders, subject to applicable requirements |
Limitations of x402
x402 has the following limitations in the blockchain payment model described in this article.
- Dependence on cryptocurrency infrastructure A wallet and blockchain network are required.
- No direct fiat payments in this model Credit cards and bank transfers are not used directly in the cryptocurrency settlement examples.
- Network-specific implementation differences Implementation details differ across blockchain networks.
- An evolving ecosystem The protocol continues to evolve, and its specifications may change.
Getting started
The following resources can help you get started with x402.
Official documentation
The official documentation includes detailed specifications and implementation guides.
Quickstart guides
Quickstart guides are available for both sellers and buyers.
See the Quickstart section of the official documentation.
Tools and templates
The following tools and templates are available in the referenced ecosystem.
- MCP server integration Integration with the Model Context Protocol is supported.
- Vercel starter template Get started with a Next.js application.
- CLI tools Interact with x402 from the command line.
Community and support
x402 is an open-source project under the Apache-2.0 license. Contributions are accepted on GitHub.
At the time of the original article, Coinbase Developer Platform sponsored the documentation.
Conclusion
This article has introduced x402.







