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)
})API Reference
Endpoint Overview
Luna Protocol provides x402-enabled LLM endpoints. All calls cost $0.01 in SOL per request.
Authentication Flow
Instead of API keys, x402 uses payment-based authentication:
POST /api/x402/llm HTTP/1.1
Host: www.lunaprotocol.xyz
Content-Type: application/json
{
"model": "gpt-4",
"prompt": "Explain quantum computing"
}HTTP/1.1 402 Payment Required
Content-Type: application/json
{
"error": "Payment required",
"payment": {
"amount": "0.01",
"currency": "SOL",
"recipient": "257zPqCSGhkrFjqtRfS6sVhx33mhCrLu9uDULTNoYFKw",
"memo": "req_abc123xyz"
}
}// Make payment on Solana blockchain
const signature = await sendPayment({
amount: 0.01,
recipient: "257zPqCSGhkrFjqtRfS6sVhx33mhCrLu9uDULTNoYFKw",
memo: "req_abc123xyz"
})
// Retry with payment proof
POST /api/x402/llm HTTP/1.1
Host: www.lunaprotocol.xyz
Content-Type: application/json
X-Payment-Signature: ${signature}
{
"model": "gpt-4",
"prompt": "Explain quantum computing"
}HTTP/1.1 200 OK
Content-Type: application/json
{
"model": "gpt-4",
"response": "Quantum computing is...",
"usage": {
"prompt_tokens": 5,
"completion_tokens": 150,
"total_tokens": 155
}
}Request Format
| Header | Required | Description |
|---|---|---|
| Content-Type | Yes | application/json |
| X-Payment-Signature | After 402 | Solana transaction signature |
| Parameter | Type | Required | Description |
|---|---|---|---|
| model | string | Yes | gpt-4, claude-3, gemini-pro, llama-3, mistral, cohere |
| prompt | string | Yes | The prompt to send to the LLM |
| max_tokens | number | No | Maximum tokens in response (default: 500) |
| temperature | number | No | Sampling temperature 0-1 (default: 0.7) |
Response Format
{
"model": "gpt-4",
"response": "Generated text response...",
"usage": {
"prompt_tokens": 10,
"completion_tokens": 150,
"total_tokens": 160
},
"payment_verified": true
}{
"error": "Payment required",
"payment": {
"amount": "0.01",
"currency": "SOL",
"recipient": "257zPqCSGhkrFjqtRfS6sVhx33mhCrLu9uDULTNoYFKw",
"memo": "req_unique_id"
}
}{
"error": "Payment verification failed",
"details": "Transaction not found or insufficient amount"
}Code Examples
import { Connection, Keypair, Transaction, SystemProgram } from '@solana/web3.js'
async function callX402API(prompt: string, model: string = 'gpt-4') {
const endpoint = 'https://www.lunaprotocol.xyz/api/x402/llm'
// Step 1: Make initial request
let response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, prompt })
})
// Step 2: Handle 402 Payment Required
if (response.status === 402) {
const paymentInfo = await response.json()
// Step 3: Send payment on Solana
const connection = new Connection('https://api.mainnet-beta.solana.com')
const wallet = Keypair.fromSecretKey(/* your wallet */)
const transaction = new Transaction().add(
SystemProgram.transfer({
fromPubkey: wallet.publicKey,
toPubkey: paymentInfo.payment.recipient,
lamports: 0.01 * 1e9 // 0.01 SOL in lamports
})
)
const signature = await connection.sendTransaction(transaction, [wallet])
await connection.confirmTransaction(signature)
// Step 4: Retry with payment proof
response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Payment-Signature': signature
},
body: JSON.stringify({ model, prompt })
})
}
// Step 5: Return result
return await response.json()
}
// Usage
const result = await callX402API('Explain blockchain', 'gpt-4')
console.log(result.response)import requests
from solana.rpc.api import Client
from solana.transaction import Transaction
from solana.system_program import TransferParams, transfer
def call_x402_api(prompt: str, model: str = 'gpt-4'):
endpoint = 'https://www.lunaprotocol.xyz/api/x402/llm'
# Step 1: Make initial request
response = requests.post(endpoint, json={
'model': model,
'prompt': prompt
})
# Step 2: Handle 402 Payment Required
if response.status_code == 402:
payment_info = response.json()
# Step 3: Send payment on Solana
client = Client('https://api.mainnet-beta.solana.com')
# wallet = load_your_wallet()
tx = Transaction().add(transfer(TransferParams(
from_pubkey=wallet.public_key,
to_pubkey=payment_info['payment']['recipient'],
lamports=int(0.01 * 1e9) # 0.01 SOL
)))
signature = client.send_transaction(tx, wallet)
client.confirm_transaction(signature.value)
# Step 4: Retry with payment proof
response = requests.post(endpoint,
headers={'X-Payment-Signature': signature.value},
json={'model': model, 'prompt': prompt}
)
# Step 5: Return result
return response.json()
# Usage
result = call_x402_api('Explain blockchain', 'gpt-4')
print(result['response'])# Step 1: Initial request
curl -X POST https://www.lunaprotocol.xyz/api/x402/llm \
-H "Content-Type: application/json" \
-d '{"model":"gpt-4","prompt":"Explain blockchain"}'
# Response: 402 with payment details
# Step 2: Send payment (using Solana CLI)
solana transfer 257zPqCSGhkrFjqtRfS6sVhx33mhCrLu9uDULTNoYFKw 0.01
# Step 3: Retry with payment signature
curl -X POST https://www.lunaprotocol.xyz/api/x402/llm \
-H "Content-Type: application/json" \
-H "X-Payment-Signature: YOUR_TX_SIGNATURE" \
-d '{"model":"gpt-4","prompt":"Explain blockchain"}'Available Models
All models cost $0.01 per call regardless of tokens used.
| Model ID | Provider | Best For |
|---|---|---|
| gpt-4 | OpenAI | Complex reasoning, coding, analysis |
| claude-3 | Anthropic | Long context, creative writing |
| gemini-pro | Multimodal, research tasks | |
| llama-3 | Meta | Open source, general purpose |
| mistral | Mistral AI | Fast inference, coding |
| cohere | Cohere | Embeddings, classification |
Error Handling
Best Practices
- ✓Cache 402 responses: Store payment details to avoid redundant requests
- ✓Wait for confirmations: Ensure transaction is confirmed before retrying
- ✓Implement retries: Handle network issues and temporary failures
- ✓Monitor wallet balance: Ensure sufficient funds before making requests
- ✓Log transactions: Keep records for debugging and auditing
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