/protected-route requires a $0.10 payment on Base Sepolia - an Agent with a test wallet pays automatically.
What it demonstrates
@x402/honomiddleware -paymentMiddleware()gates any Hono route behind a price@x402/fetch-wrapFetchWithPayment(fetch)wrapsfetchso the agent signs and pays automatically@x402/evm- EVM scheme registration for both client and server@callable- the agent exposesfetchProtectedRouteas a callable methoduseAgent+agent.call()- the React frontend triggers the paid fetch via WebSocket RPC
Architecture
Server Implementation
Gating a Route
src/server.ts
Agent That Pays
src/server.ts
How It Works
1
Server defines price
The
paymentMiddleware configures which routes require payment and at what price:2
Client makes request
The client calls the agent’s
fetchProtectedRoute method:3
Agent discovers price
When
fetchWithPay makes a request, it receives a 402 Payment Required response with payment options.4
Agent signs payment
The agent automatically:
- Selects a payment method (EVM on Base Sepolia)
- Signs a payment transaction with its private key
- Retries the request with payment headers
5
Server verifies and serves
The middleware verifies the payment signature and on-chain transaction, then serves the content.
Environment Setup
Copy.env.example to .env:
.env
Never commit real private keys! Use test keys only and get testnet funds from the Circle faucet.
Running the Example
1
Install dependencies
2
Configure environment
3
Start the server
4
Trigger payment
Open http://localhost:5173 and click “Fetch & Pay”. The agent will automatically pay and fetch the protected content.
Payment Flow Details
1. Initial Request (No Payment)
2. Server Response (402 Payment Required)
3. Client Signs Payment
The agent:- Parses the payment options
- Creates an EVM transaction
- Signs with its private key
- Submits to the blockchain
- Gets a transaction hash
4. Retry with Payment Proof
5. Server Verifies and Responds
The middleware:- Extracts the payment proof
- Verifies the transaction on-chain
- Checks amount and recipient
- Serves the content if valid
Comparison: x402 vs x402-mcp
Security Considerations
Private Key Management
- Never hardcode private keys in source code
- Use environment variables or Cloudflare secrets
- Use test keys for development, real keys only in production
- Rotate keys regularly
Payment Verification
The middleware automatically:- Verifies transaction signatures
- Checks transaction confirmation on-chain
- Validates payment amount and recipient
- Prevents replay attacks
Network Configuration
For production:- Use mainnet (
eip155:8453for Base) - Monitor payment transactions
- Set appropriate timeout values
- Handle network errors gracefully
Related Examples
x402 MCP
Paid MCP tools using Agent SDK integration
MCP Server
Build MCP servers with persistent state
GitHub Webhook
Handle webhooks with signature verification
Email Agent
Process emails with secure routing