rust-x402 0.1.0

HTTP-native micropayments with x402 protocol
Documentation

x402 Logo

x402 Rust Implementation

Crates.io Documentation License Rust GitHub

A high-performance, type-safe Rust implementation of the x402 HTTP-native micropayment protocol.

Features โ€ข Quick Start โ€ข Examples โ€ข Documentation

๐Ÿ“ฆ Installation

Add this to your Cargo.toml:

[dependencies]
rust-x402 = "0.1.0"

โœจ 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
  • ๐Ÿ”’ Type safety: Strongly typed Rust implementation with comprehensive error handling
  • ๐Ÿงช Comprehensive testing: 62+ tests with 100% pass rate covering all real implementations
  • ๐Ÿ—๏ธ Real implementations: Production-ready wallet, blockchain, and facilitator clients

๐Ÿš€ Quick Start

Creating a Payment Server with Axum

use axum::{
    extract::State,
    http::StatusCode,
    response::Json,
    routing::get,
    Router,
};
use rust_x402::{
    axum::PaymentMiddleware,
    types::{PaymentRequirements, FacilitatorConfig},
};
use std::sync::Arc;

#[tokio::main]
async fn main() {
    // Create facilitator config
    let facilitator_config = FacilitatorConfig::default();
    
    // Create payment middleware
    let payment_middleware = PaymentMiddleware::new(
        rust_decimal::Decimal::from_str("0.0001").unwrap(),
        "0x209693Bc6afc0C5328bA36FaF03C514EF312287C".to_string(),
    )
    .with_facilitator_config(facilitator_config)
    .with_description("Premium API access".to_string());

    // Create router with payment middleware
    let app = Router::new()
        .route("/joke", get(joke_handler))
        .layer(payment_middleware);

    // Start server
    let listener = tokio::net::TcpListener::bind("0.0.0.0:4021").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn joke_handler() -> Result<Json<serde_json::Value>, StatusCode> {
    Ok(Json(serde_json::json!({
        "joke": "Why do programmers prefer dark mode? Because light attracts bugs!"
    })))
}

๐Ÿ’ณ Making Payments with a Client

use rust_x402::client::X402Client;
use rust_x402::types::{PaymentPayload, PaymentRequirements};

#[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").await?;
    
    if response.status() == 402 {
        // Handle payment required response
        let payment_req = response.json::<PaymentRequirements>().await?;
        
        // Create and sign payment payload (implementation depends on wallet integration)
        let payment_payload = create_payment_payload(&payment_req)?;
        
        // Retry request with payment
        let final_response = client
            .get("http://localhost:4021/joke")
            .header("X-PAYMENT", encode_payment_payload(&payment_payload)?)
            .send()
            .await?;
            
        println!("Response: {}", final_response.text().await?);
    }
    
    Ok(())
}

๐Ÿ—๏ธ 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
  • ๐Ÿ”ง 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
  • ๐Ÿญ real_facilitator: Production-ready facilitator implementation

๐ŸŒ Supported Web Frameworks

  • ๐Ÿš€ Axum: Modern, ergonomic web framework
  • โšก Actix Web: High-performance actor-based framework
  • ๐Ÿชถ Warp: Lightweight, composable web server

โ›“๏ธ 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

  • โœ… 62+ 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

๐Ÿ“„ License

Licensed under the Apache License, Version 2.0. See LICENSE for details.