r402_http/server/mod.rs
1//! Axum middleware for enforcing [x402](https://www.x402.org) payments on protected routes (V2-only).
2//!
3//! This middleware validates incoming payment headers using a configured x402 facilitator,
4//! verifies the payment, executes the request, and settles valid payments after successful
5//! execution. If the handler returns an error (4xx/5xx), settlement is skipped.
6//!
7//! Returns a `402 Payment Required` response if the request lacks a valid payment.
8//!
9//! See [`X402Middleware`] for full configuration options.
10//! For low-level interaction with the facilitator, see [`facilitator::FacilitatorClient`].
11//!
12//! ## Configuration Notes
13//!
14//! - **[`X402Middleware::with_price_tag`]** sets the assets and amounts accepted for payment (static pricing).
15//! - **[`X402Middleware::with_dynamic_price`]** sets a callback for dynamic pricing based on request context.
16//! - **[`X402Middleware::with_base_url`]** sets the base URL for computing full resource URLs.
17//! If not set, defaults to `http://localhost/` (avoid in production).
18//! - **[`X402Middleware::with_supported_cache_ttl`]** configures the TTL for caching facilitator capabilities.
19//! - **[`X402Middleware::with_facilitator_timeout`]** sets a per-request timeout for facilitator HTTP calls.
20//! - **[`X402LayerBuilder::with_description`]** is optional but helps the payer understand what is being paid for.
21//! - **[`X402LayerBuilder::with_mime_type`]** sets the MIME type of the protected resource (default: `application/json`).
22//! - **[`X402LayerBuilder::with_resource`]** explicitly sets the full URI of the protected resource.
23
24pub mod facilitator;
25pub mod layer;
26pub mod paygate;
27pub mod pricing;
28
29pub use layer::{X402LayerBuilder, X402Middleware};
30pub use pricing::{DynamicPriceTags, PriceTagSource, StaticPriceTags};
31
32/// Common verification errors shared between protocol versions.
33#[derive(Debug, thiserror::Error)]
34pub enum VerificationError {
35 /// Required payment header is missing.
36 #[error("{0} header is required")]
37 PaymentHeaderRequired(&'static str),
38 /// Payment header is present but malformed.
39 #[error("Invalid or malformed payment header")]
40 InvalidPaymentHeader,
41 /// No matching payment requirements found.
42 #[error("Unable to find matching payment requirements")]
43 NoPaymentMatching,
44 /// Verification with facilitator failed.
45 #[error("Verification failed: {0}")]
46 VerificationFailed(String),
47}
48
49/// Paygate error type that wraps verification and settlement errors.
50#[derive(Debug, thiserror::Error)]
51pub enum PaygateError {
52 /// Payment verification failed.
53 #[error(transparent)]
54 Verification(#[from] VerificationError),
55 /// On-chain settlement failed.
56 #[error("Settlement failed: {0}")]
57 Settlement(String),
58}