Skip to main content

x402/
lib.rs

1//! # tempo-x402
2//!
3//! **HTTP 402 Payment Required** for the Tempo blockchain.
4//!
5//! Implements pay-per-request API monetization using [EIP-712](https://eips.ethereum.org/EIPS/eip-712)
6//! signed authorizations and TIP-20 (ERC-20 compatible) token transfers on the
7//! [Tempo](https://tempo.xyz) chain. One header, one on-chain transfer, zero custodial risk.
8//!
9//! ## How it works
10//!
11//! 1. Client requests a protected endpoint
12//! 2. Server responds **402** with pricing (token, amount, recipient)
13//! 3. Client signs an EIP-712 [`PaymentAuthorization`], retries with `PAYMENT-SIGNATURE` header
14//! 4. Facilitator atomically verifies the signature, checks balance/allowance/nonce,
15//!    and calls `transferFrom` on-chain
16//! 5. Server returns the content + transaction hash
17//!
18//! The facilitator holds no user funds — it only has token approval to call
19//! `transferFrom` on behalf of clients who explicitly approved it.
20//!
21//! ## Architecture
22//!
23//! Three-party model:
24//!
25//! - **Client** ([`client::X402Client`]) — signs payment authorizations, handles the 402 retry flow
26//! - **Server** ([`scheme_server::TempoSchemeServer`]) — gates endpoints, returns 402 with pricing
27//! - **Facilitator** ([`scheme_facilitator::TempoSchemeFacilitator`]) — verifies signatures and settles on-chain
28//!
29//! ## Modules
30//!
31//! | Module | Purpose |
32//! |--------|---------|
33//! | [`constants`] | Chain configuration (ID `42431`), token address, well-known addresses |
34//! | [`eip712`] | EIP-712 typed-data signing, signature verification, nonce generation |
35//! | [`wallet`] | WASM-compatible wallet: key generation, EIP-712 signing, payment payloads |
36//! | [`client`] | Client SDK — handles 402 flow automatically |
37//! | [`scheme`] | Core trait definitions ([`scheme::SchemeClient`], [`scheme::SchemeFacilitator`], [`scheme::SchemeServer`]) |
38//! | [`scheme_server`] | Server implementation: price parsing and payment requirements |
39//! | [`scheme_facilitator`] | Facilitator implementation: signature verification and on-chain settlement |
40//! | [`tip20`] | On-chain TIP-20 token operations (balance, allowance, transfer, approve) |
41//! | [`nonce_store`] | Replay protection backends (in-memory and persistent SQLite) |
42//! | [`payment`] | Payment data structures (payloads, requirements, 402 response body) |
43//! | [`response`] | Facilitator response types (verify/settle results) |
44//! | [`hmac`] | HMAC-SHA256 for facilitator request authentication |
45//! | [`security`] | Constant-time comparison utilities |
46//! | [`network`] | SSRF protection: private IP detection, DNS validation |
47//! | [`facilitator_client`] | HTTP client for calling a remote facilitator |
48//! | [`error`] | Error types for all x402 operations |
49//!
50//! ## Quick start
51//!
52//! Parse a price and generate payment requirements:
53//!
54//! ```
55//! use x402::scheme::SchemeServer;
56//! use x402::scheme_server::TempoSchemeServer;
57//!
58//! let server = TempoSchemeServer::default();
59//! let (amount, asset) = server.parse_price("$0.001").unwrap();
60//! assert_eq!(amount, "1000"); // 1000 micro-tokens (6 decimals)
61//! ```
62//!
63//! Generate a wallet and sign a payment:
64//!
65//! ```
66//! use x402::wallet::{generate_random_key, WalletSigner};
67//!
68//! let key = generate_random_key();
69//! let signer = WalletSigner::new(&key).unwrap();
70//! let address = signer.address();
71//! ```
72//!
73//! ## Workspace crates
74//!
75//! | Crate | Purpose |
76//! |-------|---------|
77//! | **tempo-x402** (this crate) | Core library |
78//! | [`tempo-x402-gateway`](https://docs.rs/tempo-x402-gateway) | API gateway + embedded facilitator |
79//! | [`tempo-x402-identity`](https://docs.rs/tempo-x402-identity) | Agent identity: wallet, faucet, ERC-8004 |
80//! | [`tempo-x402-soul`](https://docs.rs/tempo-x402-soul) | Autonomous cognition: plans, memory, coding agent |
81//! | [`tempo-x402-node`](https://docs.rs/tempo-x402-node) | Self-deploying node with clone orchestration |
82//!
83//! ## Feature flags
84//!
85//! - **`full`** (default) — all features: async runtime, SQLite nonce store, HTTP client
86//! - **`wasm`** — WASM-compatible subset: types, EIP-712 signing, wallet (no tokio/rusqlite)
87//! - **`demo`** — includes a demo private key for testing
88//!
89//! ## Network
90//!
91//! - **Chain**: Tempo Moderato, Chain ID `42431`
92//! - **Token**: pathUSD `0x20c0000000000000000000000000000000000000` (6 decimals)
93//! - **RPC**: `https://rpc.moderato.tempo.xyz`
94
95// ---------------------------------------------------------------------------
96// Public modules — organized by layer
97// ---------------------------------------------------------------------------
98
99/// Chain configuration, token addresses, and well-known constants.
100pub mod constants;
101
102/// Error types for x402 operations.
103pub mod error;
104
105/// Payment data structures exchanged between client, server, and facilitator.
106pub mod payment;
107
108/// Facilitator response types returned after verify/settle operations.
109pub mod response;
110
111/// Core trait definitions for the three-party payment model.
112pub mod scheme;
113
114/// EIP-712 typed-data signing, signature verification, and nonce generation.
115pub mod eip712;
116
117/// WASM-compatible wallet: key generation, EIP-712 signing, payment payloads.
118pub mod wallet;
119
120/// TIP-20 (ERC-20 compatible) on-chain token operations.
121#[cfg(feature = "full")]
122pub mod tip20;
123
124/// Replay protection via nonce tracking (in-memory and persistent SQLite backends).
125#[cfg(feature = "full")]
126pub mod nonce_store;
127
128/// HMAC-SHA256 utilities for authenticating facilitator requests.
129pub mod hmac;
130
131/// Constant-time comparison utilities for timing-attack resistance.
132pub mod security;
133
134/// Network validation utilities (private IP detection for SSRF protection).
135#[cfg(feature = "full")]
136pub mod network;
137
138/// [`scheme::SchemeFacilitator`] implementation: signature verification and on-chain settlement.
139#[cfg(feature = "full")]
140pub mod scheme_facilitator;
141
142/// [`scheme::SchemeServer`] implementation: price parsing and payment requirements.
143#[cfg(feature = "full")]
144pub mod scheme_server;
145
146/// HTTP client for calling a remote facilitator's `/verify-and-settle` endpoint.
147#[cfg(feature = "full")]
148pub mod facilitator_client;
149
150/// Client SDK for making paid API requests (handles 402 flow automatically).
151#[cfg(feature = "full")]
152pub mod client;
153
154// ---------------------------------------------------------------------------
155// Solidity type bindings (generated by alloy sol! macro)
156// ---------------------------------------------------------------------------
157
158use alloy::sol;
159
160// EIP-712 struct for payment authorizations.
161//
162// The `sol!` macro derives `alloy::sol_types::SolStruct` which provides
163// `eip712_signing_hash()`. This struct is the on-chain representation of a
164// payment authorization that clients sign and facilitators verify.
165//
166sol! {
167    #[derive(Debug, serde::Serialize, serde::Deserialize)]
168    struct PaymentAuthorization {
169        address from;
170        address to;
171        uint256 value;
172        address token;
173        uint256 validAfter;
174        uint256 validBefore;
175        bytes32 nonce;
176    }
177}
178
179// TIP-20 (ERC-20 compatible) contract interface for on-chain token operations.
180//
181// Used by the `tip20` module functions to interact with the pathUSD token contract.
182#[cfg(feature = "full")]
183sol! {
184    #[sol(rpc)]
185    interface TIP20 {
186        function balanceOf(address owner) external view returns (uint256);
187        function allowance(address owner, address spender) external view returns (uint256);
188        function transferFrom(address from, address to, uint256 value) external returns (bool);
189        function approve(address spender, uint256 value) external returns (bool);
190    }
191}
192
193// ---------------------------------------------------------------------------
194// Convenience re-exports — key types available at crate root
195// ---------------------------------------------------------------------------
196
197pub use constants::ChainConfig;
198pub use error::X402Error;
199#[cfg(feature = "full")]
200pub use scheme_facilitator::TempoSchemeFacilitator;
201#[cfg(feature = "full")]
202pub use scheme_server::TempoSchemeServer;
203pub use wallet::{
204    build_payment_payload, generate_random_key, recover_message_signer, WalletSigner,
205};