1use 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#[derive(Debug, Clone)]
51pub struct X402Config {
52 pub payment_address: String,
54
55 pub token_mint: String,
57
58 pub network: String,
60
61 pub rpc_url: Option<String>,
63
64 pub auto_verify: bool,
66}
67
68#[derive(Debug, Clone)]
70pub struct PaymentRequirement {
71 pub amount: String,
73
74 pub description: Option<String>,
76
77 pub expires_in: i64,
79}
80
81impl PaymentRequirement {
82 pub fn new(amount: &str) -> Self {
84 Self {
85 amount: amount.to_string(),
86 description: None,
87 expires_in: 300,
88 }
89 }
90
91 pub fn with_description(mut self, description: &str) -> Self {
93 self.description = Some(description.to_string());
94 self
95 }
96
97 pub fn with_expires_in(mut self, seconds: i64) -> Self {
99 self.expires_in = seconds;
100 self
101 }
102}
103
104pub 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 let auth_header = match req.headers().get_one("X-Payment-Authorization") {
116 Some(h) => h,
117 None => {
118 return Outcome::Error((
120 Status::PaymentRequired,
121 X402Error::PaymentRequired("Payment authorization required".to_string()),
122 ));
123 }
124 };
125
126 match PaymentAuthorization::from_header_value(auth_header) {
128 Ok(auth) => {
129 Outcome::Success(PaymentGuard { authorization: auth })
131 }
132 Err(e) => Outcome::Error((Status::BadRequest, e)),
133 }
134 }
135}
136
137#[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
151pub 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_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}