r402_http/client/mod.rs
1//! Reqwest middleware for automatic [x402](https://www.x402.org) payment handling.
2//!
3//! This crate provides a [`X402Client`] that can be used as a `reqwest` middleware
4//! to automatically handle `402 Payment Required` responses. When a request receives
5//! a 402 response, the middleware extracts payment requirements, signs a payment,
6//! and retries the request with the payment header.
7//!
8//! ## Registering Scheme Clients
9//!
10//! The [`X402Client`] uses a plugin architecture for supporting different payment schemes.
11//! Register scheme clients for each chain/network you want to support:
12//!
13//! - **`V2Eip155ExactClient`** (from `r402-evm`) - EIP-155 chains, "exact" payment scheme
14//! - **`V2SolanaExactClient`** (from `r402-svm`) - Solana chains, "exact" payment scheme
15//!
16//! See [`X402Client::register`] for more details on registering scheme clients.
17//!
18//! ## Payment Selection
19//!
20//! When multiple payment options are available, the [`X402Client`] uses a `PaymentSelector`
21//! to choose the best option. By default, it uses `FirstMatch` which selects the first
22//! matching scheme. You can implement custom selection logic by providing your own selector.
23//!
24//! See [`X402Client::with_selector`] for custom payment selection.
25
26pub mod hooks;
27mod middleware;
28
29pub use hooks::ClientHooks;
30pub use middleware::{X402Client, parse_payment_required};
31use reqwest::Client;
32use reqwest_middleware as rqm;
33
34impl<S> X402Client<S>
35where
36 Self: rqm::Middleware,
37{
38 /// Wraps a reqwest [`Client`] with x402 payment middleware.
39 ///
40 /// Returns a [`rqm::ClientWithMiddleware`] that automatically handles
41 /// 402 Payment Required responses using registered scheme clients.
42 #[must_use]
43 pub fn wrap(self, client: Client) -> rqm::ClientWithMiddleware {
44 rqm::ClientBuilder::new(client).with(self).build()
45 }
46
47 /// Wraps a reqwest [`Client`] and returns the middleware builder
48 /// for further customization (e.g., adding more middleware).
49 #[must_use]
50 pub fn wrap_builder(self, client: Client) -> rqm::ClientBuilder {
51 rqm::ClientBuilder::new(client).with(self)
52 }
53}
54
55/// Extension trait for adding x402 payment handling to a reqwest [`Client`].
56///
57/// ```rust,ignore
58/// use r402_http::client::{WithPayments, X402Client};
59///
60/// let client = reqwest::Client::new().with_payments(x402);
61/// ```
62pub trait WithPayments {
63 /// Adds x402 payment middleware, returning a ready-to-use client.
64 fn with_payments<S>(self, x402: X402Client<S>) -> rqm::ClientWithMiddleware
65 where
66 X402Client<S>: rqm::Middleware;
67}
68
69impl WithPayments for Client {
70 fn with_payments<S>(self, x402: X402Client<S>) -> rqm::ClientWithMiddleware
71 where
72 X402Client<S>: rqm::Middleware,
73 {
74 x402.wrap(self)
75 }
76}