Crate rust_x402

Crate rust_x402 

Source
Expand description

ยงx402 Rust Implementation

x402 Logo

CI docs.rs License Version

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-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:

[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

ยง๐Ÿ—๏ธ 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 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!

ยง๐Ÿ“Š 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.

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