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
// SPDX-License-Identifier: Apache-2.0

//! Ledger Ethereum Application SDK
//!
//! This crate provides a comprehensive interface for interacting with the Ethereum application
//! on Ledger hardware wallets. It implements the full APDU command set as specified in the
//! Ethereum application technical documentation.
//!
//! ## Features
//!
//! - **Core Operations**: Get addresses, sign transactions, sign personal messages
//! - **Configuration**: Query application configuration and capabilities
//! - **BIP32 Support**: Full BIP32 derivation path support with validation
//! - **Chunked Operations**: Support for large data transmission via chunked APDU commands
//! - **Type Safety**: Strongly typed parameters and responses
//! - **Async/Await**: Fully async API using async-trait
//!
//!

use async_trait::async_trait;
use ledger_sdk_device_base::App;
use ledger_sdk_transport::Exchange;

// Re-export all public types and traits
pub mod commands;
pub mod errors;
pub mod instructions;
pub mod types;
pub mod utils;

pub use commands::*;
pub use errors::*;
pub use types::*;

/// Ethereum app marker implementing `App` trait CLA.
#[derive(Debug, Clone)]
pub struct EthApp;

impl App for EthApp {
    /// CLA for Ethereum app on Ledger (0xE0)
    const CLA: u8 = 0xE0;
}

/// High-level Ethereum application client
///
/// This struct provides a convenient interface for all Ethereum application operations.
/// It wraps the transport layer and provides type-safe methods for interacting with
/// the Ledger device.
#[derive(Debug)]
pub struct EthereumApp<E: Exchange> {
    transport: E,
}

impl<E: Exchange> EthereumApp<E> {
    /// Create a new Ethereum application client
    pub fn new(transport: E) -> Self {
        Self { transport }
    }

    /// Get a reference to the underlying transport
    pub fn transport(&self) -> &E {
        &self.transport
    }
}

#[async_trait]
impl<E> GetAddress<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn get_address(
        transport: &E,
        params: GetAddressParams,
    ) -> EthAppResult<PublicKeyInfo, E::Error> {
        EthApp::get_address(transport, params).await
    }
}

#[async_trait]
impl<E> GetConfiguration<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn get_configuration(transport: &E) -> EthAppResult<AppConfiguration, E::Error> {
        EthApp::get_configuration(transport).await
    }
}

#[async_trait]
impl<E> SignPersonalMessage<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn sign_personal_message(
        transport: &E,
        params: SignMessageParams,
    ) -> EthAppResult<Signature, E::Error> {
        EthApp::sign_personal_message(transport, params).await
    }
}

#[async_trait]
impl<E> SignTransaction<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn sign_transaction(
        transport: &E,
        params: SignTransactionParams,
    ) -> EthAppResult<Signature, E::Error> {
        EthApp::sign_transaction(transport, params).await
    }

    async fn sign_transaction_with_mode(
        transport: &E,
        params: SignTransactionParams,
        mode: commands::sign_transaction::TransactionMode,
    ) -> EthAppResult<Option<Signature>, E::Error> {
        EthApp::sign_transaction_with_mode(transport, params, mode).await
    }
}

#[async_trait]
impl<E> SignEip712V0<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn sign_eip712_v0(
        transport: &E,
        params: SignEip712Params,
    ) -> EthAppResult<Signature, E::Error> {
        EthApp::sign_eip712_v0(transport, params).await
    }
}

#[async_trait]
impl<E> SignEip712Full<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn sign_eip712_full(transport: &E, path: &BipPath) -> EthAppResult<Signature, E::Error> {
        EthApp::sign_eip712_full(transport, path).await
    }
}

#[async_trait]
impl<E> Eip712StructDef<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn send_struct_definition(
        transport: &E,
        struct_def: &Eip712StructDefinition,
    ) -> EthAppResult<(), E::Error> {
        EthApp::send_struct_definition(transport, struct_def).await
    }
}

#[async_trait]
impl<E> Eip712StructImpl<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn send_struct_implementation(
        transport: &E,
        struct_impl: &Eip712StructImplementation,
    ) -> EthAppResult<(), E::Error> {
        EthApp::send_struct_implementation(transport, struct_impl).await
    }

    async fn set_array_size(transport: &E, size: u8) -> EthAppResult<(), E::Error> {
        EthApp::set_array_size(transport, size).await
    }
}

#[async_trait]
impl<E> Eip712Filtering<E> for EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    async fn send_filter_config(
        transport: &E,
        filter_params: &Eip712FilterParams,
    ) -> EthAppResult<(), E::Error> {
        EthApp::send_filter_config(transport, filter_params).await
    }

    async fn activate_filtering(transport: &E) -> EthAppResult<(), E::Error> {
        EthApp::activate_filtering(transport).await
    }
}

impl<E> EthereumApp<E>
where
    E: Exchange + Send + Sync,
    E::Error: std::error::Error,
{
    /// Get Ethereum public address for the given BIP 32 path
    ///
    /// # Arguments
    ///
    /// * `params` - Parameters for address retrieval including path, display options, etc.
    ///
    /// # Returns
    ///
    /// Returns `PublicKeyInfo` containing the public key, address, and optionally chain code.
    ///
    ///
    pub async fn get_address(
        &self,
        params: GetAddressParams,
    ) -> EthAppResult<PublicKeyInfo, E::Error> {
        EthApp::get_address(&self.transport, params).await
    }

    /// Get Ethereum application configuration
    ///
    /// Returns information about the application's capabilities and version.
    ///
    ///
    pub async fn get_configuration(&self) -> EthAppResult<AppConfiguration, E::Error> {
        EthApp::get_configuration(&self.transport).await
    }

    /// Sign an Ethereum personal message
    ///
    /// Signs a message using the personal_sign specification. The message will be
    /// displayed on the device for user confirmation.
    ///
    /// # Arguments
    ///
    /// * `params` - Parameters including BIP32 path and message data
    ///
    ///
    pub async fn sign_personal_message(
        &self,
        params: SignMessageParams,
    ) -> EthAppResult<Signature, E::Error> {
        EthApp::sign_personal_message(&self.transport, params).await
    }

    /// Sign an Ethereum transaction
    ///
    /// Signs a transaction using the provided RLP-encoded transaction data.
    /// The transaction details will be displayed on the device for user confirmation.
    ///
    /// # Arguments
    ///
    /// * `params` - Parameters including BIP32 path and RLP-encoded transaction data
    ///
    ///
    pub async fn sign_transaction(
        &self,
        params: SignTransactionParams,
    ) -> EthAppResult<Signature, E::Error> {
        EthApp::sign_transaction(&self.transport, params).await
    }

    /// Sign an Ethereum transaction with specific processing mode
    ///
    /// Provides fine-grained control over transaction processing, allowing for
    /// operations like storing transaction data without immediate signing.
    ///
    /// # Arguments
    ///
    /// * `params` - Parameters including BIP32 path and RLP-encoded transaction data
    /// * `mode` - Processing mode (ProcessAndStart, StoreOnly, or StartFlow)
    ///
    /// # Returns
    ///
    /// Returns `Some(Signature)` for modes that produce a signature, or `None` for store-only mode.
    pub async fn sign_transaction_with_mode(
        &self,
        params: SignTransactionParams,
        mode: commands::sign_transaction::TransactionMode,
    ) -> EthAppResult<Option<Signature>, E::Error> {
        EthApp::sign_transaction_with_mode(&self.transport, params, mode).await
    }

    /// Sign an EIP-712 message using v0 implementation (domain hash + message hash)
    ///
    /// This is the simpler EIP-712 signing mode where domain and message hashes
    /// are computed externally and provided directly to the device.
    ///
    /// **Version Requirements**: Requires app version >= 1.5.0
    ///
    /// # Arguments
    ///
    /// * `params` - Parameters including BIP32 path, domain hash, and message hash
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.5.0
    ///
    pub async fn sign_eip712_v0(
        &self,
        params: SignEip712Params,
    ) -> EthAppResult<Signature, E::Error> {
        // Check version requirement for EIP-712 v0 (>= 1.5.0)
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_v0() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 v0 requires app version >= 1.5.0, found {}",
                config.version
            )));
        }

        EthApp::sign_eip712_v0(&self.transport, params).await
    }

    /// Sign an EIP-712 message using full implementation
    ///
    /// This mode requires sending struct definitions and implementations before
    /// calling this final signing method. Use the struct definition and
    /// implementation methods first to set up the EIP-712 data.
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Arguments
    ///
    /// * `path` - BIP32 derivation path for the signing key
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    ///
    pub async fn sign_eip712_full(&self, path: &BipPath) -> EthAppResult<Signature, E::Error> {
        // Check version requirement for EIP-712 full (>= 1.9.19)
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 full implementation requires app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::sign_eip712_full(&self.transport, path).await
    }

    /// Send EIP-712 struct definition to the device
    ///
    /// This method sends type definitions for EIP-712 structures. Must be called
    /// before sending struct implementations in full EIP-712 mode.
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Arguments
    ///
    /// * `struct_def` - The struct definition including name and field types
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    ///
    pub async fn send_struct_definition(
        &self,
        struct_def: &Eip712StructDefinition,
    ) -> EthAppResult<(), E::Error> {
        // Check version requirement for EIP-712 full implementation
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 struct definitions require app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::send_struct_definition(&self.transport, struct_def).await
    }

    /// Send EIP-712 struct implementation to the device
    ///
    /// This method sends the actual data values for EIP-712 structures.
    /// Must be called after sending struct definitions.
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Arguments
    ///
    /// * `struct_impl` - The struct implementation with field values
    /// * `complete` - Whether this is a complete send or partial
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    ///
    pub async fn send_struct_implementation(
        &self,
        struct_impl: &Eip712StructImplementation,
    ) -> EthAppResult<(), E::Error> {
        // Check version requirement for EIP-712 full implementation
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 struct implementations require app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::send_struct_implementation(&self.transport, struct_impl).await
    }

    /// Set array size for upcoming array fields in EIP-712 implementation
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Arguments
    ///
    /// * `size` - The size of the array
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    ///
    pub async fn set_array_size(&self, size: u8) -> EthAppResult<(), E::Error> {
        // Check version requirement for EIP-712 full implementation
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 array operations require app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::set_array_size(&self.transport, size).await
    }

    /// Send EIP-712 filtering configuration
    ///
    /// Configure how EIP-712 data should be filtered and displayed on the device.
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Arguments
    ///
    /// * `filter_params` - Filtering parameters and configuration
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    ///
    pub async fn send_filter_config(
        &self,
        filter_params: &Eip712FilterParams,
    ) -> EthAppResult<(), E::Error> {
        // Check version requirement for EIP-712 full implementation
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 filtering requires app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::send_filter_config(&self.transport, filter_params).await
    }

    /// Activate EIP-712 filtering on the device
    ///
    /// Must be called to enable filtering before sending struct definitions.
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    ///
    pub async fn activate_filtering(&self) -> EthAppResult<(), E::Error> {
        // Check version requirement for EIP-712 full implementation
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 filtering requires app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::activate_filtering(&self.transport).await
    }

    /// Sign EIP-712 typed data using the high-level API (matching viem interface)
    ///
    /// This method provides a simple interface for EIP-712 signing that matches the viem
    /// interface. It automatically handles the conversion from high-level typed data to
    /// the low-level struct definitions and implementations required by the Ledger device.
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Arguments
    ///
    /// * `path` - BIP32 derivation path for the signing key
    /// * `typed_data` - EIP-712 typed data structure matching viem interface
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use ledger_eth_app::{Eip712Domain, Eip712Field, Eip712Struct, Eip712Types, Eip712TypedData};
    /// use serde_json::json;
    /// use std::collections::HashMap;
    ///
    /// 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 = 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);
    /// // let signature = app.sign_eip712_typed_data(&path, &typed_data).await?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    ///
    pub async fn sign_eip712_typed_data(
        &self,
        path: &BipPath,
        typed_data: &Eip712TypedData,
    ) -> EthAppResult<crate::types::Signature, E::Error> {
        // Check version requirement for EIP-712 full implementation
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 typed data signing requires app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::sign_eip712_typed_data(&self.transport, path, typed_data).await
    }

    /// Sign EIP-712 typed data from JSON string
    ///
    /// This method accepts a JSON string containing EIP-712 typed data and automatically
    /// parses, validates, and signs it. The JSON format should match the standard EIP-712
    /// structure with domain, types, primaryType, and message fields.
    ///
    /// **Version Requirements**: Requires app version >= 1.9.19
    ///
    /// # Arguments
    ///
    /// * `path` - BIP32 derivation path for the signing key
    /// * `json_str` - JSON string containing EIP-712 typed data
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let json_str = r#"{
    ///   "domain": {
    ///     "name": "USD Coin",
    ///     "verifyingContract": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
    ///     "chainId": 1,
    ///     "version": "2"
    ///   },
    ///   "primaryType": "Permit",
    ///   "message": {
    ///     "deadline": 1718992051,
    ///     "nonce": 0,
    ///     "spender": "0x111111125421ca6dc452d289314280a0f8842a65",
    ///     "owner": "0x6cbcd73cd8e8a42844662f0a0e76d7f79afd933d",
    ///     "value": "115792089237316195423570985008687907853269984665640564039457584007913129639935"
    ///   },
    ///   "types": {
    ///     "EIP712Domain": [
    ///       {"name": "name", "type": "string"},
    ///       {"name": "version", "type": "string"},
    ///       {"name": "chainId", "type": "uint256"},
    ///       {"name": "verifyingContract", "type": "address"}
    ///     ],
    ///     "Permit": [
    ///       {"name": "owner", "type": "address"},
    ///       {"name": "spender", "type": "address"},
    ///       {"name": "value", "type": "uint256"},
    ///       {"name": "nonce", "type": "uint256"},
    ///       {"name": "deadline", "type": "uint256"}
    ///     ]
    ///   }
    /// }"#;
    ///
    /// // let signature = app.sign_eip712_from_json(&path, json_str).await?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `EthAppError::UnsupportedVersion` if app version is below 1.9.19
    /// Returns `EthAppError::InvalidEip712Data` if JSON format is invalid
    ///
    pub async fn sign_eip712_from_json(
        &self,
        path: &BipPath,
        json_str: &str,
    ) -> EthAppResult<crate::types::Signature, E::Error> {
        // Check version requirement for EIP-712 full implementation
        let config = self.get_configuration().await?;
        if !config.version.supports_eip712_full() {
            return Err(EthAppError::UnsupportedVersion(format!(
                "EIP-712 JSON signing requires app version >= 1.9.19, found {}",
                config.version
            )));
        }

        EthApp::sign_eip712_from_json(&self.transport, path, json_str).await
    }
}