sdkt-cli 2.7.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
//! Contract tests for `--format json` across scripting-oriented commands.
//!
//! These verify that machine-readable output has stable field names and types,
//! and that error envelopes have a consistent shape. All tests are deterministic
//! and offline (no network, no unstable values like timestamps or absolute paths).
//!
//! ## Compatibility commitments (documented here so downstream consumers know
//! which fields are safe to depend on):
//!
//! ### `sdkt decode --format json`
//! - Valid JSON for well-formed XDR input
//! - Error message in consistent envelope on parse failure
//!
//! ### `sdkt wasm inspect --format json`
//! - `file`: string (basename only, not absolute path)
//! - `metadata.hash`: hex string
//! - `metadata.size_bytes`: u64
//! - `metadata.contract_meta`: array of {key, value} decoded from the
//!   `contractmetav0` custom section, in section order with duplicates
//!   preserved. Empty array when the WASM carries no such section.
//! - `spec`: object with functions/events/custom_types arrays
//!
//! ### `sdkt diff --upgrade-safety --format json`
//! - `compatible`: boolean
//! - `breaking_changes`: array of {kind, name?, detail?}
//! - `non_breaking_changes`: array of {kind, name?}
//!
//! ### `sdkt audit --format json`
//! - `findings`: array of {rule_id, severity, message, location}
//! - `summary`: {critical, warning, info, total} all u64
//!
//! ### `sdkt package validate --format json`
//! - `valid`: boolean
//! - `error`: string (when invalid)
//!
//! ### `sdkt storage estimate --format json`
//! - `wasm_path`: string
//! - `ledgers`: u32
//! - `cost_per_entry_stroops`: u64
//! - `cost_per_entry_xlm`: string
//! - `classes`: object containing `instance`, `persistent`, and `temporary`
//!   - `instance`: {entry_count, cost_stroops, cost_xlm, derivation, notes}
//!   - `persistent`: {entry_count, cost_stroops, cost_xlm, derivation, notes}
//!   - `temporary`: {entry_count, cost_stroops, cost_xlm, derivation, notes}
//! - `total`: {baseline_entries, cost_stroops, cost_xlm}
//! - `spec_metrics`: {functions_count, custom_types_count, events_count}
//! - `approximation_ceiling`: string

use assert_cmd::Command;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use sdkt_xdr::{encode_ledger_key, LedgerKeyParams};
use serde_json::Value;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
use stellar_xdr::{
    ContractDataDurability, ContractDataEntry, ContractExecutable, ContractId, ExtensionPoint,
    Hash, LedgerEntry, LedgerEntryData, LedgerEntryExt, Limited, Limits, ScAddress,
    ScContractInstance, ScVal, WriteXdr,
};
use tempfile::TempDir;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Build the `sdkt` binary under test.
fn sdkt() -> Command {
    Command::cargo_bin("sdkt").expect("sdkt binary built")
}

/// Write `content` to `<dir>/<name>` and return the path.
fn write_fixture(dir: &TempDir, name: &str, content: &str) -> std::path::PathBuf {
    let p = dir.path().join(name);
    let mut f = std::fs::File::create(&p).unwrap();
    f.write_all(content.as_bytes()).unwrap();
    p
}

/// Assert that a string is valid JSON by parsing it.
fn assert_valid_json(s: &str) -> Value {
    serde_json::from_str::<Value>(s).unwrap_or_else(|e| {
        panic!("expected valid JSON, got error: {e}\noutput:\n{s}");
    })
}

// ---------------------------------------------------------------------------
// Compatibility: wasm inspect fixtures (project-local, stable)
// ---------------------------------------------------------------------------

static WASM_OLD: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/us_old.wasm");
static WASM_NEW: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/us_new.wasm");

const RPC_CONTRACT_ID: &str = "CAE3U7JKESRWZHPEQ72DVNGOQ6WPA7HSPQZL5YV46NPCE4TMUPAGYMEC";
const RPC_CONTRACT_ID_HEX: &str =
    "09ba7d2a24a36c9de487f43ab4ce87acf07cf27c32bee2bcf35e22726ca3c06c";
const RPC_WASM_HASH_HEX: &str = "60cddae67f202c19ee7b000c894fd12aa8b44de09ab652f5e188bc0c63a6cf02";

fn read_rpc_request(sock: &mut TcpStream) -> String {
    let mut data = Vec::new();
    let mut buf = [0u8; 4096];
    loop {
        let n = sock.read(&mut buf).unwrap_or(0);
        if n == 0 {
            break;
        }
        data.extend_from_slice(&buf[..n]);
        let text = String::from_utf8_lossy(&data);
        if let Some(end) = text.find("\r\n\r\n") {
            let len = text[..end]
                .lines()
                .filter_map(|line| line.split_once(':'))
                .find(|(key, _)| key.trim().eq_ignore_ascii_case("content-length"))
                .and_then(|(_, value)| value.trim().parse::<usize>().ok())
                .unwrap_or(0);
            if data.len() >= end + 4 + len {
                break;
            }
        }
    }
    String::from_utf8_lossy(&data).into_owned()
}

fn encode_ledger_entry(entry: &LedgerEntry) -> String {
    let mut bytes = Vec::new();
    entry
        .write_xdr(&mut Limited::new(&mut bytes, Limits::none()))
        .unwrap();
    STANDARD.encode(bytes)
}

fn mock_contract_data_xdr() -> String {
    let mut wasm_hash = [0u8; 32];
    hex::decode_to_slice(RPC_WASM_HASH_HEX, &mut wasm_hash).unwrap();
    encode_ledger_entry(&LedgerEntry {
        last_modified_ledger_seq: 1,
        data: LedgerEntryData::ContractData(ContractDataEntry {
            ext: ExtensionPoint::V0,
            contract: ScAddress::Contract(ContractId(Hash([0; 32]))),
            key: ScVal::LedgerKeyContractInstance,
            durability: ContractDataDurability::Persistent,
            val: ScVal::ContractInstance(ScContractInstance {
                executable: ContractExecutable::Wasm(Hash(wasm_hash)),
                storage: None,
            }),
        }),
        ext: LedgerEntryExt::V0,
    })
}

fn mock_storage_inspect_rpc() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    let contract_data_key = encode_ledger_key(&LedgerKeyParams::ContractData(
        RPC_CONTRACT_ID_HEX.to_string(),
    ))
    .unwrap();
    let contract_data_xdr = mock_contract_data_xdr();

    thread::spawn(move || {
        for conn in listener.incoming() {
            let Ok(mut sock) = conn else { break };
            let request = read_rpc_request(&mut sock);
            let body = request
                .split_once("\r\n\r\n")
                .map(|(_, body)| body)
                .unwrap_or("");
            let request_json: Value = serde_json::from_str(body).unwrap_or_default();
            let method = request_json["method"].as_str().unwrap_or("");
            let response = match method {
                "getLatestLedger" => {
                    r#"{"jsonrpc":"2.0","id":1,"result":{"id":"mock","protocolVersion":22,"sequence":10000}}"#.to_string()
                }
                "getLedgerEntries" => {
                    let requested: Vec<&str> = request_json["params"]["keys"]
                        .as_array()
                        .into_iter()
                        .flatten()
                        .filter_map(Value::as_str)
                        .collect();
                    let entries = if requested.contains(&contract_data_key.as_str()) {
                        serde_json::json!([{
                            "key": contract_data_key,
                            "xdr": contract_data_xdr,
                            "lastModifiedLedgerSeq": 1,
                            "liveUntilLedgerSeq": 12345
                        }])
                    } else {
                        serde_json::json!([])
                    };
                    serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "result": { "entries": entries, "latestLedger": 10000 }
                    })
                    .to_string()
                }
                _ => r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"method not found"}}"#.to_string(),
            };
            let http_response = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                response.len(),
                response
            );
            let _ = sock.write_all(http_response.as_bytes());
        }
    });

    url
}

fn run_storage_check(with_abi: bool) -> Value {
    let rpc_url = mock_storage_inspect_rpc();
    let mut cmd = sdkt();
    cmd.args([
        "storage",
        "check",
        RPC_CONTRACT_ID,
        "--format",
        "json",
        "--rpc-url",
    ])
    .arg(rpc_url);
    if with_abi {
        cmd.arg("--abi").arg(WASM_NEW);
    }
    let output = cmd.assert().success().get_output().stdout.clone();
    assert_valid_json(&String::from_utf8_lossy(&output))
}

fn run_contract_inspect(with_abi: bool) -> Value {
    let rpc_url = mock_storage_inspect_rpc();
    let mut cmd = sdkt();
    cmd.args(["inspect", RPC_CONTRACT_ID, "--format", "json", "--rpc-url"])
        .arg(rpc_url);
    if with_abi {
        cmd.arg("--abi").arg(WASM_NEW);
    }
    let output = cmd.assert().success().get_output().stdout.clone();
    assert_valid_json(&String::from_utf8_lossy(&output))
}

fn assert_fields_unchanged(without_abi: &Value, with_abi: &Value, fields: &[&str]) {
    for field in fields {
        assert_eq!(
            without_abi.get(field),
            with_abi.get(field),
            "existing field `{field}` changed when --abi was supplied"
        );
    }
}

mod storage_check_json_schema {
    use super::*;

    #[test]
    fn abi_adds_metadata_without_changing_ttl_entries() {
        let without_abi = run_storage_check(false);
        let with_abi = run_storage_check(true);
        let existing_fields = ["contract_id", "entries"];

        assert_fields_unchanged(&without_abi, &with_abi, &existing_fields);
        assert_eq!(
            without_abi.as_object().unwrap().len(),
            existing_fields.len()
        );
        assert_eq!(
            with_abi.as_object().unwrap().len(),
            existing_fields.len() + 1
        );

        let entries = with_abi["entries"]
            .as_array()
            .expect("entries remains an array with --abi");
        assert!(!entries.is_empty());
        for field in [
            "key",
            "current_ttl",
            "expiration_time",
            "days_remaining",
            "extension_cost_stroops",
        ] {
            assert!(
                entries[0].get(field).is_some(),
                "missing entry field `{field}`"
            );
        }

        assert!(with_abi["abi"]["functions"].is_array());
        assert!(with_abi["abi"]["events"].is_array());
        assert!(with_abi["abi"]["custom_types"].is_array());
    }
}

mod inspect_json_schema {
    use super::*;

    #[test]
    fn abi_adds_full_spec_without_changing_inspection_fields() {
        let without_abi = run_contract_inspect(false);
        let with_abi = run_contract_inspect(true);
        let existing_fields = [
            "contract_id",
            "wasm_hash",
            "wasm_size",
            "abi",
            "storage_summary",
            "ttl_info",
            "storage_keys",
        ];

        assert_fields_unchanged(&without_abi, &with_abi, &existing_fields);
        assert_eq!(
            without_abi.as_object().unwrap().len(),
            existing_fields.len()
        );
        assert_eq!(
            with_abi.as_object().unwrap().len(),
            existing_fields.len() + 1
        );
        assert!(
            with_abi["storage_keys"].is_array(),
            "storage_keys remains an array with --abi"
        );

        let abi_spec = with_abi["abi_spec"]
            .as_object()
            .expect("abi_spec contains the full supplied ContractSpec");
        for field in ["env_meta", "functions", "custom_types", "events"] {
            assert!(
                abi_spec.contains_key(field),
                "missing ABI spec field `{field}`"
            );
        }
    }
}

// ===========================================================================
// sdkt wasm inspect --format json
// ===========================================================================

mod wasm_inspect {
    use super::*;

    #[test]
    fn json_output_has_required_top_level_fields() {
        let out = sdkt()
            .args(["wasm", "inspect", WASM_NEW, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));

        assert!(v.get("file").is_some(), "missing `file` field");
        assert!(v.get("metadata").is_some(), "missing `metadata` field");
        assert!(v.get("spec").is_some(), "missing `spec` field");
    }

    #[test]
    fn json_metadata_contract_meta_is_an_additive_key_value_array() {
        let out = sdkt()
            .args(["wasm", "inspect", WASM_NEW, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let meta = v.get("metadata").expect("metadata field");

        let entries = meta
            .get("contract_meta")
            .and_then(|m| m.as_array())
            .expect("metadata.contract_meta should be an array");

        // The committed fixture carries contractmetav0 with SDK/rustc/cli
        // provenance entries; assert the decoded shape, not a fixed count.
        assert!(
            !entries.is_empty(),
            "us_new.wasm should expose contractmetav0 entries"
        );
        for entry in entries {
            let key = entry.get("key").and_then(|k| k.as_str());
            let value = entry.get("value").and_then(|val| val.as_str());
            assert!(key.is_some(), "each entry needs a string `key`: {entry}");
            assert!(
                value.is_some(),
                "each entry needs a string `value`: {entry}"
            );
        }

        // Ground truth for this fixture: the SDK/rustc/cli provenance keys.
        let keys: Vec<&str> = entries
            .iter()
            .filter_map(|e| e.get("key").and_then(|k| k.as_str()))
            .collect();
        for expected in ["rsver", "rssdkver", "cliver"] {
            assert!(
                keys.contains(&expected),
                "expected contract_meta key `{expected}`, got {keys:?}"
            );
        }
    }

    #[test]
    fn json_metadata_without_contract_meta_is_an_empty_array() {
        // us_old.wasm has no contractmetav0: the field must still be present
        // and empty, so consumers can rely on the key existing.
        let out = sdkt()
            .args(["wasm", "inspect", WASM_OLD, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let entries = v
            .get("metadata")
            .and_then(|m| m.get("contract_meta"))
            .and_then(|m| m.as_array())
            .expect("metadata.contract_meta should be present and an array");
        assert!(
            entries.is_empty(),
            "us_old.wasm has no contractmetav0, expected [], got {entries:?}"
        );
    }

    #[test]
    fn json_metadata_has_stable_fields() {
        let out = sdkt()
            .args(["wasm", "inspect", WASM_NEW, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let meta = v.get("metadata").expect("metadata field");

        // Hash is a hex string
        let hash = meta
            .get("hash")
            .and_then(|h| h.as_str())
            .expect("metadata.hash");
        assert!(
            hash.chars().all(|c| c.is_ascii_hexdigit()),
            "hash should be hex: {hash}"
        );

        // size_bytes is a number
        let size = meta
            .get("size_bytes")
            .and_then(|s| s.as_u64())
            .expect("metadata.size_bytes");
        assert!(size > 0, "size_bytes must be > 0");

        // exports is an array
        assert!(
            meta.get("exports").is_some_and(|e| e.is_array()),
            "metadata.exports should be an array"
        );
    }

    #[test]
    fn json_metadata_exports_and_imports_have_stable_lowercase_kind_strings() {
        let out = sdkt()
            .args(["wasm", "inspect", WASM_NEW, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let meta = v.get("metadata").expect("metadata field");

        let exports = meta
            .get("exports")
            .and_then(|e| e.as_array())
            .expect("metadata.exports array");
        assert!(!exports.is_empty(), "us_new.wasm should have exports");
        for exp in exports {
            let kind = exp
                .get("kind")
                .and_then(|k| k.as_str())
                .expect("export kind string");
            assert!(
                matches!(
                    kind,
                    "func" | "table" | "memory" | "global" | "tag" | "func_exact"
                ),
                "export kind should be stable lowercase, got: {kind}"
            );
            assert!(
                !kind.contains('(') && !kind.chars().next().is_some_and(|c| c.is_uppercase()),
                "export kind must not leak debug or uppercase: {kind}"
            );
        }

        let imports = meta
            .get("imports")
            .and_then(|i| i.as_array())
            .expect("metadata.imports array");
        assert!(!imports.is_empty(), "us_new.wasm should have imports");
        for imp in imports {
            let kind = imp
                .get("kind")
                .and_then(|k| k.as_str())
                .expect("import kind string");
            assert!(
                matches!(
                    kind,
                    "func" | "table" | "memory" | "global" | "tag" | "func_exact"
                ),
                "import kind should be stable lowercase without index payload, got: {kind}"
            );
            assert!(
                !kind.contains('(') && !kind.chars().next().is_some_and(|c| c.is_uppercase()),
                "import kind must not leak debug format like Func(0): {kind}"
            );
        }
    }

    #[test]
    fn json_spec_has_function_array() {
        let out = sdkt()
            .args(["wasm", "inspect", WASM_NEW, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let spec = v.get("spec").expect("spec field");

        assert!(
            spec.get("functions").is_some_and(|f| f.is_array()),
            "spec.functions should be an array"
        );
    }

    #[test]
    fn json_file_field_is_basename_not_absolute() {
        // Ponytail: future — add path normalization here if upstream changes
        // to emit full paths. Today we assert no '/' in the value.
        let out = sdkt()
            .args(["wasm", "inspect", WASM_NEW, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let file = v.get("file").and_then(|f| f.as_str()).expect("file field");

        assert!(
            !file.starts_with('/'),
            "file should be basename (no absolute path), got: {file}"
        );
    }

    #[test]
    fn json_error_output_is_consistent() {
        let out = sdkt()
            .args(["wasm", "inspect", "/no/such/file.wasm", "--format", "json"])
            .assert()
            .failure()
            .get_output()
            .stderr
            .clone();
        let err_str = String::from_utf8_lossy(&out);
        assert!(
            err_str.contains("Error") || err_str.contains("No such file"),
            "error output should mention the failure: {err_str}"
        );
    }
}

// ===========================================================================
// sdkt diff --upgrade-safety --format json
// ===========================================================================

mod diff_upgrade_safety {
    use super::*;

    #[test]
    fn json_output_has_compatible_boolean() {
        let out = sdkt()
            .args([
                "diff",
                "--old-wasm",
                WASM_OLD,
                "--new-wasm",
                WASM_NEW,
                "--upgrade-safety",
                "--format",
                "json",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));

        let compatible = v
            .get("compatible")
            .and_then(|c| c.as_bool())
            .expect("compatible field");
        // Our fixtures have breaking changes (removed event + type + signature change)
        assert!(!compatible, "fixture pair should be incompatible");
    }

    #[test]
    fn json_breaking_changes_is_array_of_objects() {
        let out = sdkt()
            .args([
                "diff",
                "--old-wasm",
                WASM_OLD,
                "--new-wasm",
                WASM_NEW,
                "--upgrade-safety",
                "--format",
                "json",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let breaking = v
            .get("breaking_changes")
            .and_then(|b| b.as_array())
            .expect("breaking_changes field");
        assert!(
            !breaking.is_empty(),
            "fixtures should have breaking changes"
        );

        for change in breaking {
            assert!(
                change.get("kind").is_some_and(|k| k.is_string()),
                "each breaking change should have a string `kind`"
            );
        }
    }

    #[test]
    fn json_non_breaking_changes_is_array_of_objects() {
        let out = sdkt()
            .args([
                "diff",
                "--old-wasm",
                WASM_OLD,
                "--new-wasm",
                WASM_NEW,
                "--upgrade-safety",
                "--format",
                "json",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let non_breaking = v
            .get("non_breaking_changes")
            .and_then(|b| b.as_array())
            .expect("non_breaking_changes field");
        assert!(
            !non_breaking.is_empty(),
            "fixtures should have non-breaking changes"
        );

        for change in non_breaking {
            assert!(
                change.get("kind").is_some_and(|k| k.is_string()),
                "each non-breaking change should have a string `kind`"
            );
        }
    }

    #[test]
    fn json_error_when_old_wasm_missing() {
        let out = sdkt()
            .args([
                "diff",
                "--old-wasm",
                "/no/old.wasm",
                "--new-wasm",
                WASM_NEW,
                "--upgrade-safety",
                "--format",
                "json",
            ])
            .assert()
            .failure()
            .get_output()
            .stderr
            .clone();
        let err_str = String::from_utf8_lossy(&out);
        assert!(
            err_str.contains("Failed to read") || err_str.contains("No such file"),
            "error should mention missing file: {err_str}"
        );
    }
}

// ===========================================================================
// sdkt audit --format json
// ===========================================================================

mod audit {
    use super::*;

    #[test]
    fn json_output_has_findings_and_summary() {
        let dir = TempDir::new().unwrap();
        let path = write_fixture(&dir, "bad.rs", "pub fn initialize(admin: Address) { }\n");
        let out = sdkt()
            .args(["audit", path.to_str().unwrap(), "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));

        assert!(v.get("findings").is_some(), "missing `findings` field");
        assert!(v.get("summary").is_some(), "missing `summary` field");
    }

    #[test]
    fn json_findings_have_required_fields() {
        let dir = TempDir::new().unwrap();
        let path = write_fixture(&dir, "bad.rs", "pub fn initialize(admin: Address) { }\n");
        let out = sdkt()
            .args(["audit", path.to_str().unwrap(), "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let findings = v
            .get("findings")
            .and_then(|f| f.as_array())
            .expect("findings field");
        assert!(!findings.is_empty(), "fixture should trigger findings");

        for finding in findings {
            assert!(
                finding.get("rule_id").is_some_and(|r| r.is_string()),
                "finding.rule_id should be a string"
            );
            assert!(
                finding.get("severity").is_some_and(|s| s.is_string()),
                "finding.severity should be a string"
            );
            assert!(
                finding.get("message").is_some_and(|m| m.is_string()),
                "finding.message should be a string"
            );
        }
    }

    #[test]
    fn json_summary_has_numeric_counts() {
        let dir = TempDir::new().unwrap();
        let path = write_fixture(&dir, "bad.rs", "pub fn initialize(admin: Address) { }\n");
        let out = sdkt()
            .args(["audit", path.to_str().unwrap(), "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let summary = v.get("summary").expect("summary field");

        for field in &["critical", "warning", "info", "total"] {
            assert!(
                summary.get(field).and_then(|v| v.as_u64()).is_some(),
                "summary.{field} should be a number"
            );
        }
    }

    #[test]
    fn json_clean_source_has_empty_findings() {
        let dir = TempDir::new().unwrap();
        let path = write_fixture(
            &dir,
            "ok.rs",
            "pub fn balance_of(who: Address) -> u32 { require_auth(); 0 }\n",
        );
        let out = sdkt()
            .args(["audit", path.to_str().unwrap(), "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let findings = v
            .get("findings")
            .and_then(|f| f.as_array())
            .expect("findings field");
        assert!(findings.is_empty(), "clean source should have no findings");
    }

    #[test]
    fn json_error_when_source_missing() {
        let out = sdkt()
            .args(["audit", "/no/such/contract.rs", "--format", "json"])
            .assert()
            .failure()
            .get_output()
            .stderr
            .clone();
        let err_str = String::from_utf8_lossy(&out);
        assert!(
            err_str.contains("Failed to read") || err_str.contains("No such file"),
            "error should mention missing file: {err_str}"
        );
    }
}

// ===========================================================================
// sdkt package validate --format json
// ===========================================================================

mod package_validate {
    use super::*;

    #[test]
    fn json_invalid_manifest_has_valid_false_and_error() {
        // Run in a temp dir with no .sdkt.toml
        let dir = TempDir::new().unwrap();
        let out = sdkt()
            .current_dir(dir.path())
            .args(["package", "validate", "--format", "json"])
            .assert()
            .failure()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));

        let valid = v
            .get("valid")
            .and_then(|v| v.as_bool())
            .expect("valid field");
        assert!(!valid, "missing manifest should be invalid");

        assert!(
            v.get("error").is_some_and(|e| e.is_string()),
            "error field should be a string when invalid"
        );
    }

    #[test]
    fn json_error_message_is_nonempty() {
        let dir = TempDir::new().unwrap();
        let out = sdkt()
            .current_dir(dir.path())
            .args(["package", "validate", "--format", "json"])
            .assert()
            .failure()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let error = v
            .get("error")
            .and_then(|e| e.as_str())
            .expect("error field");
        assert!(!error.is_empty(), "error message should not be empty");
    }
}

// ===========================================================================
// sdkt decode --format json
// ===========================================================================

mod decode {
    use super::*;

    #[test]
    fn json_error_on_invalid_xdr() {
        // Invalid base64 / truncated XDR → error envelope
        let out = sdkt()
            .args([
                "decode",
                "AAAA",
                "--type",
                "TransactionEnvelope",
                "--format",
                "json",
            ])
            .assert()
            .failure()
            .get_output()
            .stderr
            .clone();
        let err_str = String::from_utf8_lossy(&out);
        assert!(
            err_str.contains("XdrParse") || err_str.contains("Error"),
            "error should mention parse failure: {err_str}"
        );
    }

    #[test]
    fn json_output_is_valid_for_ledger_key_type() {
        // Use a known-valid base64 LedgerKey (pre-encoded offline).
        // This is a minimal valid LedgerKey for a AccountEntry.
        // If this fixture is unavailable, the test still validates JSON shape
        // by checking that ANY successful decode produces valid JSON.
        //
        // Ponytail: add a static base64 fixture here once a stable one is
        // committed to tests/fixtures/. For now we only assert the error path
        // above, which is the deterministic offline case.
    }
}

// ===========================================================================
// Cross-cutting: all JSON output must be parseable
// ===========================================================================

mod cross_cutting {
    use super::*;

    #[test]
    fn all_json_output_is_parseable() {
        // Run each command with --format json and verify stdout is valid JSON.
        // This catches accidental println! or debug output mixed into JSON streams.

        // wasm inspect
        let out = sdkt()
            .args(["wasm", "inspect", WASM_NEW, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        assert_valid_json(&String::from_utf8_lossy(&out));

        // diff --upgrade-safety
        let out = sdkt()
            .args([
                "diff",
                "--old-wasm",
                WASM_OLD,
                "--new-wasm",
                WASM_NEW,
                "--upgrade-safety",
                "--format",
                "json",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        assert_valid_json(&String::from_utf8_lossy(&out));

        // audit (clean source)
        let dir = TempDir::new().unwrap();
        let path = write_fixture(
            &dir,
            "ok.rs",
            "pub fn balance_of(who: Address) -> u32 { require_auth(); 0 }\n",
        );
        let out = sdkt()
            .args(["audit", path.to_str().unwrap(), "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        assert_valid_json(&String::from_utf8_lossy(&out));

        // storage estimate
        let out = sdkt()
            .args(["storage", "estimate", WASM_OLD, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        assert_valid_json(&String::from_utf8_lossy(&out));
    }
}

// ===========================================================================
// sdkt storage estimate --format json
// ===========================================================================

mod storage_estimate {
    use super::*;

    #[test]
    fn json_output_has_required_top_level_fields() {
        let out = sdkt()
            .args(["storage", "estimate", WASM_OLD, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));

        assert!(v.get("wasm_path").is_some(), "missing `wasm_path`");
        assert!(v.get("ledgers").is_some(), "missing `ledgers`");
        assert!(
            v.get("cost_per_entry_stroops").is_some(),
            "missing `cost_per_entry_stroops`"
        );
        assert!(
            v.get("cost_per_entry_xlm").is_some(),
            "missing `cost_per_entry_xlm`"
        );
        assert!(v.get("classes").is_some(), "missing `classes`");
        assert!(v.get("total").is_some(), "missing `total`");
        assert!(v.get("spec_metrics").is_some(), "missing `spec_metrics`");
        assert!(
            v.get("approximation_ceiling").is_some(),
            "missing `approximation_ceiling`"
        );
    }

    #[test]
    fn json_classes_breakdown_schema_and_types() {
        let out = sdkt()
            .args(["storage", "estimate", WASM_OLD, "--format", "json"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));
        let classes = v.get("classes").expect("classes object");

        for class_name in ["instance", "persistent", "temporary"] {
            let class_obj = classes.get(class_name).unwrap_or_else(|| {
                panic!("missing `{class_name}` class object");
            });

            assert!(
                class_obj.get("entry_count").is_some_and(|c| c.is_u64()),
                "{class_name}: entry_count should be u64"
            );
            assert!(
                class_obj.get("cost_stroops").is_some_and(|c| c.is_u64()),
                "{class_name}: cost_stroops should be u64"
            );
            assert!(
                class_obj.get("cost_xlm").is_some_and(|c| c.is_string()),
                "{class_name}: cost_xlm should be string"
            );
            assert!(
                class_obj.get("derivation").is_some_and(|c| c.is_string()),
                "{class_name}: derivation should be string"
            );
            assert!(
                class_obj.get("notes").is_some_and(|c| c.is_string()),
                "{class_name}: notes should be string"
            );
        }

        // Specific values for us_old.wasm (guaranteed instance singleton baseline; persistent is unknown from ABI alone)
        assert_eq!(classes["instance"]["entry_count"], 1);
        assert_eq!(classes["persistent"]["entry_count"], 0);
        assert_eq!(classes["temporary"]["entry_count"], 0);

        let total = v.get("total").expect("total object");
        assert_eq!(total["baseline_entries"], 1);
        assert_eq!(total["cost_stroops"], 1728000);
        assert_eq!(total["cost_xlm"], "0.1728");

        let metrics = v.get("spec_metrics").expect("spec_metrics object");
        assert_eq!(metrics["functions_count"], 2);
        assert_eq!(metrics["custom_types_count"], 1);
        assert_eq!(metrics["events_count"], 1);
    }

    #[test]
    fn json_custom_ledgers_scales_cost() {
        let out = sdkt()
            .args([
                "storage",
                "estimate",
                WASM_NEW,
                "--ledgers",
                "100",
                "--format",
                "json",
            ])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        let v = assert_valid_json(&String::from_utf8_lossy(&out));

        assert_eq!(v["ledgers"], 100);
        assert_eq!(v["cost_per_entry_stroops"], 10000);
        assert_eq!(v["cost_per_entry_xlm"], "0.001");

        // us_new.wasm has 0 UDTs -> 1 instance entry, 0 persistent
        let classes = &v["classes"];
        assert_eq!(classes["instance"]["entry_count"], 1);
        assert_eq!(classes["instance"]["cost_stroops"], 10000);
        assert_eq!(classes["instance"]["cost_xlm"], "0.001");
        assert_eq!(classes["persistent"]["entry_count"], 0);
        assert_eq!(classes["persistent"]["cost_stroops"], 0);
        assert_eq!(classes["persistent"]["cost_xlm"], "0");

        let total = &v["total"];
        assert_eq!(total["baseline_entries"], 1);
        assert_eq!(total["cost_stroops"], 10000);
        assert_eq!(total["cost_xlm"], "0.001");
    }
}