A high-performance, type-safe Rust implementation of the x402 HTTP-native micropayment protocol.
π First public debut at EthGlobal Online 2025
Add this to your Cargo.toml:
[dependencies]
rust-x402 = "0.2.2"- π 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
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(())
}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(())
}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,redisThe 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
- π Axum: Modern, ergonomic web framework
- β‘ Actix Web: High-performance actor-based framework
- πͺΆ Warp: Lightweight, composable web server
- β 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
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
Currently supports:
- ποΈ Base: Base mainnet and testnet
- βοΈ Avalanche: Avalanche mainnet and Fuji testnet
- π EIP-3009: Transfer with Authorization standard
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
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 modules
Benefits:
- π 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!
- β 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
Licensed under the Apache License, Version 2.0. See LICENSE for details.
