r402 0.13.0

Core types 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Lifecycle hooks for x402 facilitator operations.
//!
//! This module provides the hook system that allows intercepting verify and settle
//! operations at three points in their lifecycle:
//!
//! - **Before**: Inspect or abort the operation before it executes
//! - **After**: Observe the result after a successful operation
//! - **On Failure**: Observe or recover from a failed operation
//!
//! # Architecture
//!
//! Hooks are defined via the [`FacilitatorHooks`] trait, which has default no-op
//! implementations for all methods. Implement only the hooks you need.
//!
//! The [`HookedFacilitator`] decorator wraps any [`Facilitator`]
//! and applies registered hooks around its verify/settle calls, following the same
//! lifecycle pattern as the official x402 Go SDK.

use std::fmt::{self, Debug};

use crate::facilitator::{BoxFuture, Facilitator, FacilitatorError};
use crate::proto;

/// Decision returned by "before" hooks to control whether an operation proceeds.
///
/// Mirrors the official x402 `BeforeHookResult` / `FacilitatorBeforeHookResult`.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum HookDecision {
    /// Allow the operation to proceed normally.
    Continue,
    /// Abort the operation with the given reason and optional human-readable message.
    Abort {
        /// Machine-readable reason for aborting (e.g., `"kyt_blocked"`).
        reason: String,
        /// Optional human-readable message describing why the operation was aborted.
        message: String,
    },
}

/// Decision returned by "on failure" hooks to optionally recover from errors.
///
/// Mirrors the official x402 `VerifyFailureHookResult` / `SettleFailureHookResult`.
#[derive(Debug)]
#[non_exhaustive]
pub enum FailureRecovery<T> {
    /// The error was not recovered; propagate the original error.
    Propagate,
    /// The hook recovered from the failure with a substitute result.
    Recovered(T),
}

/// Context passed to verify lifecycle hooks.
///
/// Provides access to the raw verify request. The request contains the full
/// JSON payload and requirements, allowing hooks to inspect any field regardless
/// of protocol version.
#[derive(Clone)]
pub struct VerifyContext {
    /// The raw verify request (contains payload + requirements as JSON).
    pub request: proto::VerifyRequest,
}

impl Debug for VerifyContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VerifyContext")
            .field("request", &"<VerifyRequest>")
            .finish()
    }
}

/// Context passed to settle lifecycle hooks.
///
/// Provides access to the raw settle request.
#[derive(Clone)]
pub struct SettleContext {
    /// The raw settle request (same structure as verify request).
    pub request: proto::SettleRequest,
}

impl Debug for SettleContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SettleContext")
            .field("request", &"<SettleRequest>")
            .finish()
    }
}

/// Lifecycle hooks for facilitator verify and settle operations.
///
/// All methods have default no-op implementations. Override only the hooks you
/// need. This trait is dyn-compatible for use in heterogeneous hook lists.
///
/// The hook lifecycle mirrors the official x402 Go SDK:
///
/// 1. **`before_*`** — Runs before the operation. Can abort with a reason.
/// 2. **Inner operation executes**
/// 3. **`after_*`** (on success) — Observes the result. Errors are logged, not propagated.
/// 4. **`on_*_failure`** (on error) — Can recover with a substitute result.
pub trait FacilitatorHooks: Send + Sync {
    /// Called before payment verification.
    ///
    /// If any hook returns [`HookDecision::Abort`], verification is skipped and
    /// an invalid `VerifyResponse` is returned with the provided reason.
    fn before_verify<'a>(&'a self, _ctx: &'a VerifyContext) -> BoxFuture<'a, HookDecision> {
        Box::pin(async { HookDecision::Continue })
    }

    /// Called after successful payment verification.
    ///
    /// Any error returned will be logged but will not affect the verification result.
    fn after_verify<'a>(
        &'a self,
        _ctx: &'a VerifyContext,
        _result: &'a proto::VerifyResponse,
    ) -> BoxFuture<'a, ()> {
        Box::pin(async {})
    }

    /// Called when payment verification fails.
    ///
    /// If a hook returns [`FailureRecovery::Recovered`], the provided `VerifyResponse`
    /// is returned instead of the error.
    fn on_verify_failure<'a>(
        &'a self,
        _ctx: &'a VerifyContext,
        _error: &'a FacilitatorError,
    ) -> BoxFuture<'a, FailureRecovery<proto::VerifyResponse>> {
        Box::pin(async { FailureRecovery::Propagate })
    }

    /// Called before payment settlement.
    ///
    /// If any hook returns [`HookDecision::Abort`], settlement is skipped and
    /// an error is returned with the provided reason.
    fn before_settle<'a>(&'a self, _ctx: &'a SettleContext) -> BoxFuture<'a, HookDecision> {
        Box::pin(async { HookDecision::Continue })
    }

    /// Called after successful payment settlement.
    ///
    /// Any error returned will be logged but will not affect the settlement result.
    fn after_settle<'a>(
        &'a self,
        _ctx: &'a SettleContext,
        _result: &'a proto::SettleResponse,
    ) -> BoxFuture<'a, ()> {
        Box::pin(async {})
    }

    /// Called when payment settlement fails.
    ///
    /// If a hook returns [`FailureRecovery::Recovered`], the provided `SettleResponse`
    /// is returned instead of the error.
    fn on_settle_failure<'a>(
        &'a self,
        _ctx: &'a SettleContext,
        _error: &'a FacilitatorError,
    ) -> BoxFuture<'a, FailureRecovery<proto::SettleResponse>> {
        Box::pin(async { FailureRecovery::Propagate })
    }
}

/// A facilitator decorator that applies lifecycle hooks around verify/settle operations.
///
/// Wraps any type implementing [`Facilitator`] and executes registered
/// [`FacilitatorHooks`] at the appropriate lifecycle points, following the
/// same pattern as the official x402 Go SDK's `x402Facilitator`.
///
/// Hooks are executed in registration order:
/// - **Before hooks**: First abort wins — remaining hooks are skipped.
/// - **After hooks**: All hooks run; errors are silently ignored.
/// - **Failure hooks**: First recovery wins — remaining hooks are skipped.
pub struct HookedFacilitator<F> {
    inner: F,
    hooks: Vec<Box<dyn FacilitatorHooks>>,
}

impl<F: Debug> Debug for HookedFacilitator<F> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HookedFacilitator")
            .field("inner", &self.inner)
            .field("hooks", &format!("[{} hooks]", self.hooks.len()))
            .finish()
    }
}

impl<F> HookedFacilitator<F> {
    /// Wraps a facilitator with hook support.
    pub fn new(inner: F) -> Self {
        Self {
            inner,
            hooks: Vec::new(),
        }
    }

    /// Registers a lifecycle hook. Hooks execute in registration order.
    #[must_use]
    pub fn with_hook(mut self, hook: impl FacilitatorHooks + 'static) -> Self {
        self.hooks.push(Box::new(hook));
        self
    }

    /// Adds a hook dynamically after construction.
    pub fn add_hook(&mut self, hook: impl FacilitatorHooks + 'static) {
        self.hooks.push(Box::new(hook));
    }

    /// Returns the number of registered hooks.
    #[must_use]
    pub fn hook_count(&self) -> usize {
        self.hooks.len()
    }

    /// Returns a reference to the inner facilitator.
    #[must_use]
    pub const fn inner(&self) -> &F {
        &self.inner
    }
}

impl<F: Send + Sync> HookedFacilitator<F> {
    async fn run_before_verify_hooks(&self, ctx: &VerifyContext) -> Result<(), FacilitatorError> {
        for hook in &self.hooks {
            if let HookDecision::Abort { reason, message } = hook.before_verify(ctx).await {
                return Err(FacilitatorError::Aborted { reason, message });
            }
        }
        Ok(())
    }

    async fn run_after_verify_hooks(&self, ctx: &VerifyContext, response: &proto::VerifyResponse) {
        for hook in &self.hooks {
            hook.after_verify(ctx, response).await;
        }
    }

    async fn run_on_verify_failure_hooks(
        &self,
        ctx: &VerifyContext,
        error: &FacilitatorError,
    ) -> Option<proto::VerifyResponse> {
        for hook in &self.hooks {
            if let FailureRecovery::Recovered(response) = hook.on_verify_failure(ctx, error).await {
                return Some(response);
            }
        }
        None
    }

    async fn run_before_settle_hooks(&self, ctx: &SettleContext) -> Result<(), FacilitatorError> {
        for hook in &self.hooks {
            if let HookDecision::Abort { reason, message } = hook.before_settle(ctx).await {
                return Err(FacilitatorError::Aborted { reason, message });
            }
        }
        Ok(())
    }

    async fn run_after_settle_hooks(&self, ctx: &SettleContext, response: &proto::SettleResponse) {
        for hook in &self.hooks {
            hook.after_settle(ctx, response).await;
        }
    }

    async fn run_on_settle_failure_hooks(
        &self,
        ctx: &SettleContext,
        error: &FacilitatorError,
    ) -> Option<proto::SettleResponse> {
        for hook in &self.hooks {
            if let FailureRecovery::Recovered(response) = hook.on_settle_failure(ctx, error).await {
                return Some(response);
            }
        }
        None
    }
}

impl<F> Facilitator for HookedFacilitator<F>
where
    F: Facilitator,
{
    fn verify(
        &self,
        request: proto::VerifyRequest,
    ) -> BoxFuture<'_, Result<proto::VerifyResponse, FacilitatorError>> {
        Box::pin(async move {
            let ctx = VerifyContext {
                request: request.clone(),
            };
            self.run_before_verify_hooks(&ctx).await?;
            match self.inner.verify(request).await {
                Ok(response) => {
                    self.run_after_verify_hooks(&ctx, &response).await;
                    Ok(response)
                }
                Err(e) => self.run_on_verify_failure_hooks(&ctx, &e).await.ok_or(e),
            }
        })
    }

    fn settle(
        &self,
        request: proto::SettleRequest,
    ) -> BoxFuture<'_, Result<proto::SettleResponse, FacilitatorError>> {
        Box::pin(async move {
            let ctx = SettleContext {
                request: request.clone(),
            };
            self.run_before_settle_hooks(&ctx).await?;
            match self.inner.settle(request).await {
                Ok(response) => {
                    self.run_after_settle_hooks(&ctx, &response).await;
                    Ok(response)
                }
                Err(e) => self.run_on_settle_failure_hooks(&ctx, &e).await.ok_or(e),
            }
        })
    }

    fn supported(&self) -> BoxFuture<'_, Result<proto::SupportedResponse, FacilitatorError>> {
        Box::pin(async move { self.inner.supported().await })
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;

    struct MockFacilitator {
        fail: bool,
    }

    impl MockFacilitator {
        fn ok() -> Self {
            Self { fail: false }
        }
        fn failing() -> Self {
            Self { fail: true }
        }
        fn mock_verify(&self) -> Result<proto::VerifyResponse, FacilitatorError> {
            if self.fail {
                Err(FacilitatorError::OnchainFailure("mock".into()))
            } else {
                Ok(proto::VerifyResponse::valid("0xPAYER".into()))
            }
        }
        fn mock_settle(&self) -> Result<proto::SettleResponse, FacilitatorError> {
            if self.fail {
                Err(FacilitatorError::OnchainFailure("mock".into()))
            } else {
                Ok(proto::SettleResponse::Success {
                    payer: "0xPAYER".into(),
                    transaction: "0xTX".into(),
                    network: "eip155:1".into(),
                    extensions: None,
                })
            }
        }
    }

    impl Facilitator for MockFacilitator {
        fn verify(
            &self,
            _request: proto::VerifyRequest,
        ) -> BoxFuture<'_, Result<proto::VerifyResponse, FacilitatorError>> {
            Box::pin(async move { self.mock_verify() })
        }

        fn settle(
            &self,
            _request: proto::SettleRequest,
        ) -> BoxFuture<'_, Result<proto::SettleResponse, FacilitatorError>> {
            Box::pin(async move { self.mock_settle() })
        }

        fn supported(&self) -> BoxFuture<'_, Result<proto::SupportedResponse, FacilitatorError>> {
            Box::pin(async { Ok(proto::SupportedResponse::default()) })
        }
    }

    struct AbortVerifyHook;
    impl FacilitatorHooks for AbortVerifyHook {
        fn before_verify<'a>(&'a self, _: &'a VerifyContext) -> BoxFuture<'a, HookDecision> {
            Box::pin(async {
                HookDecision::Abort {
                    reason: "blocked".into(),
                    message: "test".into(),
                }
            })
        }
    }

    struct AbortSettleHook;
    impl FacilitatorHooks for AbortSettleHook {
        fn before_settle<'a>(&'a self, _: &'a SettleContext) -> BoxFuture<'a, HookDecision> {
            Box::pin(async {
                HookDecision::Abort {
                    reason: "blocked".into(),
                    message: "test".into(),
                }
            })
        }
    }

    struct RecoverVerifyHook;
    impl FacilitatorHooks for RecoverVerifyHook {
        fn on_verify_failure<'a>(
            &'a self,
            _: &'a VerifyContext,
            _: &'a FacilitatorError,
        ) -> BoxFuture<'a, FailureRecovery<proto::VerifyResponse>> {
            Box::pin(async {
                FailureRecovery::Recovered(proto::VerifyResponse::valid("0xREC".into()))
            })
        }
    }

    struct RecoverSettleHook;
    impl FacilitatorHooks for RecoverSettleHook {
        fn on_settle_failure<'a>(
            &'a self,
            _: &'a SettleContext,
            _: &'a FacilitatorError,
        ) -> BoxFuture<'a, FailureRecovery<proto::SettleResponse>> {
            Box::pin(async {
                FailureRecovery::Recovered(proto::SettleResponse::Success {
                    payer: "0xREC".into(),
                    transaction: "0xREC_TX".into(),
                    network: "eip155:1".into(),
                    extensions: None,
                })
            })
        }
    }

    struct NoopHook;
    impl FacilitatorHooks for NoopHook {}

    static SECOND_HOOK_CALLS: AtomicUsize = AtomicUsize::new(0);
    struct SecondAbortHook;
    impl FacilitatorHooks for SecondAbortHook {
        fn before_verify<'a>(&'a self, _: &'a VerifyContext) -> BoxFuture<'a, HookDecision> {
            Box::pin(async {
                SECOND_HOOK_CALLS.fetch_add(1, Ordering::Relaxed);
                HookDecision::Abort {
                    reason: "second".into(),
                    message: String::new(),
                }
            })
        }
    }

    fn dummy_request() -> proto::VerifyRequest {
        serde_json::json!({}).into()
    }

    fn dummy_settle() -> proto::SettleRequest {
        serde_json::json!({}).into()
    }

    #[tokio::test]
    async fn verify_no_hooks_passes_through() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok());
        assert_eq!(hooked.hook_count(), 0);
        let resp = hooked.verify(dummy_request()).await.unwrap();
        assert!(resp.is_valid());
    }

    #[tokio::test]
    async fn verify_before_hook_aborts() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok()).with_hook(AbortVerifyHook);
        let err = hooked.verify(dummy_request()).await.unwrap_err();
        assert!(matches!(err, FacilitatorError::Aborted { reason, .. } if reason == "blocked"));
    }

    #[tokio::test]
    async fn verify_failure_hook_recovers() {
        let hooked =
            HookedFacilitator::new(MockFacilitator::failing()).with_hook(RecoverVerifyHook);
        let resp = hooked.verify(dummy_request()).await.unwrap();
        assert!(resp.is_valid());
    }

    #[tokio::test]
    async fn verify_failure_hook_propagates_by_default() {
        let hooked = HookedFacilitator::new(MockFacilitator::failing()).with_hook(NoopHook);
        assert!(hooked.verify(dummy_request()).await.is_err());
    }

    #[tokio::test]
    async fn settle_before_hook_aborts() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok()).with_hook(AbortSettleHook);
        let err = hooked.settle(dummy_settle()).await.unwrap_err();
        assert!(matches!(err, FacilitatorError::Aborted { reason, .. } if reason == "blocked"));
    }

    #[tokio::test]
    async fn settle_success_passes_through() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok());
        let resp = hooked.settle(dummy_settle()).await.unwrap();
        assert!(resp.is_success());
    }

    #[tokio::test]
    async fn settle_failure_hook_recovers() {
        let hooked =
            HookedFacilitator::new(MockFacilitator::failing()).with_hook(RecoverSettleHook);
        let resp = hooked.settle(dummy_settle()).await.unwrap();
        assert!(resp.is_success());
    }

    #[tokio::test]
    async fn first_abort_hook_wins_remaining_skipped() {
        SECOND_HOOK_CALLS.store(0, Ordering::Relaxed);

        let hooked = HookedFacilitator::new(MockFacilitator::ok())
            .with_hook(AbortVerifyHook)
            .with_hook(SecondAbortHook);

        let err = hooked.verify(dummy_request()).await.unwrap_err();
        assert!(matches!(err, FacilitatorError::Aborted { reason, .. } if reason == "blocked"));
        assert_eq!(
            SECOND_HOOK_CALLS.load(Ordering::Relaxed),
            0,
            "second hook must not run after first aborts"
        );
    }

    #[tokio::test]
    async fn add_hook_dynamic() {
        let mut hooked = HookedFacilitator::new(MockFacilitator::ok());
        assert_eq!(hooked.hook_count(), 0);
        hooked.add_hook(NoopHook);
        assert_eq!(hooked.hook_count(), 1);
        let resp = hooked.verify(dummy_request()).await.unwrap();
        assert!(resp.is_valid());
    }

    #[tokio::test]
    async fn supported_delegates_to_inner() {
        let hooked = HookedFacilitator::new(MockFacilitator::ok());
        let resp = hooked.supported().await.unwrap();
        assert!(resp.kinds.is_empty());
        assert!(resp.signers.is_empty());
    }
}