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
//! Verify and settle response types.
//!
//! Responses returned by a facilitator after processing verification or
//! settlement requests. Each response uses a flat wire format with a boolean
//! discriminator, converted to/from a Rust enum via serde.

use serde::{Deserialize, Serialize};

use super::{AsPaymentProblem, Base64Bytes, Extensions};

/// Result returned by a facilitator after verifying a payment payload
/// against the provided payment requirements.
///
/// This response indicates whether the payment authorization is valid and identifies
/// the payer. If invalid, it includes a reason describing why verification failed
/// (e.g., wrong network, invalid scheme, insufficient funds).
///
/// # Examples
///
/// ```
/// use r402::proto::VerifyResponse;
///
/// let valid = VerifyResponse::valid("0xAbC123".to_string());
/// assert!(valid.is_valid());
///
/// let invalid = VerifyResponse::invalid(None, "expired".to_string());
/// assert!(!invalid.is_valid());
///
/// let json = serde_json::to_string(&valid).unwrap();
/// assert!(json.contains("\"isValid\":true"));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(into = "VerifyResponseWire", try_from = "VerifyResponseWire")]
#[non_exhaustive]
pub enum VerifyResponse {
    /// The payload matches the requirements and passes all checks.
    Valid {
        /// The address of the payer.
        payer: String,
    },
    /// The payload was well-formed but failed verification.
    Invalid {
        /// Machine-readable reason verification failed.
        reason: String,
        /// Optional human-readable description of the failure.
        message: Option<String>,
        /// The payer address, if identifiable.
        payer: Option<String>,
    },
}

impl VerifyResponse {
    /// Constructs a successful verification response with the given payer address.
    #[must_use]
    pub const fn valid(payer: String) -> Self {
        Self::Valid { payer }
    }

    /// Constructs a failed verification response.
    #[must_use]
    pub const fn invalid(payer: Option<String>, reason: String) -> Self {
        Self::Invalid {
            reason,
            message: None,
            payer,
        }
    }

    /// Constructs a failed verification response with a human-readable message.
    #[must_use]
    pub const fn invalid_with_message(
        payer: Option<String>,
        reason: String,
        message: String,
    ) -> Self {
        Self::Invalid {
            reason,
            message: Some(message),
            payer,
        }
    }

    /// Returns `true` if the verification succeeded.
    #[must_use]
    pub const fn is_valid(&self) -> bool {
        matches!(self, Self::Valid { .. })
    }

    /// Converts a [`FacilitatorError`] into an invalid verification response,
    /// preserving the structured reason code and message from the error.
    ///
    /// This is the canonical conversion for HTTP boundaries that need to return
    /// a wire-compatible `VerifyResponse` instead of propagating errors.
    ///
    /// [`FacilitatorError`]: crate::facilitator::FacilitatorError
    #[must_use]
    pub fn from_facilitator_error(error: &crate::facilitator::FacilitatorError) -> Self {
        let problem = error.as_payment_problem();
        Self::Invalid {
            reason: problem.reason().to_string(),
            message: Some(problem.details().to_owned()),
            payer: None,
        }
    }
}

/// Wire format for [`VerifyResponse`], using a flat boolean discriminator.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct VerifyResponseWire {
    is_valid: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    payer: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    invalid_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    invalid_message: Option<String>,
}

impl From<VerifyResponse> for VerifyResponseWire {
    fn from(resp: VerifyResponse) -> Self {
        match resp {
            VerifyResponse::Valid { payer } => Self {
                is_valid: true,
                payer: Some(payer),
                invalid_reason: None,
                invalid_message: None,
            },
            VerifyResponse::Invalid {
                reason,
                message,
                payer,
            } => Self {
                is_valid: false,
                payer,
                invalid_reason: Some(reason),
                invalid_message: message,
            },
        }
    }
}

impl TryFrom<VerifyResponseWire> for VerifyResponse {
    type Error = String;

    fn try_from(wire: VerifyResponseWire) -> Result<Self, Self::Error> {
        if wire.is_valid {
            let payer = wire.payer.ok_or("missing field: payer")?;
            Ok(Self::Valid { payer })
        } else {
            let reason = wire.invalid_reason.ok_or("missing field: invalidReason")?;
            Ok(Self::Invalid {
                reason,
                message: wire.invalid_message,
                payer: wire.payer,
            })
        }
    }
}

/// Response from a payment settlement request.
///
/// Indicates whether the payment was successfully settled on-chain,
/// including the transaction hash and payer address on success.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(into = "SettleResponseWire", try_from = "SettleResponseWire")]
#[non_exhaustive]
pub enum SettleResponse {
    /// Settlement succeeded.
    Success {
        /// The address that paid.
        payer: String,
        /// The on-chain transaction hash.
        transaction: String,
        /// The network where settlement occurred (CAIP-2 chain ID).
        network: String,
        /// Optional protocol extensions returned by the facilitator.
        extensions: Option<Extensions>,
    },
    /// Settlement failed.
    Error {
        /// Machine-readable reason for failure.
        reason: String,
        /// Optional human-readable description of the failure.
        message: Option<String>,
        /// The payer address, if identifiable.
        payer: Option<String>,
        /// The network where settlement was attempted.
        network: String,
    },
}

impl SettleResponse {
    /// Returns `true` if the settlement succeeded.
    #[must_use]
    pub const fn is_success(&self) -> bool {
        matches!(self, Self::Success { .. })
    }

    /// Encode a **successful** settlement into base64 bytes suitable for the
    /// `Payment-Response` HTTP header.
    ///
    /// Returns `None` if this is an [`Error`](Self::Error) variant, preventing
    /// accidental encoding of failed settlements into response headers.
    ///
    /// The output bytes are standard base64 (RFC 4648) of the JSON-serialised
    /// [`SettleResponse`] and can be placed directly into a header value.
    #[must_use]
    pub fn encode_base64(&self) -> Option<Base64Bytes> {
        if !self.is_success() {
            return None;
        }
        let json = serde_json::to_vec(self).ok()?;
        Some(Base64Bytes::encode(json))
    }

    /// Converts a [`FacilitatorError`] into a settlement error response,
    /// preserving the structured reason code and message from the error.
    ///
    /// `network` should be the CAIP-2 chain identifier from the original request
    /// (e.g., obtained via [`super::SettleRequest::network()`]).
    ///
    /// [`FacilitatorError`]: crate::facilitator::FacilitatorError
    #[must_use]
    pub fn from_facilitator_error(
        error: &crate::facilitator::FacilitatorError,
        network: String,
    ) -> Self {
        let problem = error.as_payment_problem();
        Self::Error {
            reason: problem.reason().to_string(),
            message: Some(problem.details().to_owned()),
            payer: None,
            network,
        }
    }
}

/// Wire format for [`SettleResponse`], using a flat boolean discriminator.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct SettleResponseWire {
    success: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    error_message: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    payer: Option<String>,
    #[serde(default)]
    transaction: String,
    network: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    extensions: Option<Extensions>,
}

impl From<SettleResponse> for SettleResponseWire {
    fn from(resp: SettleResponse) -> Self {
        match resp {
            SettleResponse::Success {
                payer,
                transaction,
                network,
                extensions,
            } => Self {
                success: true,
                error_reason: None,
                error_message: None,
                payer: Some(payer),
                transaction,
                network,
                extensions,
            },
            SettleResponse::Error {
                reason,
                message,
                payer,
                network,
            } => Self {
                success: false,
                error_reason: Some(reason),
                error_message: message,
                payer,
                transaction: String::new(),
                network,
                extensions: None,
            },
        }
    }
}

impl TryFrom<SettleResponseWire> for SettleResponse {
    type Error = String;

    fn try_from(
        wire: SettleResponseWire,
    ) -> Result<Self, <Self as TryFrom<SettleResponseWire>>::Error> {
        if wire.success {
            let payer = wire.payer.ok_or("missing field: payer")?;
            if wire.transaction.is_empty() {
                return Err("missing field: transaction".to_owned());
            }
            Ok(Self::Success {
                payer,
                transaction: wire.transaction,
                network: wire.network,
                extensions: wire.extensions,
            })
        } else {
            let reason = wire.error_reason.ok_or("missing field: errorReason")?;
            Ok(Self::Error {
                reason,
                message: wire.error_message,
                payer: wire.payer,
                network: wire.network,
            })
        }
    }
}

#[cfg(test)]
#[allow(
    clippy::indexing_slicing,
    reason = "test assertions on known JSON structure"
)]
mod tests {
    use super::*;

    #[test]
    fn verify_valid_roundtrip() {
        let resp = VerifyResponse::valid("0xABC".into());
        let json = serde_json::to_value(&resp).unwrap();

        assert_eq!(json["isValid"], true);
        assert_eq!(json["payer"], "0xABC");
        assert!(json.get("invalidReason").is_none());

        let back: VerifyResponse = serde_json::from_value(json).unwrap();
        assert!(back.is_valid());
        assert!(matches!(back, VerifyResponse::Valid { payer } if payer == "0xABC"));
    }

    #[test]
    fn verify_invalid_roundtrip() {
        let resp = VerifyResponse::invalid_with_message(
            Some("0xDEF".into()),
            "insufficient_balance".into(),
            "not enough USDC".into(),
        );
        let json = serde_json::to_value(&resp).unwrap();

        assert_eq!(json["isValid"], false);
        assert_eq!(json["invalidReason"], "insufficient_balance");
        assert_eq!(json["invalidMessage"], "not enough USDC");
        assert_eq!(json["payer"], "0xDEF");

        let back: VerifyResponse = serde_json::from_value(json).unwrap();
        assert!(!back.is_valid());
        assert!(matches!(
            back,
            VerifyResponse::Invalid { reason, message, payer }
                if reason == "insufficient_balance"
                && message.as_deref() == Some("not enough USDC")
                && payer.as_deref() == Some("0xDEF")
        ));
    }

    #[test]
    fn verify_valid_missing_payer_rejects() {
        let json = serde_json::json!({"isValid": true});
        let err = serde_json::from_value::<VerifyResponse>(json).unwrap_err();
        assert!(
            err.to_string().contains("payer"),
            "should mention missing payer"
        );
    }

    #[test]
    fn verify_invalid_missing_reason_rejects() {
        let json = serde_json::json!({"isValid": false});
        let err = serde_json::from_value::<VerifyResponse>(json).unwrap_err();
        assert!(
            err.to_string().contains("invalidReason"),
            "should mention missing invalidReason"
        );
    }

    #[test]
    fn settle_success_roundtrip() {
        let resp = SettleResponse::Success {
            payer: "0xABC".into(),
            transaction: "0xTX123".into(),
            network: "eip155:8453".into(),
            extensions: None,
        };
        let json = serde_json::to_value(&resp).unwrap();

        assert_eq!(json["success"], true);
        assert_eq!(json["payer"], "0xABC");
        assert_eq!(json["transaction"], "0xTX123");
        assert_eq!(json["network"], "eip155:8453");
        assert!(json.get("errorReason").is_none());

        let back: SettleResponse = serde_json::from_value(json).unwrap();
        assert!(back.is_success());
    }

    #[test]
    fn settle_error_roundtrip() {
        let resp = SettleResponse::Error {
            reason: "tx_reverted".into(),
            message: Some("out of gas".into()),
            payer: None,
            network: "eip155:1".into(),
        };
        let json = serde_json::to_value(&resp).unwrap();

        assert_eq!(json["success"], false);
        assert_eq!(json["errorReason"], "tx_reverted");
        assert_eq!(json["errorMessage"], "out of gas");
        assert_eq!(json["network"], "eip155:1");

        let back: SettleResponse = serde_json::from_value(json).unwrap();
        assert!(!back.is_success());
    }

    #[test]
    fn settle_success_missing_payer_rejects() {
        let json = serde_json::json!({
            "success": true,
            "transaction": "0xTX",
            "network": "eip155:1"
        });
        let err = serde_json::from_value::<SettleResponse>(json).unwrap_err();
        assert!(err.to_string().contains("payer"));
    }

    #[test]
    fn settle_success_empty_tx_rejects() {
        let json = serde_json::json!({
            "success": true,
            "payer": "0xABC",
            "transaction": "",
            "network": "eip155:1"
        });
        let err = serde_json::from_value::<SettleResponse>(json).unwrap_err();
        assert!(err.to_string().contains("transaction"));
    }

    #[test]
    fn settle_encode_base64_only_for_success() {
        let success = SettleResponse::Success {
            payer: "0xA".into(),
            transaction: "0xT".into(),
            network: "eip155:1".into(),
            extensions: None,
        };
        assert!(success.encode_base64().is_some());

        let error = SettleResponse::Error {
            reason: "fail".into(),
            message: None,
            payer: None,
            network: "eip155:1".into(),
        };
        assert!(error.encode_base64().is_none());
    }
}