System Architecture
Overview
The x402 Protocol is built on a layered architecture that separates payment logic, settlement, and application concerns - enabling instant, trustless micropayments without compromising performance or user experience.
Architecture Layers
1. Protocol Layer
The core x402 protocol that defines payment semantics, message formats, and settlement rules.
┌─────────────────────────────────────────┐
│ Application Layer │
│ (Paywalls, APIs, Tasks, Communities) │
├─────────────────────────────────────────┤
│ 402x SDK Layer │
│ (JavaScript, Python, REST clients) │
├─────────────────────────────────────────┤
│ x402 Protocol Layer │
│ (Payment verification, routing) │
├─────────────────────────────────────────┤
│ Settlement Layer │
│ (On-chain transactions, Base L2) │
├─────────────────────────────────────────┤
│ Blockchain Layer │
│ (Base, Ethereum, USDC) │
└─────────────────────────────────────────┘Core Components
Payment Request Flow
// 1. Client requests protected resource
GET /api/premium-data
// 2. Server responds with 402 Payment Required
HTTP/1.1 402 Payment Required
X-402-Price: 0.05
X-402-Currency: USDC
X-402-Address: 0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
X-402-Invoice-Id: inv_abc123
// 3. Client pays
POST /api/402x/pay
{
"invoiceId": "inv_abc123",
"signature": "0x...",
"txHash": "0x..."
}
// 4. Server verifies and delivers
HTTP/1.1 200 OK
{
"data": "premium content..."
}Settlement Engine
Instant Settlement Path:
User Payment → x402 Verifier → Smart Contract → Provider Wallet
↓
Webhook Trigger
↓
Content DeliveryKey Features:
- Sub-second payment verification
- Optimistic delivery with fraud protection
- Batched on-chain settlement for efficiency
- Automatic retry and reconciliation
Payment Verification
Verification Methods
1. Signature Verification (Instant)
import { verifyPayment } from '402x-sdk';
const isValid = await verifyPayment({
signature: request.headers['x-402-signature'],
address: request.headers['x-402-address'],
amount: expectedAmount,
nonce: request.headers['x-402-nonce']
});2. On-Chain Verification (Authoritative)
const txReceipt = await provider.getTransactionReceipt(txHash);
const isConfirmed = txReceipt.confirmations >= 1;3. Hybrid Approach (Recommended)
- Use signature verification for instant delivery
- Confirm on-chain in background
- Implement fraud detection and reversal
Smart Contract Architecture
Payment Contract
contract X402Payment {
mapping(bytes32 => Payment) public payments;
struct Payment {
address payer;
address payee;
uint256 amount;
bytes32 invoiceId;
uint256 timestamp;
PaymentStatus status;
}
enum PaymentStatus {
Pending,
Confirmed,
Refunded,
Disputed
}
function pay(
address payee,
uint256 amount,
bytes32 invoiceId
) external payable {
require(msg.value >= amount, "Insufficient payment");
payments[invoiceId] = Payment({
payer: msg.sender,
payee: payee,
amount: amount,
invoiceId: invoiceId,
timestamp: block.timestamp,
status: PaymentStatus.Confirmed
});
emit PaymentConfirmed(invoiceId, msg.sender, payee, amount);
}
function refund(bytes32 invoiceId) external {
Payment storage payment = payments[invoiceId];
require(payment.payee == msg.sender, "Not authorized");
require(payment.status == PaymentStatus.Confirmed, "Invalid status");
require(block.timestamp <= payment.timestamp + 600, "Refund window expired");
payment.status = PaymentStatus.Refunded;
payable(payment.payer).transfer(payment.amount);
emit PaymentRefunded(invoiceId);
}
}Scalability Design
Layer 2 Settlement
Why Base L2?
- Ultra-low transaction fees (~$0.001)
- Fast finality (~2 seconds)
- Ethereum security guarantees
- Native USDC support
Scaling Strategy:
┌──────────────────────────────────────┐
│ Millions of micropayments/day │
├──────────────────────────────────────┤
│ Batch Settlement (every 10 min) │
│ ↓ │
│ Base L2 (low fees, fast) │
│ ↓ │
│ Ethereum L1 (periodic checkpoints) │
└──────────────────────────────────────┘Payment Channels (Future)
For ultra-high frequency scenarios:
// Open payment channel
const channel = await openChannel({
provider: providerAddress,
deposit: 100, // USDC
duration: 86400 // 24 hours
});
// Make off-chain payments
await channel.pay(0.01); // No on-chain tx
await channel.pay(0.01);
await channel.pay(0.01);
// Settle channel
await channel.close(); // Single on-chain txData Flow
End-to-End Flow
sequenceDiagram
participant User
participant App
participant 402x
participant Base
participant Provider
User->>App: Request content
App->>User: 402 Payment Required
User->>402x: Initiate payment
402x->>Base: Submit transaction
Base-->>402x: Transaction confirmed
402x->>Provider: Webhook notification
Provider->>App: Unlock content
App->>User: Deliver contentSecurity Architecture
Multi-Layer Security
1. Transport Layer
- TLS 1.3 encryption
- Certificate pinning
- HSTS enforcement
2. Application Layer
- Request signing
- Nonce validation
- Rate limiting
- DDoS protection
3. Smart Contract Layer
- Audited contracts
- Upgradeable proxies
- Emergency pause mechanism
- Multi-sig governance
4. Fraud Detection
const fraudScore = await calculateFraudScore({
userHistory: payment.userHistory,
velocity: payment.velocity,
amount: payment.amount,
pattern: payment.pattern
});
if (fraudScore > THRESHOLD) {
await flagForReview(payment);
}State Management
Payment State Machine
┌─────────┐
│ Created │
└────┬────┘
│
↓
┌─────────┐ ┌──────────┐
│ Pending │────→│ Expired │
└────┬────┘ └──────────┘
│
↓
┌──────────┐ ┌──────────┐
│ Submitted│───→│ Failed │
└────┬─────┘ └──────────┘
│
↓
┌───────────┐ ┌──────────┐
│ Confirmed │──→│ Refunded │
└───────────┘ └──────────┘State Transitions
const states = {
CREATED: 'Payment invoice generated',
PENDING: 'Awaiting user payment',
SUBMITTED: 'Transaction submitted to chain',
CONFIRMED: 'Payment confirmed',
EXPIRED: 'Payment window expired',
FAILED: 'Transaction failed',
REFUNDED: 'Payment refunded to user'
};Caching & Performance
Multi-Tier Caching
// 1. In-memory cache (fastest)
const cachedPayment = memoryCache.get(invoiceId);
// 2. Redis cache (fast, distributed)
if (!cachedPayment) {
cachedPayment = await redis.get(`payment:${invoiceId}`);
}
// 3. Database (authoritative)
if (!cachedPayment) {
cachedPayment = await db.payments.findOne({ invoiceId });
await redis.set(`payment:${invoiceId}`, cachedPayment, 'EX', 300);
}Performance Targets
| Operation | Target | Notes |
|---|---|---|
| Payment verification | <100ms | Signature check |
| Content delivery | <200ms | After verification |
| On-chain confirmation | <5s | Base L2 finality |
| Webhook delivery | <1s | Async processing |
| API response time | <50ms | Cached responses |
Monitoring & Observability
Key Metrics
Payment Metrics:
- Payment success rate
- Average confirmation time
- Failed transaction rate
- Refund rate
- Fraud detection accuracy
System Metrics:
- API response time (p50, p95, p99)
- Throughput (payments/second)
- Error rate
- Webhook delivery success
Business Metrics:
- Total volume (USD)
- Average payment size
- Active providers
- User retention
Monitoring Stack
// OpenTelemetry integration
import { trace } from '@opentelemetry/api';
const span = trace.getTracer('402x').startSpan('process_payment');
try {
await processPayment(invoice);
span.setStatus({ code: SpanStatusCode.OK });
} catch (error) {
span.setStatus({
code: SpanStatusCode.ERROR,
message: error.message
});
throw error;
} finally {
span.end();
}Deployment Architecture
Production Infrastructure
┌─────────────┐
│ CDN │
└──────┬──────┘
│
┌──────▼──────┐
│ Load Balancer│
└──────┬──────┘
│
┌──────────────────┼──────────────────┐
│ │ │
┌────▼────┐ ┌────▼────┐ ┌────▼────┐
│ API │ │ API │ │ API │
│ Server 1│ │ Server 2│ │ Server 3│
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└──────────────────┼──────────────────┘
│
┌──────▼──────┐
│ Redis │
│ Cluster │
└──────┬──────┘
│
┌──────▼──────┐
│ PostgreSQL │
│ Primary │
└──────┬──────┘
│
┌──────▼──────┐
│ PostgreSQL │
│ Replica │
└─────────────┘High Availability
- Multi-region deployment
- Active-active configuration
- Automatic failover
- Database replication
- Circuit breakers
- Graceful degradation
Integration Patterns
Middleware Pattern
// Express.js middleware
app.use('/api/premium',
x402Middleware({ price: 0.05 }),
(req, res) => {
// Payment verified, deliver content
res.json({ data: premiumData });
}
);Decorator Pattern
# Python decorator
@require_payment(price=0.05)
def premium_endpoint():
return {"data": "premium content"}Proxy Pattern
// API Gateway proxy
const proxy = new X402Proxy({
target: 'https://api.internal.com',
pricing: {
'/premium': 0.05,
'/data': 0.01
}
});Future Architecture
Roadmap Items
Phase 1: Optimization
- Payment channel implementation
- Improved caching strategies
- Edge deployment
Phase 2: Expansion
- Multi-chain support (Optimism, Arbitrum)
- Cross-chain bridges
- Gasless transactions
Phase 3: Advanced Features
- Subscription management
- Dynamic pricing algorithms
- ML-based fraud detection
- Zero-knowledge proofs for privacy
Developer Resources
Questions?
Join our Discord to discuss architecture and implementation with the core team.