x402-chain-eip155 1.5.1

EIP-155 (EVM) 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
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Wire format types for EVM chain interactions.
//!
//! This module provides types that handle serialization and deserialization
//! of EVM-specific values in the x402 protocol wire format.

use alloy_primitives::{Address, B256, Signature, U256, hex};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
use std::fmt;
use std::fmt::{Display, Formatter};
use std::ops::Mul;
use std::str::FromStr;
use x402_types::chain::{ChainId, DeployedTokenAmount};
use x402_types::util::money_amount::{MoneyAmount, MoneyAmountParseError};

/// An Ethereum address that serializes with EIP-55 checksum encoding.
///
/// This wrapper ensures addresses are always serialized in checksummed format
/// (e.g., `0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045`) for compatibility
/// with the x402 protocol wire format.
///
/// # Example
///
/// ```
/// use x402_chain_eip155::chain::ChecksummedAddress;
///
/// let addr: ChecksummedAddress = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045".parse().unwrap();
/// assert_eq!(addr.to_string(), "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045");
/// ```
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ChecksummedAddress(pub Address);

impl FromStr for ChecksummedAddress {
    type Err = hex::FromHexError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let address = Address::from_str(s)?;
        Ok(Self(address))
    }
}

impl Display for ChecksummedAddress {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0.to_checksum(None))
    }
}

impl Serialize for ChecksummedAddress {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0.to_checksum(None))
    }
}

impl<'de> Deserialize<'de> for ChecksummedAddress {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

impl From<ChecksummedAddress> for Address {
    fn from(value: ChecksummedAddress) -> Self {
        value.0
    }
}

impl From<Address> for ChecksummedAddress {
    fn from(address: Address) -> Self {
        Self(address)
    }
}

impl PartialEq<ChecksummedAddress> for Address {
    fn eq(&self, other: &ChecksummedAddress) -> bool {
        self.eq(&other.0)
    }
}

/// A `U256` amount that serializes/deserializes as a decimal string.
///
/// The x402 V2 wire format encodes payment amounts as decimal strings
/// (e.g., `"10000"` for 10000 token units). Alloy's default `U256` serde
/// implementation uses hex encoding, so this newtype provides correct
/// decimal-string handling for V2 payment requirements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct DecimalU256(pub U256);

impl From<DecimalU256> for U256 {
    fn from(v: DecimalU256) -> Self {
        v.0
    }
}

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

impl From<U256> for DecimalU256 {
    fn from(v: U256) -> Self {
        Self(v)
    }
}

impl Serialize for DecimalU256 {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0.to_string())
    }
}

impl<'de> Deserialize<'de> for DecimalU256 {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct DecimalU256Visitor;
        impl<'de> serde::de::Visitor<'de> for DecimalU256Visitor {
            type Value = DecimalU256;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "a decimal string or integer representing a U256 amount")
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<DecimalU256, E> {
                U256::from_str_radix(v, 10)
                    .map(DecimalU256)
                    .map_err(|e| E::custom(format!("invalid decimal U256: {e}")))
            }
            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<DecimalU256, E> {
                Ok(DecimalU256(U256::from(v)))
            }
            fn visit_u128<E: serde::de::Error>(self, v: u128) -> Result<DecimalU256, E> {
                Ok(DecimalU256(U256::from(v)))
            }
        }
        deserializer.deserialize_any(DecimalU256Visitor)
    }
}

pub mod decimal_u256 {
    use alloy_primitives::U256;
    use serde::{Deserialize, Deserializer, Serializer};

    /// Serialize a U256 as a decimal string.
    pub fn serialize<S>(value: &U256, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&value.to_string())
    }

    /// Deserialize a decimal string into a U256.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<U256, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        U256::from_str_radix(&s, 10).map_err(serde::de::Error::custom)
    }
}

/// The CAIP-2 namespace for EVM-compatible chains.
pub const EIP155_NAMESPACE: &str = "eip155";

/// A numeric chain ID for EVM-compatible networks.
///
/// This type wraps the numeric chain ID used by EVM networks (e.g., `1` for Ethereum mainnet,
/// `8453` for Base). It can be converted to/from a [`ChainId`] for use with the x402 protocol.
///
/// # Example
///
/// ```
/// use x402_chain_eip155::chain::Eip155ChainReference;
/// use x402_types::chain::ChainId;
///
/// let base = Eip155ChainReference::new(8453);
/// let chain_id: ChainId = base.into();
/// assert_eq!(chain_id.to_string(), "eip155:8453");
/// ```
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Eip155ChainReference(u64);

impl Eip155ChainReference {
    /// Converts this chain reference to a CAIP-2 [`ChainId`].
    pub fn as_chain_id(&self) -> ChainId {
        ChainId::new(EIP155_NAMESPACE, self.0.to_string())
    }
}

impl From<Eip155ChainReference> for ChainId {
    fn from(value: Eip155ChainReference) -> Self {
        ChainId::new(EIP155_NAMESPACE, value.0.to_string())
    }
}

impl From<&Eip155ChainReference> for ChainId {
    fn from(value: &Eip155ChainReference) -> Self {
        ChainId::new(EIP155_NAMESPACE, value.0.to_string())
    }
}

impl TryFrom<ChainId> for Eip155ChainReference {
    type Error = Eip155ChainReferenceFormatError;

    fn try_from(value: ChainId) -> Result<Self, Self::Error> {
        if value.namespace != EIP155_NAMESPACE {
            return Err(Eip155ChainReferenceFormatError::InvalidNamespace(
                value.namespace,
            ));
        }
        let chain_id: u64 = value.reference.parse().map_err(|_| {
            Eip155ChainReferenceFormatError::InvalidReference(value.reference.clone())
        })?;
        Ok(Eip155ChainReference(chain_id))
    }
}

impl TryFrom<&ChainId> for Eip155ChainReference {
    type Error = Eip155ChainReferenceFormatError;

    fn try_from(value: &ChainId) -> Result<Self, Self::Error> {
        if value.namespace != EIP155_NAMESPACE {
            return Err(Eip155ChainReferenceFormatError::InvalidNamespace(
                value.namespace.clone(),
            ));
        }
        let chain_id: u64 = value.reference.parse().map_err(|_| {
            Eip155ChainReferenceFormatError::InvalidReference(value.reference.clone())
        })?;
        Ok(Eip155ChainReference(chain_id))
    }
}

/// Error returned when converting a [`ChainId`] to an [`Eip155ChainReference`].
#[derive(Debug, thiserror::Error)]
pub enum Eip155ChainReferenceFormatError {
    /// The chain ID namespace is not `eip155`.
    #[error("Invalid namespace {0}, expected eip155")]
    InvalidNamespace(String),
    /// The chain reference is not a valid numeric value.
    #[error("Invalid eip155 chain reference {0}")]
    InvalidReference(String),
}

impl Eip155ChainReference {
    /// Creates a new chain reference from a numeric chain ID.
    pub fn new(chain_id: u64) -> Self {
        Self(chain_id)
    }

    /// Returns the numeric chain ID.
    pub fn inner(&self) -> u64 {
        self.0
    }
}

impl Display for Eip155ChainReference {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Information about a token deployment on an EVM chain.
///
/// This type contains all the information needed to interact with a token contract,
/// including its address, decimal places, and optional EIP-712 domain parameters
/// for signature verification.
///
/// # Example
///
/// ```ignore
/// use x402_rs::networks::{KnownNetworkEip155, USDC};
///
/// // Get USDC deployment on Base
/// let usdc = USDC::base();
/// assert_eq!(usdc.decimals, 6);
///
/// // Parse a human-readable amount to token units
/// let amount = usdc.parse("10.50").unwrap();
/// assert_eq!(amount.amount, U256::from(10_500_000u64));
/// ```
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
#[allow(dead_code)] // Public for consumption by downstream crates.
pub struct Eip155TokenDeployment {
    /// The chain this token is deployed on.
    pub chain_reference: Eip155ChainReference,
    /// The token contract address.
    pub address: Address,
    /// Number of decimal places for the token (e.g., 6 for USDC, 18 for most ERC-20s).
    pub decimals: u8,
    /// The method used to transfer assets.
    pub transfer_method: AssetTransferMethod,
}

#[derive(Debug, Clone, Eq, PartialEq, Hash, Serialize)]
#[serde(tag = "assetTransferMethod")]
pub enum AssetTransferMethod {
    /// EIP-712 domain parameters for signature verification of EIP3009 transfers.
    #[serde(rename = "eip3009")]
    Eip3009 {
        /// The token name as specified in the EIP-712 domain.
        name: String,
        /// The token version as specified in the EIP-712 domain.
        version: String,
    },
    /// Permit2 transfer method.
    #[serde(rename = "permit2")]
    Permit2,
}

impl<'de> Deserialize<'de> for AssetTransferMethod {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        // --- Wire types (private) ---

        #[derive(Debug, Deserialize)]
        #[serde(untagged)]
        #[allow(dead_code)]
        enum AssetTransferMethodWire {
            // { "assetTransferMethod": "permit2" }
            Permit2Tagged {
                #[serde(rename = "assetTransferMethod")]
                asset_transfer_method: Permit2Tag,
            },
            // { "assetTransferMethod": "eip3009", "name": "...", "version": "..." }
            Eip3009Tagged {
                #[serde(rename = "assetTransferMethod")]
                asset_transfer_method: Eip3009Tag,
                name: String,
                version: String,
            },
            // { "name": "...", "version": "..." }  (implicit)
            Eip3009Implicit {
                name: String,
                version: String,
            },
        }

        #[derive(Debug, Deserialize)]
        #[serde(rename_all = "lowercase")]
        enum Permit2Tag {
            Permit2,
        }

        #[derive(Debug, Deserialize)]
        #[serde(rename_all = "lowercase")]
        enum Eip3009Tag {
            Eip3009,
        }

        let wire = AssetTransferMethodWire::deserialize(deserializer)
            .map_err(|e| serde::de::Error::custom(format!("invalid asset transfer method: {e}")))?;

        Ok(match wire {
            AssetTransferMethodWire::Permit2Tagged { .. } => AssetTransferMethod::Permit2,

            AssetTransferMethodWire::Eip3009Tagged { name, version, .. }
            | AssetTransferMethodWire::Eip3009Implicit { name, version } => {
                AssetTransferMethod::Eip3009 { name, version }
            }
        })
    }
}

#[allow(dead_code)] // Public for consumption by downstream crates.
impl Eip155TokenDeployment {
    /// Creates a token amount from a raw value.
    ///
    /// The value should already be in the token's smallest unit (e.g., wei).
    pub fn amount<V: Into<u64>>(&self, v: V) -> DeployedTokenAmount<U256, Eip155TokenDeployment> {
        DeployedTokenAmount {
            amount: U256::from(v.into()),
            token: self.clone(),
        }
    }

    /// Parses a human-readable amount string into token units.
    ///
    /// Accepts formats like `"10.50"`, `"$10.50"`, `"1,000"`, etc.
    /// The amount is scaled by the token's decimal places.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The input cannot be parsed as a number
    /// - The input has more decimal places than the token supports
    /// - The value is out of range
    ///
    /// # Example
    ///
    /// ```ignore
    /// use x402_rs::networks::{KnownNetworkEip155, USDC};
    ///
    /// let usdc = USDC::base();
    /// let amount = usdc.parse("10.50").unwrap();
    /// // 10.50 USDC = 10,500,000 units (6 decimals)
    /// assert_eq!(amount.amount, U256::from(10_500_000u64));
    /// ```
    pub fn parse<V>(
        &self,
        v: V,
    ) -> Result<DeployedTokenAmount<U256, Eip155TokenDeployment>, MoneyAmountParseError>
    where
        V: TryInto<MoneyAmount>,
        MoneyAmountParseError: From<<V as TryInto<MoneyAmount>>::Error>,
    {
        let money_amount = v.try_into()?;
        let scale = money_amount.scale();
        let token_scale = self.decimals as u32;
        if scale > token_scale {
            return Err(MoneyAmountParseError::WrongPrecision {
                money: scale,
                token: token_scale,
            });
        }
        let scale_diff = token_scale - scale;
        let multiplier = U256::from(10).pow(U256::from(scale_diff));
        let digits = money_amount.mantissa();
        let value = U256::from(digits).mul(multiplier);
        Ok(DeployedTokenAmount {
            amount: value,
            token: self.clone(),
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct EOASignature(Signature); // FIXME Add to EOA variant

impl AsRef<Signature> for EOASignature {
    fn as_ref(&self) -> &Signature {
        &self.0
    }
}

impl Serialize for EOASignature {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let bytes = self.0.as_bytes(); // [u8; 65]
        let hex = format!("0x{}", hex::encode(bytes));
        serializer.serialize_str(&hex)
    }
}

impl<'de> Deserialize<'de> for EOASignature {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct EOASignatureVisitor;

        impl<'de> de::Visitor<'de> for EOASignatureVisitor {
            type Value = EOASignature;

            fn expecting(&self, f: &mut Formatter) -> fmt::Result {
                f.write_str("a 0x-prefixed 65-byte Ethereum signature hex string")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                let hex = value
                    .strip_prefix("0x")
                    .ok_or_else(|| E::custom("signature must start with 0x"))?;

                let bytes = hex::decode(hex)
                    .map_err(|err| E::custom(format!("invalid hex signature: {err}")))?;

                let arr: [u8; 65] = bytes
                    .try_into()
                    .map_err(|_| E::custom("signature must be exactly 65 bytes"))?;

                let sig = alloy_primitives::Signature::from_raw(&arr)
                    .map_err(|err| E::custom(format!("invalid signature: {err}")))?;

                Ok(EOASignature(sig))
            }
        }

        deserializer.deserialize_str(EOASignatureVisitor)
    }
}

pub trait EOASignatureExt {
    fn r_bytes(&self) -> B256;
    fn s_bytes(&self) -> B256;
    fn v_legacy(&self) -> u8;
}

impl EOASignatureExt for EOASignature {
    #[inline]
    fn r_bytes(&self) -> B256 {
        self.0.r_bytes()
    }

    #[inline]
    fn s_bytes(&self) -> B256 {
        self.0.s_bytes()
    }

    #[inline]
    fn v_legacy(&self) -> u8 {
        self.0.v_legacy()
    }
}

impl EOASignatureExt for Signature {
    #[inline]
    fn r_bytes(&self) -> B256 {
        B256::from(self.r())
    }

    #[inline]
    fn s_bytes(&self) -> B256 {
        B256::from(self.s())
    }

    #[inline]
    fn v_legacy(&self) -> u8 {
        27 + (self.v() as u8)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_deployment(decimals: u8) -> Eip155TokenDeployment {
        let chain_ref = Eip155ChainReference::new(1); // Mainnet
        Eip155TokenDeployment {
            chain_reference: chain_ref,
            address: Address::ZERO,
            decimals,
            transfer_method: AssetTransferMethod::Eip3009 {
                name: "TestToken".into(),
                version: "2".into(),
            },
        }
    }

    #[test]
    fn test_parse_whole_number() {
        let deployment = create_test_deployment(6); // 6 decimals like USDC
        let result = deployment.parse("100");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().amount, U256::from(100_000_000u64)); // 100 * 10^6
    }

    #[test]
    fn test_parse_with_decimals() {
        let deployment = create_test_deployment(6);
        let result = deployment.parse("1.50");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().amount, U256::from(1_500_000u64)); // 1.50 * 10^6
    }

    #[test]
    fn test_parse_zero_decimals() {
        let deployment = create_test_deployment(0);
        let result = deployment.parse("42");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().amount, U256::from(42u64));
    }

    #[test]
    fn test_parse_precision_too_high() {
        let deployment = create_test_deployment(2); // Only 2 decimals
        let result = deployment.parse("1.234"); // 3 decimals - should fail
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, MoneyAmountParseError::WrongPrecision { .. }));
    }

    #[test]
    fn test_parse_exact_precision() {
        let deployment = create_test_deployment(9); // 9 decimals
        let result = deployment.parse("0.123456789");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().amount, U256::from(123_456_789u64));
    }

    #[test]
    fn test_parse_smallest_amount() {
        let deployment = create_test_deployment(6);
        let result = deployment.parse("0.000001");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().amount, U256::from(1u64));
    }

    #[test]
    fn test_parse_with_currency_symbol() {
        let deployment = create_test_deployment(6);
        let result = deployment.parse("$10.50");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().amount, U256::from(10_500_000u64));
    }

    #[test]
    fn test_parse_with_commas() {
        let deployment = create_test_deployment(6);
        let result = deployment.parse("1,000");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().amount, U256::from(1_000_000_000u64));
    }

    #[test]
    fn test_parse_large_amount() {
        let deployment = create_test_deployment(6);
        let result = deployment.parse("999999999");
        assert!(result.is_ok());
        // 999999999 * 10^6 = 999999999000000
        assert_eq!(result.unwrap().amount, U256::from(999_999_999_000_000u64));
    }

    #[test]
    fn test_parse_very_large_amount_with_high_decimals() {
        // EIP155 uses U256, so we can handle much larger amounts than Solana
        let deployment = create_test_deployment(18); // 18 decimals like ETH
        let result = deployment.parse("999999999"); // 9 digits, 0 decimals
        assert!(result.is_ok());
        // 999999999 * 10^18 = 999999999000000000000000000
        let expected = U256::from(999_999_999u64) * U256::from(10).pow(U256::from(18));
        assert_eq!(result.unwrap().amount, expected);
    }
}