x402-types 1.4.6

Core types for x402 payments: chain identifiers, protocol messages, and facilitator traits
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
//! Protocol version 1 (V1) types for x402.
//!
//! This module defines the wire format types for the original x402 protocol version.
//! V1 uses network names (e.g., "base-sepolia") instead of CAIP-2 chain IDs.
//!
//! # Key Types
//!
//! - [`X402Version1`] - Version marker that serializes as `1`
//! - [`PaymentPayload`] - Signed payment authorization from the buyer
//! - [`PaymentRequirements`] - Payment terms set by the seller
//! - [`PaymentRequired`] - HTTP 402 response body
//! - [`VerifyRequest`] / [`VerifyResponse`] - Verification messages
//! - [`SettleResponse`] - Settlement result
//! - [`PriceTag`] - Builder for creating payment requirements

use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::fmt::Display;
use std::sync::Arc;

use crate::proto;
use crate::proto::{OriginalJson, SupportedResponse};

/// Version marker for x402 protocol version 1.
///
/// This type serializes as the integer `1` and is used to identify V1 protocol
/// messages in the wire format.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq)]
pub struct X402Version1;

impl X402Version1 {
    pub const VALUE: u8 = 1;
}

impl PartialEq<u8> for X402Version1 {
    fn eq(&self, other: &u8) -> bool {
        *other == Self::VALUE
    }
}

impl From<X402Version1> for u8 {
    fn from(_: X402Version1) -> Self {
        X402Version1::VALUE
    }
}

impl Serialize for X402Version1 {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_u8(Self::VALUE)
    }
}

impl<'de> Deserialize<'de> for X402Version1 {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let num = u8::deserialize(deserializer)?;
        if num == Self::VALUE {
            Ok(X402Version1)
        } else {
            Err(serde::de::Error::custom(format!(
                "expected version {}, got {}",
                Self::VALUE,
                num
            )))
        }
    }
}

impl Display for X402Version1 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", Self::VALUE)
    }
}

/// Response from a payment settlement request.
///
/// Indicates whether the payment was successfully settled on-chain.
#[derive(Debug, Clone)]
pub enum SettleResponse {
    /// Settlement succeeded.
    Success {
        /// The address that paid.
        payer: String,
        /// The transaction hash.
        transaction: String,
        /// The network where settlement occurred.
        network: String,
    },
    /// Settlement failed.
    Error {
        /// The reason for failure.
        reason: String,
        /// The network where settlement was attempted.
        network: String,
    },
}

impl From<SettleResponse> for proto::SettleResponse {
    fn from(val: SettleResponse) -> Self {
        proto::SettleResponse(
            serde_json::to_value(val).expect("SettleResponse serialization failed"),
        )
    }
}

#[derive(Serialize, Deserialize)]
struct SettleResponseWire {
    pub success: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payer: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transaction: Option<String>,
    pub network: String,
}

impl Serialize for SettleResponse {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let wire = match self {
            SettleResponse::Success {
                payer,
                transaction,
                network,
            } => SettleResponseWire {
                success: true,
                error_reason: None,
                payer: Some(payer.clone()),
                transaction: Some(transaction.clone()),
                network: network.clone(),
            },
            SettleResponse::Error { reason, network } => SettleResponseWire {
                success: false,
                error_reason: Some(reason.clone()),
                payer: None,
                transaction: None,
                network: network.clone(),
            },
        };
        wire.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for SettleResponse {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = SettleResponseWire::deserialize(deserializer)?;
        match wire.success {
            true => {
                let payer = wire
                    .payer
                    .ok_or_else(|| serde::de::Error::missing_field("payer"))?;
                let transaction = wire
                    .transaction
                    .ok_or_else(|| serde::de::Error::missing_field("transaction"))?;
                Ok(SettleResponse::Success {
                    payer,
                    transaction,
                    network: wire.network,
                })
            }
            false => {
                let reason = wire
                    .error_reason
                    .ok_or_else(|| serde::de::Error::missing_field("error_reason"))?;
                Ok(SettleResponse::Error {
                    reason,
                    network: wire.network,
                })
            }
        }
    }
}

/// Result returned by a facilitator after verifying a [`PaymentPayload`] against the provided [`PaymentRequirements`].
///
/// 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, an invalid scheme, insufficient funds).
#[derive(Debug)]
pub enum VerifyResponse {
    /// The payload matches the requirements and passes all checks.
    Valid { payer: String },
    /// The payload was well-formed but failed verification due to the specified [`FacilitatorErrorReason`]
    Invalid {
        reason: String,
        payer: Option<String>,
    },
}

impl From<VerifyResponse> for proto::VerifyResponse {
    fn from(val: VerifyResponse) -> Self {
        proto::VerifyResponse(
            serde_json::to_value(val).expect("VerifyResponse serialization failed"),
        )
    }
}

impl TryFrom<proto::VerifyResponse> for VerifyResponse {
    type Error = serde_json::Error;
    fn try_from(value: proto::VerifyResponse) -> Result<Self, Self::Error> {
        let json = value.0;
        serde_json::from_value(json)
    }
}

impl VerifyResponse {
    /// Constructs a successful verification response with the given `payer` address.
    ///
    /// Indicates that the provided payment payload has been validated against the payment requirements.
    pub fn valid(payer: String) -> Self {
        VerifyResponse::Valid { payer }
    }

    /// Constructs a failed verification response with the given `payer` address and error `reason`.
    ///
    /// Indicates that the payment was recognized but rejected due to reasons such as
    /// insufficient funds, invalid network, or scheme mismatch.
    #[allow(dead_code)]
    pub fn invalid(payer: Option<String>, reason: String) -> Self {
        VerifyResponse::Invalid { reason, payer }
    }
}

#[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>,
}

impl Serialize for VerifyResponse {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let wire = match self {
            VerifyResponse::Valid { payer } => VerifyResponseWire {
                is_valid: true,
                payer: Some(payer.clone()),
                invalid_reason: None,
            },
            VerifyResponse::Invalid { reason, payer } => VerifyResponseWire {
                is_valid: false,
                payer: payer.clone(),
                invalid_reason: Some(reason.clone()),
            },
        };
        wire.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for VerifyResponse {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = VerifyResponseWire::deserialize(deserializer)?;
        match wire.is_valid {
            true => {
                let payer = wire
                    .payer
                    .ok_or_else(|| serde::de::Error::missing_field("payer"))?;
                Ok(VerifyResponse::Valid { payer })
            }
            false => {
                let reason = wire
                    .invalid_reason
                    .ok_or_else(|| serde::de::Error::missing_field("invalid_reason"))?;
                let payer = wire.payer;
                Ok(VerifyResponse::Invalid { reason, payer })
            }
        }
    }
}

/// Request to verify a V1 payment.
///
/// Contains the payment payload and requirements for verification.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VerifyRequest<TPayload, TRequirements> {
    /// Protocol version (always 1).
    pub x402_version: X402Version1,
    /// The signed payment authorization.
    pub payment_payload: TPayload,
    /// The payment requirements to verify against.
    pub payment_requirements: TRequirements,
}

impl<TPayload, TRequirements> VerifyRequest<TPayload, TRequirements>
where
    Self: DeserializeOwned,
{
    pub fn from_proto(
        // FIXME REMOVE THIS
        request: proto::VerifyRequest,
    ) -> Result<Self, proto::PaymentVerificationError> {
        let value = serde_json::from_str(request.as_str())?;
        Ok(value)
    }
}

impl<TPayload, TRequirements> TryInto<proto::VerifyRequest>
    for VerifyRequest<TPayload, TRequirements>
where
    TPayload: Serialize,
    TRequirements: Serialize,
{
    type Error = serde_json::Error;
    fn try_into(self) -> Result<proto::VerifyRequest, Self::Error> {
        let json = serde_json::to_value(self)?;
        let raw = serde_json::value::to_raw_value(&json)?;
        Ok(proto::VerifyRequest(raw))
    }
}

/// A signed payment authorization from the buyer.
///
/// This contains the cryptographic proof that the buyer has authorized
/// a payment, along with metadata about the payment scheme and network.
///
/// # Type Parameters
///
/// - `TScheme` - The scheme identifier type (default: `String`)
/// - `TPayload` - The scheme-specific payload type (default: raw JSON)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentPayload<TScheme = String, TPayload = Box<serde_json::value::RawValue>> {
    /// Protocol version (always 1).
    pub x402_version: X402Version1,
    /// The payment scheme (e.g., "exact").
    pub scheme: TScheme,
    /// The network name (e.g., "base-sepolia").
    pub network: String,
    /// The scheme-specific signed payload.
    pub payload: TPayload,
}

/// Payment requirements set by the seller.
///
/// Defines the terms under which a payment will be accepted, including
/// the amount, recipient, asset, and timing constraints.
///
/// # Type Parameters
///
/// - `TScheme` - The scheme identifier type (default: `String`)
/// - `TAmount` - The amount type (default: `String`)
/// - `TAddress` - The address type (default: `String`)
/// - `TExtra` - Scheme-specific extra data type (default: `serde_json::Value`)
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentRequirements<
    TScheme = String,
    TAmount = String,
    TAddress = String,
    TExtra = serde_json::Value,
> {
    /// The payment scheme (e.g., "exact").
    pub scheme: TScheme,
    /// The network name (e.g., "base-sepolia").
    pub network: String,
    /// The maximum amount required for payment.
    pub max_amount_required: TAmount,
    /// The resource URL being paid for.
    pub resource: String,
    /// Human-readable description of the resource.
    pub description: String,
    /// MIME type of the resource.
    pub mime_type: Option<String>,
    /// Optional JSON schema for the resource output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<serde_json::Value>,
    /// The recipient address for payment.
    pub pay_to: TAddress,
    /// Maximum time in seconds for payment validity.
    pub max_timeout_seconds: u64,
    /// The token asset address.
    pub asset: TAddress,
    /// Scheme-specific extra data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extra: Option<TExtra>,
}

impl<TScheme, TAmount, TAddress, TExtra> TryFrom<&OriginalJson>
    for PaymentRequirements<TScheme, TAmount, TAddress, TExtra>
where
    TScheme: for<'a> serde::Deserialize<'a>,
    TAmount: for<'a> serde::Deserialize<'a>,
    TAddress: for<'a> serde::Deserialize<'a>,
    TExtra: for<'a> serde::Deserialize<'a>,
{
    type Error = serde_json::Error;

    fn try_from(value: &OriginalJson) -> Result<Self, Self::Error> {
        let payment_requirements = serde_json::from_str(value.0.get())?;
        Ok(payment_requirements)
    }
}

/// HTTP 402 Payment Required response body for V1.
///
/// This is returned when a resource requires payment. It contains
/// the list of acceptable payment methods.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentRequired<TAccepts = PaymentRequirements> {
    /// Protocol version (always 1).
    pub x402_version: X402Version1,
    /// List of acceptable payment methods.
    #[serde(default = "Vec::default")]
    pub accepts: Vec<TAccepts>,
    /// Optional error message if the request was malformed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Builder for creating payment requirements.
///
/// A `PriceTag` is a convenient way to specify payment terms that can
/// be converted into [`PaymentRequirements`] for inclusion in a 402 response.
///
/// # Example
///
/// ```rust
/// use x402_types::proto::v1::PriceTag;
///
/// let price = PriceTag {
///     scheme: "exact".to_string(),
///     pay_to: "0x1234...".to_string(),
///     asset: "0xUSDC...".to_string(),
///     network: "base".to_string(),
///     amount: "1000000".to_string(), // 1 USDC
///     max_timeout_seconds: 300,
///     extra: None,
///     enricher: None,
/// };
/// ```
#[derive(Clone)]
#[allow(dead_code)] // Public for consumption by downstream crates.
pub struct PriceTag {
    /// The payment scheme (e.g., "exact").
    pub scheme: String,
    /// The recipient address.
    pub pay_to: String,
    /// The token asset address.
    pub asset: String,
    /// The network name.
    pub network: String,
    /// The payment amount in token units.
    pub amount: String,
    /// Maximum time in seconds for payment validity.
    pub max_timeout_seconds: u64,
    /// Scheme-specific extra data.
    pub extra: Option<serde_json::Value>,
    /// Optional enrichment function for adding facilitator-specific data.
    #[doc(hidden)]
    pub enricher: Option<Enricher>,
}

impl fmt::Debug for PriceTag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PriceTag")
            .field("scheme", &self.scheme)
            .field("pay_to", &self.pay_to)
            .field("asset", &self.asset)
            .field("network", &self.network)
            .field("amount", &self.amount)
            .field("max_timeout_seconds", &self.max_timeout_seconds)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Enrichment function type for price tags.
///
/// Enrichers are called with the facilitator's capabilities to add
/// facilitator-specific data to price tags (e.g., fee payer addresses).
pub type Enricher = Arc<dyn Fn(&mut PriceTag, &SupportedResponse) + Send + Sync>;

impl PriceTag {
    /// Applies the enrichment function if one is set.
    ///
    /// This is called automatically when building payment requirements
    /// to add facilitator-specific data.
    #[allow(dead_code)]
    pub fn enrich(&mut self, capabilities: &SupportedResponse) {
        if let Some(enricher) = self.enricher.clone() {
            enricher(self, capabilities);
        }
    }

    /// Sets the maximum timeout for this price tag.
    #[allow(dead_code)]
    pub fn with_timeout(mut self, seconds: u64) -> Self {
        self.max_timeout_seconds = seconds;
        self
    }
}