Luna Protocol x402
Transforming HTTP status code 402 from a reserved placeholder into a functional payment protocol for the AI agent economy.
Introduction
What is x402?
x402 is a standardized way to request and process payments directly within HTTP communication. It enables:
- •Programmatic payments - No human intervention required
- •Instant settlement - Blockchain-backed transactions in seconds
- •Frictionless access - No accounts, forms, or KYC
- •Micropayment support - Economically viable for tiny amounts ($0.001+)
Why Luna Protocol?
Luna Protocol provides the infrastructure layer that makes x402 practical: payment verification system, multi-chain support (Solana, Base, Ethereum L2s), agent wallet management, transaction monitoring, and developer tools and SDKs.
The Problem
The AI Agent Economy is Here
AI agents are rapidly becoming autonomous actors on the internet:
- →Research agents gathering data from multiple sources
- →Shopping agents comparing prices and making purchases
- →API orchestrators calling dozens of services
- →Data processors accessing premium datasets
- →Workflow automators coordinating complex tasks
Traditional Payments Don't Work for Agents
❌ Credit cards require:
- • Manual entry of 16-digit numbers
- • Expiration dates and CVV codes
- • Billing addresses
- • Human verification (CAPTCHA, 2FA)
❌ Payment processors require:
- • Account creation
- • Email verification
- • Identity verification (KYC)
- • Terms of service acceptance
❌ Current systems have:
- • High per-transaction fees ($0.30+ making $0.01 payments impossible)
- • Slow settlement (2-3 business days)
- • Geographic restrictions
- • Fraud detection that blocks automated behavior
The Gap
There's a fundamental mismatch:
Agents need: Instant, programmatic, permissionless payments
Internet has: Human-oriented payment systems designed in the 1990s
x402 bridges this gap.
The Solution
Core Concept
Make payments as simple as HTTP requests by using HTTP itself.
Native HTTP Integration
Uses existing HTTP status code 402. Works with standard web infrastructure.
Blockchain Settlement
Payments settle on-chain. Cryptographically verifiable, no intermediaries.
Zero Friction
No accounts or signup. Agent pays automatically with instant verification.
Micropayment Friendly
Pay for exactly what you use. $0.001 per API call is economical.
How It Works
High-Level Flow
┌─────────────┐ ┌─────────────┐
│ Client │ │ Server │
│ (AI Agent) │ │ (API) │
└──────┬──────┘ └──────┬──────┘
│ │
│ 1. GET /premium-data │
├─────────────────────────────────>│
│ │
│ 2. HTTP 402 + Payment Details │
│<─────────────────────────────────┤
│ │
│ 3. Send Payment On-Chain │
├──────────┐ │
│ │ (Blockchain) │
│<─────────┘ │
│ │
│ 4. GET /premium-data │
│ X-Payment-Tx: abc123 │
├─────────────────────────────────>│
│ │
│ 5. Verify Payment On-Chain │
│ ┌────────┤
│ └───────>│
│ │
│ 6. HTTP 200 + Data │
│<─────────────────────────────────┤Initial Request
Agent makes a standard HTTP GET request to a paid endpoint.
GET /api/premium-data HTTP/1.1 Host: api.example.com User-Agent: Luna-AI-Agent/1.0
Server Returns 402
Server responds with HTTP 402 and payment details in JSON.
HTTP/1.1 402 Payment Required
Content-Type: application/json
{
"status": 402,
"message": "Payment required",
"payment": {
"price": "0.01",
"currency": "USDC",
"chain": "solana",
"recipient": "LunaPayments9xQrH7K...",
"request_id": "req_7h4k2n9"
}
}Agent Pays
Agent's wallet automatically constructs and broadcasts a blockchain transaction.
const payment = await agentWallet.sendPayment({
amount: 0.01,
currency: "USDC",
recipient: "LunaPayments9xQrH7K...",
memo: "req_7h4k2n9"
})
const txHash = payment.transactionHashRetry with Proof
Agent retries the original request with payment proof in headers.
GET /api/premium-data HTTP/1.1 Host: api.example.com X-Payment-Tx: 5qJ7K9mN2pL4rT8wX... X-Request-Id: req_7h4k2n9
Server Verifies
Server checks the blockchain to verify transaction validity.
const tx = await blockchain.getTransaction(txHash) const isValid = ( tx.confirmed && tx.amount >= requiredAmount && tx.recipient === ourWallet && tx.memo === requestId )
Data Delivered
If payment is valid, server returns the requested data.
HTTP/1.1 200 OK
Content-Type: application/json
{
"data": { "premium_content": "..." },
"payment_verified": true
}Technical Architecture
System Components
Payment Gateway
Handles 402 responses, generates payment requests, calculates pricing, and manages rate limiting.
Verification Service
Verifies blockchain transactions, validates parameters, checks confirmations, and prevents replay attacks.
Wallet Management
Manages payment wallets for agents, handles balance checking, transaction signing, and multi-chain support.
Database Layer
Tracks payments, prevents fraud, stores payment requests, and maintains verified payment records.
Implementation Examples
Client-Side (Agent)
import { LunaAgent } from '@luna-protocol/agent-sdk'
const agent = new LunaAgent({
wallet: myWallet,
autoPayThreshold: 1.00
})
// Agent automatically handles 402 responses
const response = await agent.fetch(
'https://api.example.com/premium-data'
)
const data = await response.json()Server-Side (API Provider)
import { LunaServer } from '@luna-protocol/server-sdk'
const luna = new LunaServer({ wallet: serverWallet })
app.get('/premium-data', async (req, res) => {
const paymentTx = req.headers['x-payment-tx']
if (paymentTx) {
const isValid = await luna.verifyPayment({
transactionHash: paymentTx,
expectedAmount: 0.01
})
if (isValid) {
return res.json({ data: getPremiumData() })
}
}
// Return 402 with payment details
const paymentRequest = await luna.createPaymentRequest({
price: 0.01,
currency: 'USDC'
})
return res.status(402).json(paymentRequest)
})Security Considerations
Anti-Replay Attacks
Each request_id can only be used once. Track all used IDs in database and mark as used after successful verification.
async function verifyPayment(txHash, requestId) {
// Check if already used
if (await isRequestIdUsed(requestId)) {
throw new Error('Payment already claimed')
}
const isValid = await verifyOnChain(txHash, requestId)
if (isValid) {
await markRequestIdUsed(requestId)
return true
}
return false
}Must Verify ✅
- ✅ Transaction exists on blockchain
- ✅ Transaction is confirmed
- ✅ Amount equals or exceeds price
- ✅ Recipient address matches
- ✅ Request ID in memo matches
- ✅ Payment not already used
- ✅ Payment within time window
Never Trust ❌
- ❌ Client-provided transaction data
- ❌ Unconfirmed transactions
- ❌ Partial payments
- ❌ Expired payment windows
- ❌ Reused payment proofs
- ❌ Wrong recipient addresses
- ❌ Missing request IDs
Best Practices
- →Use dedicated payment wallets (not main treasury)
- →Implement withdrawal limits and rate limiting
- →Monitor for unusual patterns
- →Regular wallet rotation for security
- →Multi-sig for large amounts
Ready to Build with x402?
Try the interactive demo or explore the full technical specification