# x402 Rust Implementation

A **high-performance, type-safe** Rust implementation of the x402 HTTP-native micropayment protocol.
## ๐ฆ Installation
Add this to your `Cargo.toml`:
```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
```rust,no_run
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
```rust
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:
```bash
# 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-data` uploads (via `multipart` feature)
- โ
**Streaming**: Chunked and streaming responses (via `streaming` feature)
- ๐ **HTTP/3** (optional): QUIC-based HTTP/3 via `http3` feature flag
## ๐๏ธ Optional Features
x402 supports optional features for a modular build:
```toml
[dependencies]
rust-x402 = { version = "0.2.2", features = ["http3", "streaming", "multipart"] }
```
- **`http3`**: Enable HTTP/3 (QUIC) support
- **`streaming`**: Enable chunked and streaming responses
- **`multipart`**: Enable `multipart/form-data` upload support (requires `streaming`)
- **`redis`**: Enable Redis backend for facilitator storage
- **`axum`**: Enable Axum web framework integration (default)
- **`actix-web`**: Enable Actix Web framework integration
- **`warp`**: 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
## ๐ 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 `http3` feature)
- ๐๏ธ **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.