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
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
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
//! Program management command implementations

use std::fs;
use std::path::Path;
use std::time::Duration;
use thru_base::rpc_types::{MakeStateProofConfig, ProofType};
use thru_base::tn_tools::{KeyPair, Pubkey};
use thru_base::txn_lib::Transaction;
use thru_base::txn_tools::TransactionBuilder;

use crate::cli::ProgramCommands;
use crate::commands::uploader::UploaderManager;
use crate::config::Config;
use crate::crypto;
use crate::error::CliError;
use crate::output;
use crate::utils::format_vm_error;
use thru_client::{Client as RpcClient, VersionContext};

const PROGRAM_SEED_MAX_LEN: usize = 32;

fn seed_with_suffix(base_seed: &str, suffix: &str) -> (String, bool) {
    let combined = format!("{}_{}", base_seed, suffix);
    if combined.len() <= PROGRAM_SEED_MAX_LEN {
        (combined, false)
    } else {
        let digest = crypto::calculate_sha256(combined.as_bytes());
        let hashed = hex::encode(&digest[..PROGRAM_SEED_MAX_LEN / 2]);
        (hashed, true)
    }
}

/// Handle program subcommands
pub async fn handle_program_command(
    config: &Config,
    subcommand: ProgramCommands,
    json_format: bool,
) -> Result<(), CliError> {
    match subcommand {
        ProgramCommands::Create {
            manager,
            ephemeral,
            seed,
            authority,
            program_file,
            chunk_size,
        } => {
            create_program(
                config,
                manager.as_deref(),
                ephemeral,
                &seed,
                authority.as_deref(),
                &program_file,
                chunk_size,
                json_format,
            )
            .await
        }
        ProgramCommands::Upgrade {
            manager,
            ephemeral,
            seed,
            program_file,
            chunk_size,
        } => {
            upgrade_program(
                config,
                manager.as_deref(),
                &seed,
                ephemeral,
                &program_file,
                chunk_size,
                json_format,
            )
            .await
        }
        ProgramCommands::SetPause {
            manager,
            ephemeral,
            seed,
            paused,
        } => {
            // Parse paused string to boolean
            let paused_bool = match paused.to_lowercase().as_str() {
                "true" | "1" | "yes" | "on" => true,
                "false" | "0" | "no" | "off" => false,
                _ => {
                    let error_msg = format!(
                        "Invalid paused value '{}'. Use: true/false, 1/0, yes/no, or on/off",
                        paused
                    );
                    if json_format {
                        let error_response = serde_json::json!({
                            "error": error_msg
                        });
                        output::print_output(error_response, true);
                    } else {
                        output::print_error(&error_msg);
                    }
                    return Err(CliError::Validation(error_msg));
                }
            };

            set_pause_program(
                config,
                manager.as_deref(),
                &seed,
                ephemeral,
                paused_bool,
                json_format,
            )
            .await
        }
        ProgramCommands::Destroy {
            manager,
            ephemeral,
            seed,
            fee_payer,
        } => {
            destroy_program(
                config,
                manager.as_deref(),
                &seed,
                ephemeral,
                fee_payer.as_deref(),
                json_format,
            )
            .await
        }
        ProgramCommands::Finalize {
            manager,
            ephemeral,
            seed,
            fee_payer,
        } => {
            finalize_program(
                config,
                manager.as_deref(),
                &seed,
                ephemeral,
                fee_payer.as_deref(),
                json_format,
            )
            .await
        }
        ProgramCommands::SetAuthority {
            manager,
            ephemeral,
            seed,
            authority_candidate,
        } => {
            set_authority_program(
                config,
                manager.as_deref(),
                &seed,
                ephemeral,
                &authority_candidate,
                json_format,
            )
            .await
        }
        ProgramCommands::ClaimAuthority {
            manager,
            seed,
            ephemeral,
            fee_payer,
        } => {
            claim_authority_program(
                config,
                manager.as_deref(),
                &seed,
                ephemeral,
                fee_payer.as_deref(),
                json_format,
            )
            .await
        }
        ProgramCommands::DeriveAddress {
            program_id,
            seed,
            ephemeral,
        } => derive_program_address(&program_id, &seed, ephemeral, json_format),
        ProgramCommands::DeriveManagerAccounts {
            manager,
            seed,
            ephemeral,
        } => derive_manager_accounts(config, manager.as_deref(), &seed, ephemeral, json_format),
        ProgramCommands::SeedToHex { seed } => seed_to_hex(&seed, json_format),
        ProgramCommands::DeriveProgramAccount {
            manager,
            seed,
            ephemeral,
        } => derive_program_account(config, manager.as_deref(), &seed, ephemeral, json_format),
        ProgramCommands::Status {
            manager,
            seed,
            ephemeral,
        } => get_program_status(config, manager.as_deref(), &seed, ephemeral, json_format).await,
    }
}

/// Program manager for transaction building and execution
pub struct ProgramManager {
    rpc_client: RpcClient,
    fee_payer_keypair: KeyPair,
    chain_id: u16,
    timeout_seconds: u64,
}

impl ProgramManager {
    /// Create new program manager
    pub async fn new(config: &Config) -> Result<Self, CliError> {
        Self::new_with_fee_payer(config, None).await
    }

    /// Create new program manager with optional fee payer override
    pub async fn new_with_fee_payer(
        config: &Config,
        fee_payer_name: Option<&str>,
    ) -> Result<Self, CliError> {
        // Create RPC client
        let rpc_url = config.get_grpc_url()?;
        let rpc_client = RpcClient::builder()
            .http_endpoint(rpc_url)
            .timeout(Duration::from_secs(config.timeout_seconds))
            .auth_token(config.auth_token.clone())
            .build()?;

        // Get manager program public key (though not stored in struct)
        let _manager_program_pubkey = config.get_manager_pubkey()?;

        // Create fee payer keypair from config
        let fee_payer_key_hex = if let Some(name) = fee_payer_name {
            config.keys.get_key(name)?
        } else {
            config.keys.get_default_key()?
        };
        let fee_payer_keypair = crypto::keypair_from_hex(fee_payer_key_hex)?;

        let chain_info = rpc_client.get_chain_info().await.map_err(|e| {
            CliError::TransactionSubmission(format!("Failed to get chain info: {}", e))
        })?;

        Ok(Self {
            rpc_client,
            fee_payer_keypair,
            chain_id: chain_info.chain_id,
            timeout_seconds: config.timeout_seconds,
        })
    }

    /// Convert manager program user error code to human-readable string
    fn decode_manager_error(user_error_code: u64) -> String {
        if user_error_code == 0 {
            return "Success".to_string();
        }

        // Check if this is a syscall error (negative values when cast as i64)
        if user_error_code as i64 >= -41 && user_error_code as i64 <= -7 {
            return Self::decode_syscall_error(user_error_code);
        }

        // Error type constants (from tn_manager_program.h)
        const ERR_SIZE_ERROR: u64 = 0x0100;
        const ERR_VALUE_ERROR: u64 = 0x0200;
        const ERR_AUTHORIZATION_ERROR: u64 = 0x0300;
        const ERR_INDEX_ERROR: u64 = 0x0400;
        const ERR_NA_ERROR: u64 = 0x0500;
        const ERR_RELATIONSHIP_ERROR: u64 = 0x0600;
        const ERR_STATE_ERROR: u64 = 0x0700;
        const ERR_NOT_WRITABLE_ERROR: u64 = 0x0800;

        // Error object constants
        const ERR_INSTRUCTION: u64 = 0x01;
        const ERR_DISCRIMINANT: u64 = 0x02;
        const ERR_SRCBUF_ACC: u64 = 0x03;
        const ERR_META_ACC: u64 = 0x04;
        const ERR_PROGRAM_ACC: u64 = 0x05;
        const ERR_AUTHORITY_ACC: u64 = 0x06;
        const ERR_AUTHORITY_CANDIDATE_ACC: u64 = 0x07;

        // Extract error type (high byte) and error object (low byte)
        let error_type = user_error_code & 0xFF00;
        let error_object = user_error_code & 0x00FF;

        // Decode error type
        let error_type_str = match error_type {
            ERR_SIZE_ERROR => "Size error",
            ERR_VALUE_ERROR => "Value error",
            ERR_AUTHORIZATION_ERROR => "Authorization error",
            ERR_INDEX_ERROR => "Index error",
            ERR_NA_ERROR => "Account not available error",
            ERR_RELATIONSHIP_ERROR => "Account relationship error",
            ERR_STATE_ERROR => "State error",
            ERR_NOT_WRITABLE_ERROR => "Not writable error",
            _ => "Unknown error type",
        };

        // Decode error object
        let error_object_str = match error_object {
            ERR_INSTRUCTION => "in instruction",
            ERR_DISCRIMINANT => "invalid discriminant",
            ERR_SRCBUF_ACC => "in source buffer account",
            ERR_META_ACC => "in meta account",
            ERR_PROGRAM_ACC => "in program account",
            ERR_AUTHORITY_ACC => "in authority account",
            ERR_AUTHORITY_CANDIDATE_ACC => "in authority candidate account",
            _ => {
                if error_object == 0 {
                    ""
                } else {
                    "in unknown object"
                }
            }
        };

        // Combine error type and object
        if error_object == 0 || error_object_str.is_empty() {
            format!("{} (0x{:04X})", error_type_str, user_error_code)
        } else {
            format!(
                "{} {} (0x{:04X})",
                error_type_str, error_object_str, user_error_code
            )
        }
    }

    /// Decode syscall error codes (from tn_vm_base.h)
    fn decode_syscall_error(error_code: u64) -> String {
        let error_code_i64 = error_code as i64;
        let error_description = match error_code_i64 {
            -7 => "Bad segment table size",
            -8 => "Invalid account index",
            -9 => "Account does not exist",
            -10 => "Account not writable",
            -11 => "Balance overflow",
            -12 => "Account too big",
            -13 => "Invalid object reference kind",
            -14 => "Object not writable",
            -15 => "Account already exists",
            -16 => "Bad account address",
            -17 => "Account is not program",
            -18 => "Account has data",
            -19 => "Segment already mapped",
            -20 => "Bad parameters",
            -21 => "Invalid segment ID",
            -22 => "Invalid address",
            -23 => "Invalid state proof",
            -24 => "Call depth too deep",
            -25 => "Revert",
            -26 => "Insufficient pages",
            -27 => "Invalid account",
            -28 => "Invalid segment size",
            -29 => "Unfreeable page",
            -30 => "Log data too large",
            -31 => "Event too large",
            -32 => "Invalid proof length",
            -33 => "Invalid proof slot",
            -34 => "Account in compression timeout",
            -35 => "Invalid account data size",
            -36 => "Invalid seed length",
            -37 => "Transaction has compressed account",
            -38 => "Insufficient balance",
            -39 => "Invalid offset",
            -40 => "Compute units exceeded",
            -41 => "Invalid flags",
            _ => "Unknown syscall error",
        };

        format!("Syscall error: {} ({})", error_description, error_code_i64)
    }

    /// Get current nonce for fee payer account
    async fn get_current_nonce(&self) -> Result<u64, CliError> {
        match self
            .rpc_client
            .get_account_info(&self.fee_payer_keypair.address_string, None, Some(VersionContext::Current))
            .await
        {
            Ok(Some(account)) => Ok(account.nonce),
            Ok(None) => Err(CliError::NonceManagement(
                "Fee payer account not found. Please ensure the account is funded.".to_string(),
            )),
            Err(e) => Err(CliError::NonceManagement(format!(
                "Failed to retrieve account nonce: {}",
                e
            ))),
        }
    }

    /// Get current slot
    async fn get_current_slot(&self) -> Result<u64, CliError> {
        let block_height = self.rpc_client.get_block_height().await.map_err(|e| {
            CliError::TransactionSubmission(format!("Failed to get current slot: {}", e))
        })?;
        Ok(block_height.finalized_height)
    }

    /// Submit and verify transaction
    async fn submit_and_verify_transaction(
        &self,
        transaction: &Transaction,
        json_format: bool,
        user_error_decoder: fn(u64) -> String,
    ) -> Result<(), CliError> {
        // Execute transaction and wait for completion
        let wire_bytes = transaction.to_wire();
        let timeout = Duration::from_secs(self.timeout_seconds);

        let transaction_details = self
            .rpc_client
            .execute_transaction(&wire_bytes, timeout)
            .await
            .map_err(|e| CliError::TransactionSubmission(e.to_string()))?;

        let has_failure =
            transaction_details.execution_result != 0 || transaction_details.vm_error != 0;
        let vm_error_label = format_vm_error(transaction_details.vm_error);
        let vm_error_suffix = if transaction_details.vm_error != 0 {
            format!(" ({})", vm_error_label)
        } else {
            String::new()
        };
        let user_error_label = if transaction_details.user_error_code != 0 {
            user_error_decoder(transaction_details.user_error_code)
        } else {
            "None".to_string()
        };
        let user_error_suffix = if transaction_details.user_error_code != 0 {
            format!(" - Manager program error: {}", user_error_label)
        } else {
            String::new()
        };

        if !json_format {
            output::print_success(&format!(
                "Transaction completed: {}",
                transaction_details.signature.as_str()
            ));

            if has_failure {
                output::print_warning(&format!(
                    "Transaction completed with execution result: {} (hex 0x{:X}) vm_error: {}{}{}",
                    transaction_details.execution_result as i64,
                    transaction_details.execution_result,
                    vm_error_label,
                    vm_error_suffix,
                    user_error_suffix
                ));
            }
        }

        if has_failure {
            let vm_error_display = if transaction_details.vm_error != 0 {
                format!("{}{}", transaction_details.vm_error, vm_error_suffix)
            } else {
                "0".to_string()
            };
            let message = format!(
                "Transaction failed (execution_result={} (hex 0x{:X}), vm_error={}, manager_error={})",
                transaction_details.execution_result,
                transaction_details.execution_result,
                vm_error_display,
                user_error_label
            );

            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(),
            });
        }

        Ok(())
    }

}

/// Create a new managed program from a program file
async fn create_program(
    config: &Config,
    manager_pubkey: Option<&str>,
    ephemeral: bool,
    seed: &str,
    authority: Option<&str>,
    program_file: &str,
    chunk_size: usize,
    json_format: bool,
) -> Result<(), CliError> {
    // Validate program file exists
    let program_path = Path::new(program_file);
    if !program_path.exists() {
        let abs_path = std::env::current_dir()
            .map(|cwd| cwd.join(program_file).display().to_string())
            .unwrap_or_else(|_| program_file.to_string());
        if json_format {
            let error_response = serde_json::json!({
                "error": {
                    "type": "file_not_found",
                    "message": format!("Program file not found: {}", program_file),
                    "path": program_file,
                    "resolved_path": abs_path
                }
            });
            output::print_output(error_response, true);
        } else {
            output::print_error(&format!("Program file not found: {}", program_file));
            output::print_error(&format!("Resolved path: {}", abs_path));
        }
        return Err(CliError::Reported);
    }

    // Read program data
    let program_data = fs::read(program_path).map_err(|e| CliError::Io(e))?;

    if !json_format {
        output::print_info(&format!(
            "Creating {} managed program from file: {} ({} bytes)",
            if ephemeral { "ephemeral" } else { "permanent" },
            program_file,
            program_data.len()
        ));
        output::print_info(&format!("User seed: {}", seed));
    }

    // Get manager program public key
    let manager_program_pubkey = if let Some(custom_manager) = manager_pubkey {
        Pubkey::new(custom_manager.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid manager public key: {}", e)))?
    } else {
        config.get_manager_pubkey()?
    };

    // Get authority public key
    let authority_pubkey = if let Some(auth_name) = authority {
        let auth_key = config.keys.get_key(auth_name)?;
        let auth_keypair = crypto::keypair_from_hex(auth_key)?;
        auth_keypair.public_key
    } else {
        let default_key = config.get_private_key_bytes()?;
        let default_keypair = crypto::keypair_from_hex(&hex::encode(default_key))?;
        default_keypair.public_key
    };

    // Step 1: Upload program to temporary buffer account
    let (temp_seed, temp_seed_hashed) = seed_with_suffix(seed, "temporary");

    if !json_format {
        output::print_info(&format!(
            "Step 1: Uploading program to temporary buffer (seed: {})",
            temp_seed
        ));
        if temp_seed_hashed {
            output::print_info("Seed + suffix exceeded 32 bytes; using hashed temporary seed");
        }
    }

    // Create uploader manager and upload the program
    let uploader_manager = UploaderManager::new(config).await?;
    let upload_session = uploader_manager
        .upload_program(&temp_seed, &program_data, chunk_size, json_format)
        .await?;

    if !json_format {
        output::print_success("✓ Program uploaded to temporary buffer successfully");
        output::print_info(&format!(
            "Temporary meta account: {}",
            upload_session.meta_account
        ));
        output::print_info(&format!(
            "Temporary buffer account: {}",
            upload_session.buffer_account
        ));
    }

    // Step 2: Create managed program from the temporary buffer
    if !json_format {
        output::print_info("Step 2: Creating managed program from temporary buffer");
    }

    // Create program manager
    let mut config_with_manager = config.clone();
    config_with_manager.manager_program_public_key = manager_program_pubkey.to_string();
    let program_manager = ProgramManager::new(&config_with_manager).await?;

    let nonce = program_manager.get_current_nonce().await?;
    let start_slot = program_manager.get_current_slot().await?;

    // Derive meta and program account addresses for the managed program
    let (meta_account, program_account) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_program_pubkey, ephemeral)?;

    if !json_format {
        output::print_info(&format!(
            "Fee payer: {}",
            program_manager.fee_payer_keypair.address_string
        ));
        output::print_info(&format!("Manager program meta account: {}", meta_account));
        output::print_info(&format!("Manager program account: {}", program_account));
    }

    // Create state proofs if not ephemeral
    let (meta_proof, program_proof) = if !ephemeral {
        if !json_format {
            output::print_info("Creating state proofs for permanent program...");
        }

        let state_proof_config = MakeStateProofConfig {
            proof_type: ProofType::Creating,
            slot: None,
        };

        // Create proof for meta account
        let meta_proof_bytes = program_manager
            .rpc_client
            .make_state_proof(&meta_account, &state_proof_config)
            .await
            .map_err(|e| {
                CliError::ProgramUpload(format!("Failed to create meta account state proof: {}", e))
            })?;

        // Create proof for program account
        let program_proof_bytes = program_manager
            .rpc_client
            .make_state_proof(&program_account, &state_proof_config)
            .await
            .map_err(|e| {
                CliError::ProgramUpload(format!(
                    "Failed to create program account state proof: {}",
                    e
                ))
            })?;

        (Some(meta_proof_bytes), Some(program_proof_bytes))
    } else {
        (None, None)
    };

    // Build and submit transaction to create managed program
    let transaction = TransactionBuilder::build_manager_create(
        program_manager.fee_payer_keypair.public_key,
        manager_program_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        meta_account
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        program_account
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        upload_session
            .buffer_account
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        authority_pubkey,
        0,                         // source_offset
        program_data.len() as u32, // source_size
        seed.as_bytes(),
        ephemeral,
        meta_proof.as_deref(),    // meta_proof
        program_proof.as_deref(), // program_proof
        0,                        // fee
        nonce,
        start_slot,
    )
    .map_err(|e| CliError::ProgramUpload(e.to_string()))?;

    // Set chain ID and sign transaction
    let mut transaction = transaction.with_chain_id(program_manager.chain_id);
    transaction
        .sign(&program_manager.fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(e.to_string()))?;

    // Submit and verify
    program_manager
        .submit_and_verify_transaction(
            &transaction,
            json_format,
            ProgramManager::decode_manager_error,
        )
        .await?;

    if !json_format {
        output::print_success("✓ Managed program created successfully");
    }

    // Step 3: Clean up temporary buffer account
    if !json_format {
        output::print_info("Step 3: Cleaning up temporary buffer account");
    }

    match uploader_manager
        .cleanup_program(&temp_seed, json_format)
        .await
    {
        Ok(()) => {
            if !json_format {
                output::print_success("✓ Temporary buffer account cleaned up successfully");
            }
        }
        Err(e) => {
            if !json_format {
                output::print_warning(&format!(
                    "Warning: Failed to clean up temporary buffer account: {}",
                    e
                ));
                output::print_info("You may need to manually clean it up later using:");
                output::print_info(&format!("  thru uploader cleanup {}", temp_seed));
            }
            // Don't fail the whole operation for cleanup failures
        }
    }

    if json_format {
        let response = serde_json::json!({
            "program_create": {
                "status": "success",
                "ephemeral": ephemeral,
                "meta_account": meta_account.to_string(),
                "program_account": program_account.to_string(),
                "seed": seed,
                "temp_seed": temp_seed,
                "program_size": program_data.len()
            }
        });
        output::print_output(response, true);
    } else {
        output::print_success(&format!(
            "🎉 {} managed program created successfully!",
            if ephemeral { "Ephemeral" } else { "Permanent" }
        ));
        output::print_info(&format!("Meta account: {}", meta_account));
        output::print_info(&format!("Program account: {}", program_account));
    }

    Ok(())
}


/// Upgrade an existing managed program from a program file
async fn upgrade_program(
    config: &Config,
    manager_pubkey: Option<&str>,
    seed: &str,
    ephemeral: bool,
    program_file: &str,
    chunk_size: usize,
    json_format: bool,
) -> Result<(), CliError> {
    // Validate program file exists
    let program_path = Path::new(program_file);
    if !program_path.exists() {
        let abs_path = std::env::current_dir()
            .map(|cwd| cwd.join(program_file).display().to_string())
            .unwrap_or_else(|_| program_file.to_string());
        if json_format {
            let error_response = serde_json::json!({
                "error": {
                    "type": "file_not_found",
                    "message": format!("Program file not found: {}", program_file),
                    "path": program_file,
                    "resolved_path": abs_path
                }
            });
            output::print_output(error_response, true);
        } else {
            output::print_error(&format!("Program file not found: {}", program_file));
            output::print_error(&format!("Resolved path: {}", abs_path));
        }
        return Err(CliError::Reported);
    }

    // Read program data
    let program_data = fs::read(program_path).map_err(|e| CliError::Io(e))?;

    if !json_format {
        output::print_info(&format!(
            "Upgrading managed program from file: {} ({} bytes)",
            program_file,
            program_data.len()
        ));
        output::print_info(&format!("User seed: {}", seed));
    }

    // Get manager program public key
    let manager_program_pubkey = if let Some(custom_manager) = manager_pubkey {
        Pubkey::new(custom_manager.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid manager public key: {}", e)))?
    } else {
        config.get_manager_pubkey()?
    };

    // Step 1: Upload program to temporary buffer account
    let (temp_seed, temp_seed_hashed) = seed_with_suffix(seed, "upgrade_temporary");

    if !json_format {
        output::print_info(&format!(
            "Step 1: Uploading program to temporary buffer (seed: {})",
            temp_seed
        ));
        if temp_seed_hashed {
            output::print_info("Seed + suffix exceeded 32 bytes; using hashed temporary seed");
        }
    }

    // Create uploader manager and upload the program
    let uploader_manager = UploaderManager::new(config).await?;
    let upload_session = uploader_manager
        .upload_program(&temp_seed, &program_data, chunk_size, json_format)
        .await?;

    if !json_format {
        output::print_success("✓ Program uploaded to temporary buffer successfully");
        output::print_info(&format!(
            "Temporary meta account: {}",
            upload_session.meta_account
        ));
        output::print_info(&format!(
            "Temporary buffer account: {}",
            upload_session.buffer_account
        ));
    }

    // Step 2: Upgrade managed program from the temporary buffer
    if !json_format {
        output::print_info("Step 2: Upgrading managed program from temporary buffer");
    }

    // Create program manager
    let mut config_with_manager = config.clone();
    config_with_manager.manager_program_public_key = manager_program_pubkey.to_string();
    let program_manager = ProgramManager::new(&config_with_manager).await?;

    let nonce = program_manager.get_current_nonce().await?;
    let start_slot = program_manager.get_current_slot().await?;

    // Derive meta and program account addresses for the managed program
    let (meta_account, program_account) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_program_pubkey, ephemeral)?;

    if !json_format {
        output::print_info(&format!(
            "Fee payer: {}",
            program_manager.fee_payer_keypair.address_string
        ));
        output::print_info(&format!("Manager program meta account: {}", meta_account));
        output::print_info(&format!("Manager program account: {}", program_account));
    }

    // Build and submit transaction to upgrade managed program
    let transaction = TransactionBuilder::build_manager_upgrade(
        program_manager.fee_payer_keypair.public_key,
        manager_program_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        meta_account
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        program_account
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        upload_session
            .buffer_account
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        0,                         // source_offset
        program_data.len() as u32, // source_size
        0,                         // fee
        nonce,
        start_slot,
    )
    .map_err(|e| CliError::ProgramUpload(e.to_string()))?;

    // Set chain ID and sign transaction
    let mut transaction = transaction.with_chain_id(program_manager.chain_id);
    transaction
        .sign(&program_manager.fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(e.to_string()))?;

    // Submit and verify
    program_manager
        .submit_and_verify_transaction(
            &transaction,
            json_format,
            ProgramManager::decode_manager_error,
        )
        .await?;

    if !json_format {
        output::print_success("✓ Managed program upgraded successfully");
    }

    // Step 3: Clean up temporary buffer account
    if !json_format {
        output::print_info("Step 3: Cleaning up temporary buffer account");
    }

    match uploader_manager
        .cleanup_program(&temp_seed, json_format)
        .await
    {
        Ok(()) => {
            if !json_format {
                output::print_success("✓ Temporary buffer account cleaned up successfully");
            }
        }
        Err(e) => {
            if !json_format {
                output::print_warning(&format!(
                    "Warning: Failed to clean up temporary buffer account: {}",
                    e
                ));
                output::print_info("You may need to manually clean it up later using:");
                output::print_info(&format!("  thru uploader cleanup {}", temp_seed));
            }
            // Don't fail the whole operation for cleanup failures
        }
    }

    if json_format {
        let response = serde_json::json!({
            "program_upgrade": {
                "status": "success",
                "meta_account": meta_account.to_string(),
                "program_account": program_account.to_string(),
                "seed": seed,
                "temp_seed": temp_seed,
                "program_size": program_data.len()
            }
        });
        output::print_output(response, true);
    } else {
        output::print_success(&format!(
            "Program upgrade completed! New program size: {} bytes",
            program_data.len()
        ));
    }

    Ok(())
}

/// Set pause state of a managed program
async fn set_pause_program(
    config: &Config,
    manager_pubkey: Option<&str>,
    seed: &str,
    ephemeral: bool,
    paused: bool,
    json_format: bool,
) -> Result<(), CliError> {
    let manager_program_pubkey = if let Some(custom_manager) = manager_pubkey {
        Pubkey::new(custom_manager.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid manager public key: {}", e)))?
    } else {
        config.get_manager_pubkey()?
    };

    // Derive meta and program account addresses from seed
    let (meta_account_pubkey, program_account_pubkey) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_program_pubkey, ephemeral)?;

    if !json_format {
        output::print_info(&format!(
            "{} managed program...",
            if paused { "Pausing" } else { "Unpausing" }
        ));
        output::print_info(&format!("Seed: {}", seed));
        output::print_info(&format!("Meta account: {}", meta_account_pubkey));
        output::print_info(&format!("Program account: {}", program_account_pubkey));
    }

    let mut config_with_manager = config.clone();
    config_with_manager.manager_program_public_key = manager_program_pubkey.to_string();
    let program_manager = ProgramManager::new(&config_with_manager).await?;

    let nonce = program_manager.get_current_nonce().await?;
    let start_slot = program_manager.get_current_slot().await?;

    let mut transaction = TransactionBuilder::build_manager_set_pause(
        program_manager.fee_payer_keypair.public_key,
        manager_program_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        meta_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        program_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        paused,
        0,
        nonce,
        start_slot,
    )
    .map_err(|e| CliError::ProgramUpload(e.to_string()))?;

    transaction
        .sign(&program_manager.fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(e.to_string()))?;

    program_manager
        .submit_and_verify_transaction(
            &transaction,
            json_format,
            ProgramManager::decode_manager_error,
        )
        .await?;

    let response = if json_format {
        serde_json::json!({
            "program_set_pause": {
                "status": "success",
                "seed": seed,
                "meta_account": meta_account_pubkey.to_string(),
                "program_account": program_account_pubkey.to_string(),
                "paused": paused
            }
        })
    } else {
        output::print_success(&format!(
            "Program {} successfully",
            if paused { "paused" } else { "unpaused" }
        ));
        return Ok(());
    };

    if json_format {
        output::print_output(response, true);
    }

    Ok(())
}

/// Destroy a managed program
async fn destroy_program(
    config: &Config,
    manager_pubkey: Option<&str>,
    seed: &str,
    ephemeral: bool,
    fee_payer: Option<&str>,
    json_format: bool,
) -> Result<(), CliError> {
    use thru_base::txn_tools::MANAGER_INSTRUCTION_DESTROY;

    let manager_program_pubkey = if let Some(custom_manager) = manager_pubkey {
        Pubkey::new(custom_manager.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid manager public key: {}", e)))?
    } else {
        config.get_manager_pubkey()?
    };

    // Derive meta and program account addresses from seed
    let (meta_account_pubkey, program_account_pubkey) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_program_pubkey, ephemeral)?;

    if !json_format {
        output::print_info("Destroying managed program...");
        output::print_info(&format!("Seed: {}", seed));
        output::print_info(&format!("Meta account: {}", meta_account_pubkey));
        output::print_info(&format!("Program account: {}", program_account_pubkey));
        if let Some(name) = fee_payer {
            output::print_info(&format!("Fee payer override: {}", name));
        }
    }

    let mut config_with_manager = config.clone();
    config_with_manager.manager_program_public_key = manager_program_pubkey.to_string();
    let program_manager =
        ProgramManager::new_with_fee_payer(&config_with_manager, fee_payer).await?;

    let nonce = program_manager.get_current_nonce().await?;
    let start_slot = program_manager.get_current_slot().await?;

    let mut transaction = TransactionBuilder::build_manager_simple(
        program_manager.fee_payer_keypair.public_key,
        manager_program_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        meta_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        program_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        MANAGER_INSTRUCTION_DESTROY,
        0,
        nonce,
        start_slot,
    )
    .map_err(|e| CliError::ProgramUpload(e.to_string()))?;

    transaction
        .sign(&program_manager.fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(e.to_string()))?;

    if let Err(err) = program_manager
        .submit_and_verify_transaction(
            &transaction,
            json_format,
            ProgramManager::decode_manager_error,
        )
        .await
    {
        if json_format {
            let mut failure_response = serde_json::json!({
                "program_destroy": {
                    "status": "failed",
                    "seed": seed,
                    "meta_account": meta_account_pubkey.to_string(),
                    "program_account": program_account_pubkey.to_string(),
                    "error": {
                        "message": err.to_string()
                    }
                }
            });

            if let Some(obj) = failure_response
                .as_object_mut()
                .and_then(|map| map.get_mut("program_destroy"))
                .and_then(|v| v.as_object_mut())
            {
                if let Some(name) = fee_payer {
                    obj.insert(
                        "fee_payer".to_string(),
                        serde_json::Value::String(name.to_string()),
                    );
                }

                if let Some(err_obj) = obj.get_mut("error").and_then(|v| v.as_object_mut()) {
                    match &err {
                        CliError::TransactionFailed {
                            message,
                            execution_result,
                            vm_error,
                            vm_error_label,
                            user_error_code,
                            user_error_label,
                            signature,
                        } => {
                            err_obj.insert(
                                "message".to_string(),
                                serde_json::Value::String(message.clone()),
                            );
                            err_obj.insert(
                                "execution_result".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(
                                    *execution_result,
                                )),
                            );
                            err_obj.insert(
                                "execution_result_hex".to_string(),
                                serde_json::Value::String(format!("0x{:X}", execution_result)),
                            );
                            err_obj.insert(
                                "vm_error".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(i64::from(
                                    *vm_error,
                                ))),
                            );
                            err_obj.insert(
                                "vm_error_label".to_string(),
                                serde_json::Value::String(vm_error_label.clone()),
                            );
                            err_obj.insert(
                                "user_error_code".to_string(),
                                serde_json::Value::Number(serde_json::Number::from(
                                    *user_error_code,
                                )),
                            );
                            err_obj.insert(
                                "user_error_code_hex".to_string(),
                                serde_json::Value::String(format!("0x{:X}", user_error_code)),
                            );
                            err_obj.insert(
                                "user_error_label".to_string(),
                                serde_json::Value::String(user_error_label.clone()),
                            );
                            if !signature.is_empty() {
                                err_obj.insert(
                                    "signature".to_string(),
                                    serde_json::Value::String(signature.clone()),
                                );
                            }
                        }
                        CliError::TransactionSubmission(msg) => {
                            err_obj.insert(
                                "message".to_string(),
                                serde_json::Value::String(msg.clone()),
                            );
                        }
                        CliError::Generic { message } => {
                            err_obj.insert(
                                "message".to_string(),
                                serde_json::Value::String(message.clone()),
                            );
                        }
                        _ => {
                            err_obj.insert(
                                "message".to_string(),
                                serde_json::Value::String(err.to_string()),
                            );
                        }
                    }
                }
            }

            output::print_output(failure_response, true);
        }

        if json_format {
            return Err(CliError::Reported);
        }

        output::print_error(&err.to_string());
        return Err(CliError::Reported);
    }

    let response = if json_format {
        let mut resp = serde_json::json!({
            "program_destroy": {
                "status": "success",
                "seed": seed,
                "meta_account": meta_account_pubkey.to_string(),
                "program_account": program_account_pubkey.to_string()
            }
        });
        if let Some(name) = fee_payer {
            if let Some(obj) = resp
                .as_object_mut()
                .and_then(|map| map.get_mut("program_destroy"))
                .and_then(|v| v.as_object_mut())
            {
                obj.insert(
                    "fee_payer".to_string(),
                    serde_json::Value::String(name.to_string()),
                );
            }
        }
        resp
    } else {
        output::print_success("Program destroyed successfully");
        return Ok(());
    };

    if json_format {
        output::print_output(response, true);
    }

    Ok(())
}

/// Finalize a managed program (make it immutable)
async fn finalize_program(
    config: &Config,
    manager_pubkey: Option<&str>,
    seed: &str,
    ephemeral: bool,
    fee_payer: Option<&str>,
    json_format: bool,
) -> Result<(), CliError> {
    use thru_base::txn_tools::MANAGER_INSTRUCTION_FINALIZE;

    let manager_program_pubkey = if let Some(custom_manager) = manager_pubkey {
        Pubkey::new(custom_manager.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid manager public key: {}", e)))?
    } else {
        config.get_manager_pubkey()?
    };

    // Derive meta and program account addresses from seed
    let (meta_account_pubkey, program_account_pubkey) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_program_pubkey, ephemeral)?;

    if !json_format {
        output::print_info("Finalizing managed program...");
        output::print_info(&format!("Seed: {}", seed));
        output::print_info(&format!("Meta account: {}", meta_account_pubkey));
        output::print_info(&format!("Program account: {}", program_account_pubkey));
        if let Some(name) = fee_payer {
            output::print_info(&format!("Fee payer override: {}", name));
        }
    }

    let mut config_with_manager = config.clone();
    config_with_manager.manager_program_public_key = manager_program_pubkey.to_string();
    let program_manager =
        ProgramManager::new_with_fee_payer(&config_with_manager, fee_payer).await?;

    let nonce = program_manager.get_current_nonce().await?;
    let start_slot = program_manager.get_current_slot().await?;

    let mut transaction = TransactionBuilder::build_manager_simple(
        program_manager.fee_payer_keypair.public_key,
        manager_program_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        meta_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        program_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        MANAGER_INSTRUCTION_FINALIZE,
        0,
        nonce,
        start_slot,
    )
    .map_err(|e| CliError::ProgramUpload(e.to_string()))?;

    transaction
        .sign(&program_manager.fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(e.to_string()))?;

    program_manager
        .submit_and_verify_transaction(
            &transaction,
            json_format,
            ProgramManager::decode_manager_error,
        )
        .await?;

    let response = if json_format {
        let mut resp = serde_json::json!({
            "program_finalize": {
                "status": "success",
                "seed": seed,
                "meta_account": meta_account_pubkey.to_string(),
                "program_account": program_account_pubkey.to_string()
            }
        });
        if let Some(name) = fee_payer {
            if let Some(obj) = resp
                .as_object_mut()
                .and_then(|map| map.get_mut("program_finalize"))
                .and_then(|v| v.as_object_mut())
            {
                obj.insert(
                    "fee_payer".to_string(),
                    serde_json::Value::String(name.to_string()),
                );
            }
        }
        resp
    } else {
        output::print_success("Program finalized successfully");
        return Ok(());
    };

    if json_format {
        output::print_output(response, true);
    }

    Ok(())
}

/// Set authority candidate for a managed program
async fn set_authority_program(
    config: &Config,
    manager_pubkey: Option<&str>,
    seed: &str,
    ephemeral: bool,
    authority_candidate: &str,
    json_format: bool,
) -> Result<(), CliError> {
    let manager_program_pubkey = if let Some(custom_manager) = manager_pubkey {
        Pubkey::new(custom_manager.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid manager public key: {}", e)))?
    } else {
        config.get_manager_pubkey()?
    };

    // Derive meta and program account addresses from seed
    let (meta_account_pubkey, program_account_pubkey) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_program_pubkey, ephemeral)?;

    let authority_candidate_pubkey = Pubkey::new(authority_candidate.to_string())
        .map_err(|e| CliError::Validation(format!("Invalid authority candidate: {}", e)))?;

    if !json_format {
        output::print_info("Setting authority candidate for managed program...");
        output::print_info(&format!("Seed: {}", seed));
        output::print_info(&format!("Meta account: {}", meta_account_pubkey));
        output::print_info(&format!("Program account: {}", program_account_pubkey));
        output::print_info(&format!("Authority candidate: {}", authority_candidate));
    }

    let mut config_with_manager = config.clone();
    config_with_manager.manager_program_public_key = manager_program_pubkey.to_string();
    let program_manager = ProgramManager::new(&config_with_manager).await?;

    let nonce = program_manager.get_current_nonce().await?;
    let start_slot = program_manager.get_current_slot().await?;

    let mut transaction = TransactionBuilder::build_manager_set_authority(
        program_manager.fee_payer_keypair.public_key,
        manager_program_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        meta_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        program_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        authority_candidate_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        0,
        nonce,
        start_slot,
    )
    .map_err(|e| CliError::ProgramUpload(e.to_string()))?;

    transaction
        .sign(&program_manager.fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(e.to_string()))?;

    program_manager
        .submit_and_verify_transaction(
            &transaction,
            json_format,
            ProgramManager::decode_manager_error,
        )
        .await?;

    let response = if json_format {
        serde_json::json!({
            "program_set_authority": {
                "status": "success",
                "seed": seed,
                "meta_account": meta_account_pubkey.to_string(),
                "program_account": program_account_pubkey.to_string(),
                "authority_candidate": authority_candidate
            }
        })
    } else {
        output::print_success("Authority candidate set successfully");
        return Ok(());
    };

    if json_format {
        output::print_output(response, true);
    }

    Ok(())
}

/// Claim authority for a managed program
async fn claim_authority_program(
    config: &Config,
    manager_pubkey: Option<&str>,
    seed: &str,
    ephemeral: bool,
    fee_payer: Option<&str>,
    json_format: bool,
) -> Result<(), CliError> {
    use thru_base::txn_tools::MANAGER_INSTRUCTION_CLAIM_AUTHORITY;

    let manager_program_pubkey = if let Some(custom_manager) = manager_pubkey {
        Pubkey::new(custom_manager.to_string())
            .map_err(|e| CliError::Validation(format!("Invalid manager public key: {}", e)))?
    } else {
        config.get_manager_pubkey()?
    };

    // Derive meta and program account addresses from seed
    let (meta_account_pubkey, program_account_pubkey) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_program_pubkey, ephemeral)?;

    if !json_format {
        output::print_info("Claiming authority for managed program...");
        output::print_info(&format!("Seed: {}", seed));
        output::print_info(&format!("Meta account: {}", meta_account_pubkey));
        output::print_info(&format!("Program account: {}", program_account_pubkey));
        if let Some(name) = fee_payer {
            output::print_info(&format!("Fee payer override: {}", name));
        }
    }

    let mut config_with_manager = config.clone();
    config_with_manager.manager_program_public_key = manager_program_pubkey.to_string();
    let program_manager =
        ProgramManager::new_with_fee_payer(&config_with_manager, fee_payer).await?;

    let nonce = program_manager.get_current_nonce().await?;
    let start_slot = program_manager.get_current_slot().await?;

    let mut transaction = TransactionBuilder::build_manager_simple(
        program_manager.fee_payer_keypair.public_key,
        manager_program_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        meta_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        program_account_pubkey
            .to_bytes()
            .map_err(|e| CliError::Crypto(e.to_string()))?,
        MANAGER_INSTRUCTION_CLAIM_AUTHORITY,
        0,
        nonce,
        start_slot,
    )
    .map_err(|e| CliError::ProgramUpload(e.to_string()))?;

    transaction
        .sign(&program_manager.fee_payer_keypair.private_key)
        .map_err(|e| CliError::Crypto(e.to_string()))?;

    program_manager
        .submit_and_verify_transaction(
            &transaction,
            json_format,
            ProgramManager::decode_manager_error,
        )
        .await?;

    let response = if json_format {
        let mut resp = serde_json::json!({
            "program_claim_authority": {
                "status": "success",
                "seed": seed,
                "meta_account": meta_account_pubkey.to_string(),
                "program_account": program_account_pubkey.to_string()
            }
        });
        if let Some(name) = fee_payer {
            if let Some(obj) = resp
                .as_object_mut()
                .and_then(|map| map.get_mut("program_claim_authority"))
                .and_then(|v| v.as_object_mut())
            {
                obj.insert(
                    "fee_payer".to_string(),
                    serde_json::Value::String(name.to_string()),
                );
            }
        }
        resp
    } else {
        output::print_success("Authority claimed successfully");
        return Ok(());
    };

    if json_format {
        output::print_output(response, true);
    }

    Ok(())
}

/// program derived address
fn derive_program_address(
    program_id: &str,
    seed: &str,
    ephemeral: bool,
    json_format: bool,
) -> Result<(), CliError> {
    let seed_bytes = if let Ok(hex_bytes) = hex::decode(seed) {
        if hex_bytes.len() != 32 {
            return Err(CliError::Validation(format!(
                "Hex seed must be exactly 32 bytes, got {}",
                hex_bytes.len()
            )));
        }
        hex_bytes
    } else {
        let mut utf8_bytes = seed.as_bytes().to_vec();
        if utf8_bytes.len() > 32 {
            return Err(CliError::Validation(format!(
                "UTF-8 seed too long: {} bytes, maximum 32",
                utf8_bytes.len()
            )));
        }
        utf8_bytes.resize(32, 0);
        utf8_bytes
    };

    // validate key
    let bytes = crate::utils::validate_address_or_hex(program_id)?;
    let program_pubkey = Pubkey::from_bytes(&bytes);

    let seed_array: [u8; 32] = seed_bytes
        .try_into()
        .map_err(|_| CliError::Validation("Seed must be exactly 32 bytes".to_string()))?;

    let derived_pubkey =
        thru_base::crypto_utils::derive_program_address(&seed_array, &program_pubkey, ephemeral)
            .map_err(|e| CliError::Validation(format!("Address derivation failed: {}", e)))?;

    if json_format {
        let response = serde_json::json!({
            "derive_address": {
                "program_id": program_id,
                "seed": seed,
                "ephemeral": ephemeral,
                "derived_address": derived_pubkey.to_string()
            }
        });
        output::print_output(response, true);
    } else {
        println!("Program ID: {}", program_id);
        println!("Seed: {}", seed);
        println!("Ephemeral: {}", ephemeral);
        println!("Derived Address: {}", derived_pubkey.to_string());
    }

    Ok(())
}

/// Convert a UTF-8 seed string into zero-padded 32-byte hex
fn seed_to_hex(seed: &str, json_format: bool) -> Result<(), CliError> {
    let seed_bytes = seed.as_bytes();
    if seed_bytes.len() > 32 {
        return Err(CliError::Validation(format!(
            "UTF-8 seed too long: {} bytes, maximum 32",
            seed_bytes.len()
        )));
    }

    let mut padded = [0u8; 32];
    padded[..seed_bytes.len()].copy_from_slice(seed_bytes);
    let padded_hex = hex::encode(padded);

    if json_format {
        let response = serde_json::json!({
            "seed_to_hex": {
                "seed": seed,
                "padded_hex": padded_hex
            }
        });
        output::print_output(response, true);
    } else {
        println!("Seed: {}", seed);
        println!("Padded Hex: {}", padded_hex);
    }

    Ok(())
}

/// Derive managed program account address from a seed
fn derive_program_account(
    config: &Config,
    manager: Option<&str>,
    seed: &str,
    ephemeral: bool,
    json_format: bool,
) -> Result<(), CliError> {
    let manager_pubkey = if let Some(manager_str) = manager {
        let bytes = crate::utils::validate_address_or_hex(manager_str)?;
        Pubkey::from_bytes(&bytes)
    } else {
        config.get_manager_pubkey()?
    };

    let (_meta_account, program_account) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_pubkey, ephemeral)?;

    if json_format {
        let response = serde_json::json!({
            "derive_program_account": {
                "manager_program": manager_pubkey.to_string(),
                "seed": seed,
                "ephemeral": ephemeral,
                "program_account": program_account.to_string()
            }
        });
        output::print_output(response, true);
    } else {
        println!("Manager Program: {}", manager_pubkey.to_string());
        println!("Seed: {}", seed);
        println!("Ephemeral: {}", ephemeral);
        println!("Program Account: {}", program_account.to_string());
    }

    Ok(())
}

/// Derive both meta and program account addresses from a seed
fn derive_manager_accounts(
    config: &Config,
    manager: Option<&str>,
    seed: &str,
    ephemeral: bool,
    json_format: bool,
) -> Result<(), CliError> {
    /* Get manager program pubkey */
    let manager_pubkey = if let Some(manager_str) = manager {
        let bytes = crate::utils::validate_address_or_hex(manager_str)?;
        Pubkey::from_bytes(&bytes)
    } else {
        config.get_manager_pubkey()?
    };

    /* Get uploader program pubkey */
    let uploader_pubkey = config.get_uploader_pubkey()?;

    /* Derive manager accounts */
    let (meta_account, program_account) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_pubkey, ephemeral)?;

    /* Derive uploader accounts (used during program create) */
    let (temp_seed, temp_seed_hashed) = seed_with_suffix(seed, "temporary");
    let (uploader_meta_account, uploader_buffer_account) =
        crypto::derive_uploader_accounts_from_seed(&temp_seed, &uploader_pubkey)?;

    if json_format {
        let response = serde_json::json!({
            "derive_manager_accounts": {
                "manager_program": manager_pubkey.to_string(),
                "uploader_program": uploader_pubkey.to_string(),
                "seed": seed,
                "ephemeral": ephemeral,
                "meta_account": meta_account.to_string(),
                "program_account": program_account.to_string(),
                "uploader": {
                    "temp_seed": temp_seed,
                    "temp_seed_hashed": temp_seed_hashed,
                    "meta_account": uploader_meta_account.to_string(),
                    "buffer_account": uploader_buffer_account.to_string()
                }
            }
        });
        output::print_output(response, true);
    } else {
        println!("Manager Program: {}", manager_pubkey.to_string());
        println!("Seed: {}", seed);
        println!("Ephemeral: {}", ephemeral);
        println!();
        println!("Program Accounts:");
        println!("  Meta Account: {}", meta_account.to_string());
        println!("  Program Account: {}", program_account.to_string());
        println!();
        println!("Uploader Accounts (temporary, used during create):");
        println!("  Temp Seed: {}{}", temp_seed, if temp_seed_hashed { " (hashed)" } else { "" });
        println!("  Meta Account: {}", uploader_meta_account.to_string());
        println!("  Buffer Account: {}", uploader_buffer_account.to_string());
    }

    Ok(())
}

/// Account status information
#[derive(Debug)]
struct AccountStatus {
    exists: bool,
    is_program: bool,
    data_size: u64,
    owner: Option<String>,
}

/// Get status of program and related accounts
async fn get_program_status(
    config: &Config,
    manager: Option<&str>,
    seed: &str,
    ephemeral: bool,
    json_format: bool,
) -> Result<(), CliError> {
    /* Get manager program pubkey */
    let manager_pubkey = if let Some(manager_str) = manager {
        let bytes = crate::utils::validate_address_or_hex(manager_str)?;
        Pubkey::from_bytes(&bytes)
    } else {
        config.get_manager_pubkey()?
    };

    /* Get uploader program pubkey */
    let uploader_pubkey = config.get_uploader_pubkey()?;

    /* Derive manager accounts */
    let (meta_account, program_account) =
        crypto::derive_manager_accounts_from_seed(seed, &manager_pubkey, ephemeral)?;

    /* Derive uploader accounts (used during program create) */
    let (temp_seed, _temp_seed_hashed) = seed_with_suffix(seed, "temporary");
    let (uploader_meta_account, uploader_buffer_account) =
        crypto::derive_uploader_accounts_from_seed(&temp_seed, &uploader_pubkey)?;

    /* Create RPC client */
    let rpc_url = config.get_grpc_url()?;
    if !json_format {
        println!("RPC endpoint: {}", rpc_url);
    }
    let client = RpcClient::builder()
        .http_endpoint(rpc_url.clone())
        .timeout(Duration::from_secs(config.timeout_seconds))
        .auth_token(config.auth_token.clone())
        .build()?;

    /* Verify connectivity with a simple call first */
    if let Err(e) = client.get_block_height().await {
        let msg = format!("Failed to connect to RPC endpoint {}: {}", rpc_url, e);
        if json_format {
            let response = serde_json::json!({
                "error": {
                    "type": "connection_failed",
                    "message": msg,
                    "endpoint": rpc_url.to_string()
                }
            });
            output::print_output(response, true);
            return Err(CliError::Reported);
        } else {
            output::print_error(&msg);
            return Err(CliError::Reported);
        }
    }

    /* Query all accounts in parallel */
    let (meta_info, program_info, uploader_meta_info, uploader_buffer_info) = tokio::join!(
        client.get_account_info(&meta_account, None, Some(VersionContext::Current)),
        client.get_account_info(&program_account, None, Some(VersionContext::Current)),
        client.get_account_info(&uploader_meta_account, None, Some(VersionContext::Current)),
        client.get_account_info(&uploader_buffer_account, None, Some(VersionContext::Current)),
    );

    /* Convert to status */
    let meta_status = account_to_status(meta_info);
    let program_status = account_to_status(program_info);
    let uploader_meta_status = account_to_status(uploader_meta_info);
    let uploader_buffer_status = account_to_status(uploader_buffer_info);

    /* Detect corrupted accounts (exist but have 0 bytes) */
    let program_meta_corrupted = meta_status.exists && meta_status.data_size == 0;
    let program_account_corrupted = program_status.exists && program_status.data_size == 0;
    let uploader_meta_corrupted = uploader_meta_status.exists && uploader_meta_status.data_size == 0;
    let uploader_buffer_corrupted = uploader_buffer_status.exists && uploader_buffer_status.data_size == 0;
    let any_corrupted = program_meta_corrupted || program_account_corrupted || uploader_meta_corrupted || uploader_buffer_corrupted;

    let program_deployed = meta_status.exists && program_status.exists && program_status.is_program && program_status.data_size > 0;

    if json_format {
        let status = if program_deployed {
            "deployed"
        } else if any_corrupted {
            "corrupted"
        } else if !meta_status.exists && !program_status.exists {
            "not_deployed"
        } else {
            "invalid"
        };

        let response = serde_json::json!({
            "program_status": {
                "seed": seed,
                "ephemeral": ephemeral,
                "manager_program": manager_pubkey.to_string(),
                "uploader_program": uploader_pubkey.to_string(),
                "summary": {
                    "status": status,
                    "program_deployed": program_deployed,
                    "corrupted_accounts": {
                        "any": any_corrupted,
                        "program_meta": program_meta_corrupted,
                        "program_account": program_account_corrupted,
                        "uploader_meta": uploader_meta_corrupted,
                        "uploader_buffer": uploader_buffer_corrupted,
                    }
                },
                "program": {
                    "meta_account": {
                        "address": meta_account.to_string(),
                        "exists": meta_status.exists,
                        "is_program": meta_status.is_program,
                        "data_size": meta_status.data_size,
                        "owner": meta_status.owner,
                    },
                    "program_account": {
                        "address": program_account.to_string(),
                        "exists": program_status.exists,
                        "is_program": program_status.is_program,
                        "data_size": program_status.data_size,
                        "owner": program_status.owner,
                    }
                },
                "uploader": {
                    "temp_seed": temp_seed,
                    "meta_account": {
                        "address": uploader_meta_account.to_string(),
                        "exists": uploader_meta_status.exists,
                        "is_program": uploader_meta_status.is_program,
                        "data_size": uploader_meta_status.data_size,
                        "owner": uploader_meta_status.owner,
                    },
                    "buffer_account": {
                        "address": uploader_buffer_account.to_string(),
                        "exists": uploader_buffer_status.exists,
                        "is_program": uploader_buffer_status.is_program,
                        "data_size": uploader_buffer_status.data_size,
                        "owner": uploader_buffer_status.owner,
                    }
                }
            }
        });
        output::print_output(response, true);
    } else {
        println!("Program Status for seed: {}", seed);
        println!("Ephemeral: {}", ephemeral);
        println!();

        println!("Program Accounts:");
        print_account_status("  Meta Account", &meta_account.to_string(), &meta_status);
        print_account_status("  Program Account", &program_account.to_string(), &program_status);
        println!();

        println!("Uploader Accounts (temp_seed: {}):", temp_seed);
        print_account_status("  Meta Account", &uploader_meta_account.to_string(), &uploader_meta_status);
        print_account_status("  Buffer Account", &uploader_buffer_account.to_string(), &uploader_buffer_status);
        println!();

        let upload_in_progress = uploader_meta_status.exists || uploader_buffer_status.exists;

        println!("Summary:");
        if program_deployed {
            println!("  Program is DEPLOYED ({} bytes)", program_status.data_size);
        } else if any_corrupted {
            println!("  CORRUPTED STATE DETECTED - accounts exist but have no data:");
            if program_meta_corrupted {
                println!("    - Program meta account (0 bytes)");
            }
            if program_account_corrupted {
                println!("    - Program account (0 bytes)");
            }
            if uploader_meta_corrupted {
                println!("    - Uploader meta account (0 bytes)");
            }
            if uploader_buffer_corrupted {
                println!("    - Uploader buffer account (0 bytes)");
            }
            println!();
            println!("  To fix, delete all corrupted accounts:");
            if uploader_meta_corrupted || uploader_buffer_corrupted {
                println!("    thru uploader cleanup {}", temp_seed);
            }
            if program_meta_corrupted || program_account_corrupted {
                println!("    thru program destroy {} --ephemeral", seed);
            }
        } else if meta_status.exists && !program_status.exists {
            println!("  Program meta exists but program account missing (INVALID STATE)");
        } else if !meta_status.exists && !program_status.exists {
            println!("  Program is NOT DEPLOYED");
        }

        if upload_in_progress && !any_corrupted {
            println!("  Upload buffer exists (cleanup may be needed: thru uploader cleanup {})", temp_seed);
        }
    }

    Ok(())
}

fn account_to_status(result: Result<Option<thru_client::Account>, thru_client::ClientError>) -> AccountStatus {
    match result {
        Ok(Some(account)) => AccountStatus {
            exists: true,
            is_program: account.program,
            data_size: account.data_size,
            owner: Some(account.owner.to_string()),
        },
        Ok(None) => AccountStatus {
            exists: false,
            is_program: false,
            data_size: 0,
            owner: None,
        },
        Err(_) => AccountStatus {
            exists: false,
            is_program: false,
            data_size: 0,
            owner: None,
        },
    }
}

fn print_account_status(label: &str, address: &str, status: &AccountStatus) {
    if status.exists {
        let program_flag = if status.is_program { " [PROGRAM]" } else { "" };
        println!("{}: {}", label, address);
        println!("    Status: EXISTS{}, {} bytes", program_flag, status.data_size);
        if let Some(owner) = &status.owner {
            println!("    Owner: {}", owner);
        }
    } else {
        println!("{}: {}", label, address);
        println!("    Status: NOT FOUND");
    }
}