Skip to content

polyjuicelab/rust-x402

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

53 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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.

About

High-performance, type-safe Rust implementation of the x402 HTTP-native micropayment protocol

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages