scope-bca-cli 0.8.3

Scope Blockchain Analysis - Command-line interface library
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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
//! # Transaction Analysis Command
//!
//! This module implements the `scope tx` command for analyzing
//! blockchain transactions. It decodes transaction data, traces
//! execution, and displays detailed transaction information.
//!
//! ## Usage
//!
//! ```bash
//! # Basic transaction analysis
//! scope tx 0xabc123...
//!
//! # Specify chain
//! scope tx 0xabc123... --chain polygon
//!
//! # Include internal transactions
//! scope tx 0xabc123... --trace
//! ```

use crate::cli::output::Output;
use crate::outln;
use clap::Args;
use scope::chains::{ChainClientFactory, validate_solana_signature, validate_tron_tx_hash};
use scope::config::{Config, OutputFormat};
use scope::error::{Result, ScopeError};

/// Arguments for the transaction analysis command.
#[derive(Debug, Clone, Args)]
#[command(after_help = "\x1b[1mExamples:\x1b[0m
  scope tx 0xabc123def456...
  scope tx 0xabc123... --chain polygon --trace
  scope tx 0xabc123... --decode --format json

\x1b[2mTip: All address/token inputs accept @label shortcuts from the address book.\x1b[0m")]
pub struct TxArgs {
    /// The transaction hash to analyze.
    ///
    /// Must be a valid transaction hash for the target chain
    /// (e.g., 0x-prefixed 64-character hex for Ethereum).
    #[arg(value_name = "HASH")]
    pub hash: String,

    #[arg(short, long, default_value = scope::chains::DEFAULT_CHAIN, help = scope::chains::registry::chain_help())]
    pub chain: String,

    /// Override output format for this command.
    #[arg(short, long, value_name = "FORMAT")]
    pub format: Option<OutputFormat>,

    /// Include internal transactions (trace).
    #[arg(long)]
    pub trace: bool,

    /// Decode transaction input data.
    #[arg(long)]
    pub decode: bool,
}

/// Result of a transaction analysis.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TransactionReport {
    /// The analyzed transaction hash.
    pub hash: String,

    /// The blockchain network.
    pub chain: String,

    /// Block information.
    pub block: BlockInfo,

    /// Transaction details.
    pub transaction: TransactionDetails,

    /// Gas information.
    pub gas: GasInfo,

    /// Decoded input data (if requested).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decoded_input: Option<DecodedInput>,

    /// Internal transactions (if requested).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub internal_transactions: Option<Vec<InternalTransaction>>,
}

/// Block information for a transaction.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct BlockInfo {
    /// Block number.
    pub number: u64,

    /// Block timestamp (Unix epoch).
    pub timestamp: u64,

    /// Block hash.
    pub hash: String,
}

/// Detailed transaction information.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TransactionDetails {
    /// Sender address.
    pub from: String,

    /// Recipient address (None for contract creation).
    pub to: Option<String>,

    /// Value transferred in native token.
    pub value: String,

    /// Transaction nonce.
    pub nonce: u64,

    /// Transaction index in block.
    pub transaction_index: u64,

    /// Transaction status (success/failure).
    pub status: bool,

    /// Raw input data.
    pub input: String,
}

/// Gas usage information.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GasInfo {
    /// Gas limit set for transaction.
    pub gas_limit: u64,

    /// Actual gas used.
    pub gas_used: u64,

    /// Gas price in wei.
    pub gas_price: String,

    /// Total transaction fee.
    pub transaction_fee: String,

    /// Effective gas price (for EIP-1559).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_gas_price: Option<String>,
}

/// Decoded transaction input.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DecodedInput {
    /// Function signature (e.g., "transfer(address,uint256)").
    pub function_signature: String,

    /// Function name.
    pub function_name: String,

    /// Decoded parameters.
    pub parameters: Vec<DecodedParameter>,
}

/// A decoded function parameter.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DecodedParameter {
    /// Parameter name.
    pub name: String,

    /// Parameter type.
    pub param_type: String,

    /// Parameter value.
    pub value: String,
}

/// An internal transaction (trace result).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InternalTransaction {
    /// Call type (call, delegatecall, staticcall, create).
    pub call_type: String,

    /// From address.
    pub from: String,

    /// To address.
    pub to: String,

    /// Value transferred.
    pub value: String,

    /// Gas provided.
    pub gas: u64,

    /// Input data.
    pub input: String,

    /// Output data.
    pub output: String,
}

/// Executes the transaction analysis command.
///
/// # Arguments
///
/// * `args` - The parsed command arguments
/// * `config` - Application configuration
///
/// # Returns
///
/// Returns `Ok(())` on success, or an error if the analysis fails.
///
/// # Errors
///
/// Returns [`ScopeError::InvalidHash`] if the transaction hash is invalid.
/// Returns [`ScopeError::Request`] if API calls fail.
pub async fn run(
    mut args: TxArgs,
    config: &Config,
    clients: &dyn ChainClientFactory,
    out: &Output,
) -> Result<()> {
    // Auto-infer chain if using default and hash format is recognizable
    if args.chain == "ethereum"
        && let Some(inferred) = scope::chains::infer_chain_from_hash(&args.hash)
        && inferred != "ethereum"
    {
        tracing::info!("Auto-detected chain: {}", inferred);
        outln!(out, "Auto-detected chain: {}", inferred)?;
        args.chain = inferred.to_string();
    }

    tracing::info!(
        hash = %args.hash,
        chain = %args.chain,
        "Starting transaction analysis"
    );

    // Validate transaction hash
    validate_tx_hash(&args.hash, &args.chain)?;

    let sp = crate::cli::progress::Spinner::new(
        &format!("Analyzing transaction on {}...", args.chain),
        out,
    );

    let report =
        fetch_transaction_report(&args.hash, &args.chain, args.decode, args.trace, clients).await?;

    sp.finish("Transaction loaded.");

    // Output based on format
    let format = args.format.unwrap_or(config.output.format);
    output_report(&report, format, out)?;

    Ok(())
}

/// Fetches and builds a transaction report for programmatic use.
///
/// Used by the insights command and batch reporting.
pub async fn fetch_transaction_report(
    hash: &str,
    chain: &str,
    decode: bool,
    trace: bool,
    clients: &dyn ChainClientFactory,
) -> Result<TransactionReport> {
    validate_tx_hash(hash, chain)?;
    let client = clients.create_chain_client(chain)?;
    let tx = client.get_transaction(hash).await?;

    let gas_price_val: u128 = tx.gas_price.parse().unwrap_or(0);
    let gas_used_val = tx.gas_used.unwrap_or(0) as u128;
    let fee_wei = gas_price_val * gas_used_val;
    let chain_lower = chain.to_lowercase();
    let fee_str = if chain_lower == "solana" || chain_lower == "sol" {
        let fee_sol = tx.gas_price.parse::<f64>().unwrap_or(0.0) / 1_000_000_000.0;
        format!("{:.9}", fee_sol)
    } else {
        fee_wei.to_string()
    };

    let report = TransactionReport {
        hash: tx.hash.clone(),
        chain: chain.to_string(),
        block: BlockInfo {
            number: tx.block_number.unwrap_or(0),
            timestamp: tx.timestamp.unwrap_or(0),
            hash: String::new(),
        },
        transaction: TransactionDetails {
            from: tx.from.clone(),
            to: tx.to.clone(),
            value: tx.value.clone(),
            nonce: tx.nonce,
            transaction_index: 0,
            status: tx.status.unwrap_or(true),
            input: tx.input.clone(),
        },
        gas: GasInfo {
            gas_limit: tx.gas_limit,
            gas_used: tx.gas_used.unwrap_or(0),
            gas_price: tx.gas_price.clone(),
            transaction_fee: fee_str,
            effective_gas_price: None,
        },
        decoded_input: if decode && !tx.input.is_empty() && tx.input != "0x" {
            let selector = if tx.input.len() >= 10 {
                &tx.input[..10]
            } else {
                &tx.input
            };
            Some(DecodedInput {
                function_signature: format!("{}(...)", selector),
                function_name: selector.to_string(),
                parameters: vec![],
            })
        } else if decode {
            Some(DecodedInput {
                function_signature: "transfer()".to_string(),
                function_name: "Native Transfer".to_string(),
                parameters: vec![],
            })
        } else {
            None
        },
        internal_transactions: if trace { Some(vec![]) } else { None },
    };
    Ok(report)
}

/// Validates a transaction hash format for the given chain.
fn validate_tx_hash(hash: &str, chain: &str) -> Result<()> {
    // The chain registry decides the address and hash format (L2).
    match scope::chains::registry::chain(chain).map(|c| c.kind) {
        // EVM-compatible chains use 0x-prefixed 64-char hex hashes
        Some(scope::chains::registry::ChainKind::Evm) => {
            if !hash.starts_with("0x") {
                return Err(ScopeError::InvalidHash(format!(
                    "Transaction hash must start with '0x': {}",
                    hash
                )));
            }
            if hash.len() != 66 {
                return Err(ScopeError::InvalidHash(format!(
                    "Transaction hash must be 66 characters (0x + 64 hex): {}",
                    hash
                )));
            }
            if !hash[2..].chars().all(|c| c.is_ascii_hexdigit()) {
                return Err(ScopeError::InvalidHash(format!(
                    "Transaction hash contains invalid hex characters: {}",
                    hash
                )));
            }
        }
        // Solana uses base58-encoded 64-byte signatures
        Some(scope::chains::registry::ChainKind::Solana) => {
            validate_solana_signature(hash)?;
        }
        // Tron uses 64-char hex hashes (no 0x prefix)
        Some(scope::chains::registry::ChainKind::Tron) => {
            validate_tron_tx_hash(hash)?;
        }
        _ => {
            return Err(ScopeError::InvalidInput(format!(
                "Unsupported chain: {}. Supported: {}",
                chain,
                scope::chains::registry::client_chain_list()
            )));
        }
    }
    Ok(())
}

/// Outputs the transaction report in the specified format.
fn output_report(report: &TransactionReport, format: OutputFormat, out: &Output) -> Result<()> {
    match format {
        OutputFormat::Json => {
            let json = serde_json::to_string_pretty(report)?;
            outln!(out, "{}", json)?;
        }
        OutputFormat::Csv => {
            outln!(out, "hash,chain,block,from,to,value,status,gas_used,fee")?;
            outln!(
                out,
                "{},{},{},{},{},{},{},{},{}",
                report.hash,
                report.chain,
                report.block.number,
                report.transaction.from,
                report.transaction.to.as_deref().unwrap_or(""),
                report.transaction.value,
                report.transaction.status,
                report.gas.gas_used,
                report.gas.transaction_fee
            )?;
        }
        OutputFormat::Table => {
            use scope::display::terminal as t;

            outln!(out, "{}", t::section_header("Transaction Analysis"))?;
            outln!(out, "{}", t::kv_row("Hash", &report.hash))?;
            outln!(out, "{}", t::kv_row("Chain", &report.chain))?;
            outln!(
                out,
                "{}",
                t::kv_row("Block", &report.block.number.to_string())
            )?;
            if report.transaction.status {
                outln!(out, "{}", t::check_pass("Success"))?;
            } else {
                outln!(out, "{}", t::check_fail("Failed"))?;
            }
            outln!(out, "{}", t::blank_row())?;
            outln!(out, "{}", t::kv_row("From", &report.transaction.from))?;
            outln!(
                out,
                "{}",
                t::kv_row(
                    "To",
                    report
                        .transaction
                        .to
                        .as_deref()
                        .unwrap_or("Contract Creation")
                )
            )?;
            outln!(out, "{}", t::kv_row("Value", &report.transaction.value))?;
            outln!(out, "{}", t::blank_row())?;
            outln!(
                out,
                "{}",
                t::kv_row("Gas Limit", &report.gas.gas_limit.to_string())
            )?;
            outln!(
                out,
                "{}",
                t::kv_row("Gas Used", &report.gas.gas_used.to_string())
            )?;
            outln!(out, "{}", t::kv_row("Gas Price", &report.gas.gas_price))?;
            outln!(out, "{}", t::kv_row("Fee", &report.gas.transaction_fee))?;

            if let Some(ref decoded) = report.decoded_input {
                outln!(out, "{}", t::blank_row())?;
                outln!(out, "{}", t::subsection_header("Decoded Input"))?;
                outln!(out, "{}", t::kv_row("Function", &decoded.function_name))?;
                outln!(
                    out,
                    "{}",
                    t::kv_row("Signature", &decoded.function_signature)
                )?;
                if !decoded.parameters.is_empty() {
                    for param in &decoded.parameters {
                        outln!(
                            out,
                            "{}",
                            t::bullet_row(&format!(
                                "{} ({}): {}",
                                param.name, param.param_type, param.value
                            ))
                        )?;
                    }
                }
            }

            if let Some(ref traces) = report.internal_transactions
                && !traces.is_empty()
            {
                outln!(out, "{}", t::blank_row())?;
                outln!(
                    out,
                    "{}",
                    t::subsection_header(&format!("Internal Transactions ({})", traces.len()))
                )?;
                for (i, trace) in traces.iter().enumerate() {
                    outln!(
                        out,
                        "{}",
                        t::bullet_row(&format!(
                            "[{}] {} {} -> {}",
                            i, trace.call_type, trace.from, trace.to
                        ))
                    )?;
                }
            }

            outln!(out, "{}", t::section_footer())?;
        }
        OutputFormat::Markdown => {
            let md = format_tx_markdown(report);
            outln!(out, "{}", md)?;
        }
    }
    Ok(())
}

/// Formats a transaction report as markdown for agent consumption.
/// Exposed for use by insights and report generation.
pub fn format_tx_markdown(report: &TransactionReport) -> String {
    let mut md = String::new();
    md.push_str("# Transaction Analysis\n\n");
    md.push_str("| Field | Value |\n|-------|-------|\n");
    md.push_str(&format!("| Hash | `{}` |\n", report.hash));
    md.push_str(&format!("| Chain | {} |\n", report.chain));
    md.push_str(&format!("| Block | {} |\n", report.block.number));
    md.push_str(&format!(
        "| Status | {} |\n",
        if report.transaction.status {
            "Success"
        } else {
            "Failed"
        }
    ));
    md.push_str(&format!("| From | `{}` |\n", report.transaction.from));
    md.push_str(&format!(
        "| To | `{}` |\n",
        report
            .transaction
            .to
            .as_deref()
            .unwrap_or("Contract Creation")
    ));
    md.push_str(&format!("| Value | {} |\n", report.transaction.value));
    md.push_str(&format!("| Gas Used | {} |\n", report.gas.gas_used));
    md.push_str(&format!("| Fee | {} |\n", report.gas.transaction_fee));
    if let Some(ref decoded) = report.decoded_input {
        md.push_str("\n## Decoded Input\n\n");
        md.push_str(&format!("- **Function:** {}\n", decoded.function_name));
        md.push_str(&format!(
            "- **Signature:** `{}`\n",
            decoded.function_signature
        ));
        if !decoded.parameters.is_empty() {
            md.push_str("\n| Parameter | Type | Value |\n|-----------|------|-------|\n");
            for param in &decoded.parameters {
                md.push_str(&format!(
                    "| {} | {} | {} |\n",
                    param.name, param.param_type, param.value
                ));
            }
        }
    }
    if let Some(ref traces) = report.internal_transactions
        && !traces.is_empty()
    {
        md.push_str("\n## Internal Transactions\n\n");
        md.push_str("| # | Type | From | To |\n|---|---|---|---|\n");
        for (i, trace) in traces.iter().enumerate() {
            md.push_str(&format!(
                "| {} | {} | `{}` | `{}` |\n",
                i + 1,
                trace.call_type,
                trace.from,
                trace.to
            ));
        }
    }
    md
}

// ============================================================================
// Unit Tests
// ============================================================================

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

    fn quiet() -> crate::cli::output::Output {
        crate::cli::output::Output::capture().0
    }

    const VALID_TX_HASH: &str =
        "0xabc123def456789012345678901234567890123456789012345678901234abcd";

    #[test]
    fn test_validate_tx_hash_valid() {
        let result = validate_tx_hash(VALID_TX_HASH, "ethereum");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_tx_hash_valid_lowercase() {
        let hash = "0xabc123def456789012345678901234567890123456789012345678901234abcd";
        let result = validate_tx_hash(hash, "ethereum");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_tx_hash_valid_polygon() {
        let result = validate_tx_hash(VALID_TX_HASH, "polygon");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_tx_hash_missing_prefix() {
        let hash = "abc123def456789012345678901234567890123456789012345678901234abcd";
        let result = validate_tx_hash(hash, "ethereum");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("0x"));
    }

    #[test]
    fn test_validate_tx_hash_too_short() {
        let hash = "0xabc123";
        let result = validate_tx_hash(hash, "ethereum");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("66 characters"));
    }

    #[test]
    fn test_validate_tx_hash_too_long() {
        let hash = "0xabc123def456789012345678901234567890123456789012345678901234abcde";
        let result = validate_tx_hash(hash, "ethereum");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_tx_hash_invalid_hex_cli() {
        let hash = "0xabc123def456789012345678901234567890123456789012345678901234GHIJ";
        let result = validate_tx_hash(hash, "ethereum");
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("invalid hex"));
    }

    #[test]
    fn test_validate_tx_hash_unsupported_chain() {
        let result = validate_tx_hash(VALID_TX_HASH, "bitcoin");
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Unsupported chain")
        );
    }

    #[test]
    fn test_validate_tx_hash_valid_bsc() {
        let result = validate_tx_hash(VALID_TX_HASH, "bsc");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_tx_hash_valid_aegis() {
        let result = validate_tx_hash(VALID_TX_HASH, "aegis");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_tx_hash_valid_solana() {
        // Solana signature (base58 encoded, ~88 chars)
        let sig = "5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW";
        let result = validate_tx_hash(sig, "solana");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_tx_hash_invalid_solana() {
        // EVM hash should fail for Solana
        let result = validate_tx_hash(VALID_TX_HASH, "solana");
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_tx_hash_valid_tron() {
        // Tron uses 64-char hex without 0x prefix
        let hash = "abc123def456789012345678901234567890123456789012345678901234abcd";
        let result = validate_tx_hash(hash, "tron");
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_tx_hash_invalid_tron() {
        // 0x-prefixed hash should fail for Tron
        let result = validate_tx_hash(VALID_TX_HASH, "tron");
        assert!(result.is_err());
    }

    #[test]
    fn test_tx_args_default_values() {
        use clap::Parser;

        #[derive(Parser)]
        struct TestCli {
            #[command(flatten)]
            args: TxArgs,
        }

        let cli = TestCli::try_parse_from(["test", VALID_TX_HASH]).unwrap();

        assert_eq!(cli.args.chain, "ethereum");
        assert!(!cli.args.trace);
        assert!(!cli.args.decode);
        assert!(cli.args.format.is_none());
    }

    #[test]
    fn test_tx_args_with_options() {
        use clap::Parser;

        #[derive(Parser)]
        struct TestCli {
            #[command(flatten)]
            args: TxArgs,
        }

        let cli = TestCli::try_parse_from([
            "test",
            VALID_TX_HASH,
            "--chain",
            "polygon",
            "--trace",
            "--decode",
            "--format",
            "json",
        ])
        .unwrap();

        assert_eq!(cli.args.chain, "polygon");
        assert!(cli.args.trace);
        assert!(cli.args.decode);
        assert_eq!(cli.args.format, Some(OutputFormat::Json));
    }

    #[test]
    fn test_transaction_report_serialization() {
        let report = TransactionReport {
            hash: VALID_TX_HASH.to_string(),
            chain: "ethereum".to_string(),
            block: BlockInfo {
                number: 12345678,
                timestamp: 1700000000,
                hash: "0xblock".to_string(),
            },
            transaction: TransactionDetails {
                from: "0xfrom".to_string(),
                to: Some("0xto".to_string()),
                value: "1.0".to_string(),
                nonce: 42,
                transaction_index: 5,
                status: true,
                input: "0x".to_string(),
            },
            gas: GasInfo {
                gas_limit: 100000,
                gas_used: 21000,
                gas_price: "20000000000".to_string(),
                transaction_fee: "0.00042".to_string(),
                effective_gas_price: None,
            },
            decoded_input: None,
            internal_transactions: None,
        };

        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains(VALID_TX_HASH));
        assert!(json.contains("12345678"));
        assert!(json.contains("21000"));
        assert!(!json.contains("decoded_input"));
        assert!(!json.contains("internal_transactions"));
    }

    #[test]
    fn test_block_info_serialization() {
        let block = BlockInfo {
            number: 12345678,
            timestamp: 1700000000,
            hash: "0xblockhash".to_string(),
        };

        let json = serde_json::to_string(&block).unwrap();
        assert!(json.contains("12345678"));
        assert!(json.contains("1700000000"));
        assert!(json.contains("0xblockhash"));
    }

    #[test]
    fn test_gas_info_serialization() {
        let gas = GasInfo {
            gas_limit: 100000,
            gas_used: 50000,
            gas_price: "20000000000".to_string(),
            transaction_fee: "0.001".to_string(),
            effective_gas_price: Some("25000000000".to_string()),
        };

        let json = serde_json::to_string(&gas).unwrap();
        assert!(json.contains("100000"));
        assert!(json.contains("50000"));
        assert!(json.contains("effective_gas_price"));
    }

    #[test]
    fn test_decoded_input_serialization() {
        let decoded = DecodedInput {
            function_signature: "transfer(address,uint256)".to_string(),
            function_name: "transfer".to_string(),
            parameters: vec![
                DecodedParameter {
                    name: "to".to_string(),
                    param_type: "address".to_string(),
                    value: "0xrecipient".to_string(),
                },
                DecodedParameter {
                    name: "amount".to_string(),
                    param_type: "uint256".to_string(),
                    value: "1000000".to_string(),
                },
            ],
        };

        let json = serde_json::to_string(&decoded).unwrap();
        assert!(json.contains("transfer(address,uint256)"));
        assert!(json.contains("0xrecipient"));
        assert!(json.contains("1000000"));
    }

    #[test]
    fn test_internal_transaction_serialization() {
        let internal = InternalTransaction {
            call_type: "call".to_string(),
            from: "0xfrom".to_string(),
            to: "0xto".to_string(),
            value: "1.0".to_string(),
            gas: 50000,
            input: "0x".to_string(),
            output: "0x".to_string(),
        };

        let json = serde_json::to_string(&internal).unwrap();
        assert!(json.contains("call"));
        assert!(json.contains("0xfrom"));
        assert!(json.contains("50000"));
    }

    // ========================================================================
    // Output formatting tests
    // ========================================================================

    fn make_test_tx_report() -> TransactionReport {
        TransactionReport {
            hash: VALID_TX_HASH.to_string(),
            chain: "ethereum".to_string(),
            block: BlockInfo {
                number: 12345678,
                timestamp: 1700000000,
                hash: "0xblock".to_string(),
            },
            transaction: TransactionDetails {
                from: "0xfrom".to_string(),
                to: Some("0xto".to_string()),
                value: "1.0".to_string(),
                nonce: 42,
                transaction_index: 5,
                status: true,
                input: "0xa9059cbb0000000000".to_string(),
            },
            gas: GasInfo {
                gas_limit: 100000,
                gas_used: 21000,
                gas_price: "20000000000".to_string(),
                transaction_fee: "0.00042".to_string(),
                effective_gas_price: None,
            },
            decoded_input: Some(DecodedInput {
                function_signature: "transfer(address,uint256)".to_string(),
                function_name: "transfer".to_string(),
                parameters: vec![DecodedParameter {
                    name: "to".to_string(),
                    param_type: "address".to_string(),
                    value: "0xrecipient".to_string(),
                }],
            }),
            internal_transactions: Some(vec![InternalTransaction {
                call_type: "call".to_string(),
                from: "0xfrom".to_string(),
                to: "0xto".to_string(),
                value: "0.5".to_string(),
                gas: 30000,
                input: "0x".to_string(),
                output: "0x".to_string(),
            }]),
        }
    }

    #[test]
    fn test_output_report_json() {
        let report = make_test_tx_report();
        let result = output_report(&report, OutputFormat::Json, &quiet());
        assert!(result.is_ok());
    }

    #[test]
    fn test_output_report_csv() {
        let report = make_test_tx_report();
        let result = output_report(&report, OutputFormat::Csv, &quiet());
        assert!(result.is_ok());
    }

    #[test]
    fn test_output_report_table() {
        let report = make_test_tx_report();
        let result = output_report(&report, OutputFormat::Table, &quiet());
        assert!(result.is_ok());
    }

    #[test]
    fn test_output_report_table_no_decoded() {
        let mut report = make_test_tx_report();
        report.decoded_input = None;
        report.internal_transactions = None;
        let result = output_report(&report, OutputFormat::Table, &quiet());
        assert!(result.is_ok());
    }

    #[test]
    fn test_output_report_table_failed_tx() {
        let mut report = make_test_tx_report();
        report.transaction.status = false;
        report.transaction.to = None; // Contract creation
        let result = output_report(&report, OutputFormat::Table, &quiet());
        assert!(result.is_ok());
    }

    #[test]
    fn test_output_report_table_empty_traces() {
        let mut report = make_test_tx_report();
        report.internal_transactions = Some(vec![]);
        let result = output_report(&report, OutputFormat::Table, &quiet());
        assert!(result.is_ok());
    }

    #[test]
    fn test_output_report_csv_no_to() {
        let mut report = make_test_tx_report();
        report.transaction.to = None;
        let result = output_report(&report, OutputFormat::Csv, &quiet());
        assert!(result.is_ok());
    }

    // ========================================================================
    // Mock-based tests for fetch_transaction_report
    // ========================================================================

    use async_trait::async_trait;
    use scope::chains::{
        Balance as ChainBalance, ChainClient, ChainClientFactory, DexDataSource,
        TokenBalance as ChainTokenBalance, Transaction as ChainTransaction,
    };

    struct MockTxClient;

    #[async_trait]
    impl ChainClient for MockTxClient {
        fn chain_name(&self) -> &str {
            "ethereum"
        }
        fn native_token_symbol(&self) -> &str {
            "ETH"
        }
        async fn get_balance(&self, _a: &str) -> scope::error::Result<ChainBalance> {
            Ok(ChainBalance {
                raw: "0".into(),
                formatted: "0 ETH".into(),
                decimals: 18,
                symbol: "ETH".into(),
                usd_value: None,
            })
        }
        async fn enrich_balance_usd(&self, _b: &mut ChainBalance) {}
        async fn get_transaction(&self, _h: &str) -> scope::error::Result<ChainTransaction> {
            Ok(ChainTransaction {
                hash: "0xabc123def456789012345678901234567890123456789012345678901234abcd".into(),
                block_number: Some(12345678),
                timestamp: Some(1700000000),
                from: "0xfrom".into(),
                to: Some("0xto".into()),
                value: "1000000000000000000".into(),
                gas_limit: 21000,
                gas_used: Some(21000),
                gas_price: "20000000000".into(),
                nonce: 42,
                input: "0xa9059cbb0000000000000000000000001234".into(),
                status: Some(true),
            })
        }
        async fn get_transactions(
            &self,
            _a: &str,
            _l: u32,
        ) -> scope::error::Result<Vec<ChainTransaction>> {
            Ok(vec![])
        }
        async fn get_block_number(&self) -> scope::error::Result<u64> {
            Ok(12345678)
        }
        async fn get_token_balances(
            &self,
            _a: &str,
        ) -> scope::error::Result<Vec<ChainTokenBalance>> {
            Ok(vec![])
        }
        async fn get_code(&self, _addr: &str) -> scope::error::Result<String> {
            Ok("0x".into())
        }
    }

    struct MockTxFactory;
    impl ChainClientFactory for MockTxFactory {
        fn http(&self) -> std::sync::Arc<dyn scope::http::HttpClient> {
            scope::http::test_transport()
        }
        fn create_chain_client(&self, _chain: &str) -> scope::error::Result<Box<dyn ChainClient>> {
            Ok(Box::new(MockTxClient))
        }
        fn create_dex_client(&self) -> Box<dyn DexDataSource> {
            let http: std::sync::Arc<dyn scope::http::HttpClient> =
                std::sync::Arc::new(scope::http::NativeHttpClient::new().unwrap());
            scope::chains::DefaultClientFactory {
                chains_config: Default::default(),
                http,
            }
            .create_dex_client()
        }
    }

    #[tokio::test]
    async fn test_fetch_transaction_report_mock() {
        let factory = MockTxFactory;
        let result = fetch_transaction_report(
            "0xabc123def456789012345678901234567890123456789012345678901234abcd",
            "ethereum",
            false,
            false,
            &factory,
        )
        .await;
        assert!(result.is_ok());
        let report = result.unwrap();
        assert_eq!(report.transaction.from, "0xfrom");
        assert!(report.transaction.status);
    }

    #[tokio::test]
    async fn test_fetch_transaction_report_with_decode() {
        let factory = MockTxFactory;
        let result = fetch_transaction_report(
            "0xabc123def456789012345678901234567890123456789012345678901234abcd",
            "ethereum",
            true,
            false,
            &factory,
        )
        .await;
        assert!(result.is_ok());
    }

    // ========================================================================
    // End-to-end tests using MockClientFactory
    // ========================================================================

    use scope::chains::mocks::MockClientFactory;

    fn mock_factory() -> MockClientFactory {
        MockClientFactory::new()
    }

    #[tokio::test]
    async fn test_run_ethereum_tx() {
        let config = Config::default();
        let factory = mock_factory();
        let args = TxArgs {
            hash: "0xabc123def456789012345678901234567890123456789012345678901234abcd".to_string(),
            chain: "ethereum".to_string(),
            format: Some(OutputFormat::Json),
            trace: false,
            decode: false,
        };
        let result = super::run(args, &config, &factory, &quiet()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_run_tx_with_decode() {
        let config = Config::default();
        let mut factory = mock_factory();
        factory.mock_client.transaction.input = "0xa9059cbb000000000000000000000000".to_string();
        let args = TxArgs {
            hash: "0xabc123def456789012345678901234567890123456789012345678901234abcd".to_string(),
            chain: "ethereum".to_string(),
            format: Some(OutputFormat::Table),
            trace: false,
            decode: true,
        };
        let result = super::run(args, &config, &factory, &quiet()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_run_tx_with_trace() {
        let config = Config::default();
        let factory = mock_factory();
        let args = TxArgs {
            hash: "0xabc123def456789012345678901234567890123456789012345678901234abcd".to_string(),
            chain: "ethereum".to_string(),
            format: Some(OutputFormat::Csv),
            trace: true,
            decode: false,
        };
        let result = super::run(args, &config, &factory, &quiet()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_run_tx_invalid_hash() {
        let config = Config::default();
        let factory = mock_factory();
        let args = TxArgs {
            hash: "invalid".to_string(),
            chain: "ethereum".to_string(),
            format: Some(OutputFormat::Json),
            trace: false,
            decode: false,
        };
        let result = super::run(args, &config, &factory, &quiet()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_run_tx_auto_detect_tron() {
        let config = Config::default();
        let factory = mock_factory();
        let args = TxArgs {
            // 64 hex chars = tron
            hash: "abc123def456789012345678901234567890123456789012345678901234abcd".to_string(),
            chain: "ethereum".to_string(), // Will be auto-detected to tron
            format: Some(OutputFormat::Json),
            trace: false,
            decode: false,
        };
        let result = super::run(args, &config, &factory, &quiet()).await;
        assert!(result.is_ok());
    }

    // ========================================================================
    // Markdown formatting tests
    // ========================================================================

    #[test]
    fn test_format_tx_markdown_basic() {
        let report = make_test_tx_report();
        let md = format_tx_markdown(&report);
        assert!(md.contains("# Transaction Analysis"));
        assert!(md.contains(&report.hash));
        assert!(md.contains(&report.chain));
        assert!(md.contains("Success"));
        assert!(md.contains(&report.transaction.from));
    }

    #[test]
    fn test_format_tx_markdown_contract_creation() {
        let mut report = make_test_tx_report();
        report.transaction.to = None;
        let md = format_tx_markdown(&report);
        assert!(md.contains("Contract Creation"));
    }

    #[test]
    fn test_format_tx_markdown_failed_tx() {
        let mut report = make_test_tx_report();
        report.transaction.status = false;
        let md = format_tx_markdown(&report);
        assert!(md.contains("Failed"));
    }

    #[test]
    fn test_format_tx_markdown_with_decoded_input() {
        let report = make_test_tx_report();
        let md = format_tx_markdown(&report);
        assert!(md.contains("## Decoded Input"));
        assert!(md.contains("transfer"));
        assert!(md.contains("transfer(address,uint256)"));
    }

    #[test]
    fn test_format_tx_markdown_with_internal_transactions() {
        let report = make_test_tx_report();
        let md = format_tx_markdown(&report);
        assert!(md.contains("## Internal Transactions"));
        assert!(md.contains("call"));
    }

    #[test]
    fn test_format_tx_markdown_no_decoded_input() {
        let mut report = make_test_tx_report();
        report.decoded_input = None;
        let md = format_tx_markdown(&report);
        assert!(!md.contains("## Decoded Input"));
    }

    #[test]
    fn test_format_tx_markdown_no_internal_transactions() {
        let mut report = make_test_tx_report();
        report.internal_transactions = None;
        let md = format_tx_markdown(&report);
        assert!(!md.contains("## Internal Transactions"));
    }

    #[test]
    fn test_format_tx_markdown_empty_internal_transactions() {
        let mut report = make_test_tx_report();
        report.internal_transactions = Some(vec![]);
        let md = format_tx_markdown(&report);
        assert!(!md.contains("## Internal Transactions"));
    }
}