ledger-sdk-eth-app 0.0.1

Ledger Ethereum app interaction helpers with EIP-712 support
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
// SPDX-License-Identifier: Apache-2.0

//! Core data types for Ethereum application

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

/// BIP32 derivation path for Ethereum accounts
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BipPath {
    /// Derivation indices (max 10 levels)
    pub indices: Vec<u32>,
}

impl BipPath {
    /// Create a new BIP32 path from derivation indices
    pub fn new(indices: Vec<u32>) -> Result<Self, String> {
        if indices.len() > crate::instructions::length::MAX_BIP32_PATH_DEPTH {
            return Err(format!(
                "BIP32 path too deep: {} (max {})",
                indices.len(),
                crate::instructions::length::MAX_BIP32_PATH_DEPTH
            ));
        }
        Ok(BipPath { indices })
    }

    /// Parse BIP32 path from string format (e.g., "m/44'/60'/0'/0/0")
    pub fn from_string(path_str: &str) -> Result<Self, String> {
        const PADDING: u32 = 0x80000000;

        if !path_str.starts_with("m/") {
            return Err("BIP32 path must start with 'm/'".to_string());
        }

        let components: Vec<&str> = path_str[2..].split('/').collect();
        let mut indices = Vec::new();

        for component in components {
            if component.is_empty() {
                continue;
            }

            let (number_str, is_hardened) = if let Some(stripped) = component.strip_suffix("'") {
                (stripped, true)
            } else {
                (component, false)
            };

            let number: u32 = number_str
                .parse()
                .map_err(|_| format!("Invalid number in path component: {}", component))?;

            let final_number = if is_hardened {
                number + PADDING
            } else {
                number
            };

            indices.push(final_number);
        }

        if indices.is_empty() {
            return Err("BIP32 path cannot be empty".to_string());
        }

        Self::new(indices)
    }

    /// Create a standard Ethereum derivation path: m/44'/60'/account'/0/address_index
    pub fn ethereum_standard(account: u32, address_index: u32) -> Self {
        BipPath {
            indices: vec![
                0x8000002C,           // 44' (hardened)
                0x8000003C,           // 60' (hardened) - Ethereum
                0x80000000 | account, // account' (hardened)
                0,                    // 0 (external chain)
                address_index,        // address index
            ],
        }
    }

    /// Get the encoded length for APDU
    pub fn encoded_len(&self) -> usize {
        1 + self.indices.len() * crate::instructions::length::BIP32_INDEX_SIZE
    }
}

impl fmt::Display for BipPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "m")?;
        for index in &self.indices {
            if *index >= 0x80000000 {
                write!(f, "/{}'", index - 0x80000000)?;
            } else {
                write!(f, "/{}", index)?;
            }
        }
        Ok(())
    }
}

/// Ethereum address information
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct EthAddress {
    /// ASCII-encoded Ethereum address (with 0x prefix)
    pub address: String,
}

impl EthAddress {
    /// Create a new Ethereum address from hex string
    pub fn new(address: String) -> Result<Self, String> {
        if !address.starts_with("0x") {
            return Err("Ethereum address must start with 0x".to_string());
        }
        if address.len() != 42 {
            return Err("Ethereum address must be 42 characters long".to_string());
        }
        Ok(EthAddress { address })
    }

    /// Get the address without 0x prefix
    pub fn without_prefix(&self) -> &str {
        &self.address[2..]
    }

    /// Get the raw bytes of the address
    pub fn to_bytes(&self) -> Result<Vec<u8>, hex::FromHexError> {
        hex::decode(self.without_prefix())
    }
}

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

/// Public key information returned from device
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PublicKeyInfo {
    /// Uncompressed public key (65 bytes)
    pub public_key: Vec<u8>,
    /// Ethereum address derived from public key
    pub address: EthAddress,
    /// Optional chain code (32 bytes) if requested
    pub chain_code: Option<Vec<u8>>,
}

/// Signature result from signing operations
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Signature {
    /// Recovery value (0 or 1)
    pub v: u8,
    /// Signature component r (32 bytes)
    pub r: Vec<u8>,
    /// Signature component s (32 bytes)
    pub s: Vec<u8>,
}

impl Signature {
    /// Create a new signature from components
    pub fn new(v: u8, r: Vec<u8>, s: Vec<u8>) -> Result<Self, String> {
        if r.len() != crate::instructions::length::SIGNATURE_COMPONENT_SIZE {
            return Err(format!("Invalid r length: {} (expected 32)", r.len()));
        }
        if s.len() != crate::instructions::length::SIGNATURE_COMPONENT_SIZE {
            return Err(format!("Invalid s length: {} (expected 32)", s.len()));
        }
        Ok(Signature { v, r, s })
    }

    /// Get the signature in DER format
    pub fn to_der(&self) -> Vec<u8> {
        let mut result = Vec::new();
        result.push(self.v);
        result.extend_from_slice(&self.r);
        result.extend_from_slice(&self.s);
        result
    }
}

/// Application configuration information
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppConfiguration {
    /// Configuration flags
    pub flags: ConfigFlags,
    /// Application version
    pub version: AppVersion,
}

/// Configuration flags for the Ethereum application
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfigFlags {
    /// Arbitrary data signature enabled by user
    pub arbitrary_data_signature: bool,
    /// ERC 20 Token information needs to be provided externally
    pub erc20_external_info: bool,
    /// Transaction Check enabled
    pub transaction_check_enabled: bool,
    /// Transaction Check Opt-In done
    pub transaction_check_opt_in: bool,
}

impl ConfigFlags {
    /// Parse configuration flags from raw byte
    pub fn from_byte(flags: u8) -> Self {
        ConfigFlags {
            arbitrary_data_signature: (flags
                & crate::instructions::config_flags::ARBITRARY_DATA_SIGNATURE)
                != 0,
            erc20_external_info: (flags & crate::instructions::config_flags::ERC20_EXTERNAL_INFO)
                != 0,
            transaction_check_enabled: (flags
                & crate::instructions::config_flags::TRANSACTION_CHECK_ENABLED)
                != 0,
            transaction_check_opt_in: (flags
                & crate::instructions::config_flags::TRANSACTION_CHECK_OPT_IN)
                != 0,
        }
    }

    /// Convert configuration flags to raw byte
    pub fn to_byte(&self) -> u8 {
        let mut flags = 0u8;
        if self.arbitrary_data_signature {
            flags |= crate::instructions::config_flags::ARBITRARY_DATA_SIGNATURE;
        }
        if self.erc20_external_info {
            flags |= crate::instructions::config_flags::ERC20_EXTERNAL_INFO;
        }
        if self.transaction_check_enabled {
            flags |= crate::instructions::config_flags::TRANSACTION_CHECK_ENABLED;
        }
        if self.transaction_check_opt_in {
            flags |= crate::instructions::config_flags::TRANSACTION_CHECK_OPT_IN;
        }
        flags
    }
}

/// Application version information
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AppVersion {
    /// Major version
    pub major: u8,
    /// Minor version
    pub minor: u8,
    /// Patch version
    pub patch: u8,
}

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

impl AppVersion {
    /// Create a new AppVersion
    pub fn new(major: u8, minor: u8, patch: u8) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    /// Check if this version supports EIP-712 v0 implementation (>= 1.5.0)
    pub fn supports_eip712_v0(&self) -> bool {
        self.major > 1 || (self.major == 1 && self.minor >= 5)
    }

    /// Check if this version supports EIP-712 full implementation (>= 1.9.19)
    pub fn supports_eip712_full(&self) -> bool {
        self.major > 1
            || (self.major == 1 && self.minor > 9)
            || (self.major == 1 && self.minor == 9 && self.patch >= 19)
    }

    /// Compare with another version
    pub fn compare(&self, other: &AppVersion) -> std::cmp::Ordering {
        use std::cmp::Ordering;

        match self.major.cmp(&other.major) {
            Ordering::Equal => match self.minor.cmp(&other.minor) {
                Ordering::Equal => self.patch.cmp(&other.patch),
                other => other,
            },
            other => other,
        }
    }

    /// Check if this version is greater than or equal to another version
    pub fn is_at_least(&self, other: &AppVersion) -> bool {
        matches!(
            self.compare(other),
            std::cmp::Ordering::Greater | std::cmp::Ordering::Equal
        )
    }
}

/// Parameters for GET ETH PUBLIC ADDRESS command
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GetAddressParams {
    /// BIP32 derivation path
    pub path: BipPath,
    /// Whether to display address on device and require confirmation
    pub display: bool,
    /// Whether to return chain code
    pub return_chain_code: bool,
    /// Optional chain ID for validation
    pub chain_id: Option<u64>,
}

impl GetAddressParams {
    /// Create new parameters for getting an address
    pub fn new(path: BipPath) -> Self {
        GetAddressParams {
            path,
            display: false,
            return_chain_code: false,
            chain_id: None,
        }
    }

    /// Enable display and confirmation on device
    pub fn with_display(mut self) -> Self {
        self.display = true;
        self
    }

    /// Enable chain code return
    pub fn with_chain_code(mut self) -> Self {
        self.return_chain_code = true;
        self
    }

    /// Set chain ID for validation
    pub fn with_chain_id(mut self, chain_id: u64) -> Self {
        self.chain_id = Some(chain_id);
        self
    }
}

/// Parameters for SIGN ETH TRANSACTION command
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SignTransactionParams {
    /// BIP32 derivation path
    pub path: BipPath,
    /// RLP-encoded transaction data
    pub transaction_data: Vec<u8>,
}

impl SignTransactionParams {
    /// Create new parameters for signing a transaction
    pub fn new(path: BipPath, transaction_data: Vec<u8>) -> Self {
        SignTransactionParams {
            path,
            transaction_data,
        }
    }
}

/// Parameters for SIGN ETH PERSONAL MESSAGE command
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SignMessageParams {
    /// BIP32 derivation path
    pub path: BipPath,
    /// Message data to sign
    pub message: Vec<u8>,
}

impl SignMessageParams {
    /// Create new parameters for signing a personal message
    pub fn new(path: BipPath, message: Vec<u8>) -> Self {
        SignMessageParams { path, message }
    }
}

/// EIP-712 implementation mode
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Eip712Mode {
    /// v0 implementation: provides domain hash and message hash directly
    V0Implementation,
    /// Full implementation: uses JSON data and performs hashing on device
    FullImplementation,
}

/// Parameters for SIGN ETH EIP 712 command (v0 mode)
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SignEip712Params {
    /// BIP32 derivation path
    pub path: BipPath,
    /// Domain hash (32 bytes)
    pub domain_hash: [u8; 32],
    /// Message hash (32 bytes)
    pub message_hash: [u8; 32],
}

impl SignEip712Params {
    /// Create new parameters for EIP-712 v0 signing
    pub fn new(path: BipPath, domain_hash: [u8; 32], message_hash: [u8; 32]) -> Self {
        SignEip712Params {
            path,
            domain_hash,
            message_hash,
        }
    }
}

/// EIP-712 field type enumeration
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Eip712FieldType {
    /// Custom struct type
    Custom(String),
    /// Integer type with size in bytes
    Int(u8),
    /// Unsigned integer type with size in bytes
    Uint(u8),
    /// Ethereum address type
    Address,
    /// Boolean type
    Bool,
    /// String type
    String,
    /// Fixed-size bytes with size
    FixedBytes(u8),
    /// Dynamic-size bytes
    DynamicBytes,
}

impl Eip712FieldType {
    /// Get the type ID for encoding
    pub fn type_id(&self) -> u8 {
        match self {
            Eip712FieldType::Custom(_) => 0,
            Eip712FieldType::Int(_) => 1,
            Eip712FieldType::Uint(_) => 2,
            Eip712FieldType::Address => 3,
            Eip712FieldType::Bool => 4,
            Eip712FieldType::String => 5,
            Eip712FieldType::FixedBytes(_) => 6,
            Eip712FieldType::DynamicBytes => 7,
        }
    }

    /// Get the type size if applicable
    pub fn type_size(&self) -> Option<u8> {
        match self {
            Eip712FieldType::Int(size) => Some(*size),
            Eip712FieldType::Uint(size) => Some(*size),
            Eip712FieldType::FixedBytes(size) => Some(*size),
            _ => None,
        }
    }

    /// Get the type name for custom types
    pub fn type_name(&self) -> Option<&str> {
        match self {
            Eip712FieldType::Custom(name) => Some(name),
            _ => None,
        }
    }
}

/// EIP-712 array level type
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Eip712ArrayLevel {
    /// Dynamic array (type[])
    Dynamic,
    /// Fixed-size array (type[N])
    Fixed(u8),
}

impl Eip712ArrayLevel {
    /// Get the array level type ID for encoding
    pub fn type_id(&self) -> u8 {
        match self {
            Eip712ArrayLevel::Dynamic => 0,
            Eip712ArrayLevel::Fixed(_) => 1,
        }
    }

    /// Get the array size if fixed
    pub fn size(&self) -> Option<u8> {
        match self {
            Eip712ArrayLevel::Fixed(size) => Some(*size),
            Eip712ArrayLevel::Dynamic => None,
        }
    }
}

/// EIP-712 struct field definition
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712FieldDefinition {
    /// Field data type
    pub field_type: Eip712FieldType,
    /// Field name
    pub name: String,
    /// Array levels (empty if not an array)
    pub array_levels: Vec<Eip712ArrayLevel>,
}

impl Eip712FieldDefinition {
    /// Create a new field definition
    pub fn new(field_type: Eip712FieldType, name: String) -> Self {
        Eip712FieldDefinition {
            field_type,
            name,
            array_levels: Vec::new(),
        }
    }

    /// Add an array level to the field
    pub fn with_array_level(mut self, level: Eip712ArrayLevel) -> Self {
        self.array_levels.push(level);
        self
    }

    /// Check if this field is an array
    pub fn is_array(&self) -> bool {
        !self.array_levels.is_empty()
    }
}

/// EIP-712 struct definition
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712StructDefinition {
    /// Struct name
    pub name: String,
    /// Struct fields
    pub fields: Vec<Eip712FieldDefinition>,
}

impl Eip712StructDefinition {
    /// Create a new struct definition
    pub fn new(name: String) -> Self {
        Eip712StructDefinition {
            name,
            fields: Vec::new(),
        }
    }

    /// Add a field to the struct
    pub fn with_field(mut self, field: Eip712FieldDefinition) -> Self {
        self.fields.push(field);
        self
    }

    /// Sort fields alphabetically by name (important for EIP-712 hash consistency)
    pub fn with_sorted_fields(mut self) -> Self {
        self.fields.sort_by(|a, b| a.name.cmp(&b.name));
        self
    }
}

/// EIP-712 struct implementation value
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712FieldValue {
    /// Raw value data
    pub value: Vec<u8>,
}

impl Eip712FieldValue {
    /// Create a new field value
    pub fn new(value: Vec<u8>) -> Self {
        Eip712FieldValue { value }
    }

    /// Create from a string value
    pub fn from_string(s: &str) -> Self {
        Eip712FieldValue {
            value: s.as_bytes().to_vec(),
        }
    }

    /// Create from a u256 value
    pub fn from_u256(value: &[u8; 32]) -> Self {
        Eip712FieldValue {
            value: value.to_vec(),
        }
    }

    /// Create from an address
    pub fn from_address(address: &[u8; 20]) -> Self {
        Eip712FieldValue {
            value: address.to_vec(),
        }
    }

    /// Create from a boolean
    pub fn from_bool(value: bool) -> Self {
        Eip712FieldValue {
            value: vec![if value { 1 } else { 0 }],
        }
    }

    /// Create from a uint value (defaults to 8-byte u64)
    pub fn from_uint(value: u64) -> Self {
        Eip712FieldValue {
            value: value.to_be_bytes().to_vec(),
        }
    }

    /// Create from a uint value with specific size
    pub fn from_uint_sized(size: u8, value: u64) -> Self {
        let mut bytes = vec![0u8; size as usize];
        let value_bytes = value.to_be_bytes();
        let start = bytes.len().saturating_sub(value_bytes.len());
        let copy_len = (bytes.len() - start).min(value_bytes.len());
        bytes[start..start + copy_len]
            .copy_from_slice(&value_bytes[value_bytes.len() - copy_len..]);
        Eip712FieldValue { value: bytes }
    }

    /// Create from a uint32 value (4 bytes)
    pub fn from_uint32(value: u32) -> Self {
        Eip712FieldValue {
            value: value.to_be_bytes().to_vec(),
        }
    }

    /// Create from an address string (hex format)
    pub fn from_address_string(address: &str) -> Result<Self, String> {
        // Remove 0x prefix if present
        let hex_str = if let Some(stripped) = address.strip_prefix("0x") {
            stripped
        } else {
            address
        };

        // Validate length
        if hex_str.len() != 40 {
            return Err(format!(
                "Invalid address length: expected 40 hex characters, got {}",
                hex_str.len()
            ));
        }

        // Parse hex
        let bytes = hex::decode(hex_str).map_err(|e| format!("Invalid hex: {}", e))?;
        if bytes.len() != 20 {
            return Err("Address must be 20 bytes".to_string());
        }

        Ok(Eip712FieldValue { value: bytes })
    }

    /// Create a reference to a nested struct (empty value for struct references)
    pub fn from_struct() -> Self {
        Eip712FieldValue { value: vec![] }
    }

    /// Create from an int value with specific size
    pub fn from_int_sized(size: u8, value: i64) -> Self {
        let mut bytes = vec![0u8; size as usize];
        let value_bytes = value.to_be_bytes();
        let start = bytes.len().saturating_sub(value_bytes.len());
        let copy_len = (bytes.len() - start).min(value_bytes.len());
        bytes[start..start + copy_len]
            .copy_from_slice(&value_bytes[value_bytes.len() - copy_len..]);
        Eip712FieldValue { value: bytes }
    }

    /// Create from bytes
    pub fn from_bytes(bytes: Vec<u8>) -> Self {
        Eip712FieldValue { value: bytes }
    }
}

/// EIP-712 struct implementation
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712StructImplementation {
    /// Struct name
    pub name: String,
    /// Field values in order
    pub values: Vec<Eip712FieldValue>,
}

impl Eip712StructImplementation {
    /// Create a new struct implementation
    pub fn new(name: String) -> Self {
        Eip712StructImplementation {
            name,
            values: Vec::new(),
        }
    }

    /// Add a field value
    pub fn with_value(mut self, value: Eip712FieldValue) -> Self {
        self.values.push(value);
        self
    }
}

/// EIP-712 filtering operation type
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Eip712FilterType {
    /// Activation
    Activation,
    /// Discarded filter path
    DiscardedFilterPath(String),
    /// Message info
    MessageInfo {
        display_name: String,
        filters_count: u8,
        signature: Vec<u8>,
    },
    /// Trusted name
    TrustedName {
        display_name: String,
        name_types: Vec<u8>,
        name_sources: Vec<u8>,
        signature: Vec<u8>,
    },
    /// Date/time
    DateTime {
        display_name: String,
        signature: Vec<u8>,
    },
    /// Amount-join token
    AmountJoinToken { token_index: u8, signature: Vec<u8> },
    /// Amount-join value
    AmountJoinValue {
        display_name: String,
        token_index: u8,
        signature: Vec<u8>,
    },
    /// Raw field
    RawField {
        display_name: String,
        signature: Vec<u8>,
    },
}

/// Parameters for EIP-712 filtering operations
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Eip712FilterParams {
    /// Filter operation type
    pub filter_type: Eip712FilterType,
    /// Whether this filter is discarded
    pub discarded: bool,
}

// ============================================================================
// High-level EIP-712 Types (matching viem interface)
// ============================================================================

/// EIP-712 domain separator
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712Domain {
    /// Domain name
    pub name: Option<String>,
    /// Domain version
    pub version: Option<String>,
    /// Chain ID
    pub chain_id: Option<u64>,
    /// Verifying contract address
    pub verifying_contract: Option<String>,
    /// Salt (optional)
    pub salt: Option<Vec<u8>>,
}

impl Eip712Domain {
    /// Create a new domain
    pub fn new() -> Self {
        Eip712Domain {
            name: None,
            version: None,
            chain_id: None,
            verifying_contract: None,
            salt: None,
        }
    }

    /// Set the domain name
    pub fn with_name(mut self, name: String) -> Self {
        self.name = Some(name);
        self
    }

    /// Set the domain version
    pub fn with_version(mut self, version: String) -> Self {
        self.version = Some(version);
        self
    }

    /// Set the chain ID
    pub fn with_chain_id(mut self, chain_id: u64) -> Self {
        self.chain_id = Some(chain_id);
        self
    }

    /// Set the verifying contract address
    pub fn with_verifying_contract(mut self, address: String) -> Self {
        self.verifying_contract = Some(address);
        self
    }

    /// Set the salt
    pub fn with_salt(mut self, salt: Vec<u8>) -> Self {
        self.salt = Some(salt);
        self
    }
}

impl Default for Eip712Domain {
    fn default() -> Self {
        Self::new()
    }
}

/// EIP-712 field definition for high-level API
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712Field {
    /// Field name
    pub name: String,
    /// Field type (e.g., "string", "uint256", "address", "Person[]")
    pub r#type: String,
}

impl Eip712Field {
    /// Create a new field definition
    pub fn new(name: String, r#type: String) -> Self {
        Eip712Field { name, r#type }
    }
}

/// EIP-712 struct definition for high-level API
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712Struct {
    /// Struct fields
    pub fields: Vec<Eip712Field>,
}

impl Eip712Struct {
    /// Create a new struct definition
    pub fn new() -> Self {
        Eip712Struct { fields: Vec::new() }
    }

    /// Add a field to the struct
    pub fn with_field(mut self, field: Eip712Field) -> Self {
        self.fields.push(field);
        self
    }
}

impl Default for Eip712Struct {
    fn default() -> Self {
        Self::new()
    }
}

/// EIP-712 types mapping (struct name -> struct definition)
pub type Eip712Types = HashMap<String, Eip712Struct>;

/// EIP-712 typed data (matching viem interface)
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Eip712TypedData {
    /// Domain separator
    pub domain: Eip712Domain,
    /// Type definitions
    pub types: Eip712Types,
    /// Primary type (the main struct being signed)
    pub primary_type: String,
    /// Message data (as serde_json::Value for flexibility)
    pub message: serde_json::Value,
}

impl Eip712TypedData {
    /// Create new typed data
    pub fn new(
        domain: Eip712Domain,
        types: Eip712Types,
        primary_type: String,
        message: serde_json::Value,
    ) -> Self {
        Eip712TypedData {
            domain,
            types,
            primary_type,
            message,
        }
    }
}

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

    #[test]
    fn test_eip712_domain_creation() {
        let domain = Eip712Domain::new()
            .with_name("Ether Mail".to_string())
            .with_version("1".to_string())
            .with_chain_id(1)
            .with_verifying_contract("0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC".to_string());

        assert_eq!(domain.name, Some("Ether Mail".to_string()));
        assert_eq!(domain.version, Some("1".to_string()));
        assert_eq!(domain.chain_id, Some(1));
        assert_eq!(
            domain.verifying_contract,
            Some("0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC".to_string())
        );
    }

    #[test]
    fn test_eip712_struct_creation() {
        let person_struct = Eip712Struct::new()
            .with_field(Eip712Field::new("name".to_string(), "string".to_string()))
            .with_field(Eip712Field::new(
                "wallet".to_string(),
                "address".to_string(),
            ));

        assert_eq!(person_struct.fields.len(), 2);
        assert_eq!(person_struct.fields[0].name, "name");
        assert_eq!(person_struct.fields[0].r#type, "string");
        assert_eq!(person_struct.fields[1].name, "wallet");
        assert_eq!(person_struct.fields[1].r#type, "address");
    }

    #[test]
    fn test_eip712_typed_data_creation() {
        let domain = Eip712Domain::new()
            .with_name("Ether Mail".to_string())
            .with_version("1".to_string())
            .with_chain_id(1);

        let mut types = Eip712Types::new();
        types.insert(
            "Person".to_string(),
            Eip712Struct::new()
                .with_field(Eip712Field::new("name".to_string(), "string".to_string()))
                .with_field(Eip712Field::new(
                    "wallet".to_string(),
                    "address".to_string(),
                )),
        );

        let message = serde_json::json!({
            "from": {
                "name": "Cow",
                "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"
            },
            "to": {
                "name": "Bob",
                "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"
            },
            "contents": "Hello, Bob!"
        });

        let typed_data = Eip712TypedData::new(domain, types, "Mail".to_string(), message);

        assert_eq!(typed_data.primary_type, "Mail");
        assert!(typed_data.types.contains_key("Person"));
    }
}