thru-core 0.2.17

Shared implementation for the Thru CLI
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
//! Transaction signing and execution commands

use crate::cli::TxnCommands;
use crate::commands::debug::run_txn_debug;
use crate::commands::state_proof::make_state_proof as make_state_proof_util;
use crate::config::Config;
use crate::crypto;
use crate::error::CliError;
use crate::output;
use crate::utils::format_vm_error;
use base64::Engine;
use base64::engine::general_purpose;
use std::time::Duration;
use thru_base::rpc_types::ProofType;
use thru_base::tn_tools::{KeyPair, Pubkey};
use thru_base::txn_lib::{TnPubkey, Transaction};
use thru_client::{Client, ClientBuilder};

/// Handle transaction-related commands
pub async fn handle_txn_command(
    config: &Config,
    subcommand: TxnCommands,
    json_format: bool,
) -> Result<(), CliError> {
    match subcommand {
        TxnCommands::Sign {
            program,
            instruction_data,
            fee_payer,
            fee,
            compute_units,
            state_units,
            memory_units,
            expiry_after,
            readwrite_accounts,
            readonly_accounts,
        } => {
            sign_transaction(
                config,
                &program,
                &instruction_data,
                fee_payer.as_deref(),
                fee,
                compute_units,
                state_units,
                memory_units,
                expiry_after,
                &readwrite_accounts,
                &readonly_accounts,
                json_format,
            )
            .await
        }
        TxnCommands::Execute {
            program,
            instruction_data,
            fee_payer,
            fee,
            compute_units,
            state_units,
            memory_units,
            expiry_after,
            timeout,
            readwrite_accounts,
            readonly_accounts,
        } => {
            execute_transaction(
                config,
                &program,
                &instruction_data,
                fee_payer.as_deref(),
                fee,
                compute_units,
                state_units,
                memory_units,
                expiry_after,
                timeout,
                &readwrite_accounts,
                &readonly_accounts,
                json_format,
            )
            .await
        }
        TxnCommands::MakeStateProof {
            proof_type,
            account,
            slot,
        } => make_state_proof(config, &proof_type, &account, slot, json_format).await,
        TxnCommands::Get {
            signature,
            retry_count,
        } => get_transaction(config, &signature, json_format, retry_count).await,
        TxnCommands::Debug {
            signature,
            include_state_before,
            include_state_after,
            include_account_data,
            output_trace,
            inline_trace,
            include_memory_dump,
        } => {
            run_txn_debug(
                config,
                &signature,
                include_state_before,
                include_state_after,
                include_account_data,
                include_memory_dump,
                output_trace.as_deref(),
                inline_trace,
                json_format,
            )
            .await
        }
        TxnCommands::Sort { pubkeys } => sort_pubkeys(&pubkeys, json_format),
    }
}

/// Sign a transaction and output as base64 string
async fn sign_transaction(
    config: &Config,
    program: &str,
    instruction_data: &str,
    fee_payer: Option<&str>,
    fee: u64,
    compute_units: u32,
    state_units: u16,
    memory_units: u16,
    expiry_after: u32,
    readwrite_accounts: &[String],
    readonly_accounts: &[String],
    json_format: bool,
) -> Result<(), CliError> {
    // Parse instruction data from hex
    let instruction_bytes = hex::decode(instruction_data)
        .map_err(|e| CliError::Validation(format!("Invalid hex instruction data: {}", e)))?;

    // Build and sign transaction
    let transaction = build_and_sign_transaction(
        config,
        program,
        &instruction_bytes,
        fee_payer,
        fee,
        compute_units,
        state_units,
        memory_units,
        expiry_after,
        readwrite_accounts,
        readonly_accounts,
    )
    .await?;

    // Convert to wire format and encode as base64
    let transaction_bytes = transaction.to_wire();
    let base64_transaction = general_purpose::STANDARD.encode(&transaction_bytes);

    if json_format {
        let response = serde_json::json!({
            "transaction_sign": {
                "status": "success",
                "base64_transaction": base64_transaction,
                "size_bytes": transaction_bytes.len()
            }
        });
        output::print_output(response, true);
    } else {
        println!("{}", base64_transaction);
    }

    Ok(())
}

/// Execute a transaction and print response
async fn execute_transaction(
    config: &Config,
    program: &str,
    instruction_data: &str,
    fee_payer: Option<&str>,
    fee: u64,
    compute_units: u32,
    state_units: u16,
    memory_units: u16,
    expiry_after: u32,
    timeout: u64,
    readwrite_accounts: &[String],
    readonly_accounts: &[String],
    json_format: bool,
) -> Result<(), CliError> {
    // Parse instruction data from hex
    let instruction_bytes = hex::decode(instruction_data)
        .map_err(|e| CliError::Validation(format!("Invalid hex instruction data: {}", e)))?;

    // Create RPC client
    let client = create_rpc_client(config)?;

    let timeout_duration = Duration::from_secs(timeout);
    /* TN_RUNTIME_TXN_ERR_NONCE_TOO_LOW = (int)(0x01 | 0xFFFFFE00) = -511 */
    const TN_ERR_NONCE_TOO_LOW: i32 = -511;
    const MAX_NONCE_RETRIES: u32 = 3;

    /* Retry loop: on nonce-too-low errors the RPC may return a stale nonce;
    rebuild and re-sign with a fresh nonce fetch on each attempt. */
    let mut transaction_details_opt = None;
    for attempt in 0..MAX_NONCE_RETRIES {
        if attempt > 0 {
            tokio::time::sleep(Duration::from_millis(500)).await;
        }

        /* Build and sign transaction (fetches fresh nonce each attempt) */
        let transaction = build_and_sign_transaction(
            config,
            program,
            &instruction_bytes,
            fee_payer,
            fee,
            compute_units,
            state_units,
            memory_units,
            expiry_after,
            readwrite_accounts,
            readonly_accounts,
        )
        .await?;

        let transaction_bytes = transaction.to_wire();
        let details = client
            .execute_transaction(&transaction_bytes, timeout_duration)
            .await
            .map_err(|e| {
                CliError::TransactionSubmission(format!("Failed to execute transaction: {:?}", e))
            })?;

        let is_nonce_err = details.execution_result as i32 == TN_ERR_NONCE_TOO_LOW;
        transaction_details_opt = Some(details);
        if !is_nonce_err {
            break;
        }
    }
    let transaction_details = transaction_details_opt.unwrap();

    let has_failure =
        transaction_details.execution_result != 0 || transaction_details.vm_error != 0;
    if has_failure {
        let vm_error_label = format_vm_error(transaction_details.vm_error);
        let vm_error_display = if transaction_details.vm_error != 0 {
            format!("{} ({})", transaction_details.vm_error, vm_error_label)
        } else {
            "0".to_string()
        };
        let user_error_label = if transaction_details.user_error_code != 0 {
            format!("0x{:X}", transaction_details.user_error_code)
        } else {
            "0x0".to_string()
        };
        let message = format!(
            "Transaction failed (execution_result={} (hex 0x{:X}), vm_error={}, user_error={})",
            transaction_details.execution_result,
            transaction_details.execution_result,
            vm_error_display,
            user_error_label
        );

        if !json_format {
            output::print_error(&message);
        }

        return Err(CliError::TransactionFailed {
            message,
            execution_result: transaction_details.execution_result,
            vm_error: transaction_details.vm_error,
            vm_error_label,
            user_error_code: transaction_details.user_error_code,
            user_error_label,
            signature: transaction_details.signature.as_str().to_string(),
        });
    }

    // Format and display the result
    if json_format {
        let mut events_json = Vec::new();

        // Parse events for JSON output
        for event in &transaction_details.events {
            let mut event_json = serde_json::Map::new();
            event_json.insert(
                "call_idx".to_string(),
                serde_json::Value::Number(serde_json::Number::from(event.call_idx as u64)),
            );
            event_json.insert(
                "program_idx".to_string(),
                serde_json::Value::Number(serde_json::Number::from(event.program_idx as u64)),
            );

            if let Some(event_id) = &event.event_id {
                event_json.insert(
                    "event_id".to_string(),
                    serde_json::Value::String(event_id.clone()),
                );
            }

            if let Some(program) = &event.program {
                event_json.insert(
                    "program".to_string(),
                    serde_json::Value::String(program.as_str().to_string()),
                );
            }

            if event.data.len() > 8 {
                // Extract first 8 bytes as event type
                let event_type_bytes = &event.data[0..8];
                let event_type = u64::from_le_bytes([
                    event_type_bytes[0],
                    event_type_bytes[1],
                    event_type_bytes[2],
                    event_type_bytes[3],
                    event_type_bytes[4],
                    event_type_bytes[5],
                    event_type_bytes[6],
                    event_type_bytes[7],
                ]);
                event_json.insert(
                    "event_type".to_string(),
                    serde_json::Value::Number(serde_json::Number::from(event_type)),
                );

                // Process remaining data
                let remaining_data = &event.data[8..];
                if !remaining_data.is_empty() {
                    let parsed_data = parse_event_data_for_json(remaining_data);
                    event_json.insert("data".to_string(), parsed_data);
                }
            } else if !event.data.is_empty() {
                event_json.insert(
                    "data_hex".to_string(),
                    serde_json::Value::String(hex::encode(&event.data)),
                );
            }

            events_json.push(serde_json::Value::Object(event_json));
        }

        let response = serde_json::json!({
            "transaction_execute": {
            "status": "success",
            "signature": transaction_details.signature.as_str(),
            "slot": transaction_details.slot,
            "compute_units_consumed": transaction_details.compute_units_consumed,
            "state_units_consumed": transaction_details.state_units_consumed,
            "execution_result": transaction_details.execution_result,
            "vm_error": transaction_details.vm_error,
            "vm_error_name": format_vm_error(transaction_details.vm_error),
            "user_error_code": transaction_details.user_error_code,
            "events_count": transaction_details.events_cnt,
            "events_size": transaction_details.events_sz,
            "pages_used": transaction_details.pages_used,
            "readwrite_accounts": transaction_details.rw_accounts.iter().map(|pk| pk.as_str().to_string()).collect::<Vec<_>>(),
            "readonly_accounts": transaction_details.ro_accounts.iter().map(|pk| pk.as_str().to_string()).collect::<Vec<_>>(),
            "events": events_json
            }
        });
        output::print_output(response, true);
    } else {
        output::print_success(&format!("Transaction executed successfully"));
        println!("Signature: {}", transaction_details.signature.as_str());
        println!("Slot: {}", transaction_details.slot);
        println!(
            "Compute Units Consumed: {}",
            transaction_details.compute_units_consumed
        );
        println!(
            "State Units Consumed: {}",
            transaction_details.state_units_consumed
        );
        println!("Execution Result: {}", transaction_details.execution_result);
        println!(
            "VM Error: {}",
            format_vm_error(transaction_details.vm_error)
        );
        println!("User Error Code: {}", transaction_details.user_error_code);
        println!("Events Count: {}", transaction_details.events_cnt);
        println!("Events Size: {}", transaction_details.events_sz);
        println!("Pages Used: {}", transaction_details.pages_used);

        if !transaction_details.rw_accounts.is_empty() {
            println!("\nRead-write Accounts:");
            for account in &transaction_details.rw_accounts {
                println!("  {}", account.as_str());
            }
        }

        if !transaction_details.ro_accounts.is_empty() {
            println!("\nRead-only Accounts:");
            for account in &transaction_details.ro_accounts {
                println!("  {}", account.as_str());
            }
        }

        // Display events if any are present
        if transaction_details.events_cnt > 0 {
            println!("\nEvents:");
            for (i, event) in transaction_details.events.iter().enumerate() {
                println!(
                    "  Event {}: call_idx={}, program_idx={}",
                    i + 1,
                    event.call_idx,
                    event.program_idx
                );

                if let Some(event_id) = &event.event_id {
                    println!("    Event ID: {}", event_id);
                }
                if let Some(program) = &event.program {
                    println!("    Program: {}", program.as_str());
                }

                if event.data.len() > 8 {
                    // Extract first 8 bytes as event type
                    let event_type_bytes = &event.data[0..8];
                    let event_type = u64::from_le_bytes([
                        event_type_bytes[0],
                        event_type_bytes[1],
                        event_type_bytes[2],
                        event_type_bytes[3],
                        event_type_bytes[4],
                        event_type_bytes[5],
                        event_type_bytes[6],
                        event_type_bytes[7],
                    ]);
                    println!("    Event type: {}", event_type);

                    // Process remaining data
                    let remaining_data = &event.data[8..];
                    if !remaining_data.is_empty() {
                        display_event_data(remaining_data);
                    }
                } else if !event.data.is_empty() {
                    // If data is 8 bytes or less, just display as hex
                    println!("    Data (hex): {}", hex::encode(&event.data));
                }
            }
        }
    }

    Ok(())
}

/// Build and sign a transaction with the given parameters
async fn build_and_sign_transaction(
    config: &Config,
    program: &str,
    instruction_data: &[u8],
    fee_payer: Option<&str>,
    fee: u64,
    compute_units: u32,
    state_units: u16,
    memory_units: u16,
    expiry_after: u32,
    readwrite_accounts: &[String],
    readonly_accounts: &[String],
) -> Result<Transaction, CliError> {
    // Resolve fee payer account
    let fee_payer_key = fee_payer.unwrap_or("default");
    let fee_payer_private_key = config.keys.get_key(fee_payer_key)?;
    let fee_payer_keypair = KeyPair::from_hex_private_key(fee_payer_key, fee_payer_private_key)
        .map_err(|e| CliError::Crypto(format!("Failed to create fee payer keypair: {}", e)))?;

    // Resolve program public key
    let program_pubkey = resolve_program_public_key(config, program)?;

    // Create RPC client to get current nonce and slot
    let client = create_rpc_client(config)?;

    // Get current nonce from fee payer account
    let account_info = client
        .get_account_info(&fee_payer_keypair.address_string, None, None)
        .await
        .map_err(|e| CliError::NonceManagement(format!("Failed to get account info: {}", e)))?;

    let nonce = if let Some(account) = account_info {
        account.nonce
    } else {
        return Err(CliError::AccountNotFound(format!(
            "Fee payer account {} not found",
            fee_payer_keypair.address_string.as_str()
        )));
    };

    // Get current block height
    let block_height = client
        .get_block_height()
        .await
        .map_err(|e| CliError::NonceManagement(format!("Failed to get block height: {}", e)))?;

    // Parse account lists
    let rw_accounts: Result<Vec<TnPubkey>, CliError> = readwrite_accounts
        .iter()
        .map(|addr| crate::utils::validate_address_or_hex(addr))
        .collect();
    let rw_accounts = validate_and_process_accounts(rw_accounts?)?;

    let r_accounts: Result<Vec<TnPubkey>, CliError> = readonly_accounts
        .iter()
        .map(|addr| crate::utils::validate_address_or_hex(addr))
        .collect();
    let r_accounts = validate_and_process_accounts(r_accounts?)?;

    // Build transaction
    let mut transaction =
        Transaction::new(fee_payer_keypair.public_key, program_pubkey, fee, nonce)
            .with_instructions(instruction_data.to_vec())
            .with_compute_units(compute_units)
            .with_state_units(state_units)
            .with_memory_units(memory_units)
            .with_expiry_after(expiry_after)
            .with_start_slot(block_height.finalized_height);

    // Add account lists if provided
    if !rw_accounts.is_empty() {
        transaction = transaction.with_rw_accounts(rw_accounts);
    }
    if !r_accounts.is_empty() {
        transaction = transaction.with_r_accounts(r_accounts);
    }

    // Sign the transaction
    transaction
        .sign(&fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(format!("Failed to sign transaction: {}", e)))?;

    Ok(transaction)
}

/// Resolve program public key from string (either ta... address or key name from config)
fn resolve_program_public_key(config: &Config, program: &str) -> Result<TnPubkey, CliError> {
    // Try as ta... address first
    if program.starts_with("ta") && program.len() == 46 {
        let pubkey = Pubkey::new(program.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid program public key: {}", e)))?;
        return pubkey.to_bytes().map_err(|e| {
            CliError::Validation(format!("Failed to decode program public key: {}", e))
        });
    }

    // Try as key name from config
    if let Ok(private_key_hex) = config.keys.get_key(program) {
        let keypair = KeyPair::from_hex_private_key(program, private_key_hex).map_err(|e| {
            CliError::Validation(format!("Failed to resolve program key from config: {}", e))
        })?;
        return Ok(keypair.public_key);
    }

    // If neither works, try as hex public key
    if program.len() == 64 {
        let program_bytes = crypto::hex_to_bytes(program).map_err(|e| {
            CliError::Validation(format!("Failed to decode hex program key: {}", e))
        })?;
        if program_bytes.len() == 32 {
            let mut pubkey = [0u8; 32];
            pubkey.copy_from_slice(&program_bytes);
            return Ok(pubkey);
        }
    }

    Err(CliError::Validation(format!(
        "Invalid program identifier: {}. Must be a ta... address, key name from config, or 64-character hex public key",
        program
    )))
}

/// Display event data as string if human-readable, otherwise as hex
fn display_event_data(data: &[u8]) {
    // Remove trailing zeros
    let trimmed_data = data
        .iter()
        .rposition(|&b| b != 0)
        .map(|pos| &data[..=pos])
        .unwrap_or(&[]);

    if trimmed_data.is_empty() {
        println!("    Data: (empty)");
        return;
    }

    // Try to convert to UTF-8 string
    if let Ok(string_data) = std::str::from_utf8(trimmed_data) {
        // Check if it's reasonably printable (no control characters except common whitespace)
        let is_printable = string_data
            .chars()
            .all(|c| c.is_ascii_graphic() || c == ' ' || c == '\t' || c == '\n' || c == '\r');

        if is_printable && !string_data.is_empty() {
            println!("    Data (string): \"{}\"", string_data);
            return;
        }
    }

    // If not a valid string, display as hex
    println!("    Data (hex): {}", hex::encode(trimmed_data));
}

/// Parse event data for JSON output - returns either string or hex
fn parse_event_data_for_json(data: &[u8]) -> serde_json::Value {
    // Remove trailing zeros
    let trimmed_data = data
        .iter()
        .rposition(|&b| b != 0)
        .map(|pos| &data[..=pos])
        .unwrap_or(&[]);

    if trimmed_data.is_empty() {
        return serde_json::json!({
            "type": "empty"
        });
    }

    // Try to convert to UTF-8 string
    if let Ok(string_data) = std::str::from_utf8(trimmed_data) {
        // Check if it's reasonably printable (no control characters except common whitespace)
        let is_printable = string_data
            .chars()
            .all(|c| c.is_ascii_graphic() || c == ' ' || c == '\t' || c == '\n' || c == '\r');

        if is_printable && !string_data.is_empty() {
            return serde_json::json!({
                "type": "string",
                "value": string_data
            });
        }
    }

    // If not a valid string, return as hex
    serde_json::json!({
        "type": "hex",
        "value": hex::encode(trimmed_data)
    })
}

/// Create a cryptographic state proof for a given account
async fn make_state_proof(
    config: &Config,
    proof_type: &str,
    account: &str,
    slot: Option<u64>,
    json_format: bool,
) -> Result<(), CliError> {
    // Parse proof type
    let parsed_proof_type = match proof_type.to_lowercase().as_str() {
        "creating" => ProofType::Creating,
        "updating" => ProofType::Updating,
        "existing" => ProofType::Existing,
        _ => {
            return Err(CliError::Validation(format!(
                "Invalid proof type: {}. Must be one of: creating, updating, existing",
                proof_type
            )));
        }
    };

    // Parse account public key
    let account_pubkey = if account.starts_with("ta") && account.len() == 46 {
        // It's a ta... address
        Pubkey::new(account.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid account public key: {}", e)))?
    } else if let Ok(private_key_hex) = config.keys.get_key(account) {
        // It's a key name from config - get the public key
        let keypair = KeyPair::from_hex_private_key(account, private_key_hex).map_err(|e| {
            CliError::Validation(format!("Failed to resolve account key from config: {}", e))
        })?;
        keypair.address_string
    } else if account.len() == 64 {
        // Try as hex public key
        let account_bytes = crypto::hex_to_bytes(account).map_err(|e| {
            CliError::Validation(format!("Failed to decode hex account key: {}", e))
        })?;
        if account_bytes.len() == 32 {
            let mut pubkey_bytes = [0u8; 32];
            pubkey_bytes.copy_from_slice(&account_bytes);
            Pubkey::from_bytes(&pubkey_bytes)
        } else {
            return Err(CliError::Validation(format!(
                "Hex account key must be exactly 32 bytes (64 hex characters), got {} bytes",
                account_bytes.len()
            )));
        }
    } else {
        return Err(CliError::Validation(format!(
            "Invalid account identifier: {}. Must be a ta... address, key name from config, or 64-character hex public key",
            account
        )));
    };

    // Create RPC client
    let client = create_rpc_client(config)?;

    // Call makeStateProof using the common utility
    let proof_data =
        make_state_proof_util(&client, &account_pubkey, parsed_proof_type, slot).await?;

    // Encode proof as base64
    let base64_proof = general_purpose::STANDARD.encode(&proof_data);
    let hex_proof = hex::encode(&proof_data);

    if json_format {
        let response = serde_json::json!({
            "makeStateProof": {
                "status": "success",
                "account": account_pubkey.to_string(),
                "proof_type": proof_type,
                "slot": slot,
                "proof_data": base64_proof,
                "proof_data_hex": hex_proof,
                "proof_size_bytes": proof_data.len()
            }
        });
        output::print_output(response, true);
    } else {
        output::print_success("State proof created successfully");
        println!("Account: {}", account_pubkey.to_string());
        println!("Proof Type: {}", proof_type);
        if let Some(slot_num) = slot {
            println!("Slot: {}", slot_num);
        }
        println!("Proof Size: {} bytes", proof_data.len());
        println!("Proof Data (base64): {}", base64_proof);
        println!("Proof Data (hex): {}", hex_proof);
    }

    Ok(())
}

/// Create RPC client from config
fn create_rpc_client(config: &Config) -> Result<Client, CliError> {
    let rpc_url = config.get_grpc_url()?;

    ClientBuilder::new()
        .http_endpoint(rpc_url)
        .timeout(Duration::from_secs(config.timeout_seconds))
        .auth_token(config.auth_token.clone())
        .build()
        .map_err(|e| e.into())
}

/// Check account list size, deduplicate, and return sorted
fn validate_and_process_accounts(mut accounts: Vec<TnPubkey>) -> Result<Vec<TnPubkey>, CliError> {
    // Check maximum account limit (1024 as defined in docs)
    if accounts.len() > 1024 {
        return Err(CliError::Validation(format!(
            "Too many accounts: {} (maximum 1024 allowed)",
            accounts.len(),
        )));
    }

    accounts.sort();
    accounts.dedup();

    Ok(accounts)
}

/// Get transaction details by signature
async fn get_transaction(
    config: &Config,
    signature_str: &str,
    json_format: bool,
    retry_count: u32,
) -> Result<(), CliError> {
    // Parse signature - try ts... format first, then hex
    let signature = if signature_str.starts_with("ts") && signature_str.len() == 90 {
        thru_base::tn_tools::Signature::new(signature_str.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid signature: {}", e)))?
    } else if signature_str.len() == 128 {
        // Try as hex signature (64 bytes = 128 hex characters)
        let sig_bytes = hex::decode(signature_str)
            .map_err(|e| CliError::Validation(format!("Invalid hex signature: {}", e)))?;
        if sig_bytes.len() != 64 {
            return Err(CliError::Validation(format!(
                "Hex signature must be exactly 64 bytes (128 hex characters), got {} bytes",
                sig_bytes.len()
            )));
        }
        let mut sig_array = [0u8; 64];
        sig_array.copy_from_slice(&sig_bytes);
        thru_base::tn_tools::Signature::from_bytes(&sig_array)
    } else {
        return Err(CliError::Validation(format!(
            "Invalid signature: {}. Must be a ts... signature (90 characters) or 128-character hex string",
            signature_str
        )));
    };

    let timeout_duration = Duration::from_secs(config.timeout_seconds);

    // Create RPC client
    let client = create_rpc_client(config)?;

    // Get transaction
    let transaction_details = client
        .get_transaction(&signature, timeout_duration, retry_count)
        .await
        .map_err(|e| {
            CliError::TransactionSubmission(format!("Failed to get transaction: {:?}", e))
        })?;

    match transaction_details {
        None => {
            if json_format {
                let response = serde_json::json!({
                    "transaction_get": {
                        "status": "not_found",
                        "signature": signature.as_str()
                    }
                });
                output::print_output(response, true);
            } else {
                output::print_error(&format!("Transaction not found: {}", signature.as_str()));
            }
            Err(CliError::TransactionSubmission(format!(
                "Transaction not found: {}",
                signature.as_str()
            )))
        }
        Some(details) => {
            let has_failure = details.execution_result != 0 || details.vm_error != 0;

            if json_format {
                let mut events_json = Vec::new();

                // Parse events for JSON output
                for event in &details.events {
                    let mut event_json = serde_json::Map::new();
                    event_json.insert(
                        "call_idx".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(event.call_idx as u64)),
                    );
                    event_json.insert(
                        "program_idx".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(
                            event.program_idx as u64,
                        )),
                    );

                    if let Some(event_id) = &event.event_id {
                        event_json.insert(
                            "event_id".to_string(),
                            serde_json::Value::String(event_id.clone()),
                        );
                    }

                    if let Some(program) = &event.program {
                        event_json.insert(
                            "program".to_string(),
                            serde_json::Value::String(program.as_str().to_string()),
                        );
                    }

                    if event.data.len() > 8 {
                        // Extract first 8 bytes as event type
                        let event_type_bytes = &event.data[0..8];
                        let event_type = u64::from_le_bytes([
                            event_type_bytes[0],
                            event_type_bytes[1],
                            event_type_bytes[2],
                            event_type_bytes[3],
                            event_type_bytes[4],
                            event_type_bytes[5],
                            event_type_bytes[6],
                            event_type_bytes[7],
                        ]);
                        event_json.insert(
                            "event_type".to_string(),
                            serde_json::Value::Number(serde_json::Number::from(event_type)),
                        );

                        // Process remaining data
                        let remaining_data = &event.data[8..];
                        if !remaining_data.is_empty() {
                            let parsed_data = parse_event_data_for_json(remaining_data);
                            event_json.insert("data".to_string(), parsed_data);
                        }
                    } else if !event.data.is_empty() {
                        event_json.insert(
                            "data_hex".to_string(),
                            serde_json::Value::String(hex::encode(&event.data)),
                        );
                    }

                    events_json.push(serde_json::Value::Object(event_json));
                }

                // Extract instruction data from body if available
                let instruction_data_hex = if let Some(body) = &details.body {
                    if details.instruction_data_size > 0
                        && body.len() >= details.instruction_data_size as usize
                    {
                        Some(hex::encode(
                            &body[0..details.instruction_data_size as usize],
                        ))
                    } else {
                        None
                    }
                } else {
                    None
                };

                let response = serde_json::json!({
                    "transaction_get": {
                        "status": if has_failure { "failed" } else { "success" },
                        /* Transaction metadata */
                        "signature": details.signature.as_str(),
                        "slot": details.slot,
                        "block_offset": details.block_offset,
                        "body": details.body.as_ref().map(|b| hex::encode(b)),
                        "instruction_data": instruction_data_hex,
                        /* Transaction header */
                        "fee_payer_signature": details.fee_payer_signature.as_str(),
                        "version": details.version,
                        "flags": details.flags,
                        "readwrite_accounts_count": details.readwrite_accounts_count,
                        "readonly_accounts_count": details.readonly_accounts_count,
                        "instruction_data_size": details.instruction_data_size,
                        "requested_compute_units": details.requested_compute_units,
                        "requested_state_units": details.requested_state_units,
                        "requested_memory_units": details.requested_memory_units,
                        "expiry_after": details.expiry_after,
                        "fee": details.fee,
                        "nonce": details.nonce,
                        "start_slot": details.start_slot,
                        "fee_payer_pubkey": details.fee_payer_pubkey.as_str(),
                        "program_pubkey": details.program_pubkey.as_str(),
                        /* Execution result */
                        "compute_units_consumed": details.compute_units_consumed,
                        "memory_units_consumed": details.memory_units_consumed,
                        "state_units_consumed": details.state_units_consumed,
                        "execution_result": details.execution_result,
                        "vm_error": details.vm_error,
                        "vm_error_name": format_vm_error(details.vm_error),
                        "user_error_code": details.user_error_code,
                        "events_count": details.events_cnt,
                        "events_size": details.events_sz,
                        "pages_used": details.pages_used,
                        "readwrite_accounts": details.rw_accounts.iter().map(|pk| pk.as_str().to_string()).collect::<Vec<_>>(),
                        "readonly_accounts": details.ro_accounts.iter().map(|pk| pk.as_str().to_string()).collect::<Vec<_>>(),
                        "events": events_json
                    }
                });
                output::print_output(response, true);
            } else {
                if has_failure {
                    output::print_error("Transaction failed");
                } else {
                    output::print_success("Transaction found");
                }

                /* Transaction metadata */
                println!("\n=== Transaction Metadata ===");
                println!("Signature: {}", details.signature.as_str());
                println!("Slot: {}", details.slot);
                if let Some(block_offset) = details.block_offset {
                    println!("Block Offset: {}", block_offset);
                }

                /* Parse and display instruction data from body */
                if let Some(body) = &details.body {
                    println!("\n=== Transaction Body ===");
                    println!("Total Body Size: {} bytes", body.len());
                    println!("Full Body (hex): {}", hex::encode(body));

                    // The body contains the serialized transaction data
                    // We can display the instruction data portion separately
                    if details.instruction_data_size > 0
                        && body.len() >= details.instruction_data_size as usize
                    {
                        let instruction_data = &body[0..details.instruction_data_size as usize];
                        println!("\nInstruction Data Size: {} bytes", instruction_data.len());
                        println!("Instruction Data (hex): {}", hex::encode(instruction_data));

                        // Try to display as ASCII if printable
                        if let Ok(ascii_str) = std::str::from_utf8(instruction_data) {
                            if ascii_str
                                .chars()
                                .all(|c| c.is_ascii_graphic() || c.is_ascii_whitespace())
                            {
                                println!("Instruction Data (ASCII): {}", ascii_str);
                            }
                        }
                    }
                }

                /* Transaction header */
                println!("\n=== Transaction Header ===");
                println!(
                    "Fee Payer Signature: {}",
                    details.fee_payer_signature.as_str()
                );
                println!("Version: {}", details.version);
                println!("Flags: {}", details.flags);
                println!(
                    "Read-write Accounts Count: {}",
                    details.readwrite_accounts_count
                );
                println!(
                    "Read-only Accounts Count: {}",
                    details.readonly_accounts_count
                );
                println!("Instruction Data Size: {}", details.instruction_data_size);
                println!(
                    "Requested Compute Units: {}",
                    details.requested_compute_units
                );
                println!("Requested State Units: {}", details.requested_state_units);
                println!("Requested Memory Units: {}", details.requested_memory_units);
                println!("Expiry After: {}", details.expiry_after);
                println!("Fee: {}", details.fee);
                println!("Nonce: {}", details.nonce);
                println!("Start Slot: {}", details.start_slot);
                println!("Fee Payer Pubkey: {}", details.fee_payer_pubkey.as_str());
                println!("Program Pubkey: {}", details.program_pubkey.as_str());

                /* Accounts */
                if !details.rw_accounts.is_empty() {
                    println!("\n=== Read-write Accounts ===");
                    for account in &details.rw_accounts {
                        println!("  {}", account.as_str());
                    }
                }

                if !details.ro_accounts.is_empty() {
                    println!("\n=== Read-only Accounts ===");
                    for account in &details.ro_accounts {
                        println!("  {}", account.as_str());
                    }
                }

                /* Execution result */
                println!("\n=== Execution Result ===");
                println!("Compute Units Consumed: {}", details.compute_units_consumed);
                println!("Memory Units Consumed: {}", details.memory_units_consumed);
                println!("State Units Consumed: {}", details.state_units_consumed);
                println!("Execution Result: {}", details.execution_result);
                println!("VM Error: {}", format_vm_error(details.vm_error));
                println!("User Error Code: {}", details.user_error_code);
                println!("Events Count: {}", details.events_cnt);
                println!("Events Size: {}", details.events_sz);
                println!("Pages Used: {}", details.pages_used);

                // Display events if any are present
                if details.events_cnt > 0 {
                    println!("\nEvents:");
                    for (i, event) in details.events.iter().enumerate() {
                        println!(
                            "  Event {}: call_idx={}, program_idx={}",
                            i + 1,
                            event.call_idx,
                            event.program_idx
                        );

                        if let Some(event_id) = &event.event_id {
                            println!("    Event ID: {}", event_id);
                        }
                        if let Some(program) = &event.program {
                            println!("    Program: {}", program.as_str());
                        }

                        if event.data.len() > 8 {
                            // Extract first 8 bytes as event type
                            let event_type_bytes = &event.data[0..8];
                            let event_type = u64::from_le_bytes([
                                event_type_bytes[0],
                                event_type_bytes[1],
                                event_type_bytes[2],
                                event_type_bytes[3],
                                event_type_bytes[4],
                                event_type_bytes[5],
                                event_type_bytes[6],
                                event_type_bytes[7],
                            ]);
                            println!("    Event type: {}", event_type);

                            // Process remaining data
                            let remaining_data = &event.data[8..];
                            if !remaining_data.is_empty() {
                                display_event_data(remaining_data);
                            }
                        } else if !event.data.is_empty() {
                            // If data is 8 bytes or less, just display as hex
                            println!("    Data (hex): {}", hex::encode(&event.data));
                        }
                    }
                }
            }

            Ok(())
        }
    }
}

/// Sort public keys for transaction inclusion and output with indices
fn sort_pubkeys(pubkeys: &[String], json_format: bool) -> Result<(), CliError> {
    // Parse all pubkeys and validate them
    let mut parsed_pubkeys: Vec<([u8; 32], String)> = Vec::with_capacity(pubkeys.len());

    for pubkey_str in pubkeys {
        let bytes = crate::utils::validate_address_or_hex(pubkey_str)?;
        // Convert to thrufmt for output
        let thrufmt = Pubkey::from_bytes(&bytes).to_string();
        parsed_pubkeys.push((bytes, thrufmt));
    }

    // Sort by bytes
    parsed_pubkeys.sort_by(|a, b| a.0.cmp(&b.0));

    if json_format {
        let mut result_map = serde_json::Map::new();
        for (index, (_, thrufmt)) in parsed_pubkeys.iter().enumerate() {
            result_map.insert(thrufmt.clone(), serde_json::json!(index));
        }
        output::print_output(serde_json::Value::Object(result_map), true);
    } else {
        for (index, (_, thrufmt)) in parsed_pubkeys.iter().enumerate() {
            println!("{}: {}", thrufmt, index);
        }
    }

    Ok(())
}

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

    fn create_test_config() -> Config {
        let mut keys = KeyManager::new();
        // Add a test key
        keys.add_key(
            "test",
            "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
            false,
        )
        .unwrap();

        let mut config = Config::default();
        config.rpc_base_url = "http://localhost:8080".to_string();
        config.keys = keys;
        config
    }

    #[test]
    fn test_resolve_program_public_key_hex() {
        let config = create_test_config();
        let hex_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        let result = resolve_program_public_key(&config, hex_key);
        assert!(result.is_ok());
    }

    #[test]
    fn test_resolve_program_public_key_key_name() {
        let config = create_test_config();
        let result = resolve_program_public_key(&config, "test");
        assert!(result.is_ok());
    }

    #[test]
    fn test_resolve_program_public_key_invalid() {
        let config = create_test_config();
        let result = resolve_program_public_key(&config, "invalid");
        assert!(result.is_err());
    }
}