visualsign 0.1.0

Visualsign package defines the structures helper methods to create VisualSign payloads for Anchorage's Open Source VisualSign
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
use std::collections::HashMap;
use std::marker::PhantomData;
use std::str::FromStr;

use crate::{
    vsptrait::{
        Transaction, VisualSignConverter, VisualSignConverterFromString, VisualSignError,
        VisualSignOptions,
    },
    SignablePayload,
};

/// Supported blockchain types
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Chain {
    Unspecified,
    Solana,
    Ethereum,
    Bitcoin,
    Sui,
    Aptos,
    Polkadot,
    Tron,
    // Add other chains as needed
    Custom(String), // For extensibility without modifying the enum
}

impl Chain {
    pub fn as_str(&self) -> &str {
        match self {
            Chain::Unspecified => "Unspecified",
            Chain::Solana => "Solana",
            Chain::Ethereum => "Ethereum",
            Chain::Bitcoin => "Bitcoin",
            Chain::Sui => "Sui",
            Chain::Aptos => "Aptos",
            Chain::Polkadot => "Polkadot",
            Chain::Tron => "Tron",
            Chain::Custom(name) => name.as_str(),
        }
    }
}

impl FromStr for Chain {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.to_lowercase().as_str() {
            "unspecified" => Chain::Unspecified,
            "solana" => Chain::Solana,
            "ethereum" => Chain::Ethereum,
            "bitcoin" => Chain::Bitcoin,
            "sui" => Chain::Sui,
            "aptos" => Chain::Aptos,
            "polkadot" => Chain::Polkadot,
            "tron" => Chain::Tron,
            _ => Chain::Custom(s.to_string()),
        })
    }
}

/// Type-erased trait for converters that can be stored in the registry
pub trait VisualSignConverterAny: Send + Sync {
    fn to_visual_sign_payload_from_string_any(
        &self,
        transaction_data: &str,
        options: VisualSignOptions,
    ) -> Result<SignablePayload, VisualSignError>;

    fn supports_format(&self, transaction_data: &str) -> bool;
}

// Create a wrapper type to hold both the converter and a marker for the transaction type
struct ConverterWrapper<T, C>
where
    T: Transaction + Send + Sync,
    C: VisualSignConverter<T> + VisualSignConverterFromString<T>,
{
    converter: C,
    _phantom: PhantomData<T>,
}

impl<T, C> ConverterWrapper<T, C>
where
    T: Transaction + Send + Sync,
    C: VisualSignConverter<T> + VisualSignConverterFromString<T>,
{
    fn new(converter: C) -> Self {
        Self {
            converter,
            _phantom: PhantomData,
        }
    }
}

// Implement VisualSignConverterAny for the wrapper
impl<T, C> VisualSignConverterAny for ConverterWrapper<T, C>
where
    T: Transaction + Send + Sync, // Add Send + Sync bounds to T for thread safety
    C: VisualSignConverter<T> + VisualSignConverterFromString<T> + Send + Sync,
{
    fn to_visual_sign_payload_from_string_any(
        &self,
        transaction_data: &str,
        options: VisualSignOptions,
    ) -> Result<SignablePayload, VisualSignError> {
        self.converter
            .to_visual_sign_payload_from_string(transaction_data, options)
    }

    fn supports_format(&self, transaction_data: &str) -> bool {
        // Try to parse and see if it succeeds
        T::from_string(transaction_data).is_ok()
    }
}

/// Registry for transaction converters
pub struct TransactionConverterRegistry {
    converters: HashMap<Chain, Box<dyn VisualSignConverterAny>>,
}

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

impl TransactionConverterRegistry {
    pub fn new() -> Self {
        Self {
            converters: HashMap::new(),
        }
    }

    pub fn register<T, C>(&mut self, chain: Chain, converter: C)
    where
        T: Transaction + Send + Sync + 'static,
        C: VisualSignConverter<T> + VisualSignConverterFromString<T> + Send + Sync + 'static,
    {
        self.converters
            .insert(chain, Box::new(ConverterWrapper::<T, C>::new(converter)));
    }

    pub fn get_converter(&self, chain: &Chain) -> Option<&dyn VisualSignConverterAny> {
        self.converters.get(chain).map(|c| c.as_ref())
    }

    pub fn convert_transaction(
        &self,
        chain: &Chain,
        transaction_data: &str,
        options: VisualSignOptions,
    ) -> Result<SignablePayload, VisualSignError> {
        match self.get_converter(chain) {
            Some(converter) => {
                converter.to_visual_sign_payload_from_string_any(transaction_data, options)
            }
            None => Err(VisualSignError::ConversionError(format!(
                "No converter registered for chain: {}",
                chain.as_str()
            ))),
        }
    }

    pub fn auto_detect_and_convert(
        &self,
        transaction_data: &str,
        options: VisualSignOptions,
    ) -> Result<(Chain, SignablePayload), VisualSignError> {
        // Try each converter to see if it can parse the transaction
        for (chain, converter) in &self.converters {
            if converter.supports_format(transaction_data) {
                match converter
                    .to_visual_sign_payload_from_string_any(transaction_data, options.clone())
                {
                    Ok(payload) => return Ok((chain.clone(), payload)),
                    Err(_) => continue, // Try next converter
                }
            }
        }

        Err(VisualSignError::ConversionError(
            "Could not detect transaction type or no compatible converter found".to_string(),
        ))
    }

    pub fn supported_chains(&self) -> Vec<Chain> {
        self.converters.keys().cloned().collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{SignablePayloadField, SignablePayloadFieldCommon, SignablePayloadFieldTextV2};
    // Import TransactionParseError only in tests where it's actually used
    use crate::vsptrait::TransactionParseError;

    // Mock transactions for different chains with realistic format detection
    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    struct MockSolanaTransaction {
        data: Vec<u8>,
    }

    #[derive(Debug, Clone)]
    #[allow(dead_code)]
    struct MockEthereumTransaction {
        data: Vec<u8>,
    }

    // Implement Transaction trait with format detection without external crates
    impl Transaction for MockSolanaTransaction {
        fn from_string(data: &str) -> Result<Self, TransactionParseError> {
            // Simplified detection logic - Solana transactions start with byte 0x01
            // For testing purposes, we'll use a pattern where "01" at the start indicates Solana
            if data.starts_with("01") {
                // Simple hex decode without using hex crate
                let bytes = match decode_hex(data) {
                    Ok(b) => b,
                    Err(_) => {
                        return Err(TransactionParseError::DecodeError(
                            "Invalid hex".to_string(),
                        ))
                    }
                };

                if !bytes.is_empty() && bytes[0] == 0x01 {
                    return Ok(Self { data: bytes });
                }
            }

            Err(TransactionParseError::InvalidFormat(
                "Not a Solana transaction".to_string(),
            ))
        }

        fn transaction_type(&self) -> String {
            "Solana".to_string()
        }
    }

    impl Transaction for MockEthereumTransaction {
        fn from_string(data: &str) -> Result<Self, TransactionParseError> {
            // Simplified detection logic - Ethereum transactions start with byte 0x02
            // For testing purposes, we'll use a pattern where "02" at the start indicates Ethereum
            if data.starts_with("02") {
                // Simple hex decode without using hex crate
                let bytes = match decode_hex(data) {
                    Ok(b) => b,
                    Err(_) => {
                        return Err(TransactionParseError::DecodeError(
                            "Invalid hex".to_string(),
                        ))
                    }
                };

                if !bytes.is_empty() && bytes[0] == 0x02 {
                    return Ok(Self { data: bytes });
                }
            }

            Err(TransactionParseError::InvalidFormat(
                "Not an Ethereum transaction".to_string(),
            ))
        }

        fn transaction_type(&self) -> String {
            "Ethereum".to_string()
        }
    }

    // Simple hex decoder function to avoid dependency on hex crate
    fn decode_hex(s: &str) -> Result<Vec<u8>, &'static str> {
        if s.len() % 2 != 0 {
            return Err("Hex string must have even length");
        }

        let mut result = Vec::with_capacity(s.len() / 2);
        let mut chars = s.chars();

        while let (Some(a), Some(b)) = (chars.next(), chars.next()) {
            let byte = match (a.to_digit(16), b.to_digit(16)) {
                (Some(high), Some(low)) => ((high as u8) << 4) | (low as u8),
                _ => return Err("Invalid hex character"),
            };
            result.push(byte);
        }

        Ok(result)
    }

    // Mock converter implementations
    struct MockSuccessConverter<T> {
        phantom: PhantomData<T>,
    }

    impl<T> MockSuccessConverter<T> {
        fn new() -> Self {
            Self {
                phantom: PhantomData,
            }
        }
    }

    impl<T: Transaction> VisualSignConverter<T> for MockSuccessConverter<T> {
        fn to_visual_sign_payload(
            &self,
            _transaction: T,
            _options: VisualSignOptions,
        ) -> Result<SignablePayload, VisualSignError> {
            // Create a simple payload using SignablePayload::new
            Ok(SignablePayload::new(
                0,
                "Test Transaction".to_string(),
                None,
                vec![SignablePayloadField::TextV2 {
                    common: SignablePayloadFieldCommon {
                        fallback_text: "Test".to_string(),
                        label: "Test Label".to_string(),
                    },
                    text_v2: SignablePayloadFieldTextV2 {
                        text: "Test Value".to_string(),
                    },
                }],
                "Test Source".to_string(),
            ))
        }
    }

    impl<T: Transaction> VisualSignConverterFromString<T> for MockSuccessConverter<T> {}

    struct MockFailingConverter<T> {
        phantom: PhantomData<T>,
    }

    impl<T> MockFailingConverter<T> {
        fn new() -> Self {
            Self {
                phantom: PhantomData,
            }
        }
    }

    impl<T: Transaction> VisualSignConverter<T> for MockFailingConverter<T> {
        fn to_visual_sign_payload(
            &self,
            _transaction: T,
            _options: VisualSignOptions,
        ) -> Result<SignablePayload, VisualSignError> {
            Err(VisualSignError::ConversionError(
                "Mock conversion failed".to_string(),
            ))
        }
    }

    impl<T: Transaction> VisualSignConverterFromString<T> for MockFailingConverter<T> {}

    #[test]
    fn test_auto_detect_solana_success() {
        let mut registry = TransactionConverterRegistry::new();

        registry.register::<MockSolanaTransaction, _>(Chain::Solana, MockSuccessConverter::new());

        registry
            .register::<MockEthereumTransaction, _>(Chain::Ethereum, MockSuccessConverter::new());

        let result =
            registry.auto_detect_and_convert("01abcdef1234567890", VisualSignOptions::default());

        assert!(result.is_ok());
        let (chain, _) = result.unwrap();
        assert_eq!(chain, Chain::Solana);
    }

    #[test]
    fn test_auto_detect_ethereum_success() {
        let mut registry = TransactionConverterRegistry::new();

        registry.register::<MockSolanaTransaction, _>(Chain::Solana, MockSuccessConverter::new());
        registry
            .register::<MockEthereumTransaction, _>(Chain::Ethereum, MockSuccessConverter::new());

        let result =
            registry.auto_detect_and_convert("02abcdef1234567890", VisualSignOptions::default());

        assert!(result.is_ok());
        let (chain, _) = result.unwrap();
        assert_eq!(chain, Chain::Ethereum);
    }

    #[test]
    fn test_auto_detect_no_matching_converter() {
        let mut registry = TransactionConverterRegistry::new();

        registry.register::<MockSolanaTransaction, _>(Chain::Solana, MockSuccessConverter::new());
        registry
            .register::<MockEthereumTransaction, _>(Chain::Ethereum, MockSuccessConverter::new());

        let result = registry.auto_detect_and_convert(
            "03abcdef1234567890", // Starts with 03, not supported
            VisualSignOptions::default(),
        );

        assert!(result.is_err());
    }

    #[test]
    fn test_auto_detect_format_supported_but_conversion_fails() {
        let mut registry = TransactionConverterRegistry::new();

        registry.register::<MockSolanaTransaction, _>(Chain::Solana, MockFailingConverter::new());

        registry
            .register::<MockEthereumTransaction, _>(Chain::Ethereum, MockSuccessConverter::new());

        let result = registry.auto_detect_and_convert(
            "01abcdef1234567890", // Solana format but conversion will fail
            VisualSignOptions::default(),
        );

        // Should try Ethereum after Solana fails, but Ethereum won't match the format
        assert!(result.is_err());
    }

    #[test]
    fn test_empty_registry() {
        let registry = TransactionConverterRegistry::new();

        let result =
            registry.auto_detect_and_convert("01abcdef1234567890", VisualSignOptions::default());

        assert!(result.is_err());
    }

    #[test]
    fn test_chain_from_str() {
        assert_eq!(Chain::from_str("solana"), Ok(Chain::Solana));
        assert_eq!(Chain::from_str("SOLANA"), Ok(Chain::Solana)); // Case insensitive
        assert_eq!(Chain::from_str("ethereum"), Ok(Chain::Ethereum));
        assert_eq!(Chain::from_str("bitcoin"), Ok(Chain::Bitcoin));
        assert_eq!(Chain::from_str("sui"), Ok(Chain::Sui));
        assert_eq!(Chain::from_str("aptos"), Ok(Chain::Aptos));
        assert_eq!(Chain::from_str("polkadot"), Ok(Chain::Polkadot));
        assert_eq!(Chain::from_str("tron"), Ok(Chain::Tron));
        assert_eq!(
            Chain::from_str("unknown"),
            Ok(Chain::Custom("unknown".to_string()))
        );
    }

    #[test]
    fn test_chain_as_str() {
        assert_eq!(Chain::Solana.as_str(), "Solana");
        assert_eq!(Chain::Ethereum.as_str(), "Ethereum");
        assert_eq!(Chain::Bitcoin.as_str(), "Bitcoin");
        assert_eq!(Chain::Sui.as_str(), "Sui");
        assert_eq!(Chain::Aptos.as_str(), "Aptos");
        assert_eq!(Chain::Polkadot.as_str(), "Polkadot");
        assert_eq!(Chain::Tron.as_str(), "Tron");
        assert_eq!(Chain::Custom("MyChain".to_string()).as_str(), "MyChain");
    }
}