r402-casper 0.15.0

Casper chain support for the x402 payment protocol.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Facilitator-side verification and settlement for the Casper exact scheme.
//!
//! Casper settlement is executed by a facilitator that holds a funded Casper
//! account and a node connection: it relays the buyer's signed EIP-712
//! authorisation to the CEP-18 token's `transfer_with_authorization` entry
//! point and pays the gas. The Casper Association operates a hosted instance
//! at <https://x402-facilitator.cspr.cloud> (documented at
//! <https://docs.cspr.cloud>).
//!
//! [`CasperExactFacilitator`] implements [`Facilitator`] against such a
//! service, so a Casper chain plugs into the same registry, hook pipeline,
//! and Axum middleware as the EVM and SVM crates. Every request is validated
//! locally first (see [`crate::exact::verify`]) so a malformed payment is
//! rejected with a precise typed error instead of an opaque remote failure.

mod config;
#[cfg(feature = "http-client")]
mod transport;

use std::time::Duration;

pub use config::{
    CasperFacilitatorConfig, CasperFacilitatorConfigError, DEFAULT_FACILITATOR_URL,
    FACILITATOR_URL_ENV,
};
use r402_core::error::VerificationError;
use r402_core::facilitator::{Facilitator, FacilitatorError};
use r402_core::wire;
#[cfg(feature = "http-client")]
pub use transport::ReqwestTransport;

use crate::exact::types::v2;
use crate::exact::verify::validate_request;

/// Facilitator for Casper exact scheme payments backed by a remote x402
/// facilitator service.
#[derive(Debug, Clone)]
pub struct CasperExactFacilitator<T> {
    config: CasperFacilitatorConfig,
    transport: T,
}

/// Transport abstraction over the facilitator's HTTP surface.
///
/// Implemented for any HTTP stack the host application already uses; r402
/// therefore does not force a specific client (or TLS backend) on downstream
/// consumers of this crate.
///
/// Callers MUST honour `timeout` (from [`CasperFacilitatorConfig::timeout`])
/// so that operator configuration is not silently ignored.
pub trait FacilitatorTransport: Send + Sync {
    /// Sends a `POST` with a JSON body and returns the JSON response.
    fn post_json(
        &self,
        url: &url::Url,
        body: serde_json::Value,
        timeout: Duration,
    ) -> impl Future<Output = Result<serde_json::Value, FacilitatorError>> + Send;

    /// Sends a `GET` and returns the JSON response.
    fn get_json(
        &self,
        url: &url::Url,
        timeout: Duration,
    ) -> impl Future<Output = Result<serde_json::Value, FacilitatorError>> + Send;
}

impl<T> CasperExactFacilitator<T> {
    /// Creates a facilitator with an explicit configuration and transport.
    pub const fn new(config: CasperFacilitatorConfig, transport: T) -> Self {
        Self { config, transport }
    }

    /// Creates a facilitator pointing at the hosted Casper facilitator.
    pub fn hosted(transport: T) -> Self {
        Self::new(CasperFacilitatorConfig::default(), transport)
    }

    /// Creates a facilitator configured from the environment.
    ///
    /// # Errors
    ///
    /// Returns [`CasperFacilitatorConfigError`] when
    /// [`FACILITATOR_URL_ENV`] is set to an invalid URL.
    pub fn from_env(transport: T) -> Result<Self, CasperFacilitatorConfigError> {
        Ok(Self::new(CasperFacilitatorConfig::from_env()?, transport))
    }

    /// Returns the active configuration.
    #[must_use]
    pub const fn config(&self) -> &CasperFacilitatorConfig {
        &self.config
    }

    /// Runs the local pre-flight validation pass, if enabled.
    ///
    /// # Errors
    ///
    /// Returns the typed [`VerificationError`] for the first failed check.
    fn preflight(&self, request: &serde_json::Value) -> Result<(), VerificationError> {
        if !self.config.validate_locally {
            return Ok(());
        }
        let typed = v2::VerifyRequest::from_verify(wire::VerifyRequest::from(request.clone()))?;
        validate_request(&typed).map_err(VerificationError::from)?;
        Ok(())
    }
}

#[cfg(feature = "http-client")]
impl CasperExactFacilitator<ReqwestTransport> {
    /// Hosted facilitator with the default `reqwest` transport.
    #[must_use]
    pub fn hosted_http() -> Self {
        Self::hosted(ReqwestTransport::new())
    }

    /// Environment-configured facilitator with the default `reqwest` transport.
    ///
    /// # Errors
    ///
    /// Returns [`CasperFacilitatorConfigError`] when
    /// [`FACILITATOR_URL_ENV`] is set to an invalid URL.
    pub fn from_env_http() -> Result<Self, CasperFacilitatorConfigError> {
        Self::from_env(ReqwestTransport::new())
    }
}

impl<T> Facilitator for CasperExactFacilitator<T>
where
    T: FacilitatorTransport,
{
    async fn verify(
        &self,
        request: wire::VerifyRequest,
    ) -> Result<wire::VerifyResponse, FacilitatorError> {
        let body = request.into_json();
        self.preflight(&body)?;
        let response = self
            .transport
            .post_json(&self.config.verify_url(), body, self.config.timeout)
            .await?;
        serde_json::from_value(response)
            .map_err(|e| FacilitatorError::from(VerificationError::InvalidFormat(e.to_string())))
    }

    async fn settle(
        &self,
        request: wire::SettleRequest,
    ) -> Result<wire::SettleResponse, FacilitatorError> {
        let body = request.into_json();
        self.preflight(&body)?;
        let response = self
            .transport
            .post_json(&self.config.settle_url(), body, self.config.timeout)
            .await?;
        serde_json::from_value(response)
            .map_err(|e| FacilitatorError::from(VerificationError::InvalidFormat(e.to_string())))
    }

    async fn supported(&self) -> Result<wire::SupportedResponse, FacilitatorError> {
        let response = self
            .transport
            .get_json(&self.config.supported_url(), self.config.timeout)
            .await?;
        serde_json::from_value(response)
            .map_err(|e| FacilitatorError::from(VerificationError::InvalidFormat(e.to_string())))
    }
}

#[allow(
    clippy::indexing_slicing,
    reason = "tests index serde_json values; panic-on-missing-key is the desired assertion behaviour"
)]
#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use r402_core::error_reason::ErrorReason;

    use super::*;

    /// Secp256k1 fixture from `scheme_exact_casper.md` (publicKey → from).
    const PAYER: &str = "0076d080b4e769f0b29c77fc6472d6e425710840c2f46a4506e5544d2ce34f43a3";
    const PUBLIC_KEY: &str = "020376e4f8766e4f33bcc6e20b331b5163f363dc0106063b052ad38afe08637bd867";
    const PAYEE: &str = "00fedcba0987654321fedcba0987654321fedcba0987654321fedcba0987654321";
    const ASSET: &str = "3d80df21ba4ee4d66a2a1f60c32570dd5685e4b279f6538162a5fd1314847c1e";

    /// Records the URLs + timeouts it was called with and replays a canned response.
    #[derive(Debug)]
    struct MockTransport {
        response: serde_json::Value,
        calls: Mutex<Vec<(String, Duration)>>,
    }

    impl MockTransport {
        fn new(response: serde_json::Value) -> Self {
            Self {
                response,
                calls: Mutex::new(Vec::new()),
            }
        }

        fn call_urls(&self) -> Vec<String> {
            self.calls
                .lock()
                .unwrap()
                .iter()
                .map(|(url, _)| url.clone())
                .collect()
        }

        fn call_timeouts(&self) -> Vec<Duration> {
            self.calls
                .lock()
                .unwrap()
                .iter()
                .map(|(_, timeout)| *timeout)
                .collect()
        }
    }

    impl FacilitatorTransport for MockTransport {
        fn post_json(
            &self,
            url: &url::Url,
            _body: serde_json::Value,
            timeout: Duration,
        ) -> impl Future<Output = Result<serde_json::Value, FacilitatorError>> {
            self.calls.lock().unwrap().push((url.to_string(), timeout));
            std::future::ready(Ok(self.response.clone()))
        }

        fn get_json(
            &self,
            url: &url::Url,
            timeout: Duration,
        ) -> impl Future<Output = Result<serde_json::Value, FacilitatorError>> {
            self.calls.lock().unwrap().push((url.to_string(), timeout));
            std::future::ready(Ok(self.response.clone()))
        }
    }

    fn requirements(amount: &str) -> serde_json::Value {
        serde_json::json!({
            "scheme": "exact",
            "network": "casper:casper-test",
            "amount": amount,
            "payTo": PAYEE,
            "maxTimeoutSeconds": 300,
            "asset": ASSET,
            "extra": { "name": "Wrapped CSPR", "version": "1" }
        })
    }

    fn verify_request(amount: &str, valid_before: u64) -> wire::VerifyRequest {
        let requirements = requirements(amount);
        wire::VerifyRequest::from(serde_json::json!({
            "x402Version": 2,
            "paymentPayload": {
                "x402Version": 2,
                "accepted": requirements,
                "payload": {
                    "signature": format!("02{}", "aa".repeat(64)),
                    "publicKey": PUBLIC_KEY,
                    "authorization": {
                        "from": PAYER,
                        "to": PAYEE,
                        "value": amount,
                        "validAfter": "0",
                        "validBefore": valid_before.to_string(),
                        "nonce": "cc".repeat(32),
                    }
                }
            },
            "paymentRequirements": requirements
        }))
    }

    fn far_future() -> u64 {
        crate::exact::verify::now_unix() + 600
    }

    #[tokio::test]
    async fn verify_posts_to_the_configured_verify_endpoint() {
        let transport = MockTransport::new(serde_json::json!({
            "isValid": true,
            "payer": PAYER
        }));
        let facilitator = CasperExactFacilitator::hosted(transport);
        let response = facilitator
            .verify(verify_request("1500000000", far_future()))
            .await
            .unwrap();
        assert!(response.is_valid());
        assert_eq!(
            facilitator.transport.call_urls(),
            vec!["https://x402-facilitator.cspr.cloud/verify".to_owned()]
        );
        assert_eq!(
            facilitator.transport.call_timeouts(),
            vec![Duration::from_secs(30)]
        );
    }

    #[tokio::test]
    async fn settle_posts_to_the_configured_settle_endpoint() {
        let transport = MockTransport::new(serde_json::json!({
            "success": true,
            "payer": PAYER,
            "transaction": "9f".repeat(32),
            "network": "casper:casper-test",
            "amount": "1500000000"
        }));
        let facilitator = CasperExactFacilitator::hosted(transport);
        let request =
            wire::SettleRequest::from(verify_request("1500000000", far_future()).into_json());
        let response = facilitator.settle(request).await.unwrap();
        assert!(response.is_success());
        assert_eq!(
            facilitator.transport.call_urls(),
            vec!["https://x402-facilitator.cspr.cloud/settle".to_owned()]
        );
    }

    #[tokio::test]
    async fn supported_gets_the_supported_endpoint() {
        let transport = MockTransport::new(serde_json::json!({
            "kinds": [{
                "x402Version": 2,
                "scheme": "exact",
                "network": "casper:casper-test",
                "extra": { "feePayer": PAYEE }
            }]
        }));
        let facilitator = CasperExactFacilitator::hosted(transport);
        let response = facilitator.supported().await.unwrap();
        assert_eq!(response.kinds.len(), 1);
        assert_eq!(response.kinds[0].network, "casper:casper-test");
        assert_eq!(
            facilitator.transport.call_urls(),
            vec!["https://x402-facilitator.cspr.cloud/supported".to_owned()]
        );
    }

    #[tokio::test]
    async fn preflight_rejects_expired_payments_without_a_round_trip() {
        let transport = MockTransport::new(serde_json::json!({ "isValid": true, "payer": PAYER }));
        let facilitator = CasperExactFacilitator::hosted(transport);
        let error = facilitator
            .verify(verify_request("1500000000", 1))
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            FacilitatorError::Verification(VerificationError::Expired)
        ));
        assert!(
            facilitator.transport.call_urls().is_empty(),
            "an expired payment must not reach the network"
        );
    }

    #[tokio::test]
    async fn preflight_rejects_zero_amounts() {
        let transport = MockTransport::new(serde_json::json!({ "isValid": true, "payer": PAYER }));
        let facilitator = CasperExactFacilitator::hosted(transport);
        let error = facilitator
            .verify(verify_request("0", far_future()))
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            FacilitatorError::Verification(VerificationError::InvalidPaymentAmount)
        ));
    }

    #[tokio::test]
    async fn preflight_can_be_disabled() {
        let transport = MockTransport::new(serde_json::json!({ "isValid": true, "payer": PAYER }));
        let facilitator = CasperExactFacilitator::new(
            CasperFacilitatorConfig::default().with_local_validation(false),
            transport,
        );
        let response = facilitator
            .verify(verify_request("1500000000", 1))
            .await
            .unwrap();
        assert!(response.is_valid());
        assert_eq!(facilitator.transport.call_urls().len(), 1);
    }

    #[tokio::test]
    async fn remote_invalid_response_is_surfaced_verbatim() {
        let transport = MockTransport::new(serde_json::json!({
            "isValid": false,
            "invalidReason": "insufficient_funds",
            "payer": PAYER
        }));
        let facilitator = CasperExactFacilitator::hosted(transport);
        let response = facilitator
            .verify(verify_request("1500000000", far_future()))
            .await
            .unwrap();
        assert!(matches!(
            response,
            wire::VerifyResponse::Invalid {
                reason: ErrorReason::InsufficientFunds,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn malformed_remote_response_becomes_an_invalid_format_error() {
        let transport = MockTransport::new(serde_json::json!({ "unexpected": true }));
        let facilitator = CasperExactFacilitator::hosted(transport);
        let error = facilitator
            .verify(verify_request("1500000000", far_future()))
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            FacilitatorError::Verification(VerificationError::InvalidFormat(_))
        ));
    }

    #[tokio::test]
    async fn custom_base_url_is_honoured() {
        let transport = MockTransport::new(serde_json::json!({ "isValid": true, "payer": PAYER }));
        let facilitator = CasperExactFacilitator::new(
            CasperFacilitatorConfig::new("https://facilitator.internal/x402/").unwrap(),
            transport,
        );
        let _ = facilitator
            .verify(verify_request("1500000000", far_future()))
            .await
            .unwrap();
        assert_eq!(
            facilitator.transport.call_urls(),
            vec!["https://facilitator.internal/x402/verify".to_owned()]
        );
    }

    #[tokio::test]
    async fn configured_timeout_is_forwarded_to_the_transport() {
        let transport = MockTransport::new(serde_json::json!({ "isValid": true, "payer": PAYER }));
        let facilitator = CasperExactFacilitator::new(
            CasperFacilitatorConfig::default().with_timeout(Duration::from_secs(7)),
            transport,
        );
        let _ = facilitator
            .verify(verify_request("1500000000", far_future()))
            .await
            .unwrap();
        assert_eq!(
            facilitator.transport.call_timeouts(),
            vec![Duration::from_secs(7)]
        );
    }
}