sdkt-cli 2.5.0

Command Line Interface (CLI) application combining core Soroban DevKit components.
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
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
use clap::{Args, CommandFactory, Parser, Subcommand};
use clap_complete::Shell;
use sdkt_core::fee::{FeeConfig, FeeEstimator, LedgerFeeSample, NetworkKind};
use sdkt_core::fetch::DependencyFetcher;
use sdkt_core::{DevKitConfig, NetworkConfig, OutputFormat};
use sdkt_rpc::inspect::StorageSummary;
use sdkt_rpc::wasm::get_wasm_bytecode;
use sdkt_rpc::{
    estimate_dynamic_fee, get_contract_events, get_ttl_info, get_wasm_metadata, inspect_account,
    inspect_contract, inspect_transaction, simulate_transaction, SorobanRpcClient, StorageKeyInfo,
    TtlInfoSummary,
};
use sdkt_storage::WasmCache;
use sdkt_storage::{NetworkProfile, NetworkStore, StorageAnalyzer};
use sdkt_wasm::spec::parse_contract_spec;
use sdkt_xdr::abi_decode::decode_event_topics;
use sdkt_xdr::decode;
use sdkt_xdr::{
    build_invoke_transaction, sign_transaction, Ed25519Signer, InvokeTransactionParams, Network,
    SigningError, SigningOptions,
};
use std::fs;
use std::io::{self, Write};
use std::path::Path;
use std::process;

/// Version string used by `sdkt --version` / `sdkt --long-version` (M39).
///
/// Default (`provenance` feature off): returns just the semantic version, so
/// the build stays reproducible and identical to pre-M39 releases.
///
/// When compiled with `--features provenance`, appends an optional
/// `commit@date` provenance suffix supplied at build time via the
/// `SDKT_GIT_COMMIT` / `SDKT_BUILD_DATE` environment variables. If those are
/// absent the provenance line is simply omitted — there is never any implicit
/// `git` invocation that would make the binary non-reproducible.
///
/// Returns `&'static str` because clap's `long_version` requires a static
/// string; the provenance branch leases a boxed string (one-time, at command
/// construction) which is intentional and harmless for a CLI binary.
fn sdkt_version_string() -> &'static str {
    let base = env!("CARGO_PKG_VERSION");
    #[cfg(feature = "provenance")]
    {
        let commit = option_env!("SDKT_GIT_COMMIT");
        let date = option_env!("SDKT_BUILD_DATE");
        match (commit, date) {
            (Some(c), Some(d)) => {
                Box::leak(format!("{} (commit {} built {})", base, c, d).into_boxed_str())
            }
            (Some(c), None) => Box::leak(format!("{} (commit {})", base, c).into_boxed_str()),
            (None, Some(d)) => Box::leak(format!("{} (built {})", base, d).into_boxed_str()),
            (None, None) => base,
        }
    }
    #[cfg(not(feature = "provenance"))]
    {
        base
    }
}

/// Reusable network-resolution flags shared by every command that talks to a
/// Soroban/Stellar RPC endpoint.
///
/// Flattened into those commands via `#[command(flatten)]` so the resolution
/// semantics stay identical everywhere (no copy/paste).
#[derive(Args, Clone, Debug, Default)]
struct NetworkArgs {
    /// Use a saved network profile (see `sdkt network add`) for the RPC URL and
    /// network passphrase. Overrides .sdkt.toml defaults.
    #[arg(long, value_name = "NAME")]
    network_profile: Option<String>,
    /// Explicit RPC endpoint URL. Overrides any profile and .sdkt.toml value.
    #[arg(long, value_name = "URL")]
    rpc_url: Option<String>,
    /// Explicit network passphrase. Overrides any profile and .sdkt.toml value.
    #[arg(long, value_name = "PASSPHRASE")]
    network_passphrase: Option<String>,
}
/// Apply resolution precedence onto a base [`NetworkConfig`].
///
/// Pure function (no I/O, no network) — this is the single source of truth for
/// M29 precedence and is unit-tested directly.
///
/// Priority (highest wins):
/// 1. explicit `rpc_url` / `network_passphrase`,
/// 2. a resolved `profile` (loaded from `--network-profile`),
/// 3. the `base` config (`.sdkt.toml`, then `NetworkConfig::default()`).
fn apply_profile_overrides(
    base: NetworkConfig,
    profile: Option<NetworkProfile>,
    rpc_url: Option<String>,
    network_passphrase: Option<String>,
) -> NetworkConfig {
    let mut cfg = base;

    if let Some(p) = profile {
        cfg.rpc_url = p.rpc_url;
        cfg.passphrase = p.network_passphrase;
    }

    if let Some(url) = rpc_url {
        cfg.rpc_url = url;
    }
    if let Some(p) = network_passphrase {
        cfg.passphrase = p;
    }

    cfg
}

/// Resolve the effective [`NetworkConfig`] from explicit CLI overrides, an
/// optional named profile, and built-in defaults.
///
/// Resolution priority (highest wins):
/// 1. explicit `--rpc-url` / `--network-passphrase` CLI flags,
/// 2. `--network-profile <NAME>` (loaded from `sdkt_storage::NetworkStore`),
/// 3. built-in defaults: `.sdkt.toml` `[network]`, then `NetworkConfig::default()`.
///
/// Explicit flags always override values loaded from a profile, and a profile
/// always overrides the built-in defaults.
fn resolve_network_config(
    rpc_url: Option<String>,
    network_passphrase: Option<String>,
    network_profile: Option<String>,
) -> Result<NetworkConfig, String> {
    let base = DevKitConfig::from_file(".sdkt.toml")
        .ok()
        .map(|c| c.network)
        .unwrap_or_default();

    let profile = if let Some(name) = network_profile {
        let store = NetworkStore::new().map_err(|e| format!("cannot open network store: {}", e))?;
        let profile = store
            .get(&name)
            .map_err(|e| format!("network profile '{}' not found: {}", name, e))?;
        Some(profile)
    } else {
        None
    };

    Ok(apply_profile_overrides(
        base,
        profile,
        rpc_url,
        network_passphrase,
    ))
}

/// Build a [`SorobanRpcClient`] from the resolved network configuration,
/// exiting with a clear error message if resolution fails.
fn resolve_rpc_client(
    rpc_url: Option<String>,
    network_passphrase: Option<String>,
    network_profile: Option<String>,
) -> SorobanRpcClient {
    match resolve_network_config(rpc_url, network_passphrase, network_profile) {
        Ok(cfg) => SorobanRpcClient::from_config(&cfg),
        Err(e) => {
            eprintln!("Error: {}", e);
            process::exit(1);
        }
    }
}

/// Whether the operator explicitly named the target network (via `--rpc-url`,
/// `--network-passphrase`, or `--network-profile`). When this is `false` the
/// resolved [`NetworkConfig`] came entirely from built-in defaults (testnet),
/// and mutating operations must therefore refuse mainnet.
fn network_is_explicit(
    rpc_url: &Option<String>,
    network_passphrase: &Option<String>,
    network_profile: &Option<String>,
) -> bool {
    rpc_url.is_some() || network_passphrase.is_some() || network_profile.is_some()
}

/// Build a [`SorobanRpcClient`] for a *mutating* (state-changing) RPC operation.
///
/// This reuses the existing M29 resolution path and then applies the conservative
/// mainnet-safety guard from `sdkt_core::guard_mutating_network`. A mutating
/// command is only allowed to touch mainnet when the operator has explicitly
/// selected the network; an implicit testnet default combined with a mainnet
/// endpoint/passphrase is rejected before any request leaves the process.
///
/// Resolution or guard failures print a clear message and exit non-zero.
fn resolve_rpc_client_mutating(
    rpc_url: Option<String>,
    network_passphrase: Option<String>,
    network_profile: Option<String>,
) -> SorobanRpcClient {
    let explicit = network_is_explicit(&rpc_url, &network_passphrase, &network_profile);
    let cfg = match resolve_network_config(
        rpc_url.clone(),
        network_passphrase.clone(),
        network_profile.clone(),
    ) {
        Ok(cfg) => cfg,
        Err(e) => {
            eprintln!("Error: {}", e);
            process::exit(1);
        }
    };
    if let Err(e) = sdkt_core::guard_mutating_network(&cfg, explicit) {
        eprintln!("Error: {}", e);
        process::exit(1);
    }
    SorobanRpcClient::from_config(&cfg)
}

/// Adapter that makes a closed consumer (EPIPE / `BrokenPipe`) look like a
/// successful write.
///
/// `clap_complete::generate` writes the script to the provided `Write` and
/// (in this version) unwraps write errors internally. When the consumer closes
/// the pipe early — e.g. `sdkt completions bash | head` — the underlying write
/// fails with `BrokenPipe`, which would otherwise panic. By mapping that one
/// error to `Ok`, downstream writers never see it and `sdkt` exits cleanly.
/// Every other I/O error is passed through unchanged, preserving the existing
/// failure behavior for real write problems.
struct BrokenPipeOk<W: Write>(W);

impl<W: Write> Write for BrokenPipeOk<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self.0.write(buf) {
            Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(buf.len()),
            other => other,
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self.0.flush() {
            Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(()),
            other => other,
        }
    }
}

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

    fn base_testnet() -> NetworkConfig {
        NetworkConfig {
            rpc_url: "https://soroban-testnet.stellar.org".to_string(),
            passphrase: "Test SDF Network ; September 2015".to_string(),
            timeout_secs: Some(15),
            pool_max_idle_per_host: Some(100),
        }
    }

    fn profile(name: &str, url: &str, pass: &str) -> NetworkProfile {
        NetworkProfile::new(name, url, pass)
    }

    #[test]
    fn built_in_default_when_nothing_set() {
        let cfg = apply_profile_overrides(base_testnet(), None, None, None);
        assert_eq!(cfg.rpc_url, "https://soroban-testnet.stellar.org");
        assert_eq!(cfg.passphrase, "Test SDF Network ; September 2015");
    }

    #[test]
    fn profile_overrides_built_in_default() {
        let p = profile("local", "http://127.0.0.1:8000", "Standalone");
        let cfg = apply_profile_overrides(base_testnet(), Some(p), None, None);
        assert_eq!(cfg.rpc_url, "http://127.0.0.1:8000");
        assert_eq!(cfg.passphrase, "Standalone");
    }

    #[test]
    fn rpc_url_flag_overrides_profile() {
        let p = profile("local", "http://127.0.0.1:8000", "Standalone");
        let cfg = apply_profile_overrides(
            base_testnet(),
            Some(p),
            Some("http://override.example".to_string()),
            None,
        );
        assert_eq!(cfg.rpc_url, "http://override.example");
        // passphrase comes from the profile when no passphrase flag is given
        assert_eq!(cfg.passphrase, "Standalone");
    }

    #[test]
    fn passphrase_flag_overrides_profile() {
        let p = profile("local", "http://127.0.0.1:8000", "Standalone");
        let cfg = apply_profile_overrides(
            base_testnet(),
            Some(p),
            None,
            Some("Override Passphrase".to_string()),
        );
        assert_eq!(cfg.rpc_url, "http://127.0.0.1:8000");
        assert_eq!(cfg.passphrase, "Override Passphrase");
    }

    #[test]
    fn explicit_flags_win_over_profile_both() {
        let p = profile("local", "http://127.0.0.1:8000", "Standalone");
        let cfg = apply_profile_overrides(
            base_testnet(),
            Some(p),
            Some("http://rpc.example".to_string()),
            Some("RPC Passphrase".to_string()),
        );
        assert_eq!(cfg.rpc_url, "http://rpc.example");
        assert_eq!(cfg.passphrase, "RPC Passphrase");
    }

    #[test]
    fn rpc_url_flag_without_profile_overrides_built_in() {
        let cfg = apply_profile_overrides(
            base_testnet(),
            None,
            Some("http://flag.example".to_string()),
            None,
        );
        assert_eq!(cfg.rpc_url, "http://flag.example");
        assert_eq!(cfg.passphrase, "Test SDF Network ; September 2015");
    }
}

/// Soroban DevKit — unified toolkit for Stellar/Soroban development.
#[derive(Parser)]
#[command(name = "sdkt")]
#[command(about = "Soroban DevKit — unified toolkit for Stellar/Soroban development")]
#[command(version = env!("CARGO_PKG_VERSION"))]
#[command(long_version = sdkt_version_string())]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Decode base64-encoded XDR to JSON
    Decode {
        /// Base64 XDR string to decode. Optional when --file is provided.
        #[arg(value_name = "XDR")]
        payload: Option<String>,
        #[arg(short, long, value_name = "TYPE")]
        r#type: Option<String>,
        #[arg(short, long, value_name = "FORMAT", default_value = "pretty")]
        format: String,
        /// Read the XDR payload from a file instead of the positional argument.
        #[arg(short = 'i', long, value_name = "FILE")]
        file: Option<String>,
    },
    /// Inspect storage TTL for a contract
    Storage {
        #[command(subcommand)]
        action: StorageAction,
        /// Path to contract WASM for ABI-aware storage decoding
        #[arg(long, value_name = "WASM", global = true)]
        abi: Option<String>,
        /// Use the ABI of a deployed contract (fetched on-chain via M41 path) for
        /// storage decoding. Mutually exclusive with `--abi`.
        #[arg(long, value_name = "CONTRACT_ID", global = true)]
        abi_contract: Option<String>,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Inspect a contract's ABI and storage
    Inspect {
        contract_id: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Path to contract WASM for ABI-aware storage inspection
        #[arg(long, value_name = "WASM")]
        abi: Option<String>,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Verify a deployed contract matches a local WASM binary (M22)
    Verify {
        /// Stellar contract ID (C...)
        #[arg(short, long, value_name = "CONTRACT_ID")]
        contract: String,
        /// Path to a local WASM file to compare against the on-chain code
        #[arg(long, value_name = "WASM")]
        wasm: Option<String>,
        /// Network to fetch the on-chain contract from
        #[arg(short, long, default_value = "testnet")]
        network: String,
        /// Output format
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Emit an upgrade-safety verdict comparing the live deployed contract
        /// (fetched on-chain) against the local `--wasm` candidate. Requires `--wasm`.
        #[arg(long, default_value_t = false)]
        upgrade_safety: bool,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Unified read-only contract posture report (M23)
    Health {
        /// Stellar contract ID (C...)
        #[arg(short, long, value_name = "CONTRACT_ID")]
        contract: String,
        /// Optional local WASM to verify against the on-chain hash
        #[arg(long, value_name = "WASM")]
        wasm: Option<String>,
        /// Network label for the report
        #[arg(short, long, default_value = "testnet")]
        network: String,
        /// Output format
        #[arg(short, long, default_value = "pretty")]
        format: String,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Inspect a Soroban transaction
    Tx {
        #[command(subcommand)]
        action: TxAction,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Event explorer
    Events {
        contract_id: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Path to contract WASM for ABI-aware decoding
        #[arg(long, value_name = "WASM")]
        abi: Option<String>,
        /// Use the ABI of a deployed contract (fetched on-chain via M41 path) for
        /// decoding. Mutually exclusive with `--abi`.
        #[arg(long, value_name = "CONTRACT_ID")]
        abi_contract: Option<String>,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Inspect an account's balances and signers
    Account {
        address: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Estimate transaction fee from recent ledger base fees
    Fee {
        #[command(subcommand)]
        action: FeeAction,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Manage WASM metadata and caching
    Wasm {
        #[command(subcommand)]
        action: WasmAction,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Offline diff of two contract WASM files (ABI/function/event/type changes)
    Diff {
        /// Path to the OLD (baseline) WASM file
        #[arg(long, value_name = "WASM")]
        old_wasm: String,
        /// Path to the NEW (candidate) WASM file
        #[arg(long, value_name = "WASM")]
        new_wasm: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Emit an upgrade-safety verdict (breaking vs non-breaking changes)
        #[arg(long, default_value_t = false)]
        upgrade_safety: bool,
    },
    /// Static security analysis of a Soroban contract source file (Gap C)
    Audit {
        /// Path to the Rust source file (.rs) to analyze
        path: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Disable a rule by id (repeatable), e.g. --disable MOVE-001
        #[arg(long, value_name = "RULE_ID", action = clap::ArgAction::Append)]
        disable: Vec<String>,
        /// Path to an external rule crate or local rule source directory to load.
        /// Repeatable. (Phase A: the rule must be compiled into the binary; this
        /// flag validates the path and runs the registered rules.)
        #[arg(long, value_name = "PATH", action = clap::ArgAction::Append)]
        rules: Vec<String>,
    },
    /// Manage Soroban identities (keys)
    Identity {
        #[command(subcommand)]
        action: IdentityAction,
    },
    /// Manage named network profiles (RPC endpoint + passphrase)
    Network {
        #[command(subcommand)]
        action: NetworkAction,
    },
    /// Initialize a new Soroban contract project
    Init {
        /// Project name (directory)
        name: String,
        /// Generate only essential files
        #[arg(long, default_value_t = false)]
        minimal: bool,
        /// Overwrite existing directory
        #[arg(long, default_value_t = false)]
        force: bool,
        /// Output format (pretty or json)
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Deploy a contract (Upload WASM + Instantiate)
    Deploy {
        #[arg(short, long)]
        wasm: String,
        #[arg(short, long)]
        salt: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Abort deployment if the upgrade is not backwards-compatible.
        /// Requires --old-wasm (the currently deployed WASM) to be supplied.
        #[arg(long, default_value_t = false)]
        deny_breaking: bool,
        /// Path to the currently deployed (baseline) WASM, used with --deny-breaking.
        #[arg(long, value_name = "WASM")]
        old_wasm: Option<String>,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Compile Rust contracts into WASM artifacts
    Build,
    /// Generate or inspect the project lock file (`sdkt.lock`)
    Lock {
        #[command(subcommand)]
        action: LockCommand,
    },
    /// Validate and inspect local package manifests (M35.0)
    Package {
        #[command(subcommand)]
        action: PackageCommand,
    },
    /// Manage multi-contract projects
    Project {
        #[command(subcommand)]
        action: ProjectCommand,
        #[command(flatten)]
        net: NetworkArgs,
    },
    /// Manage local audit plugins (install/remove/list/show/update) — M40
    Plugin {
        #[command(subcommand)]
        action: PluginAction,
    },
    /// Generate shell completion scripts for your shell
    Completions {
        /// Shell to generate completions for (bash, zsh, fish, powershell, elvish)
        #[arg(value_enum)]
        shell: Shell,
    },
}

#[derive(Subcommand)]
enum IdentityAction {
    Generate { name: String },
    Import { name: String, secret: String },
    List,
    Show { name: String },
    Delete { name: String },
    Default { name: String },
}

#[derive(Subcommand)]
enum PluginAction {
    /// List installed plugins
    List,
    /// Show metadata for an installed plugin
    Show { id: String },
    /// Install a plugin from a local artifact + sibling plugin.toml
    Install {
        /// Path to the local plugin artifact (.so/.dylib/.dll/.wasm)
        source: String,
        /// Override the plugin id from metadata (rarely needed)
        #[arg(long)]
        id: Option<String>,
        /// Overwrite an existing install of the same id
        #[arg(long)]
        force: bool,
    },
    /// Remove an installed plugin by id (idempotent)
    Remove { id: String },
    /// Update an installed plugin from a new local artifact (local-only)
    Update {
        id: String,
        /// Path to the new local plugin artifact
        source: String,
    },
}

#[derive(Subcommand)]
enum NetworkAction {
    /// Add or update a named network profile
    Add {
        /// Profile name (referenced by other commands)
        name: String,
        /// RPC endpoint URL (e.g. https://soroban-testnet.stellar.org)
        #[arg(short, long, value_name = "URL")]
        rpc_url: String,
        /// Network passphrase (e.g. "Test SDF Network ; September 2015")
        #[arg(short, long, value_name = "PASSPHRASE")]
        passphrase: String,
        /// Optional friendbot URL for test networks
        #[arg(long, value_name = "URL")]
        friendbot: Option<String>,
        /// Optional human-readable description
        #[arg(short, long)]
        description: Option<String>,
        /// Output format (pretty or json)
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// List all saved network profiles
    List {
        /// Output format (pretty or json)
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Show a single network profile by name
    Show {
        /// Profile name
        name: String,
        /// Output format (pretty or json)
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Remove a network profile by name
    Remove {
        /// Profile name
        name: String,
        /// Output format (pretty or json)
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
}

#[derive(Subcommand)]
enum WasmAction {
    /// Inspect a local WASM contract file offline
    Inspect {
        /// Path to the WASM file to inspect
        file: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Inspect WASM metadata for a deployed contract
    Metadata {
        #[arg(short, long)]
        contract: String,
        #[arg(short, long, default_value = "testnet")]
        network: String,
        /// Force bypass the cache and fetch fresh from RPC
        #[arg(long, default_value_t = false)]
        refresh: bool,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Manage the local WASM cache
    Cache {
        #[command(subcommand)]
        action: CacheAction,
    },
}

#[derive(Subcommand)]
enum CacheAction {
    /// Show stats about the cache (size, item count)
    Info {
        #[arg(short, long, default_value = "testnet")]
        network: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Remove a specific hash from the cache
    Remove {
        hash: String,
        #[arg(short, long, default_value = "testnet")]
        network: String,
    },
    /// Clear all items in the cache for the network
    Clear {
        #[arg(short, long, default_value = "testnet")]
        network: String,
    },
}

#[derive(Subcommand)]
enum FeeAction {
    Estimate {
        /// Network: testnet, mainnet, standalone
        #[arg(short, long, default_value = "testnet")]
        network: String,
        /// Comma-separated recent base fees in stroops (e.g. "100,120,110"). Optional if --rpc is used.
        #[arg(short, long, value_name = "FEES")]
        base_fees: Option<String>,
        /// Fetch fee statistics directly from Soroban RPC instead of manual base fees
        #[arg(long, default_value_t = false)]
        rpc: bool,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
}

#[derive(Subcommand)]
enum TxAction {
    Inspect {
        hash: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Validate a transaction envelope offline (pre-flight checks)
    Validate {
        /// Base64 XDR transaction envelope or path to a file containing it
        #[arg(short, long)]
        envelope: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Simulate a transaction envelope without submitting it
    Simulate {
        /// Base64 XDR transaction envelope or path to a file containing it
        #[arg(short, long)]
        envelope: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Submit a transaction envelope to the network, optionally waiting
    Submit {
        /// Base64 XDR transaction envelope or path to a file containing it
        #[arg(short, long)]
        envelope: String,
        /// Wait and poll until the transaction settles
        #[arg(short, long)]
        wait: bool,
        /// Timeout in seconds while waiting
        #[arg(short = 't', long, default_value = "60")]
        timeout: u64,
        /// Polling interval in seconds while waiting
        #[arg(short, long, default_value = "2")]
        interval: u64,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Build a Soroban transaction envelope XDR
    Build {
        #[arg(long)]
        source: String,
        #[arg(long)]
        sequence: i64,
        #[arg(long, default_value = "100")]
        fee: u32,
        #[arg(long)]
        contract: String,
        #[arg(long)]
        function: String,
        /// Optional arguments: `type:value` (e.g. `u32:100`, `string:hello`,
        /// `bool:true`, `bytes:0a0b`). Base64-encoded ScVal strings are also
        /// accepted as-is (passthrough).
        #[arg(long)]
        arg: Vec<String>,
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Optional file path to write the output envelope XDR
        #[arg(short, long)]
        output: Option<String>,
    },
    /// Sign a transaction envelope using a local identity (M27 / PR2)
    Sign {
        /// Input: base64 XDR envelope, or a path to a file containing it
        #[arg(short, long, value_name = "INPUT")]
        input: String,
        /// Output file to write the signed base64 envelope. Prints to stdout if omitted.
        #[arg(short, long, value_name = "OUTPUT")]
        output: Option<String>,
        /// Identity name to sign with. Defaults to "default".
        #[arg(short = 'I', long, default_value = "default")]
        identity: String,
        /// Network: testnet | mainnet | futurenet | custom:<passphrase>
        #[arg(short, long, default_value = "testnet")]
        network: String,
        /// Output format
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
}

#[derive(Subcommand)]
enum ProjectCommand {
    /// Deploy all contracts defined in the workspace
    Deploy {
        /// Optional deployment salt base
        #[arg(short, long, default_value = "deploy")]
        salt: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
}

#[derive(Subcommand)]
enum LockCommand {
    /// Generate `sdkt.lock` from the current build artifacts (next to
    /// `.sdkt.toml`). Requires `sdkt build` to have run first.
    Generate {
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Verify the lock file against the current on-disk artifacts.
    /// Advisory: reports drift but never fails the build.
    Verify {
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Print the contents of `sdkt.lock` if present.
    Show {
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
}

#[derive(Subcommand)]
enum PackageCommand {
    /// Validate the local package manifest (metadata + dependency graph).
    /// Offline: never performs network or registry operations.
    Validate {
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    /// Fetch declared dependencies into the local cache.
    /// Git deps are cloned/checked out; local `path` deps are passed through.
    /// Never builds automatically. Use `--force` to update existing checkouts.
    Fetch {
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Re-fetch / update existing checkouts instead of reusing them.
        #[arg(long)]
        force: bool,
    },
    /// Synchronize dependencies with what is available upstream and refresh the
    /// lock. `rev` deps stay pinned; `tag`/`branch` deps update when the remote
    /// commit changed. Use `--check` to report only, `--dry-run` to preview
    /// changes without touching the cache or lock.
    Update {
        #[arg(short, long, default_value = "pretty")]
        format: String,
        /// Only report available updates; do not fetch or rewrite the lock.
        #[arg(long)]
        check: bool,
        /// Compute and preview changes; do not modify the cache or lock.
        #[arg(long)]
        dry_run: bool,
    },
    /// Bundle the resolved project into a portable offline artifact: the
    /// manifest, the lockfile, and the cached git dependency checkouts. The
    /// artifact can be unpacked on another machine and rebuilt without network.
    Pack {
        /// Output directory for the artifact (default: `./dist`).
        #[arg(short, long, default_value = "dist")]
        out: String,
        /// Artifact format: `tar.zst` (compressed tarball) or `dir` (directory tree).
        #[arg(long, default_value = "tar.zst")]
        format: String,
    },
    /// Validate publish readiness (read-only): manifest valid, lock consistent,
    /// all cached commits present, integrity hashes match. Default is
    /// `--dry-run`; nothing is published. `--broadcast` is opt-in and only acts
    /// when a registry source is configured (none in M38, so it stays offline).
    Publish {
        /// Perform a read-only readiness check (default: true). No publish.
        #[arg(long, default_value_t = true)]
        dry_run: bool,
        /// Actually publish. Opt-in only; requires a configured registry source.
        #[arg(long)]
        broadcast: bool,
    },
}

#[derive(Subcommand)]
enum StorageAction {
    Check {
        contract_id: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
    Estimate {
        wasm: String,
    },
    /// Analyze a contract's storage layout (Instance/Persistent/Temporary
    /// categorization, TTL summary, and per-entry detail).
    Analyze {
        contract_id: String,
        #[arg(short, long, default_value = "pretty")]
        format: String,
    },
}

/// M22 — Contract verification report.
///
/// Serializes directly to the JSON schema defined in M22_PLAN.md §10.
/// `local_wasm_hash` / `local_wasm_size_bytes` / `match` are `Option` so they
/// serialize as `null` when no local WASM is supplied (OnChainOnly mode).
#[derive(Debug, serde::Serialize)]
struct VerificationReport {
    contract_id: String,
    network: String,
    on_chain_wasm_hash: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    local_wasm_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    local_wasm_size_bytes: Option<usize>,
    #[serde(rename = "match", skip_serializing_if = "Option::is_none")]
    matches: Option<bool>,
    verification_status: String,
    explanation: String,
}

/// M23 — Contract health / posture report.
///
/// Aggregates the existing read-only surfaces (`inspect_contract` +
/// `StorageAnalyzer`) plus optional M22 verification into one report.
/// Serializes to the JSON schema in M23_PLAN.md §12.
#[derive(Debug, serde::Serialize)]
struct ContractHealthReport {
    contract_id: String,
    network: String,
    /// "healthy" | "at_risk" | "critical" (snake_case for stable parsing)
    health: String,
    /// bool when --wasm supplied, null otherwise
    #[serde(rename = "verified", skip_serializing_if = "Option::is_none")]
    verified: Option<bool>,
    on_chain_wasm_hash: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    local_wasm_hash: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    local_wasm_size_bytes: Option<usize>,
    storage: HealthStorage,
    /// Human-readable verdict reasons (empty when healthy)
    #[serde(default)]
    reasons: Vec<String>,
}

/// Storage subsection of [`ContractHealthReport`] (mirrors `StorageReport`
/// field names; omits `total_size_bytes`/`entries` per M23_PLAN.md §12).
#[derive(Debug, serde::Serialize)]
struct HealthStorage {
    total_entries: usize,
    instance_entries: usize,
    persistent_entries: usize,
    temporary_entries: usize,
    other_entries: usize,
    ttl: Option<HealthTtl>,
}

#[derive(Debug, serde::Serialize)]
struct HealthTtl {
    minimum_ttl: u32,
    maximum_ttl: u32,
    average_ttl: u32,
    expiring_entries_count: usize,
    estimated_rent_cost: Option<u64>,
}

/// M23 — Pure health-verdict derivation (no I/O, fully testable).
///
/// Rules (transparent, per M23_PLAN.md §10):
/// - `verified == Some(false)` → Critical (deployed != built).
/// - else `expiring_soon > 0`   → AtRisk (entries near TTL expiry).
/// - else `total_entries == 0`  → AtRisk (empty contract).
/// - else                        → Healthy.
fn derive_verdict(
    verified: Option<bool>,
    expiring_soon: usize,
    total_entries: usize,
) -> (String, Vec<String>) {
    let mut reasons: Vec<String> = Vec::new();

    if verified == Some(false) {
        reasons.push(
            "On-chain WASM does NOT match the supplied local file. Rebuild and redeploy, \
or confirm you are comparing the correct artifact."
                .to_string(),
        );
        return ("critical".to_string(), reasons);
    }

    if expiring_soon > 0 {
        reasons.push(format!(
            "{} storage entr{} expiring soon (< 30 days).",
            expiring_soon,
            if expiring_soon == 1 {
                "y is"
            } else {
                "ies are"
            }
        ));
    }

    if total_entries == 0 {
        reasons.push("Contract has no storage entries (unusual for a live contract).".to_string());
    }

    if !reasons.is_empty() {
        return ("at_risk".to_string(), reasons);
    }

    ("healthy".to_string(), reasons)
}

/// Orchestrates the M23 contract health report (read-only).
///
/// - Offline-hashes `--wasm` first (fail-fast) when supplied.
/// - Fetches on-chain WASM hash via `sdkt-rpc::inspect_contract` (no bytecode download).
/// - Fetches storage posture via `sdkt-storage::StorageAnalyzer` (no new RPC).
/// - Reuses M22 `verification_outcome` for the local-vs-onchain comparison.
async fn contract_health(
    client: &SorobanRpcClient,
    contract_id: &str,
    local_wasm: Option<&[u8]>,
    network: &str,
) -> Result<ContractHealthReport, String> {
    // Optional local WASM — hashed fully offline FIRST (fail fast).
    let local_hash = match local_wasm {
        Some(bytes) => {
            let meta = sdkt_wasm::parse_metadata(bytes).map_err(|e| format!("{}", e))?;
            Some((meta.hash, meta.size_bytes))
        }
        None => None,
    };

    // On-chain WASM hash only (read-only, existing RPC).
    let inspection = inspect_contract(client, contract_id)
        .await
        .map_err(|e| match e {
            sdkt_rpc::RpcError::ContractNotFound => {
                format!("contract {} not found on {}", contract_id, network)
            }
            other => format!("{}", other),
        })?;
    let on_chain_hash = inspection.wasm_hash;

    // Storage posture (read-only, existing RPC via StorageAnalyzer).
    let storage_report = sdkt_storage::StorageAnalyzer::new(client.clone())
        .inspect_contract_storage(contract_id)
        .await
        .map_err(|e| format!("{}", e))?;

    // Optional M22-style verification (reuse existing helper, no duplicate logic).
    let verified = local_hash
        .as_ref()
        .and_then(|(h, s)| verification_outcome(&on_chain_hash, Some((h.clone(), *s))).0);

    let expiring_soon = storage_report
        .ttl_summary
        .as_ref()
        .map(|t| t.expiring_entries_count)
        .unwrap_or(0);

    let (health, reasons) = derive_verdict(verified, expiring_soon, storage_report.total_entries);

    let ttl = storage_report.ttl_summary.as_ref().map(|t| HealthTtl {
        minimum_ttl: t.minimum_ttl,
        maximum_ttl: t.maximum_ttl,
        average_ttl: t.average_ttl,
        expiring_entries_count: t.expiring_entries_count,
        estimated_rent_cost: t.estimated_rent_cost,
    });

    Ok(ContractHealthReport {
        contract_id: contract_id.to_string(),
        network: network.to_string(),
        health,
        verified,
        on_chain_wasm_hash: on_chain_hash,
        local_wasm_hash: local_hash.as_ref().map(|(h, _)| h.clone()),
        local_wasm_size_bytes: local_hash.as_ref().map(|(_, s)| *s),
        storage: HealthStorage {
            total_entries: storage_report.total_entries,
            instance_entries: storage_report.instance_entries,
            persistent_entries: storage_report.persistent_entries,
            temporary_entries: storage_report.temporary_entries,
            other_entries: storage_report.other_entries,
            ttl,
        },
        reasons,
    })
}

/// Pure comparison logic for M22 (no I/O, fully testable).
///
/// Given the on-chain hash and an optional local `(hash, size)` pair, returns
/// the `(match, status, explanation)` triple per M22_PLAN.md §10/§11.
fn verification_outcome(
    on_chain_hash: &str,
    local: Option<(String, usize)>,
) -> (Option<bool>, String, String) {
    match local {
        Some((ref lh, _size)) => {
            if *lh == on_chain_hash {
                (Some(true), "Verified".to_string(), String::new())
            } else {
                (
                    Some(false),
                    "Mismatch".to_string(),
                    format!(
                        "The deployed bytecode does NOT match the local file.\nOn-chain : {}\nLocal    : {}\nRebuild and redeploy, or confirm you are comparing the correct artifact.",
                        on_chain_hash, lh
                    ),
                )
            }
        }
        None => (
            None,
            "OnChainOnly".to_string(),
            "No local WASM provided; reporting on-chain hash only.".to_string(),
        ),
    }
}

/// Orchestrates contract verification (M22).
///
/// Fetches the on-chain WASM hash via `sdkt-rpc::inspect_contract` (no bytecode
/// download) and compares it against the offline local WASM hash from
/// `sdkt-wasm::parse_metadata`. `local_wasm` is optional: when `None`, the
/// report is `OnChainOnly` (no comparison verdict).
async fn verify_contract(
    client: &SorobanRpcClient,
    contract_id: &str,
    local_wasm: Option<&[u8]>,
    network: &str,
) -> Result<VerificationReport, String> {
    // Hash the local WASM fully offline FIRST (fail fast on bad/missing files
    // before touching the network), per M22_PLAN.md "Offline hashing".
    let local_hash = match local_wasm {
        Some(bytes) => {
            let meta = sdkt_wasm::parse_metadata(bytes).map_err(|e| format!("{}", e))?;
            Some((meta.hash, meta.size_bytes))
        }
        None => None,
    };

    // On-chain hash only — never download the bytecode.
    let inspection = inspect_contract(client, contract_id)
        .await
        .map_err(|e| format!("{}", e))?;

    let on_chain_hash = inspection.wasm_hash;

    // Capture report fields from the (still-owned) local hash before the
    // comparison consumes it.
    let local_wasm_hash = local_hash.as_ref().map(|(h, _)| h.clone());
    let local_wasm_size_bytes = local_hash.as_ref().map(|(_, s)| *s);

    let (matches, status, explanation) = verification_outcome(&on_chain_hash, local_hash);

    Ok(VerificationReport {
        contract_id: contract_id.to_string(),
        network: network.to_string(),
        on_chain_wasm_hash: on_chain_hash,
        local_wasm_hash,
        local_wasm_size_bytes,
        matches,
        verification_status: status,
        explanation,
    })
}

fn parse_format_str(s: &str) -> OutputFormat {
    match s.to_lowercase().as_str() {
        "json" => OutputFormat::Json,
        "pretty" => OutputFormat::Pretty,
        other => {
            eprintln!("Invalid format '{}'. Use 'json' or 'pretty'.", other);
            process::exit(1);
        }
    }
}

/// Load `.sdkt.toml` from the current directory.
///
/// A missing file yields the default config (so commands like `sdkt lock
/// verify` still run meaningfully). A present-but-unparseable file (e.g. a
/// duplicate contract name or malformed TOML) is a hard error surfaced with a
/// clear message, rather than silently falling back to an empty config.
fn load_config() -> DevKitConfig {
    match DevKitConfig::from_file(".sdkt.toml") {
        Ok(c) => c,
        Err(e) => {
            eprintln!("Error loading .sdkt.toml: {}", e);
            process::exit(1);
        }
    }
}

/// Resolve a `--input` value to envelope text.
///
/// Filesystem rules (matching the rest of the `tx` subcommands):
/// - If the path exists, read it as a file.
/// - If it does not exist but looks like a (missing) path, report a clear
///   "invalid file" error instead of silently mis-parsing it as base64.
/// - Otherwise treat the value as an inline base64 string.
fn resolve_tx_input(input: &str) -> Result<String, String> {
    if fs::metadata(input).is_ok() {
        return fs::read_to_string(input)
            .map_err(|e| format!("invalid file '{}': cannot read ({})", input, e));
    }
    let looks_like_path = input.contains('/')
        || input.contains('\\')
        || input.ends_with(".xdr")
        || input.ends_with(".txt");
    if looks_like_path {
        return Err(format!(
            "invalid file '{}': no such file or directory",
            input
        ));
    }
    Ok(input.to_string())
}

/// Render a `ContractFunction`'s signature as `name(params) -> outputs`.
fn sig_string(f: &sdkt_wasm::ContractFunction) -> String {
    let params: Vec<String> = f
        .parameters
        .iter()
        .map(|p| format!("{}: {}", p.name, p.type_.name))
        .collect();
    let outs: Vec<String> = f.outputs.iter().map(|o| o.name.clone()).collect();
    let out = if outs.is_empty() {
        "void".to_string()
    } else {
        outs.join(", ")
    };
    format!("{}({}) -> {}", f.name, params.join(", "), out)
}

/// Pretty-print an upgrade-safety verdict (used by `sdkt diff --upgrade-safety`).
fn print_upgrade_verdict(v: &sdkt_wasm::UpgradeVerdict) {
    println!("Upgrade Safety");
    println!("==============");
    println!();
    println!("Compatible: {}", if v.compatible { "YES" } else { "NO" });
    println!();
    println!("Breaking:");
    if v.breaking_changes.is_empty() {
        println!("  (none)");
    } else {
        for c in &v.breaking_changes {
            println!("  - {}", c.label());
        }
    }
    println!();
    println!("Non-breaking:");
    if v.non_breaking_changes.is_empty() {
        println!("  (none)");
    } else {
        for c in &v.non_breaking_changes {
            println!("  - {}", c.label());
        }
    }
}

/// M42 — On-chain upgrade-safety verification.
///
/// Fetches the deployed contract's on-chain WASM via the M41 path
/// (`inspect_contract` -> `get_wasm_bytecode`), parses its `ContractSpec`, and
/// runs the existing M14 `SpecDiff`/`UpgradeVerdict` engine against a local
/// candidate WASM. No new RPC method, no new parser, no new verdict engine — it
/// reuses `sdkt-rpc` retrieval and `sdkt-wasm` diffing verbatim. Read-only; the
/// network/mainnet-safety guard is inherited from `resolve_rpc_client` in the
/// caller.
async fn run_upgrade_safety(
    client: &SorobanRpcClient,
    contract_id: &str,
    candidate_bytes: &[u8],
    network: &str,
    fmt: OutputFormat,
) -> Result<(), String> {
    // Candidate WASM is parsed offline first (fail-fast on malformed input).
    let _candidate_meta = sdkt_wasm::parse_metadata(candidate_bytes)
        .map_err(|e| format!("{} is not valid WASM: {}", "<candidate>", e))?;

    // On-chain WASM hash (M41 path).
    let inspection = inspect_contract(client, contract_id)
        .await
        .map_err(|e| match e {
            sdkt_rpc::RpcError::ContractNotFound => {
                format!("contract {} not found on {}", contract_id, network)
            }
            other => format!("{}", other),
        })?;
    let wasm_hash = inspection.wasm_hash;

    // Fetch the raw on-chain WASM bytecode (M41 path) — reuse existing extractor.
    let deployed_bytes = get_wasm_bytecode(client, &wasm_hash)
        .await
        .map_err(|e| format!("could not fetch on-chain WASM for {}: {}", contract_id, e))?;

    // Compare the two ContractSpecs with the M14 engine (raw entry point reuses
    // diff_specs internally). The "old" side is the deployed contract; the "new"
    // side is the candidate local WASM.
    let diff = sdkt_wasm::diff_wasm(&deployed_bytes, candidate_bytes)
        .map_err(|e| format!("failed to diff contracts: {}", e))?;

    let verdict = sdkt_wasm::UpgradeVerdict::from_diff(&diff);

    if fmt == OutputFormat::Json {
        println!(
            "{}",
            serde_json::to_string_pretty(&verdict).map_err(|e| format!("{}", e))?
        );
    } else {
        print_upgrade_verdict(&verdict);
        println!();
        println!(
            "Baseline: live contract {} on {} (WASM {})",
            contract_id, network, wasm_hash
        );
    }
    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();

    match cli.command {
        Commands::Decode {
            payload,
            r#type,
            format,
            file,
        } => {
            let input = match (file, payload) {
                (Some(path), _) => fs::read_to_string(&path)?,
                (None, Some(p)) => p,
                (None, None) => {
                    return Err("no input provided: pass XDR as an argument or use --file".into());
                }
            };

            let fmt = parse_format_str(&format);
            let json = decode(&input, r#type.as_deref(), fmt)?;
            println!("{}", json);
        }
        Commands::Storage {
            action,
            abi,
            abi_contract,
            net,
        } => {
            let client = resolve_rpc_client(
                net.rpc_url.clone(),
                net.network_passphrase.clone(),
                net.network_profile.clone(),
            );

            // Load ABI spec if provided. Two mutually exclusive sources:
            // a local WASM file (`--abi`) or a deployed contract's on-chain WASM
            // fetched via the M41 path (`--abi-contract`).
            if abi.is_some() && abi_contract.is_some() {
                eprintln!("Error: specify only one of --abi or --abi-contract");
                process::exit(1);
            }

            let contract_spec: Option<sdkt_wasm::ContractSpec> =
                if let Some(wasm_path) = abi.as_ref() {
                    let wasm_bytes =
                        fs::read(wasm_path).map_err(|e| format!("Failed to read WASM: {}", e))?;
                    Some(
                        parse_contract_spec(&wasm_bytes)
                            .map_err(|e| format!("Failed to parse ABI: {}", e))?,
                    )
                } else if let Some(id) = abi_contract.as_ref() {
                    // M41 on-chain retrieval: inspect_contract -> wasm hash, then
                    // get_wasm_bytecode -> raw bytes, then parse_contract_spec.
                    let inspection = inspect_contract(&client, id).await.map_err(|e| match e {
                        sdkt_rpc::RpcError::ContractNotFound => {
                            format!("contract {} not found", id)
                        }
                        other => format!("{}", other),
                    })?;
                    let deployed_bytes = get_wasm_bytecode(&client, &inspection.wasm_hash)
                        .await
                        .map_err(|e| format!("could not fetch on-chain WASM for {}: {}", id, e))?;
                    Some(
                        parse_contract_spec(&deployed_bytes)
                            .map_err(|e| format!("failed to parse deployed ABI: {}", e))?,
                    )
                } else {
                    None
                };

            match action {
                StorageAction::Check {
                    contract_id,
                    format,
                } => {
                    let fmt = parse_format_str(&format);
                    let client = resolve_rpc_client(
                        net.rpc_url.clone(),
                        net.network_passphrase.clone(),
                        net.network_profile.clone(),
                    );

                    // Load ABI spec if provided for storage decoding
                    match get_ttl_info(&client, &contract_id).await {
                        Ok(ttl_info) => {
                            if fmt == OutputFormat::Json {
                                if let Some(spec) = contract_spec {
                                    let json_str = serde_json::to_string(&serde_json::json!({
                                        "contract_id": contract_id,
                                        "entries": ttl_info.entries.len(),
                                        "abi": serde_json::json!({
                                            "functions": spec.functions.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),
                                            "events": spec.events.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
                                            "custom_types": spec.custom_types.iter().map(|t| t.name.as_str()).collect::<Vec<_>>()
                                        })
                                    }))?;
                                    println!("{}", json_str);
                                } else {
                                    let json_str = serde_json::to_string(&ttl_info)?;
                                    println!("{}", json_str);
                                }
                            } else {
                                println!("Storage Check for Contract ID: {}", contract_id);
                                println!("Total Entries: {}", ttl_info.entries.len());
                                for (i, entry) in ttl_info.entries.iter().enumerate() {
                                    println!("\nEntry #{}", i + 1);
                                    println!("  Key: {}", entry.key);
                                    println!("  Current TTL: {} ledgers", entry.current_ttl);
                                    println!("  Remaining: {}", entry.expiration_time);
                                    println!(
                                        "  Est. Extension Cost: {} stroops",
                                        entry.extension_cost_stroops
                                    );
                                }

                                if let Some(spec) = contract_spec {
                                    println!("\nABI Functions:");
                                    for f in &spec.functions {
                                        println!("  - {} ({})", f.name, f.doc);
                                    }
                                    println!("\nABI Events:");
                                    for e in &spec.events {
                                        println!("  - {}", e.name);
                                    }
                                    if !spec.custom_types.is_empty() {
                                        println!("\nABI Custom Types:");
                                        for t in &spec.custom_types {
                                            println!("  - {} ({})", t.name, t.kind);
                                        }
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!("Error fetching storage TTL: {}", e);
                            process::exit(1);
                        }
                    }
                }
                StorageAction::Estimate { wasm } => {
                    println!("Storage Estimate for {} (Not yet implemented)", wasm);
                }
                StorageAction::Analyze {
                    contract_id,
                    format,
                } => {
                    let fmt = parse_format_str(&format);
                    let client = resolve_rpc_client(
                        net.rpc_url.clone(),
                        net.network_passphrase.clone(),
                        net.network_profile.clone(),
                    );
                    let analyzer = sdkt_storage::StorageAnalyzer::new(client);

                    match analyzer.inspect_contract_storage(&contract_id).await {
                        Ok(report) => {
                            if fmt == OutputFormat::Json {
                                println!("{}", serde_json::to_string(&report)?);
                            } else {
                                println!("Storage Analysis for Contract: {}", report.contract_id);
                                println!("Total Entries: {}", report.total_entries);
                                println!("  Instance:    {}", report.instance_entries);
                                println!("  Persistent: {}", report.persistent_entries);
                                println!("  Temporary:   {}", report.temporary_entries);
                                if report.other_entries > 0 {
                                    println!("  Other:      {}", report.other_entries);
                                }
                                if let Some(summary) = &report.ttl_summary {
                                    println!("\nTTL Summary:");
                                    println!("  Min TTL:        {}", summary.minimum_ttl);
                                    println!("  Max TTL:        {}", summary.maximum_ttl);
                                    println!("  Average TTL:    {}", summary.average_ttl);
                                    println!(
                                        "  Expiring Soon:  {}",
                                        summary.expiring_entries_count
                                    );
                                    if let Some(cost) = summary.estimated_rent_cost {
                                        println!("  Est. Rent Cost: {} stroops", cost);
                                    }
                                }
                                if !report.entries.is_empty() {
                                    println!("\nEntries:");
                                    for (i, entry) in report.entries.iter().enumerate() {
                                        println!(
                                            "  #{:<3} [{}] ttl={} (~{}d) cost={} stroops",
                                            i + 1,
                                            entry.class.label(),
                                            entry.current_ttl,
                                            entry.days_remaining,
                                            entry.extension_cost_stroops
                                        );
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            eprintln!("Error analyzing storage: {}", e);
                            process::exit(1);
                        }
                    }
                }
            }
        }
        Commands::Inspect {
            contract_id,
            format,
            abi,
            net,
        } => {
            let fmt = parse_format_str(&format);
            let client = resolve_rpc_client(
                net.rpc_url.clone(),
                net.network_passphrase.clone(),
                net.network_profile.clone(),
            );

            // Load ABI spec if provided for storage decoding
            let contract_spec = if let Some(wasm_path) = abi.as_ref() {
                let wasm_bytes =
                    fs::read(wasm_path).map_err(|e| format!("Failed to read WASM: {}", e))?;
                Some(
                    parse_contract_spec(&wasm_bytes)
                        .map_err(|e| format!("Failed to parse ABI: {}", e))?,
                )
            } else {
                None
            };

            match inspect_contract(&client, &contract_id).await {
                Ok(inspection) => {
                    if fmt == OutputFormat::Json {
                        if let Some(spec) = contract_spec {
                            let json_str = serde_json::to_string(&serde_json::json!({
                                "contract_id": inspection.contract_id,
                                "wasm_hash": inspection.wasm_hash,
                                "storage_keys": inspection.storage_keys.len(),
                                "abi": serde_json::json!({
                                    "functions": spec.functions.iter().map(|f| f.name.as_str()).collect::<Vec<_>>(),
                                    "events": spec.events.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(),
                                    "custom_types": spec.custom_types.iter().map(|t| t.name.as_str()).collect::<Vec<_>>()
                                })
                            }))?;
                            println!("{}", json_str);
                        } else {
                            let json_str = serde_json::to_string(&inspection)?;
                            println!("{}", json_str);
                        }
                    } else {
                        println!("Contract Inspection");
                        println!("Contract ID: {}", inspection.contract_id);
                        println!("WASM Hash: {}", inspection.wasm_hash);
                        println!("Storage Keys: {}", inspection.storage_keys.len());

                        if let Some(spec) = contract_spec {
                            println!("\nABI Functions:");
                            for f in &spec.functions {
                                println!("  - {} ({})", f.name, f.doc);
                            }
                            println!("\nABI Events:");
                            for e in &spec.events {
                                println!("  - {}", e.name);
                            }
                            if !spec.custom_types.is_empty() {
                                println!("\nABI Custom Types:");
                                for t in &spec.custom_types {
                                    println!("  - {} ({})", t.name, t.kind);
                                }
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error inspecting contract: {}", e);
                    process::exit(1);
                }
            }
        }
        Commands::Verify {
            contract,
            wasm,
            network,
            format,
            upgrade_safety,
            net,
        } => {
            let fmt = parse_format_str(&format);
            let client = resolve_rpc_client(
                net.rpc_url.clone(),
                net.network_passphrase.clone(),
                net.network_profile.clone(),
            );

            // On-chain upgrade-safety verification: compare the live deployed
            // contract's interface against a local candidate WASM.
            if upgrade_safety {
                match wasm.as_ref() {
                    None => {
                        eprintln!("Error: --upgrade-safety requires --wasm <candidate.wasm>");
                        process::exit(1);
                    }
                    Some(path) => {
                        let candidate_bytes = fs::read(path).unwrap_or_else(|e| {
                            eprintln!("Error reading WASM file {}: {}", path, e);
                            process::exit(1);
                        });
                        match run_upgrade_safety(
                            &client,
                            &contract,
                            &candidate_bytes,
                            &network,
                            fmt,
                        )
                        .await
                        {
                            Ok(()) => return Ok(()),
                            Err(e) => {
                                eprintln!("Error verifying upgrade safety: {}", e);
                                process::exit(1);
                            }
                        }
                    }
                }
            }

            // Read + hash the local WASM fully offline (no RPC).
            let local_bytes = match wasm.as_ref() {
                Some(path) => {
                    let bytes = fs::read(path).unwrap_or_else(|e| {
                        eprintln!("Error reading WASM file {}: {}", path, e);
                        process::exit(1);
                    });
                    Some(bytes)
                }
                None => None,
            };

            match verify_contract(&client, &contract, local_bytes.as_deref(), &network).await {
                Ok(report) => {
                    if fmt == OutputFormat::Json {
                        println!(
                            "{}",
                            serde_json::to_string_pretty(&report).unwrap_or_else(|e| {
                                eprintln!("Error serializing report: {}", e);
                                process::exit(1);
                            })
                        );
                    } else {
                        println!("Contract Verification Report");
                        println!("============================");
                        println!("Contract ID : {}", report.contract_id);
                        println!("Network     : {}", report.network);
                        println!("On-chain WASM: {}", report.on_chain_wasm_hash);
                        if let (Some(lh), Some(sz)) =
                            (&report.local_wasm_hash, &report.local_wasm_size_bytes)
                        {
                            println!("Local WASM   : {}   ({} bytes)", lh, sz);
                        }
                        let match_str = match report.matches {
                            Some(true) => "YES".to_string(),
                            Some(false) => "NO".to_string(),
                            None => "N/A (no local WASM provided)".to_string(),
                        };
                        println!("Match        : {}", match_str);
                        println!("Status       : {}", report.verification_status);
                        if !report.explanation.is_empty() {
                            println!();
                            println!("{}", report.explanation);
                        }
                    }
                }
                Err(e) => {
                    // Surface actionable messages per M22_PLAN.md §9.
                    if let Some(path) = wasm.as_ref() {
                        if e.contains("WASM parse error") {
                            eprintln!("Error: {} is not valid WASM", path);
                            process::exit(1);
                        }
                        if e.contains("Empty") {
                            eprintln!("Error: {} is empty", path);
                            process::exit(1);
                        }
                    }
                    eprintln!("Error verifying contract: {}", e);
                    process::exit(1);
                }
            }
        }
        Commands::Health {
            contract,
            wasm,
            network,
            format,
            net,
        } => {
            let fmt = parse_format_str(&format);
            let client = resolve_rpc_client(
                net.rpc_url.clone(),
                net.network_passphrase.clone(),
                net.network_profile.clone(),
            );

            // Read + hash the local WASM fully offline (no RPC).
            let local_bytes = match wasm.as_ref() {
                Some(path) => {
                    let bytes = fs::read(path).unwrap_or_else(|e| {
                        eprintln!("Error reading WASM file {}: {}", path, e);
                        process::exit(1);
                    });
                    Some(bytes)
                }
                None => None,
            };

            match contract_health(&client, &contract, local_bytes.as_deref(), &network).await {
                Ok(report) => {
                    if fmt == OutputFormat::Json {
                        println!(
                            "{}",
                            serde_json::to_string_pretty(&report).unwrap_or_else(|e| {
                                eprintln!("Error serializing report: {}", e);
                                process::exit(1);
                            })
                        );
                    } else {
                        println!("Contract Health Report");
                        println!("=======================");
                        println!("Contract ID : {}", report.contract_id);
                        println!("Network     : {}", report.network);
                        println!("Health      : {}", report.health.to_uppercase());
                        if let Some(v) = report.verified {
                            let local_str = report.local_wasm_hash.as_deref().unwrap_or("");
                            println!(
                                "On-chain WASM : {} (verified against local: {})",
                                report.on_chain_wasm_hash,
                                if v { "YES" } else { "NO — MISMATCH" }
                            );
                            if !local_str.is_empty() {
                                println!("Local WASM   : {}", local_str);
                            }
                        } else {
                            println!("On-chain WASM : {}", report.on_chain_wasm_hash);
                        }
                        println!("Storage:");
                        println!("  Total Entries: {}", report.storage.total_entries);
                        println!("    Instance:    {}", report.storage.instance_entries);
                        println!("    Persistent: {}", report.storage.persistent_entries);
                        println!("    Temporary:   {}", report.storage.temporary_entries);
                        if report.storage.other_entries > 0 {
                            println!("    Other:      {}", report.storage.other_entries);
                        }
                        if let Some(ttl) = &report.storage.ttl {
                            println!("TTL:");
                            println!("  Min TTL:       {}", ttl.minimum_ttl);
                            println!("  Max TTL:       {}", ttl.maximum_ttl);
                            println!("  Average TTL:   {}", ttl.average_ttl);
                            println!("  Expiring Soon: {}", ttl.expiring_entries_count);
                            if let Some(cost) = ttl.estimated_rent_cost {
                                println!("  Est. Rent Cost: {} stroops", cost);
                            }
                        }
                        if !report.reasons.is_empty() {
                            println!();
                            println!("Verdict: {}", report.reasons.join(" "));
                        } else {
                            println!();
                            let verified_note = match report.verified {
                                Some(true) => "WASM verified, ",
                                Some(false) => "MISMATCH; ",
                                None => "No local WASM supplied; verification skipped. ",
                            };
                            println!(
                                "Verdict: Contract posture is healthy. {}no entries expiring soon.",
                                verified_note
                            );
                        }
                    }
                }
                Err(e) => {
                    // Surface actionable messages per M23_PLAN.md §11.
                    if let Some(path) = wasm.as_ref() {
                        if e.contains("WASM parse error") {
                            eprintln!("Error: {} is not valid WASM", path);
                            process::exit(1);
                        }
                        if e.contains("Empty") {
                            eprintln!("Error: {} is empty", path);
                            process::exit(1);
                        }
                    }
                    if e.contains("not found on") {
                        eprintln!("Error: contract {} not found on {}", contract, network);
                        process::exit(1);
                    }
                    eprintln!("Error fetching contract: {}", e);
                    process::exit(1);
                }
            }
        }
        Commands::Tx { action, net } => match action {
            TxAction::Inspect { hash, format } => {
                let fmt = parse_format_str(&format);
                let client = resolve_rpc_client(
                    net.rpc_url.clone(),
                    net.network_passphrase.clone(),
                    net.network_profile.clone(),
                );

                match inspect_transaction(&client, &hash).await {
                    Ok(tx_info) => {
                        if fmt == OutputFormat::Json {
                            let json_str = serde_json::to_string(&tx_info)?;
                            println!("{}", json_str);
                        } else {
                            println!("Transaction:");
                            println!();
                            println!("Hash: {}", tx_info.hash);
                            println!("Status: {}", tx_info.status.as_deref().unwrap_or("Unknown"));
                            println!(
                                "Ledger: {}",
                                tx_info.ledger.map_or("N/A".to_string(), |v| v.to_string())
                            );
                            println!(
                                "Fee: {}",
                                tx_info
                                    .fee_charged
                                    .map_or("N/A".to_string(), |v| v.to_string())
                            );
                            println!(
                                "Operations: {}",
                                tx_info
                                    .operation_count
                                    .map_or("N/A".to_string(), |v| v.to_string())
                            );
                        }
                    }
                    Err(e) => {
                        eprintln!("Error inspecting transaction: {}", e);
                        process::exit(1);
                    }
                }
            }
            TxAction::Validate { envelope, format } => {
                let fmt = parse_format_str(&format);
                let env_data = if fs::metadata(&envelope).is_ok() {
                    fs::read_to_string(&envelope)?
                } else {
                    envelope.clone()
                };

                use sdkt_core::validation::validate_base64;
                let report = validate_base64(env_data.trim());

                if fmt == OutputFormat::Json {
                    let json_str = serde_json::to_string(&report)?;
                    println!("{}", json_str);
                } else {
                    println!("Validation Report:");
                    if report.valid {
                        println!("  Status: VALID");
                    } else {
                        println!("  Status: INVALID");
                    }
                    if !report.errors.is_empty() {
                        println!("  Errors:");
                        for err in &report.errors {
                            println!("    - {}", err.message());
                        }
                    }
                    if !report.warnings.is_empty() {
                        println!("  Warnings:");
                        for warn in &report.warnings {
                            println!("    - {:?}", warn);
                        }
                    }
                }

                if !report.valid {
                    process::exit(1);
                }
            }
            TxAction::Simulate { envelope, format } => {
                let fmt = parse_format_str(&format);
                let client = resolve_rpc_client(
                    net.rpc_url.clone(),
                    net.network_passphrase.clone(),
                    net.network_profile.clone(),
                );

                let env_data = if fs::metadata(&envelope).is_ok() {
                    fs::read_to_string(&envelope)?
                } else {
                    envelope.clone()
                };

                match simulate_transaction(&client, &env_data).await {
                    Ok(sim) => {
                        if fmt == OutputFormat::Json {
                            let json_str = serde_json::to_string(&sim)?;
                            println!("{}", json_str);
                        } else {
                            println!("Simulation Result:");
                            if let Some(err) = &sim.error {
                                println!("  Status: FAILED");
                                println!("  Error: {}", err);
                            } else {
                                println!("  Status: SUCCESS");
                            }
                            println!(
                                "  Ledger: {}",
                                sim.latest_ledger.as_deref().unwrap_or("N/A")
                            );
                            println!("  Min Resource Fee: {} stroops", sim.min_resource_fee);

                            if let Some(preamble) = &sim.restore_preamble {
                                println!("  Restore Preamble Required:");
                                println!(
                                    "    Min Resource Fee: {} stroops",
                                    preamble.min_resource_fee
                                );
                                println!(
                                    "    Transaction Data: ({} bytes)",
                                    preamble.transaction_data.len()
                                );
                            }

                            if let Some(cost) = &sim.cost {
                                println!("  Cost:");
                                println!("    CPU Instructions: {}", cost.cpu_insns);
                                println!("    Memory Bytes: {}", cost.mem_bytes);
                            }
                            if !sim.events.is_empty() {
                                println!("  Events: {} emitted", sim.events.len());
                            }
                            if !sim.state_changes.is_empty() {
                                println!(
                                    "  State Changes: {} entries modified",
                                    sim.state_changes.len()
                                );
                            }
                            if !sim.results.is_empty() {
                                println!("  Operations: {} results", sim.results.len());
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("Error simulating transaction: {}", e);
                        process::exit(1);
                    }
                }
            }
            TxAction::Submit {
                envelope,
                wait,
                timeout,
                interval,
                format,
            } => {
                let fmt = parse_format_str(&format);
                let client = resolve_rpc_client_mutating(
                    net.rpc_url.clone(),
                    net.network_passphrase.clone(),
                    net.network_profile.clone(),
                );

                use sdkt_rpc::{submit_and_wait, PollConfig};
                use std::time::Duration;

                let env_data = if fs::metadata(&envelope).is_ok() {
                    fs::read_to_string(&envelope)?
                } else {
                    envelope.clone()
                };

                let poll_cfg = PollConfig {
                    timeout: Duration::from_secs(timeout),
                    interval: Duration::from_secs(interval),
                };

                match submit_and_wait(&client, &env_data, wait, &poll_cfg).await {
                    Ok(res) => {
                        if fmt == OutputFormat::Json {
                            println!("{}", serde_json::to_string(&res)?);
                        } else {
                            println!("Submission Result:");
                            println!("  Hash:   {}", res.hash);
                            println!("  Status: {:?}", res.status);
                            if let Some(ledger) = &res.latest_ledger {
                                println!("  Ledger: {}", ledger);
                            }
                            if let Some(xdr) = &res.result_xdr {
                                println!("  Result XDR: {}", xdr);
                            }
                        }
                    }
                    Err(e) => {
                        eprintln!("Error submitting transaction: {}", e);
                        std::process::exit(1);
                    }
                }
            }
            TxAction::Build {
                source,
                sequence,
                fee,
                contract,
                function,
                arg,
                format,
                output,
            } => {
                let fmt = parse_format_str(&format);

                // If source doesn't start with 'G' and isn't 56 chars, try to load it as an identity
                let mut source_account = source.clone();
                if !source_account.starts_with('G') || source_account.len() != 56 {
                    use sdkt_storage::IdentityStore;
                    if let Ok(store) = IdentityStore::new() {
                        if let Ok(identity) = store.get(&source_account) {
                            source_account = identity.public_key;
                        }
                    }
                }

                let mut parsed_args = Vec::new();
                for a in arg.iter() {
                    if let Some((t, v)) = a.split_once(':') {
                        use sdkt_xdr::{scval_to_base64, Address, IntoScVal};
                        let b64 = match t.to_lowercase().as_str() {
                            "u32" => {
                                let n: u32 =
                                    v.parse().map_err(|_| format!("invalid u32 value: {v}"))?;
                                scval_to_base64(&n.into_scval()?)?
                            }
                            "i32" => {
                                let n: i32 =
                                    v.parse().map_err(|_| format!("invalid i32 value: {v}"))?;
                                scval_to_base64(&n.into_scval()?)?
                            }
                            "u64" => {
                                let n: u64 =
                                    v.parse().map_err(|_| format!("invalid u64 value: {v}"))?;
                                scval_to_base64(&n.into_scval()?)?
                            }
                            "i64" => {
                                let n: i64 =
                                    v.parse().map_err(|_| format!("invalid i64 value: {v}"))?;
                                scval_to_base64(&n.into_scval()?)?
                            }
                            "u128" => {
                                let n: u128 =
                                    v.parse().map_err(|_| format!("invalid u128 value: {v}"))?;
                                scval_to_base64(&n.into_scval()?)?
                            }
                            "i128" => {
                                let n: i128 =
                                    v.parse().map_err(|_| format!("invalid i128 value: {v}"))?;
                                scval_to_base64(&n.into_scval()?)?
                            }
                            "bool" => {
                                let b: bool =
                                    v.parse().map_err(|_| format!("invalid bool value: {v}"))?;
                                scval_to_base64(&b.into_scval()?)?
                            }
                            "string" => scval_to_base64(&v.into_scval()?)?,
                            "bytes" => {
                                let mut b = Vec::new();
                                let s = v.trim();
                                for i in (0..s.len()).step_by(2) {
                                    let byte = u8::from_str_radix(&s[i..i + 2], 16)
                                        .map_err(|_| format!("invalid hex byte in: {v}"))?;
                                    b.push(byte);
                                }
                                scval_to_base64(&b.into_scval()?)?
                            }
                            "address" => {
                                let addr = Address::from_strkey(v)
                                    .map_err(|_| format!("invalid Stellar address: {v}"))?;
                                scval_to_base64(&addr.into_scval()?)?
                            }
                            _ => a.clone(), // Unknown type fallback to direct base64
                        };
                        parsed_args.push(b64);
                    } else {
                        parsed_args.push(a.clone());
                    }
                }

                let params = InvokeTransactionParams {
                    source_account,
                    sequence,
                    fee,
                    contract_id: contract.clone(),
                    function: function.clone(),
                    args: parsed_args,
                };

                match build_invoke_transaction(&params) {
                    Ok(env) => {
                        if let Some(ref path) = output {
                            if let Err(e) = fs::write(path, &env) {
                                eprintln!("Error writing to file: {}", e);
                                process::exit(1);
                            }
                            if fmt != OutputFormat::Json {
                                println!("Transaction envelope written to {}", path);
                            }
                        }

                        if fmt == OutputFormat::Json {
                            println!(r#"{{"envelope": "{}"}}"#, env);
                        } else if output.is_none() {
                            println!("Transaction Envelope (Base64):");
                            println!("{}", env);
                        }
                    }
                    Err(e) => {
                        eprintln!("Error building transaction: {}", e);
                        process::exit(1);
                    }
                }
            }
            TxAction::Sign {
                input,
                output,
                identity,
                network,
                format,
            } => {
                let fmt = parse_format_str(&format);

                // --- Network resolution (strict; reject unknown labels) ---
                let network = match network.trim().to_ascii_lowercase().as_str() {
                    "testnet" => Network::Testnet,
                    "mainnet" => Network::Mainnet,
                    "futurenet" => Network::Futurenet,
                    other if other.starts_with("custom:") => Network::parse(other),
                    _ => {
                        eprintln!(
                            "Error: invalid network '{}' (expected testnet|mainnet|futurenet|custom:<passphrase>)",
                            network
                        );
                        process::exit(1);
                    }
                };

                // --- Input resolution (file or inline base64) ---
                let env_data = match resolve_tx_input(&input) {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("Error: {}", e);
                        process::exit(1);
                    }
                };

                // --- Identity resolution (keystore) ---
                if identity.trim().is_empty() {
                    eprintln!("Error: missing identity (use --identity <name>)");
                    process::exit(1);
                }
                use sdkt_storage::IdentityStore;
                let store = match IdentityStore::new() {
                    Ok(s) => s,
                    Err(e) => {
                        eprintln!("Error: cannot open identity store: {}", e);
                        process::exit(1);
                    }
                };
                let signing_key = match store.load_signing_key(&identity) {
                    Ok(k) => k,
                    Err(_) => {
                        eprintln!("Error: unknown identity '{}'", identity);
                        process::exit(1);
                    }
                };
                let signer = Ed25519Signer::from_seed(&signing_key.to_bytes());

                let opts = SigningOptions::with(network);
                match sign_transaction(env_data.trim(), &signer, &opts) {
                    Ok(signed) => {
                        if let Some(path) = &output {
                            if let Err(e) = fs::write(path, &signed) {
                                eprintln!("Error: cannot write output to '{}': {}", path, e);
                                process::exit(1);
                            }
                            if fmt != OutputFormat::Json {
                                println!("Signed transaction envelope written to {}", path);
                            }
                        }
                        if fmt == OutputFormat::Json {
                            println!(r#"{{"envelope": "{}"}}"#, signed);
                        } else if output.is_none() {
                            println!("Signed Transaction Envelope (Base64):");
                            println!("{}", signed);
                        }
                    }
                    Err(e) => {
                        let msg = match e {
                            SigningError::Base64(_) => "invalid base64 input".to_string(),
                            SigningError::Xdr(_) => {
                                "invalid envelope: does not parse as a transaction envelope"
                                    .to_string()
                            }
                            SigningError::EmptyEnvelope => {
                                "invalid envelope: input is empty".to_string()
                            }
                            SigningError::InvalidKeyLength(_)
                            | SigningError::InvalidSecretKey(_)
                            | SigningError::Sign(_) => "internal signing error".to_string(),
                        };
                        eprintln!("Error signing transaction: {}", msg);
                        process::exit(1);
                    }
                }
            }
        },
        Commands::Events {
            contract_id,
            format,
            abi,
            abi_contract,
            net,
        } => {
            let fmt = parse_format_str(&format);
            let client = resolve_rpc_client(
                net.rpc_url.clone(),
                net.network_passphrase.clone(),
                net.network_profile.clone(),
            );

            // Resolve the ABI ContractSpec from one of two sources (mutually
            // exclusive): a local WASM file (`--abi`) or a deployed contract's
            // on-chain WASM fetched via the M41 path (`--abi-contract`).
            if abi.is_some() && abi_contract.is_some() {
                eprintln!("Error: specify only one of --abi or --abi-contract");
                process::exit(1);
            }

            let contract_spec: Option<sdkt_wasm::ContractSpec> =
                if let Some(wasm_path) = abi.as_ref() {
                    let wasm_bytes =
                        fs::read(wasm_path).map_err(|e| format!("Failed to read WASM: {}", e))?;
                    Some(
                        parse_contract_spec(&wasm_bytes)
                            .map_err(|e| format!("Failed to parse ABI: {}", e))?,
                    )
                } else if let Some(id) = abi_contract.as_ref() {
                    // M41 on-chain retrieval: inspect_contract -> wasm hash, then
                    // get_wasm_bytecode -> raw bytes, then parse_contract_spec.
                    let inspection = inspect_contract(&client, id).await.map_err(|e| match e {
                        sdkt_rpc::RpcError::ContractNotFound => {
                            format!("contract {} not found", id)
                        }
                        other => format!("{}", other),
                    })?;
                    let deployed_bytes = get_wasm_bytecode(&client, &inspection.wasm_hash)
                        .await
                        .map_err(|e| format!("could not fetch on-chain WASM for {}: {}", id, e))?;
                    Some(
                        parse_contract_spec(&deployed_bytes)
                            .map_err(|e| format!("failed to parse deployed ABI: {}", e))?,
                    )
                } else {
                    None
                };

            match get_contract_events(&client, &contract_id).await {
                Ok(events) => {
                    if let Some(spec) = contract_spec {
                        // ABI-aware decoding: topics[0] is the event symbol,
                        // remaining topics + the data value carry the payload.
                        if fmt == OutputFormat::Json {
                            let decoded_events: Vec<serde_json::Value> = events
                                .iter()
                                .map(|ev| {
                                    let topic_scvals: Vec<stellar_xdr::ScVal> = ev
                                        .topics
                                        .iter()
                                        .filter_map(|t| sdkt_xdr::scval_from_base64(t))
                                        .collect();
                                    let data_scvals: Vec<stellar_xdr::ScVal> = ev
                                        .value
                                        .as_deref()
                                        .and_then(sdkt_xdr::scval_from_base64)
                                        .into_iter()
                                        .collect();
                                    let decoded =
                                        decode_event_topics(&spec, &topic_scvals, &data_scvals);
                                    serde_json::json!({
                                        "contract_id": ev.contract_id,
                                        "ledger": ev.ledger,
                                        "decoded": decoded.iter().map(|d| serde_json::json!({
                                            "raw": d.raw,
                                            "label": d.label,
                                            "matched_type": d.matched_type,
                                            "fields": d.fields
                                        })).collect::<Vec<_>>()
                                    })
                                })
                                .collect();
                            let json_str = serde_json::to_string(&decoded_events)?;
                            println!("{}", json_str);
                        } else {
                            println!("Contract Events (ABI-decoded):");
                            if events.is_empty() {
                                println!("No events found.");
                            } else {
                                for (i, ev) in events.iter().enumerate() {
                                    println!("\nEvent #{}", i + 1);
                                    println!(
                                        "Ledger: {}",
                                        ev.ledger.map_or("Unknown".to_string(), |v| v.to_string())
                                    );
                                    println!("Topics: {:?}", ev.topics);
                                    println!("Value: {}", ev.value.as_deref().unwrap_or("N/A"));

                                    // Decode with ABI using the real topics/value
                                    let topic_scvals: Vec<stellar_xdr::ScVal> = ev
                                        .topics
                                        .iter()
                                        .filter_map(|t| sdkt_xdr::scval_from_base64(t))
                                        .collect();
                                    let data_scvals: Vec<stellar_xdr::ScVal> = ev
                                        .value
                                        .as_deref()
                                        .and_then(sdkt_xdr::scval_from_base64)
                                        .into_iter()
                                        .collect();
                                    let decoded =
                                        decode_event_topics(&spec, &topic_scvals, &data_scvals);
                                    for d in decoded {
                                        println!("  Decoded: {}", d.label);
                                        if let Some(fields) = d.fields {
                                            for (k, v) in fields {
                                                println!("    {}: {}", k, v);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        // Original raw output
                        if fmt == OutputFormat::Json {
                            let json_str = serde_json::to_string(&events)?;
                            println!("{}", json_str);
                        } else {
                            println!("Contract Events:");
                            if events.is_empty() {
                                println!("No events found.");
                            } else {
                                for (i, ev) in events.iter().enumerate() {
                                    println!("\nEvent #{}", i + 1);
                                    println!(
                                        "Ledger: {}",
                                        ev.ledger.map_or("Unknown".to_string(), |v| v.to_string())
                                    );
                                    println!("Topics: {:?}", ev.topics);
                                    println!("Value: {}", ev.value.as_deref().unwrap_or("N/A"));
                                }
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error fetching events: {}", e);
                    process::exit(1);
                }
            }
        }
        Commands::Account {
            address,
            format,
            net,
        } => {
            let fmt = parse_format_str(&format);
            let client = resolve_rpc_client(
                net.rpc_url.clone(),
                net.network_passphrase.clone(),
                net.network_profile.clone(),
            );

            match inspect_account(&client, &address).await {
                Ok(account) => {
                    if fmt == OutputFormat::Json {
                        let json_str = serde_json::to_string(&account)?;
                        println!("{}", json_str);
                    } else {
                        println!("Account:");
                        println!();
                        println!("Address: {}", account.address);
                        println!(
                            "Sequence: {}",
                            account.sequence.as_deref().unwrap_or("Unknown")
                        );
                        println!("\nBalances:");
                        if account.balances.is_empty() {
                            println!("  (none)");
                        } else {
                            for b in account.balances {
                                println!("  Asset: {}", b.asset_type);
                                println!("  Balance: {}", b.balance);
                            }
                        }
                        println!("\nSigners:");
                        if account.signers.is_empty() {
                            println!("  (none)");
                        } else {
                            for s in account.signers {
                                println!("  Public Key: {}", s.public_key);
                                println!(
                                    "  Weight: {}",
                                    s.weight.map_or("Unknown".to_string(), |w| w.to_string())
                                );
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error inspecting account: {}", e);
                    process::exit(1);
                }
            }
        }
        Commands::Fee { action, net } => match action {
            FeeAction::Estimate {
                network,
                base_fees,
                rpc,
                format,
            } => {
                let fmt = parse_format_str(&format);
                let network_kind = match network.parse::<NetworkKind>() {
                    Ok(nk) => nk,
                    Err(e) => {
                        eprintln!("Invalid network: {}", e);
                        std::process::exit(1);
                    }
                };
                let fee_config = FeeConfig {
                    network: network_kind,
                    multiplier_override: None,
                };

                let (stroops, xlm) = if rpc {
                    let client = resolve_rpc_client(
                        net.rpc_url.clone(),
                        net.network_passphrase.clone(),
                        net.network_profile.clone(),
                    );
                    match estimate_dynamic_fee(&client, fee_config).await {
                        Ok(result) => result,
                        Err(e) => {
                            eprintln!("Error fetching RPC fee stats: {}", e);
                            std::process::exit(1);
                        }
                    }
                } else {
                    let base_fees_str = match base_fees {
                        Some(bf) => bf,
                        None => {
                            eprintln!("--base-fees is required when not using --rpc");
                            std::process::exit(1);
                        }
                    };
                    let samples: Result<Vec<LedgerFeeSample>, _> = base_fees_str
                        .split(',')
                        .map(|s| {
                            s.trim()
                                .parse::<u32>()
                                .map(|base_fee| LedgerFeeSample { base_fee })
                        })
                        .collect();
                    let samples = match samples {
                        Ok(s) => s,
                        Err(_) => {
                            eprintln!("Invalid base_fees. Must be comma-separated integers.");
                            std::process::exit(1);
                        }
                    };
                    let estimator = FeeEstimator::new(fee_config);
                    match estimator.estimate(&samples) {
                        Ok(result) => result,
                        Err(e) => {
                            eprintln!("Error estimating fee: {}", e);
                            std::process::exit(1);
                        }
                    }
                };

                if fmt == OutputFormat::Json {
                    println!("{{\"stroops\":{},\"xlm\":\"{}\"}}", stroops, xlm);
                } else {
                    println!("Fee Estimate ({}):", network_kind);
                    if rpc {
                        println!("Source: RPC");
                    }
                    println!("Stroops: {}", stroops);
                    println!("XLM: {}", xlm);
                }
            }
        },
        Commands::Diff {
            old_wasm,
            new_wasm,
            format,
            upgrade_safety,
        } => {
            let fmt = parse_format_str(&format);
            let old_bytes = fs::read(&old_wasm)
                .map_err(|e| format!("Failed to read OLD WASM '{}': {}", old_wasm, e))?;
            let new_bytes = fs::read(&new_wasm)
                .map_err(|e| format!("Failed to read NEW WASM '{}': {}", new_wasm, e))?;

            match sdkt_wasm::diff_wasm(&old_bytes, &new_bytes) {
                Ok(report) => {
                    if upgrade_safety {
                        // Upgrade-safety verdict mode: reuse the diff, classify.
                        let verdict = sdkt_wasm::UpgradeVerdict::from_diff(&report);
                        if fmt == OutputFormat::Json {
                            println!("{}", serde_json::to_string(&verdict)?);
                        } else {
                            print_upgrade_verdict(&verdict);
                        }
                        return Ok(());
                    }
                    if fmt == OutputFormat::Json {
                        println!("{}", serde_json::to_string(&report)?);
                    } else {
                        println!("Contract WASM Diff");
                        println!(
                            "  OLD: {} ({} bytes)",
                            report.old.hash, report.old.size_bytes
                        );
                        println!(
                            "  NEW: {} ({} bytes)",
                            report.new.hash, report.new.size_bytes
                        );
                        println!();
                        if report.is_identical() {
                            println!("No ABI differences detected.");
                        } else {
                            if !report.added_functions.is_empty() {
                                println!("Added functions ({}):", report.added_functions.len());
                                for f in &report.added_functions {
                                    println!("  + {} ({})", f.name, sig_string(f));
                                }
                            }
                            if !report.removed_functions.is_empty() {
                                println!("Removed functions ({}):", report.removed_functions.len());
                                for f in &report.removed_functions {
                                    println!("  - {} ({})", f.name, sig_string(f));
                                }
                            }
                            if !report.changed_functions.is_empty() {
                                println!(
                                    "Changed signatures ({}):",
                                    report.changed_functions.len()
                                );
                                for c in &report.changed_functions {
                                    println!("  ~ {} :", c.name);
                                    println!("      old: {}", sig_string(&c.old));
                                    println!("      new: {}", sig_string(&c.new));
                                }
                            }
                            if !report.added_events.is_empty() {
                                println!("Added events ({}):", report.added_events.len());
                                for e in &report.added_events {
                                    println!("  + {}", e);
                                }
                            }
                            if !report.removed_events.is_empty() {
                                println!("Removed events ({}):", report.removed_events.len());
                                for e in &report.removed_events {
                                    println!("  - {}", e);
                                }
                            }
                            if !report.added_types.is_empty() {
                                println!("Added types ({}):", report.added_types.len());
                                for t in &report.added_types {
                                    println!("  + {}", t);
                                }
                            }
                            if !report.removed_types.is_empty() {
                                println!("Removed types ({}):", report.removed_types.len());
                                for t in &report.removed_types {
                                    println!("  - {}", t);
                                }
                            }
                        }
                        println!();
                        println!("Total changes: {}", report.total_changes());
                    }
                }
                Err(e) => {
                    eprintln!("Error diffing WASM: {}", e);
                    process::exit(1);
                }
            }
        }
        Commands::Audit {
            path,
            format,
            disable,
            rules,
        } => {
            let fmt = parse_format_str(&format);

            // Validate/resolve each --rules entry. A bare filesystem path keeps
            // the M17/M18/M19 behavior unchanged. A plugin *id* (not an existing
            // file) is resolved through the local store (M40) to its artifact
            // path; if the store has it, we use that path for the existing loader.
            for r in &rules {
                let resolved = sdkt_audit::plugin_store::resolve(r)
                    .unwrap_or_else(|| std::path::PathBuf::from(r));
                if !resolved.exists() {
                    eprintln!("Error: rule path '{}' does not exist", r);
                    process::exit(1);
                }
            }

            let src = fs::read_to_string(&path)
                .map_err(|e| format!("Failed to read source '{}': {}", path, e))?;

            for r in &rules {
                // Re-resolve: a plugin id maps to its stored artifact path; a raw
                // path is used verbatim. This preserves the M17–M19 loader flow.
                let resolved = sdkt_audit::plugin_store::resolve(r)
                    .unwrap_or_else(|| std::path::PathBuf::from(r));
                let path_r = resolved.as_path();

                // Directories pass through as M17 no-ops (validated for existence above).
                if path_r.is_dir() {
                    continue;
                }

                let ext = path_r
                    .extension()
                    .and_then(|e| e.to_str())
                    .map(|e| e.to_ascii_lowercase())
                    .unwrap_or_default();

                match ext.as_str() {
                    "so" | "dylib" | "dll" => {
                        #[cfg(feature = "plugins")]
                        {
                            if let Err(e) = sdkt_audit::load_and_register(path_r, &src) {
                                eprintln!("Error loading native plugin '{}': {}", r, e);
                                process::exit(1);
                            }
                        }
                        #[cfg(not(feature = "plugins"))]
                        {
                            eprintln!(
                                "Error: '{}' is a native plugin artifact but this build was compiled \
                                 without the `plugins` feature. Rebuild with --features plugins.",
                                r
                            );
                            process::exit(1);
                        }
                    }
                    "wasm" => {
                        #[cfg(feature = "wasm-plugins")]
                        {
                            if let Err(e) = sdkt_audit::load_and_register_wasm(path_r, &src) {
                                eprintln!("Error loading WASM plugin '{}': {}", r, e);
                                process::exit(1);
                            }
                        }
                        #[cfg(not(feature = "wasm-plugins"))]
                        {
                            eprintln!(
                                "Error: '{}' is a WASM plugin artifact but this build was compiled \
                                 without the `wasm-plugins` feature. Rebuild with --features wasm-plugins.",
                                r
                            );
                            process::exit(1);
                        }
                    }
                    "rs" => {
                        // M17 semantic: source files passed in --rules are existence-validated
                        // above but not loaded at runtime (built-in rules register themselves).
                    }
                    _ => {
                        eprintln!(
                            "Error: Unsupported plugin format: {}\n\nSupported plugin formats:\n  .so\n  .dll\n  .dylib\n  .wasm",
                            r
                        );
                        process::exit(1);
                    }
                }
            }

            // When the `plugins` feature is enabled, link the reference example
            // rule into the registry. Off by default → M16-identical behavior.
            #[cfg(feature = "plugins")]
            sdkt_audit_example_rule::register();

            let disabled_refs: Vec<&str> = disable.iter().map(String::as_str).collect();
            match sdkt_audit::audit_source_with(&src, &disabled_refs) {
                Ok(report) => {
                    if fmt == OutputFormat::Json {
                        println!("{}", serde_json::to_string(&report)?);
                    } else {
                        println!("Static Analysis Report: {}", path);
                        println!(
                            "Severity: {} critical, {} warning, {} info ({} total)",
                            report.summary.critical,
                            report.summary.warning,
                            report.summary.info,
                            report.summary.total
                        );
                        if report.is_clean() {
                            println!("No issues found.");
                        } else {
                            println!();
                            for f in &report.findings {
                                let loc = f
                                    .location
                                    .as_ref()
                                    .map(|l| format!(" [{}]", l))
                                    .unwrap_or_default();
                                println!("  [{}] {} {}: {}", f.severity, f.rule_id, loc, f.message);
                            }
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error auditing source: {}", e);
                    process::exit(1);
                }
            }
        }
        Commands::Wasm { action, net } => match action {
            WasmAction::Inspect { file, format } => {
                let fmt = parse_format_str(&format);

                let wasm_bytes = fs::read(&file).unwrap_or_else(|e| {
                    eprintln!("Error reading WASM file {}: {}", file, e);
                    process::exit(1);
                });

                let metadata = sdkt_wasm::parse_metadata(&wasm_bytes).unwrap_or_else(|e| {
                    eprintln!("Error parsing WASM metadata: {}", e);
                    process::exit(1);
                });

                // Attempt to parse contract spec, but it's optional
                let spec = parse_contract_spec(&wasm_bytes).ok();

                if fmt == OutputFormat::Json {
                    let json = serde_json::json!({
                        "file": file,
                        "metadata": metadata,
                        "spec": spec,
                    });
                    println!("{}", serde_json::to_string_pretty(&json).unwrap());
                } else {
                    println!("WASM Inspection Report: {}", file);
                    println!("========================================");
                    println!("Size: {} bytes", metadata.size_bytes);
                    println!("SHA-256 Hash: {}", metadata.hash);
                    println!("Version: {}", metadata.version);

                    println!("\nCustom Sections ({}):", metadata.custom_sections.len());
                    for section in &metadata.custom_sections {
                        println!("  - {}", section);
                    }

                    println!("\nExported Functions ({}):", metadata.exports.len());
                    for export in &metadata.exports {
                        println!("  - {} [{}]", export.name, export.kind);
                    }

                    if let Some(spec) = spec {
                        println!("\nContract Spec Available: Yes");
                        println!("  Functions: {}", spec.functions.len());
                        for f in &spec.functions {
                            println!(
                                "    - fn {}({}) -> {}",
                                f.name,
                                f.parameters.len(),
                                f.outputs.len()
                            );
                        }
                        println!("  Custom Types: {}", spec.custom_types.len());
                        println!("  Events: {}", spec.events.len());
                    } else {
                        println!("\nContract Spec Available: No");
                    }
                }
            }
            WasmAction::Metadata {
                contract,
                network,
                refresh,
                format,
            } => {
                let fmt = parse_format_str(&format);
                let client = resolve_rpc_client(
                    net.rpc_url.clone(),
                    net.network_passphrase.clone(),
                    net.network_profile.clone(),
                );

                // Initialize cache
                let cache = match WasmCache::new() {
                    Ok(c) => c,
                    Err(e) => {
                        eprintln!("Warning: could not initialize cache: {}", e);
                        WasmCache::with_dir(std::env::temp_dir().join("sdkt-fallback-cache"))
                    }
                };

                // First, inspect the contract to get its WASM hash
                let inspection = match inspect_contract(&client, &contract).await {
                    Ok(ins) => ins,
                    Err(e) => {
                        eprintln!("Error inspecting contract {}: {}", contract, e);
                        process::exit(1);
                    }
                };

                let wasm_hash = &inspection.wasm_hash;

                // Check cache if not forcing refresh
                let mut metadata = None;
                let mut cache_status = "Miss";

                if !refresh {
                    match cache.get(&network, wasm_hash) {
                        Ok(Some(m)) => {
                            metadata = Some(m);
                            cache_status = "Hit";
                        }
                        Ok(None) => {} // normal miss
                        Err(e) => {
                            eprintln!("Warning: Cache read error: {}", e);
                        }
                    }
                }

                // If no metadata from cache, fetch it
                let meta = if let Some(m) = metadata {
                    m
                } else {
                    let fetched = match get_wasm_metadata(&client, wasm_hash).await {
                        Ok(m) => m,
                        Err(e) => {
                            eprintln!("Error fetching WASM metadata: {}", e);
                            process::exit(1);
                        }
                    };

                    // Put into cache for future
                    if let Err(e) = cache.put(&network, &fetched, &[]) {
                        eprintln!("Warning: Failed to write to cache: {}", e);
                    }

                    fetched
                };

                // Enrich with storage/TTL/storage-key posture using the existing
                // StorageAnalyzer (available in the CLI layer). This populates the
                // remaining ContractInspection fields without adding a circular
                // sdkt-rpc -> sdkt-storage dependency.
                let mut inspection = inspection;
                if let Ok(report) = StorageAnalyzer::new(client.clone())
                    .inspect_contract_storage(&contract)
                    .await
                {
                    inspection.storage_summary = StorageSummary {
                        instance_entries: report.instance_entries,
                        persistent_entries: report.persistent_entries,
                        temporary_entries: report.temporary_entries,
                    };
                    inspection.ttl_info = report.ttl_summary.clone().map(|t| TtlInfoSummary {
                        minimum_ttl: t.minimum_ttl,
                        maximum_ttl: t.maximum_ttl,
                        average_ttl: t.average_ttl,
                        expiring_entries_count: t.expiring_entries_count,
                        estimated_rent_cost: t.estimated_rent_cost,
                    });
                    inspection.storage_keys = report
                        .entries
                        .iter()
                        .map(|e| StorageKeyInfo {
                            key: e.key.clone(),
                            key_type: format!("{:?}", e.class),
                            permissions: "read_write".to_string(),
                        })
                        .collect();
                }

                if fmt == OutputFormat::Json {
                    let json_str = serde_json::to_string(&inspection)?;
                    println!("{}", json_str);
                } else {
                    println!("WASM Metadata:");
                    println!("Contract ID: {}", contract);
                    println!("Network: {}", network);
                    println!("WASM Hash: {}", inspection.wasm_hash);
                    println!("Cache Status: {}", cache_status);
                    let size = inspection.wasm_size.unwrap_or(meta.size_bytes);
                    println!("Size: {} bytes", size);
                    println!("Exports: {}", meta.exports.len());
                    println!("Imports: {}", meta.imports.len());
                    println!("Custom Sections: {}", meta.custom_sections.len());
                    if let Some(abi) = &inspection.abi {
                        println!(
                            "Functions ({}): {}",
                            abi.functions.len(),
                            abi.functions.join(", ")
                        );
                        println!("Events ({}): {}", abi.events.len(), abi.events.join(", "));
                        println!("Types ({}): {}", abi.types.len(), abi.types.join(", "));
                    } else {
                        println!(
                            "ABI: (unavailable — on-chain WASM not fetched or no contractspecv0)"
                        );
                    }
                    let s = &inspection.storage_summary;
                    println!(
                        "Storage: instance={} persistent={} temporary={}",
                        s.instance_entries, s.persistent_entries, s.temporary_entries
                    );
                    if let Some(ttl) = &inspection.ttl_info {
                        println!(
                            "TTL: min={} max={} avg={} expiring={}",
                            ttl.minimum_ttl,
                            ttl.maximum_ttl,
                            ttl.average_ttl,
                            ttl.expiring_entries_count
                        );
                    }
                }
            }
            WasmAction::Cache { action } => {
                // Initialize cache; fall back to a temp dir if the OS cache
                // directory cannot be resolved (e.g. fresh CI runner).
                let cache = match WasmCache::new() {
                    Ok(c) => c,
                    Err(e) => {
                        eprintln!("Warning: could not initialize cache: {}", e);
                        WasmCache::with_dir(std::env::temp_dir().join("sdkt-fallback-cache"))
                    }
                };

                match action {
                    CacheAction::Info { network, format } => {
                        let fmt = parse_format_str(&format);
                        match cache.cache_info(&network) {
                            Ok(info) => {
                                if fmt == OutputFormat::Json {
                                    // In a real app we'd derive Serialize for CacheInfo,
                                    // but we can manually output JSON here or derive it in sdkt-storage
                                    println!(
                                        "{{\"network\":\"{}\",\"entry_count\":{},\"total_metadata_size_bytes\":{},\"total_wasm_size_bytes\":{}}}",
                                        info.network,
                                        info.entry_count,
                                        info.total_metadata_size_bytes,
                                        info.total_wasm_size_bytes
                                    );
                                } else {
                                    println!("Cache Info for Network '{}':", info.network);
                                    println!("Entries: {}", info.entry_count);
                                    println!(
                                        "Metadata Size: {} bytes",
                                        info.total_metadata_size_bytes
                                    );
                                    println!("WASM Size: {} bytes", info.total_wasm_size_bytes);
                                }
                            }
                            Err(e) => {
                                eprintln!("Error getting cache info: {}", e);
                                process::exit(1);
                            }
                        }
                    }
                    CacheAction::Remove { hash, network } => match cache.remove(&network, &hash) {
                        Ok(_) => {
                            println!("Removed {} from {} cache.", hash, network);
                        }
                        Err(e) => {
                            eprintln!("Error removing cache entry: {}", e);
                            process::exit(1);
                        }
                    },
                    CacheAction::Clear { network } => match cache.clear(&network) {
                        Ok(_) => {
                            println!("Cleared all cache entries for {}.", network);
                        }
                        Err(e) => {
                            eprintln!("Error clearing cache: {}", e);
                            process::exit(1);
                        }
                    },
                }
            }
        },
        Commands::Identity { action } => {
            use sdkt_storage::IdentityStore;
            let store = IdentityStore::new()?;
            match action {
                IdentityAction::Generate { name } => {
                    let identity = store.generate(&name)?;
                    println!("Identity '{}' generated successfully.", identity.name);
                    println!("Public Key: {}", identity.public_key);
                }
                IdentityAction::Import { name, secret } => {
                    let identity = store.import(&name, &secret)?;
                    println!("Identity '{}' imported successfully.", identity.name);
                    println!("Public Key: {}", identity.public_key);
                }
                IdentityAction::List => {
                    let mut list = store.list()?;
                    list.sort_by(|a, b| a.name.cmp(&b.name));
                    let default_id = store.get_default().ok();

                    if list.is_empty() {
                        println!("No identities found.");
                    } else {
                        println!("Identities:");
                        for id in list {
                            let is_def = default_id.as_ref().is_some_and(|d| d.name == id.name);
                            println!(
                                "  {} {} ({})",
                                if is_def { "*" } else { " " },
                                id.name,
                                id.public_key
                            );
                        }
                    }
                }
                IdentityAction::Show { name } => {
                    let identity = store.get(&name)?;
                    println!("Identity: {}", identity.name);
                    println!("Public Key: {}", identity.public_key);
                }
                IdentityAction::Delete { name } => {
                    store.remove(&name)?;
                    println!("Identity '{}' removed.", name);
                }
                IdentityAction::Default { name } => {
                    store.set_default(&name)?;
                    println!("Identity '{}' set as default.", name);
                }
            }
        }
        Commands::Network { action } => {
            use sdkt_storage::{NetworkProfile, NetworkStore};
            let store = NetworkStore::new()?;
            match action {
                NetworkAction::Add {
                    name,
                    rpc_url,
                    passphrase,
                    friendbot,
                    description,
                    format,
                } => {
                    let fmt = parse_format_str(&format);
                    let mut profile = NetworkProfile::new(name.clone(), rpc_url, passphrase);
                    if let Some(url) = friendbot {
                        profile = profile.with_friendbot(url);
                    }
                    if let Some(desc) = description {
                        profile = profile.with_description(desc);
                    }
                    store.add(profile)?;
                    if fmt == OutputFormat::Json {
                        println!("{}", serde_json::to_string(&store.get(&name)?)?);
                    } else {
                        println!("Network profile '{}' saved.", name);
                    }
                }
                NetworkAction::List { format } => {
                    let fmt = parse_format_str(&format);
                    let profiles = store.list()?;
                    if fmt == OutputFormat::Json {
                        println!("{}", serde_json::to_string(&profiles)?);
                    } else if profiles.is_empty() {
                        println!("No network profiles found.");
                    } else {
                        println!("Network profiles:");
                        for p in profiles {
                            println!("  {} ({})", p.name, p.rpc_url);
                        }
                    }
                }
                NetworkAction::Show { name, format } => {
                    let fmt = parse_format_str(&format);
                    let profile = store.get(&name)?;
                    if fmt == OutputFormat::Json {
                        println!("{}", serde_json::to_string(&profile)?);
                    } else {
                        println!("Network profile: {}", profile.name);
                        println!("  RPC URL:         {}", profile.rpc_url);
                        println!("  Passphrase:      {}", profile.network_passphrase);
                        if let Some(url) = &profile.friendbot_url {
                            println!("  Friendbot URL:   {}", url);
                        }
                        if let Some(desc) = &profile.description {
                            println!("  Description:     {}", desc);
                        }
                    }
                }
                NetworkAction::Remove { name, format } => {
                    let fmt = parse_format_str(&format);
                    store.remove(&name)?;
                    if fmt == OutputFormat::Json {
                        let json = serde_json::json!({
                            "status": "removed",
                            "name": name,
                        });
                        println!("{}", serde_json::to_string(&json)?);
                    } else {
                        println!("Network profile '{}' removed.", name);
                    }
                }
            }
        }
        Commands::Init {
            name,
            minimal,
            force,
            format,
        } => {
            use sdkt_core::scaffold::{generate_project, ScaffoldConfig};

            let fmt = parse_format_str(&format);
            let scaffold_cfg = ScaffoldConfig {
                name: name.clone(),
                minimal,
                force,
            };

            match generate_project(&scaffold_cfg) {
                Ok(result) => {
                    if fmt == OutputFormat::Json {
                        let json = serde_json::json!({
                            "status": "created",
                            "project": name,
                            "files": result.files_created,
                        });
                        println!("{}", serde_json::to_string(&json)?);
                    } else {
                        println!("✓ Project '{}' created", name);
                        for f in &result.files_created {
                            println!("  ✓ {}", f);
                        }
                        println!("✓ Ready to build");
                    }
                }
                Err(e) => {
                    if fmt == OutputFormat::Json {
                        let json = serde_json::json!({
                            "status": "error",
                            "message": e.to_string(),
                        });
                        println!("{}", serde_json::to_string(&json)?);
                    } else {
                        eprintln!("Error: {}", e);
                    }
                    process::exit(1);
                }
            }
        }
        Commands::Deploy {
            wasm,
            salt,
            format,
            deny_breaking,
            old_wasm,
            net,
        } => {
            let fmt = parse_format_str(&format);

            // Optional deploy guard: abort on a backwards-incompatible upgrade.
            if deny_breaking {
                let baseline = old_wasm.ok_or_else(|| {
                    "The --deny-breaking flag requires --old-wasm <deployed.wasm> (the currently deployed contract)".to_string()
                })?;
                let old_bytes = fs::read(&baseline)
                    .map_err(|e| format!("Failed to read OLD WASM '{}': {}", baseline, e))?;
                let new_bytes = fs::read(&wasm)
                    .map_err(|e| format!("Failed to read NEW WASM '{}': {}", wasm, e))?;
                match sdkt_wasm::upgrade_safety_wasm(&old_bytes, &new_bytes) {
                    Ok(verdict) => {
                        if !verdict.compatible {
                            eprintln!("Deployment aborted: upgrade is NOT backwards-compatible.");
                            print_upgrade_verdict(&verdict);
                            process::exit(1);
                        }
                        eprintln!(
                            "Upgrade-safety check passed: deployment is backwards-compatible."
                        );
                    }
                    Err(e) => {
                        eprintln!("Upgrade-safety check failed to compute verdict: {}", e);
                        process::exit(1);
                    }
                }
            }

            use sdkt_rpc::deploy_contract;
            let client = resolve_rpc_client_mutating(
                net.rpc_url.clone(),
                net.network_passphrase.clone(),
                net.network_profile.clone(),
            );
            // For CLI demo, read wasm file; if file missing, use empty bytes
            let wasm_bytes = fs::read(&wasm).unwrap_or_default();
            match deploy_contract(&client, &wasm_bytes, &salt).await {
                Ok(res) => {
                    if fmt == OutputFormat::Json {
                        println!("{}", sdkt_rpc::format_json(&res));
                    } else {
                        println!("{}", sdkt_rpc::format_pretty(&res));
                    }
                }
                Err(e) => {
                    eprintln!("Deployment error: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::Build => {
            let config = load_config();
            match sdkt_core::build::build_workspace(&config) {
                Ok(results) => {
                    println!("✓ Workspace built successfully");
                    for res in results {
                        println!("  ✓ {} -> {}", res.alias, res.wasm_artifact.display());
                    }
                }
                Err(e) => {
                    eprintln!("Error building workspace: {}", e);
                    std::process::exit(1);
                }
            }
        }
        Commands::Lock { action } => match action {
            LockCommand::Generate { format } => {
                let fmt = parse_format_str(&format);
                let config = load_config();
                match sdkt_core::lock::generate_lock(Path::new("."), &config) {
                    Ok(lock) => match sdkt_core::lock::write_lock(Path::new("."), &lock) {
                        Ok(path) => {
                            if fmt != OutputFormat::Json {
                                println!("✓ Wrote {}", path.display());
                                println!("{}", sdkt_core::lock::lock_to_toml(&lock).unwrap());
                            } else {
                                println!(
                                    "{}",
                                    serde_json::to_string_pretty(&serde_json::json!({
                                        "lock_file": path.display().to_string(),
                                        "version": lock.version,
                                        "deploy_order": lock.deploy_order,
                                        "contracts": lock.contracts,
                                    }))
                                    .unwrap()
                                );
                            }
                        }
                        Err(e) => {
                            eprintln!("Error generating lock: {}", e);
                            std::process::exit(1);
                        }
                    },
                    Err(e) => {
                        eprintln!("Error generating lock: {}", e);
                        std::process::exit(1);
                    }
                }
            }
            LockCommand::Verify { format } => {
                let fmt = parse_format_str(&format);
                let config = load_config();
                let base = Path::new(".");
                let report = sdkt_core::lock::verify_lock(base, &config);
                let dep_report = sdkt_core::lock::verify_dependencies(base, &config);
                if fmt != OutputFormat::Json {
                    // --- Contract artifact verification (existing behavior) ---
                    if report.present {
                        if report.consistent {
                            println!("✓ sdkt.lock is consistent with current artifacts");
                        } else {
                            if !report.mismatched.is_empty() {
                                println!(
                                    "⚠ sdkt.lock drift — artifact hash changed for: {}",
                                    report.mismatched.join(", ")
                                );
                            }
                            if !report.missing_in_lock.is_empty() {
                                println!(
                                    "⚠ sdkt.lock missing entries for: {}",
                                    report.missing_in_lock.join(", ")
                                );
                            }
                        }
                    } else {
                        println!("⚠ No sdkt.lock found; run `sdkt build` to generate one");
                    }

                    // --- Package dependency verification (M35.2) ---
                    if dep_report.present {
                        if dep_report.consistent {
                            println!("✓ package dependencies verified");
                        } else {
                            for m in &dep_report.mismatches {
                                println!(
                                    "⚠ dependency '{}' drift ({:?}): {}",
                                    m.name, m.kind, m.detail
                                );
                            }
                        }
                    } else if !config.dependencies.is_empty() {
                        println!("⚠ No sdkt.lock present; package dependencies unverified");
                        for m in &dep_report.mismatches {
                            println!(
                                "⚠ dependency '{}' not locked ({:?}): {}",
                                m.name, m.kind, m.detail
                            );
                        }
                    }
                } else {
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&serde_json::json!({
                            "present": report.present,
                            "consistent": report.consistent,
                            "mismatched": report.mismatched,
                            "missing_in_lock": report.missing_in_lock,
                            "dependencies": {
                                "present": dep_report.present,
                                "consistent": dep_report.consistent,
                                "checked": dep_report.checked,
                                "mismatches": dep_report.mismatches.iter().map(|m| serde_json::json!({
                                    "name": m.name,
                                    "kind": format!("{:?}", m.kind),
                                    "detail": m.detail,
                                })).collect::<Vec<_>>(),
                            },
                        }))
                        .unwrap()
                    );
                }
            }
            LockCommand::Show { format } => {
                let fmt = parse_format_str(&format);
                match sdkt_core::lock::read_lock(Path::new(".")) {
                    Ok(lock) => {
                        if fmt != OutputFormat::Json {
                            println!("{}", sdkt_core::lock::lock_to_toml(&lock).unwrap());
                        } else {
                            println!(
                                "{}",
                                serde_json::to_string_pretty(&serde_json::json!({
                                    "version": lock.version,
                                    "deploy_order": lock.deploy_order,
                                    "contracts": lock.contracts,
                                }))
                                .unwrap()
                            );
                        }
                    }
                    Err(e) => {
                        eprintln!("Error reading lock: {}", e);
                        std::process::exit(1);
                    }
                }
            }
        },
        Commands::Package { action } => match action {
            PackageCommand::Validate { format } => {
                let fmt = parse_format_str(&format);
                let config = load_config();
                let base = Path::new(".");
                let result = sdkt_core::package::validate_manifest(base, &config);
                if let Some(pkg) = &config.package {
                    if fmt != OutputFormat::Json {
                        println!("Package: {}", pkg.name.as_deref().unwrap_or("(unnamed)"));
                        println!("Version: {}", pkg.version.as_deref().unwrap_or("(none)"));
                        if let Some(d) = &pkg.description {
                            println!("Description: {}", d);
                        }
                        println!("Dependencies: {}", config.dependencies.len());
                    }
                } else if fmt != OutputFormat::Json {
                    println!("No [package] section present.");
                }
                match result {
                    Ok(()) => {
                        if fmt != OutputFormat::Json {
                            println!("Package manifest is valid");
                        } else {
                            println!(
                                "{}",
                                serde_json::to_string_pretty(&serde_json::json!({ "valid": true }))
                                    .unwrap()
                            );
                        }
                    }
                    Err(e) => {
                        if fmt != OutputFormat::Json {
                            eprintln!("Package validation failed: {}", e);
                        } else {
                            println!(
                                "{}",
                                serde_json::to_string_pretty(
                                    &serde_json::json!({ "valid": false, "error": e.to_string() })
                                )
                                .unwrap()
                            );
                        }
                        std::process::exit(1);
                    }
                }
            }
            PackageCommand::Fetch { format, force } => {
                let fmt = parse_format_str(&format);
                let config = load_config();
                // Validation first, so a malformed manifest never triggers a fetch.
                let base = Path::new(".");
                if let Err(e) = sdkt_core::package::validate_manifest(base, &config) {
                    eprintln!("Package validation failed: {}", e);
                    std::process::exit(1);
                }

                // Deterministic cache at `.sdkt-cache` (workspace-local).
                // Use an absolute path so `git clone <url> <checkout>` is not
                // resolved relative to the fetcher's working dir (which would
                // double the path). Fall back to the relative form only if the
                // current dir cannot be resolved.
                let cache = std::env::current_dir()
                    .map(|c| c.join(".sdkt-cache"))
                    .unwrap_or_else(|_| std::path::PathBuf::from(".sdkt-cache"));
                let fetcher = sdkt_core::fetch::GitFetcher::new(cache);

                if config.dependencies.is_empty() {
                    if fmt != OutputFormat::Json {
                        println!("No dependencies to fetch.");
                    }
                    return Ok(());
                }

                let mut fetched = Vec::new();
                for (name, dep) in &config.dependencies {
                    let outcome = if dep.git.is_some() {
                        fetcher.fetch(name, dep, force)
                    } else {
                        sdkt_core::fetch::PathResolver.fetch(name, dep, force)
                    };
                    match outcome {
                        Ok(o) => {
                            fetched.push(o);
                        }
                        Err(e) => {
                            eprintln!("Failed to fetch '{}': {}", name, e);
                            std::process::exit(1);
                        }
                    }
                }

                // M35.2 — record resolved dependency state into sdkt.lock so
                // `sdkt lock verify` can enforce reproducibility offline. We
                // update the lock in place (preserving contract artifacts) when
                // one already exists; otherwise we generate a fresh lock.
                {
                    use sdkt_core::lock::LockFile;
                    let mut lock = sdkt_core::lock::read_lock(base).unwrap_or_else(|_| LockFile {
                        version: sdkt_core::lock::LOCK_VERSION,
                        deploy_order: vec![],
                        contracts: vec![],
                        dependencies: vec![],
                    });
                    // Single source of truth shared with `sdkt package update`.
                    lock.dependencies =
                        sdkt_core::lock::lock_dependencies_resolved(base, &config, &fetched);
                    if let Err(e) = sdkt_core::lock::write_lock(base, &lock) {
                        eprintln!("Warning: could not write sdkt.lock: {}", e);
                    }
                }

                if fmt != OutputFormat::Json {
                    for o in &fetched {
                        let rev = if o.resolved_rev.is_empty() {
                            "(local)".to_string()
                        } else {
                            o.resolved_rev.chars().take(12).collect()
                        };
                        println!(
                            "Fetched '{}' -> {} @ {}",
                            o.name,
                            o.local_path.display(),
                            rev
                        );
                    }
                    println!("Fetched {} dependenc(y/ies).", fetched.len());
                } else {
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&serde_json::json!({
                            "fetched": fetched
                                .iter()
                                .map(|o| serde_json::json!({
                                    "name": o.name,
                                    "local_path": o.local_path.display().to_string(),
                                    "resolved_rev": o.resolved_rev,
                                    "already_present": o.already_present,
                                }))
                                .collect::<Vec<_>>()
                        }))
                        .unwrap()
                    );
                }
            }
            PackageCommand::Update {
                format,
                check,
                dry_run,
            } => {
                let fmt = parse_format_str(&format);
                let config = load_config();
                let base = Path::new(".");

                // Build the update plan (read-only: resolves available commits via
                // git ls-remote; never fetches, never writes the lock).
                let plan = match sdkt_core::sync::plan_updates(base, &config) {
                    Ok(p) => p,
                    Err(e) => {
                        eprintln!("Error: {}", e);
                        std::process::exit(1);
                    }
                };

                if fmt == OutputFormat::Json {
                    println!(
                        "{}",
                        serde_json::to_string_pretty(&serde_json::json!({
                            "checked": plan.checked,
                            "updated": plan.updated,
                            "unchanged": plan.unchanged,
                            "changes": plan.changes.iter().map(|c| serde_json::json!({
                                "name": c.name,
                                "source": c.source,
                                "status": format!("{:?}", c.status),
                                "old_commit": c.old_commit,
                                "new_commit": c.new_commit,
                                "detail": c.detail,
                            })).collect::<Vec<_>>(),
                        }))
                        .unwrap()
                    );
                } else if check {
                    // --check: report available updates only; exit 0 (errors are
                    // listed, but a non-zero exit is reserved for hard failures
                    // which already surfaced above via process::exit).
                    println!("Checking dependencies...");
                    let mut available = 0;
                    for c in &plan.changes {
                        match c.status {
                            sdkt_core::sync::UpdateStatus::Updated => {
                                available += 1;
                                println!("↑ {} has an update", c.name);
                            }
                            sdkt_core::sync::UpdateStatus::Pinned => {
                                println!("✓ {} pinned (rev)", c.name);
                            }
                            sdkt_core::sync::UpdateStatus::Constraint => {
                                println!("⚠ {} constraint unsatisfied", c.name);
                            }
                            sdkt_core::sync::UpdateStatus::Error => {
                                println!("✗ {} error: {}", c.name, c.detail);
                            }
                            _ => {
                                println!("✓ {} unchanged", c.name);
                            }
                        }
                    }
                    if available > 0 {
                        println!(
                            "{} update(s) available. Run `sdkt package update`.",
                            available
                        );
                    } else {
                        println!("All dependencies up to date.");
                    }
                } else if dry_run {
                    // --dry-run: preview the changes without modifying anything.
                    let mut would = 0;
                    println!("Would update:");
                    for c in &plan.changes {
                        if c.status == sdkt_core::sync::UpdateStatus::Updated {
                            would += 1;
                            let old = &c.old_commit;
                            let new = &c.new_commit;
                            println!("  {}", c.name);
                            println!(
                                "    old commit: {}",
                                if old.is_empty() {
                                    "(none)".to_string()
                                } else {
                                    old.chars().take(12).collect()
                                }
                            );
                            println!(
                                "    new commit: {}",
                                if new.is_empty() {
                                    "(none)".to_string()
                                } else {
                                    new.chars().take(12).collect()
                                }
                            );
                        } else if c.status == sdkt_core::sync::UpdateStatus::Pinned {
                            println!("  {} (pinned, skip)", c.name);
                        } else if c.status == sdkt_core::sync::UpdateStatus::Constraint {
                            println!("  {} (constraint unsatisfied, skip)", c.name);
                        } else if c.status == sdkt_core::sync::UpdateStatus::Error {
                            println!("  {} (error: {})", c.name, c.detail);
                        } else {
                            println!("  {} (unchanged)", c.name);
                        }
                    }
                    if would > 0 {
                        println!("Lock would change.");
                    } else {
                        println!("Nothing to change.");
                    }
                } else {
                    // Real apply: refresh cache + rewrite lock (the plan is already
                    // computed; apply_updates performs the actual fetch).
                    let report = match sdkt_core::sync::apply_updates(base, &config) {
                        Ok((r, _lock)) => r,
                        Err(e) => {
                            eprintln!("Error updating dependencies: {}", e);
                            std::process::exit(1);
                        }
                    };
                    println!("Checking dependencies...");
                    for c in &report.changes {
                        match c.status {
                            sdkt_core::sync::UpdateStatus::Updated => {
                                println!("↑ {} updated", c.name);
                            }
                            sdkt_core::sync::UpdateStatus::Pinned => {
                                println!("✓ {} pinned (rev)", c.name);
                            }
                            sdkt_core::sync::UpdateStatus::Constraint => {
                                println!("⚠ {} constraint unsatisfied", c.name);
                            }
                            sdkt_core::sync::UpdateStatus::Error => {
                                println!("✗ {} error: {}", c.name, c.detail);
                            }
                            _ => {
                                println!("✓ {} unchanged", c.name);
                            }
                        }
                    }
                    if report.updated > 0 {
                        println!("Updated:");
                        println!("{} dependency", report.updated);
                        println!("Lock refreshed.");
                    } else {
                        println!("Nothing to update.");
                    }
                }
            }
            PackageCommand::Pack { out, format } => {
                let base = Path::new(".");
                let out_dir = Path::new(&out);
                std::fs::create_dir_all(out_dir).unwrap_or_else(|e| {
                    eprintln!("Error creating output dir {}: {}", out_dir.display(), e);
                    std::process::exit(1);
                });
                match sdkt_core::package::pack(base, out_dir, &format) {
                    Ok(bundle) => {
                        println!("Packed {} v{}", bundle.name, bundle.version);
                        println!("  format:  {}", bundle.format);
                        println!("  artifact: {}", bundle.out_path);
                        println!("  lock sha256: {}", bundle.lock_sha256);
                        println!("  dependencies bundled: {}", bundle.entries.len());
                    }
                    Err(e) => {
                        eprintln!("Error packing package: {}", e);
                        std::process::exit(1);
                    }
                }
            }
            PackageCommand::Publish { dry_run, broadcast } => {
                let base = Path::new(".");
                let config = load_config();
                // `--broadcast` is opt-in; M38 defines no registry source, so it is
                // rejected (stays offline / dry-run only). No network is ever used.
                if broadcast {
                    eprintln!(
                        "Error: `--broadcast` requires a configured registry source; none is defined in M38."
                    );
                    std::process::exit(1);
                }
                let _ = dry_run; // default true; readiness is always read-only here.
                match sdkt_core::package::publish_plan(base, &config) {
                    Ok(readiness) => {
                        println!("Publish readiness check:");
                        for (name, ok, detail) in &readiness.checks {
                            let mark = if *ok { "✓" } else { "✗" };
                            println!("  {} {} — {}", mark, name, detail);
                        }
                        if readiness.ready {
                            println!("Package is ready to publish (dry-run).");
                        } else {
                            eprintln!("Package is NOT ready to publish. Fix the issues above.");
                            std::process::exit(1);
                        }
                    }
                    Err(e) => {
                        eprintln!("Error evaluating publish readiness: {}", e);
                        std::process::exit(1);
                    }
                }
            }
        },
        Commands::Project { action, net } => match action {
            ProjectCommand::Deploy { salt, format } => {
                let fmt = parse_format_str(&format);
                let config = load_config();

                // M34.1 — advisory lock check. If an `sdkt.lock` exists, warn
                // (non-fatally) when it has drifted from the current artifacts.
                // This never blocks deployment; it simply surfaces a stale-lock
                // signal so operators can re-run `sdkt build` if needed.
                let lock_report = sdkt_core::lock::verify_lock(Path::new("."), &config);
                if lock_report.present && !lock_report.consistent && fmt != OutputFormat::Json {
                    eprintln!("⚠ Warning: sdkt.lock is stale — run `sdkt build` to refresh it.");
                }

                let client = resolve_rpc_client_mutating(
                    net.rpc_url.clone(),
                    net.network_passphrase.clone(),
                    net.network_profile.clone(),
                );

                match sdkt_core::project::resolve_project(&config) {
                    Ok(resolved) => {
                        if fmt != OutputFormat::Json {
                            println!(
                                "✓ Project dependency graph resolved. Deploying {} contract(s).",
                                resolved.len()
                            );
                        }

                        let mut results = std::collections::HashMap::new();

                        for contract in resolved {
                            if fmt != OutputFormat::Json {
                                println!(
                                    "  Deploying alias '{}' from '{}'...",
                                    contract.alias,
                                    contract.wasm_artifact.display()
                                );
                            }

                            // Use alias + base salt to keep deployments unique per contract
                            let contract_salt = format!("{}_{}", salt, contract.alias);
                            let wasm_bytes =
                                fs::read(&contract.wasm_artifact).unwrap_or_else(|e| {
                                    eprintln!(
                                        "Failed to read WASM for '{}': {}",
                                        contract.alias, e
                                    );
                                    std::process::exit(1);
                                });

                            match sdkt_rpc::deploy_contract(&client, &wasm_bytes, &contract_salt)
                                .await
                            {
                                Ok(res) => {
                                    if fmt != OutputFormat::Json {
                                        println!("    ✓ Contract ID: {}", res.contract_id);
                                    }
                                    results.insert(contract.alias, res.contract_id);
                                }
                                Err(e) => {
                                    eprintln!("Deployment failed for '{}': {}", contract.alias, e);
                                    std::process::exit(1);
                                }
                            }
                        }

                        if fmt == OutputFormat::Json {
                            let json = serde_json::json!({
                                "status": "success",
                                "contracts_deployed": results,
                            });
                            println!("{}", serde_json::to_string(&json).unwrap());
                        } else {
                            println!("✓ Project deployment complete.");
                        }
                    }
                    Err(e) => {
                        eprintln!("Error resolving project: {}", e);
                        std::process::exit(1);
                    }
                }
            }
        },
        Commands::Plugin { action } => match action {
            PluginAction::List => {
                let plugins = sdkt_audit::plugin_store::list();
                if plugins.is_empty() {
                    println!("No plugins installed.");
                } else {
                    for p in plugins {
                        println!("{}  v{}  ({})  {}", p.id, p.version, p.kind, p.description);
                    }
                }
            }
            PluginAction::Show { id } => match sdkt_audit::plugin_store::show(&id) {
                Some(p) => {
                    println!("id: {}", p.id);
                    println!("name: {}", p.name);
                    println!("version: {}", p.version);
                    println!("author: {}", p.author);
                    println!("kind: {}", p.kind);
                    println!("artifact: {}", p.artifact);
                    println!("abi: {}.{}", p.abi_major, p.abi_minor);
                    println!("description: {}", p.description);
                }
                None => {
                    eprintln!("Error: plugin '{}' is not installed", id);
                    process::exit(1);
                }
            },
            PluginAction::Install { source, id, force } => {
                let opts = sdkt_audit::plugin_store::InstallOpts { id, force };
                match sdkt_audit::plugin_store::install(std::path::Path::new(&source), &opts) {
                    Ok(meta) => {
                        if meta.kind == "native" {
                            eprintln!(
                                    "Warning: native plugins run UNSANDBOXED. Only install from trusted sources."
                                );
                        }
                        println!(
                            "Installed plugin '{}' ({} v{})",
                            meta.id, meta.kind, meta.version
                        );
                    }
                    Err(e) => {
                        eprintln!("Error installing plugin: {}", e);
                        process::exit(1);
                    }
                }
            }
            PluginAction::Remove { id } => {
                if let Err(e) = sdkt_audit::plugin_store::remove(&id) {
                    eprintln!("Error removing plugin: {}", e);
                    process::exit(1);
                }
                println!("Removed plugin '{}' (if it was installed).", id);
            }
            PluginAction::Update { id, source } => {
                match sdkt_audit::plugin_store::update(&id, std::path::Path::new(&source)) {
                    Ok(meta) => {
                        if meta.kind == "native" {
                            eprintln!(
                                    "Warning: native plugins run UNSANDBOXED. Only install from trusted sources."
                                );
                        }
                        println!("Updated plugin '{}' to v{}", meta.id, meta.version);
                    }
                    Err(e) => {
                        eprintln!("Error updating plugin: {}", e);
                        process::exit(1);
                    }
                }
            }
        },
        Commands::Completions { shell } => {
            let mut cmd = Cli::command();
            // Wrap stdout so a consumer that closes the pipe early
            // (`sdkt completions bash | head`) yields EPIPE, which we treat as
            // success instead of letting clap_complete panic on it.
            let mut out = BrokenPipeOk(std::io::stdout());
            clap_complete::generate(shell, &mut cmd, "sdkt", &mut out);
        }
    }

    Ok(())
}

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

    #[test]
    fn verification_outcome_verified() {
        let (m, status, exp) = verification_outcome("abc123", Some(("abc123".to_string(), 4096)));
        assert_eq!(m, Some(true));
        assert_eq!(status, "Verified");
        assert!(exp.is_empty());
    }

    #[test]
    fn verification_outcome_mismatch() {
        let (m, status, exp) = verification_outcome("abc123", Some(("def456".to_string(), 4096)));
        assert_eq!(m, Some(false));
        assert_eq!(status, "Mismatch");
        assert!(exp.contains("abc123"));
        assert!(exp.contains("def456"));
    }

    #[test]
    fn verification_outcome_onchain_only() {
        let (m, status, exp) = verification_outcome("abc123", None);
        assert_eq!(m, None);
        assert_eq!(status, "OnChainOnly");
        assert!(exp.contains("No local WASM"));
    }

    #[test]
    fn verification_report_json_schema() {
        // Verified case
        let r = VerificationReport {
            contract_id: "CABCDEFG".to_string(),
            network: "testnet".to_string(),
            on_chain_wasm_hash: "abc123".to_string(),
            local_wasm_hash: Some("abc123".to_string()),
            local_wasm_size_bytes: Some(4096),
            matches: Some(true),
            verification_status: "Verified".to_string(),
            explanation: String::new(),
        };
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("\"contract_id\":\"CABCDEFG\""));
        assert!(json.contains("\"on_chain_wasm_hash\":\"abc123\""));
        assert!(json.contains("\"local_wasm_hash\":\"abc123\""));
        assert!(json.contains("\"local_wasm_size_bytes\":4096"));
        assert!(json.contains("\"match\":true"));
        assert!(json.contains("\"verification_status\":\"Verified\""));

        // OnChainOnly case — local fields must be absent (null/omitted)
        let r2 = VerificationReport {
            contract_id: "CABCDEFG".to_string(),
            network: "testnet".to_string(),
            on_chain_wasm_hash: "abc123".to_string(),
            local_wasm_hash: None,
            local_wasm_size_bytes: None,
            matches: None,
            verification_status: "OnChainOnly".to_string(),
            explanation: "No local WASM provided; reporting on-chain hash only.".to_string(),
        };
        let json2 = serde_json::to_string(&r2).unwrap();
        assert!(json2.contains("\"match\":null") || !json2.contains("\"match\""));
        assert!(!json2.contains("\"local_wasm_hash\":\"abc123\""));
    }
}

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

    #[test]
    fn derive_verdict_healthy() {
        let (h, reasons) = derive_verdict(Some(true), 0, 12);
        assert_eq!(h, "healthy");
        assert!(reasons.is_empty());
    }

    #[test]
    fn derive_verdict_at_risk_expiring() {
        let (h, reasons) = derive_verdict(Some(true), 2, 12);
        assert_eq!(h, "at_risk");
        assert!(reasons.iter().any(|r| r.contains("2 storage entries")));
    }

    #[test]
    fn derive_verdict_critical_mismatch() {
        // Mismatch wins over TTL, regardless of expiring count.
        let (h, reasons) = derive_verdict(Some(false), 5, 12);
        assert_eq!(h, "critical");
        assert!(reasons.iter().any(|r| r.contains("does NOT match")));
    }

    #[test]
    fn derive_verdict_at_risk_empty() {
        let (h, reasons) = derive_verdict(None, 0, 0);
        assert_eq!(h, "at_risk");
        assert!(reasons.iter().any(|r| r.contains("no storage entries")));
    }

    #[test]
    fn derive_verdict_onchain_only_healthy() {
        // No --wasm supplied (verified == None), nothing expiring → healthy.
        let (h, reasons) = derive_verdict(None, 0, 7);
        assert_eq!(h, "healthy");
        assert!(reasons.is_empty());
    }

    #[test]
    fn health_report_json_schema() {
        // Healthy with --wasm verified
        let r = ContractHealthReport {
            contract_id: "CABCDEFG".to_string(),
            network: "testnet".to_string(),
            health: "healthy".to_string(),
            verified: Some(true),
            on_chain_wasm_hash: "abc123".to_string(),
            local_wasm_hash: Some("abc123".to_string()),
            local_wasm_size_bytes: Some(4096),
            storage: HealthStorage {
                total_entries: 12,
                instance_entries: 1,
                persistent_entries: 9,
                temporary_entries: 2,
                other_entries: 0,
                ttl: Some(HealthTtl {
                    minimum_ttl: 518400,
                    maximum_ttl: 518400,
                    average_ttl: 518400,
                    expiring_entries_count: 0,
                    estimated_rent_cost: Some(240000),
                }),
            },
            reasons: vec![],
        };
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("\"health\":\"healthy\""));
        assert!(json.contains("\"verified\":true"));
        assert!(json.contains("\"on_chain_wasm_hash\":\"abc123\""));
        assert!(json.contains("\"storage\""));
        assert!(json.contains("\"total_entries\":12"));
        assert!(json.contains("\"ttl\""));
        assert!(json.contains("\"expiring_entries_count\":0"));

        // OnChainOnly (no --wasm) → verified/local fields null/omitted
        let r2 = ContractHealthReport {
            contract_id: "CABCDEFG".to_string(),
            network: "testnet".to_string(),
            health: "healthy".to_string(),
            verified: None,
            on_chain_wasm_hash: "abc123".to_string(),
            local_wasm_hash: None,
            local_wasm_size_bytes: None,
            storage: HealthStorage {
                total_entries: 7,
                instance_entries: 1,
                persistent_entries: 5,
                temporary_entries: 1,
                other_entries: 0,
                ttl: None,
            },
            reasons: vec![],
        };
        let json2 = serde_json::to_string(&r2).unwrap();
        assert!(json2.contains("\"verified\":null") || !json2.contains("\"verified\""));
    }
}