Skip to main content

fly402_rocket/
lib.rs

1//! # 402fly Rocket
2//!
3//! Rocket web framework integration for the 402fly payment protocol.
4//!
5//! This library provides guards and utilities to protect Rocket endpoints
6//! with payment requirements using the 402fly protocol.
7//!
8//! ## Example
9//!
10//! ```rust,no_run
11//! use rocket::{get, routes, State};
12//! use fly402_rocket::{PaymentGuard, X402Config};
13//!
14//! #[get("/premium-data")]
15//! fn premium_data(_auth: PaymentGuard) -> &'static str {
16//!     "Premium content!"
17//! }
18//!
19//! #[rocket::main]
20//! async fn main() {
21//!     let config = X402Config {
22//!         payment_address: "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU".to_string(),
23//!         token_mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".to_string(),
24//!         network: "solana-devnet".to_string(),
25//!         rpc_url: None,
26//!         auto_verify: true,
27//!     };
28//!
29//!     rocket::build()
30//!         .manage(config)
31//!         .mount("/", routes![premium_data])
32//!         .launch()
33//!         .await
34//!         .unwrap();
35//! }
36//! ```
37
38use chrono::{Duration, Utc};
39use fly402_core::{PaymentAuthorization, PaymentRequest, X402Error};
40use rocket::{
41    http::Status,
42    request::{FromRequest, Outcome, Request},
43    response::Responder,
44    serde::json::Json,
45};
46use serde::{Deserialize, Serialize};
47use uuid::Uuid;
48
49/// Global X402 configuration
50#[derive(Debug, Clone)]
51pub struct X402Config {
52    /// Wallet address to receive payments
53    pub payment_address: String,
54
55    /// SPL token mint address (USDC)
56    pub token_mint: String,
57
58    /// Solana network (e.g., "solana-devnet", "solana-mainnet")
59    pub network: String,
60
61    /// Optional custom RPC URL
62    pub rpc_url: Option<String>,
63
64    /// Whether to verify payments on-chain
65    pub auto_verify: bool,
66}
67
68/// Payment requirement configuration for a specific endpoint
69#[derive(Debug, Clone)]
70pub struct PaymentRequirement {
71    /// Amount required in USDC
72    pub amount: String,
73
74    /// Optional description
75    pub description: Option<String>,
76
77    /// Expiration time in seconds (default: 300)
78    pub expires_in: i64,
79}
80
81impl PaymentRequirement {
82    /// Create a new payment requirement
83    pub fn new(amount: &str) -> Self {
84        Self {
85            amount: amount.to_string(),
86            description: None,
87            expires_in: 300,
88        }
89    }
90
91    /// Set the description
92    pub fn with_description(mut self, description: &str) -> Self {
93        self.description = Some(description.to_string());
94        self
95    }
96
97    /// Set the expiration time
98    pub fn with_expires_in(mut self, seconds: i64) -> Self {
99        self.expires_in = seconds;
100        self
101    }
102}
103
104/// Request guard that enforces payment requirements
105pub struct PaymentGuard {
106    pub authorization: PaymentAuthorization,
107}
108
109#[rocket::async_trait]
110impl<'r> FromRequest<'r> for PaymentGuard {
111    type Error = X402Error;
112
113    async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
114        // Get payment authorization header
115        let auth_header = match req.headers().get_one("X-Payment-Authorization") {
116            Some(h) => h,
117            None => {
118                // No payment provided, return 402 with payment request
119                return Outcome::Error((
120                    Status::PaymentRequired,
121                    X402Error::PaymentRequired("Payment authorization required".to_string()),
122                ));
123            }
124        };
125
126        // Parse authorization
127        match PaymentAuthorization::from_header_value(auth_header) {
128            Ok(auth) => {
129                // TODO: Verify payment if auto_verify is enabled
130                Outcome::Success(PaymentGuard { authorization: auth })
131            }
132            Err(e) => Outcome::Error((Status::BadRequest, e)),
133        }
134    }
135}
136
137/// Response type for 402 Payment Required
138#[derive(Debug, Serialize, Deserialize)]
139pub struct PaymentRequiredResponse {
140    pub payment_request: PaymentRequest,
141}
142
143impl<'r, 'o: 'r> Responder<'r, 'o> for PaymentRequiredResponse {
144    fn respond_to(self, req: &'r Request<'_>) -> rocket::response::Result<'o> {
145        rocket::response::Response::build_from(Json(self.payment_request).respond_to(req)?)
146            .status(Status::PaymentRequired)
147            .ok()
148    }
149}
150
151/// Create a payment request for an endpoint
152pub fn create_payment_request(
153    config: &X402Config,
154    requirement: &PaymentRequirement,
155    resource: &str,
156) -> PaymentRequest {
157    let expires_at = Utc::now() + Duration::seconds(requirement.expires_in);
158    let payment_id = Uuid::new_v4().to_string();
159    let nonce = Uuid::new_v4().to_string();
160
161    let mut request = PaymentRequest::new(
162        requirement.amount.clone(),
163        config.token_mint.clone(),
164        config.payment_address.clone(),
165        config.network.clone(),
166        expires_at,
167        nonce,
168        payment_id,
169        resource.to_string(),
170    );
171
172    if let Some(desc) = &requirement.description {
173        request = request.with_description(desc.clone());
174    }
175
176    request
177}
178
179/// Macro to create a payment-protected route handler
180#[macro_export]
181macro_rules! payment_required {
182    ($amount:expr) => {
183        $crate::PaymentRequirement::new($amount)
184    };
185    ($amount:expr, $description:expr) => {
186        $crate::PaymentRequirement::new($amount).with_description($description)
187    };
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn test_payment_requirement() {
196        let req = PaymentRequirement::new("0.10")
197            .with_description("Premium data access")
198            .with_expires_in(600);
199
200        assert_eq!(req.amount, "0.10");
201        assert_eq!(req.description, Some("Premium data access".to_string()));
202        assert_eq!(req.expires_in, 600);
203    }
204
205    #[test]
206    fn test_create_payment_request() {
207        let config = X402Config {
208            payment_address: "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU".to_string(),
209            token_mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v".to_string(),
210            network: "solana-devnet".to_string(),
211            rpc_url: None,
212            auto_verify: false,
213        };
214
215        let requirement = PaymentRequirement::new("0.10");
216        let request = create_payment_request(&config, &requirement, "/api/premium");
217
218        assert_eq!(request.max_amount_required, "0.10");
219        assert_eq!(request.payment_address, config.payment_address);
220        assert_eq!(request.asset_address, config.token_mint);
221    }
222}