Expand description
ยงx402 Rust Implementation
A high-performance, type-safe Rust implementation of the x402 HTTP-native micropayment protocol.
๐ First public debut at EthGlobal Online 2025
ยง๐ฆ Installation
Add this to your Cargo.toml:
[dependencies]
rust-x402 = "0.2.2"ยงโจ Features
- ๐ HTTP-native micropayments: Leverage the HTTP 402 status code for payment requirements
- โ๏ธ Blockchain integration: Support for EIP-3009 token transfers with real wallet integration
- ๐ Web framework support: Middleware for Axum, Actix Web, and Warp
- ๐ฐ Facilitator integration: Built-in support for payment verification and settlement
- ๐ฆ Standalone facilitator: Production-ready facilitator server as standalone binary
- ๐๏ธ Redis storage: Optional Redis backend for distributed nonce storage
- ๐ Type safety: Strongly typed Rust implementation with comprehensive error handling
- ๐งช Comprehensive testing: 114 tests with 100% pass rate covering all real implementations
- ๐๏ธ Real implementations: Production-ready wallet, blockchain, and facilitator clients
- ๐ Multipart & Streaming: Full support for large file uploads and streaming responses
- ๐ก HTTP/3 Support: Optional HTTP/3 (QUIC) support for modern high-performance networking
ยง๐ Quick Start
ยงCreating a Payment Server with Axum
use axum::{response::Json, routing::get};
use rust_x402::{
axum::{create_payment_app, examples, AxumPaymentConfig},
types::FacilitatorConfig,
};
use rust_decimal::Decimal;
use std::str::FromStr;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create facilitator config
let facilitator_config = FacilitatorConfig::default();
// Create payment configuration
let payment_config = AxumPaymentConfig::new(
Decimal::from_str("0.0001")?,
"0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
)
.with_description("Premium API access")
.with_facilitator_config(facilitator_config)
.with_testnet(true);
// Create the application with payment middleware
let app = create_payment_app(payment_config, |router| {
router.route("/joke", get(examples::joke_handler))
});
// Start server
let listener = tokio::net::TcpListener::bind("0.0.0.0:4021").await?;
axum::serve(listener, app).await?;
Ok(())
}ยง๐ณ Making Payments with a Client
use rust_x402::client::X402Client;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = X402Client::new()?;
// Make a request to a protected resource
let response = client.get("http://localhost:4021/joke").send().await?;
if response.status() == 402 {
println!("Payment required! Status: {}", response.status());
// Handle payment required - parse PaymentRequirements and create signed payload
// See examples/client.rs for complete implementation
} else {
let text = response.text().await?;
println!("Response: {}", text);
}
Ok(())
}ยง๐ญ Running the Standalone Facilitator Server
The facilitator can run as a standalone binary with optional Redis storage:
# In-memory storage (default)
cargo run --bin facilitator --features axum
# Redis storage backend
STORAGE_BACKEND=redis cargo run --bin facilitator --features axum,redis
# Custom configuration
BIND_ADDRESS=0.0.0.0:4020 \
REDIS_URL=redis://localhost:6379 \
REDIS_KEY_PREFIX=x402:nonce: \
cargo run --bin facilitator --features axum,redisยง๐๏ธ Architecture
The Rust implementation is organized into several modules:
- ๐ฆ
types: Core data structures and type definitions - ๐
client: HTTP client with x402 payment support - ๐ฐ
facilitator: Payment verification and settlement - ๐๏ธ
facilitator_storage: Nonce storage backends (in-memory and Redis) - ๐ง
middleware: Web framework middleware implementations - ๐
crypto: Cryptographic utilities for payment signing - โ
error: Comprehensive error handling - ๐ฆ
wallet: Real wallet integration with EIP-712 signing - โ๏ธ
blockchain: Blockchain client for network interactions - ๐ญ
blockchain_facilitator: Blockchain-based facilitator implementation - ๐ก
http3: HTTP/3 (QUIC) support (feature-gated) - ๐
proxy: Reverse proxy with streaming support
ยง๐ Supported Web Frameworks
- ๐ Axum: Modern, ergonomic web framework
- โก Actix Web: High-performance actor-based framework
- ๐ชถ Warp: Lightweight, composable web server
ยง๐ HTTP Protocol Support
- โ HTTP/1.1: Full support with chunked transfer encoding
- โ HTTP/2: Full support with multiplexing
- โ
Multipart: Support for
multipart/form-datauploads (viamultipartfeature) - โ
Streaming: Chunked and streaming responses (via
streamingfeature) - ๐ HTTP/3 (optional): QUIC-based HTTP/3 via
http3feature flag
ยง๐๏ธ Optional Features
x402 supports optional features for a modular build:
[dependencies]
rust-x402 = { version = "0.2.2", features = ["http3", "streaming", "multipart"] }http3: Enable HTTP/3 (QUIC) supportstreaming: Enable chunked and streaming responsesmultipart: Enablemultipart/form-dataupload support (requiresstreaming)redis: Enable Redis backend for facilitator storageaxum: Enable Axum web framework integration (default)actix-web: Enable Actix Web framework integrationwarp: Enable Warp web framework integration
ยงโ๏ธ Blockchain Support
Currently supports:
- ๐๏ธ Base: Base mainnet and testnet
- โ๏ธ Avalanche: Avalanche mainnet and Fuji testnet
- ๐ EIP-3009: Transfer with Authorization standard
ยง๐ Examples
See the examples/ directory for complete working examples:
- ๐
axum_server.rs: Payment server using Axum - ๐ณ
client.rs: Client making payments - ๐ฐ
facilitator.rs: Custom facilitator implementation - ๐ฆ
real_implementation_demo.rs: Real wallet and blockchain integration - ๐
real_wallet_integration.rs: Production-ready wallet integration
ยง๐๏ธ Module Structure
This project follows a clean, modular architecture for better maintainability:
src/
โโโ facilitator/ # Payment verification & settlement
โ โโโ mod.rs # Main client implementation
โ โโโ coinbase.rs # Coinbase CDP integration
โ โโโ tests.rs # Comprehensive test suite
โ
โโโ crypto/ # Cryptographic utilities
โ โโโ mod.rs # Module exports
โ โโโ jwt.rs # JWT authentication
โ โโโ eip712.rs # EIP-712 typed data hashing
โ โโโ signature.rs # ECDSA signature verification
โ โโโ tests.rs # Crypto test suite
โ
โโโ types/ # Core protocol types
โ โโโ mod.rs # Type exports
โ โโโ network.rs # Network configurations
โ โโโ payment.rs # Payment types
โ โโโ facilitator.rs # Facilitator types
โ โโโ discovery.rs # Discovery API types
โ โโโ constants.rs # Protocol constants
โ
โโโ middleware/ # Web framework middleware
โ โโโ mod.rs # Module exports
โ โโโ config.rs # Middleware configuration
โ โโโ payment.rs # Payment processing logic
โ โโโ service.rs # Tower service layer
โ โโโ tests.rs # Middleware tests
โ
โโโ ... # Other modulesBenefits:
- ๐ Clear Organization: Each module has a single, well-defined responsibility
- ๐ Easy Navigation: Find code quickly in focused, smaller files
- ๐ Self-Documenting: Rich module-level documentation in each
mod.rs - ๐งช Better Testing: Isolated test suites per module
- ๐ค Team Friendly: Reduces merge conflicts
All module documentation is embedded in the code - run cargo doc --no-deps --open to view!
ยง๐ Testing
- โ 114 tests with 100% pass rate
- ๐งช Comprehensive coverage of all real implementations
- ๐ Integration tests for end-to-end workflows
- ๐ก๏ธ Error handling tests for robust error scenarios
- ๐ Multipart & streaming tests for file upload/download scenarios
- ๐ก HTTP/3 tests (with
http3feature) - ๐๏ธ Redis storage tests with auto-skip when unavailable
- โ๏ธ Feature-gated tests for modular builds
ยง๐ License
Licensed under the Apache License, Version 2.0. See LICENSE for details.
Re-exportsยง
pub use blockchain::BlockchainClient;pub use blockchain::BlockchainClientFactory;pub use blockchain_facilitator::BlockchainFacilitatorClient;pub use blockchain_facilitator::BlockchainFacilitatorConfig;pub use blockchain_facilitator::BlockchainFacilitatorFactory;pub use client::X402Client;pub use error::Result;pub use error::X402Error;pub use wallet::Wallet;pub use wallet::WalletFactory;pub use types::*;
Modulesยง
- axum
- Axum integration for x402 payments
- blockchain
- Real blockchain integration for x402 payments
- blockchain_
facilitator - Blockchain facilitator client implementation
- client
- HTTP client with x402 payment support
- crypto
- Cryptographic utilities for x402 payments
- error
- Error types for the x402 library
- facilitator
- Facilitator client for payment verification and settlement
- facilitator_
storage - Storage trait for facilitator nonce tracking
- middleware
- Middleware implementations for web frameworks
- proxy
- Proxy server implementation for x402 payments
- server
- Unified HTTP server abstractions for x402
- template
- HTML template system for x402 paywall
- types
- Core types for the x402 protocol
- wallet
- Real wallet integration for x402 payments
Constantsยง
- VERSION
- Current version of the x402 library
- X402_
VERSION - x402 protocol version