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
use assert_cmd::Command;

#[test]
fn test_cli_wasm_cache_info_default() {
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd.arg("wasm").arg("cache").arg("info").assert();
    assert
        .success()
        .stdout(predicates::str::contains("Cache Info for Network"));
}

#[test]
fn test_cli_wasm_cache_info_json() {
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .arg("wasm")
        .arg("cache")
        .arg("info")
        .arg("--format")
        .arg("json")
        .assert();
    assert
        .success()
        .stdout(predicates::str::contains("\"network\":\"testnet\""));
}

#[test]
fn test_cli_wasm_cache_clear() {
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .arg("wasm")
        .arg("cache")
        .arg("clear")
        .arg("--network")
        .arg("testnet")
        .assert();
    assert.success().stdout(predicates::str::contains(
        "Cleared all cache entries for testnet.",
    ));
}

#[test]
fn test_cli_wasm_cache_remove_existing_entry_succeeds() {
    // Real cache layout, so the removal genuinely happens: <cache>/wasm/testnet/<hash>.{json,wasm}
    let cache = tempfile::tempdir().unwrap();
    let net_dir = cache.path().join("wasm").join("testnet");
    std::fs::create_dir_all(&net_dir).unwrap();
    std::fs::write(net_dir.join("fakehash123.json"), "{}").unwrap();
    std::fs::write(net_dir.join("fakehash123.wasm"), b"wasm-bytes").unwrap();

    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .env("SDKT_CACHE_DIR", cache.path())
        .arg("wasm")
        .arg("cache")
        .arg("remove")
        .arg("fakehash123")
        .assert();
    assert.success().stdout(predicates::str::contains(
        "Removed fakehash123 from testnet cache.",
    ));

    // Both files are physically gone.
    assert!(!net_dir.join("fakehash123.json").exists());
    assert!(!net_dir.join("fakehash123.wasm").exists());
}

#[test]
fn test_cli_wasm_cache_remove_missing_entry_is_not_a_success() {
    // Regression: removing a hash that is not cached used to print
    // "Removed …" and exit 0, which reads as a completed mutation to scripts
    // and agents. It must fail like `identity delete` / `network remove`.
    let cache = tempfile::tempdir().unwrap();

    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .env("SDKT_CACHE_DIR", cache.path())
        .arg("wasm")
        .arg("cache")
        .arg("remove")
        .arg("definitelynotcached")
        .assert();
    assert
        .failure()
        .stderr(predicates::str::contains("Not found"))
        .stderr(predicates::str::contains("'definitelynotcached'"))
        .stderr(predicates::str::contains("not found in testnet cache"))
        .stdout(predicates::str::contains("Removed").not());
}

#[test]
fn test_cli_wasm_cache_clear_reports_truthfully_on_empty_cache() {
    // Clearing an empty cache is a true no-op success (the post-condition
    // holds), unlike removing a named artifact that does not exist.
    let cache = tempfile::tempdir().unwrap();

    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .env("SDKT_CACHE_DIR", cache.path())
        .arg("wasm")
        .arg("cache")
        .arg("clear")
        .arg("--network")
        .arg("testnet")
        .assert();
    assert.success().stdout(predicates::str::contains(
        "Cleared all cache entries for testnet.",
    ));
}

#[test]
fn test_cli_wasm_cache_clear_removes_existing_entries() {
    let cache = tempfile::tempdir().unwrap();
    let net_dir = cache.path().join("wasm").join("testnet");
    std::fs::create_dir_all(&net_dir).unwrap();
    std::fs::write(net_dir.join("aaa.json"), "{}").unwrap();
    std::fs::write(net_dir.join("aaa.wasm"), b"wasm-bytes").unwrap();

    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .env("SDKT_CACHE_DIR", cache.path())
        .arg("wasm")
        .arg("cache")
        .arg("clear")
        .arg("--network")
        .arg("testnet")
        .assert();
    assert.success().stdout(predicates::str::contains(
        "Cleared all cache entries for testnet.",
    ));

    let mut info = Command::cargo_bin("sdkt").unwrap();
    info.env("SDKT_CACHE_DIR", cache.path())
        .arg("wasm")
        .arg("cache")
        .arg("info")
        .assert()
        .success()
        .stdout(predicates::str::contains("Entries: 0"));
}

#[test]
fn test_cli_wasm_inspect_missing_file() {
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .arg("wasm")
        .arg("inspect")
        .arg("non_existent_file.wasm")
        .assert();
    assert
        .failure()
        .stderr(predicates::str::contains("Error reading WASM file"));
}

#[test]
fn test_cli_wasm_inspect_invalid_wasm() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    std::fs::write(tmp.path(), b"invalid wasm data").unwrap();

    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd.arg("wasm").arg("inspect").arg(tmp.path()).assert();
    assert
        .failure()
        .stderr(predicates::str::contains("Error parsing WASM metadata"));
}

#[test]
fn test_cli_wasm_inspect_valid_empty_wasm() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    // A minimal valid WASM binary (magic + version 1)
    std::fs::write(tmp.path(), [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).unwrap();

    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd.arg("wasm").arg("inspect").arg(tmp.path()).assert();
    assert
        .success()
        .stdout(predicates::str::contains("WASM Inspection Report"))
        .stdout(predicates::str::contains("Size: 8 bytes"))
        .stdout(predicates::str::contains("Contract Spec Available: No"));
}

#[test]
fn test_cli_wasm_inspect_json() {
    let tmp = tempfile::NamedTempFile::new().unwrap();
    std::fs::write(tmp.path(), [0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]).unwrap();

    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .arg("wasm")
        .arg("inspect")
        .arg(tmp.path())
        .arg("--format")
        .arg("json")
        .assert();
    assert
        .success()
        .stdout(predicates::str::contains("\"size_bytes\": 8"));
}

#[test]
fn test_cli_wasm_inspect_us_new_json_kind_strings() {
    let wasm_path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/us_new.wasm");
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .arg("wasm")
        .arg("inspect")
        .arg(wasm_path)
        .arg("--format")
        .arg("json")
        .assert();

    let output = assert.success().get_output().stdout.clone();
    let stdout = String::from_utf8_lossy(&output);
    assert!(!stdout.contains("Func("));
    assert!(!stdout.contains("\"Func\""));
    assert!(!stdout.contains("\"Memory\""));
    assert!(stdout.contains("\"kind\": \"func\""));
    assert!(stdout.contains("\"kind\": \"memory\""));
}

#[test]
fn test_cli_wasm_inspect_us_new_pretty_kind_strings() {
    let wasm_path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/us_new.wasm");
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd.arg("wasm").arg("inspect").arg(wasm_path).assert();

    let output = assert.success().get_output().stdout.clone();
    let stdout = String::from_utf8_lossy(&output);
    assert!(!stdout.contains("[Func]"));
    assert!(!stdout.contains("[Memory]"));
    assert!(stdout.contains("[func]") || stdout.contains("[memory]"));
}

#[test]
fn test_cli_wasm_inspect_us_new_contract_metadata_pretty() {
    // contractmetav0 payload must be decoded and surfaced as key = value
    // lines (issue #171), not just the section name.
    let wasm_path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/us_new.wasm");
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd.arg("wasm").arg("inspect").arg(wasm_path).assert();

    let output = assert.success().get_output().stdout.clone();
    let stdout = String::from_utf8_lossy(&output);
    assert!(
        stdout.contains("Contract Metadata (3):"),
        "expected a Contract Metadata block, got:\n{stdout}"
    );
    // Values matching XDR ground truth for this fixture.
    assert!(stdout.contains("rsver = 1.97.1"));
    assert!(stdout.contains("rssdkver = 22.0.11#"));
    assert!(stdout.contains("cliver = 27.1.0#"));
}

#[test]
fn test_cli_wasm_inspect_us_old_contract_metadata_empty() {
    // us_old.wasm carries no contractmetav0: the block is shown as (none)
    // and everything else renders as before.
    let wasm_path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/us_old.wasm");
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd.arg("wasm").arg("inspect").arg(wasm_path).assert();

    let output = assert.success().get_output().stdout.clone();
    let stdout = String::from_utf8_lossy(&output);
    assert!(stdout.contains("Contract Metadata (0):"));
    assert!(stdout.contains("(none)"));
}

#[test]
fn test_cli_wasm_metadata_missing_contract() {
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    let assert = cmd
        .arg("wasm")
        .arg("metadata")
        // No --contract
        .assert();
    assert.failure();
}

use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use predicates::prelude::*;
use sdkt_xdr::{encode_ledger_key, LedgerKeyParams};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
use stellar_xdr::{
    ContractCodeEntry, ContractCodeEntryExt, ContractDataDurability, ContractDataEntry,
    ContractExecutable, ContractId, ExtensionPoint, Hash, LedgerEntry, LedgerEntryData,
    LedgerEntryExt, Limited, Limits, ScAddress, ScContractInstance, ScVal, WriteXdr,
};
use tempfile::tempdir;

static WASM_FIXTURE: &[u8] = include_bytes!("fixtures/us_new.wasm");
const CONTRACT_ID: &str = "CAE3U7JKESRWZHPEQ72DVNGOQ6WPA7HSPQZL5YV46NPCE4TMUPAGYMEC";
const WASM_HASH_HEX: &str = "551c5a9c7fd4c4a71e57e9c8a0ece1e7bd506ea065993c63db2dc35516406775";

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

fn contract_data_entry_xdr(wasm_hash: [u8; 32]) -> String {
    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 contract_code_entry_xdr(wasm_hash: [u8; 32], code: &[u8]) -> String {
    encode_ledger_entry(&LedgerEntry {
        last_modified_ledger_seq: 1,
        data: LedgerEntryData::ContractCode(ContractCodeEntry {
            ext: ContractCodeEntryExt::V0,
            hash: Hash(wasm_hash),
            code: code.to_vec().try_into().unwrap(),
        }),
        ext: LedgerEntryExt::V0,
    })
}

fn spawn_mock_rpc_server(wasm_bytes: &'static [u8]) -> String {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://{}", addr);

    let contract_id_hex = "09ba7d2a24a36c9de487f43ab4ce87acf07cf27c32bee2bcf35e22726ca3c06c";
    let contract_data_key =
        encode_ledger_key(&LedgerKeyParams::ContractData(contract_id_hex.to_string())).unwrap();
    let contract_code_key =
        encode_ledger_key(&LedgerKeyParams::ContractCode(WASM_HASH_HEX.to_string())).unwrap();

    let mut wasm_hash = [0u8; 32];
    hex::decode_to_slice(WASM_HASH_HEX, &mut wasm_hash).unwrap();

    let inspect_xdr = contract_data_entry_xdr(wasm_hash);
    let code_xdr = contract_code_entry_xdr(wasm_hash, wasm_bytes);

    thread::spawn(move || {
        for conn in listener.incoming() {
            let mut sock = match conn {
                Ok(s) => s,
                Err(_) => break,
            };
            let mut buf = [0u8; 16384];
            let n = sock.read(&mut buf).unwrap_or(0);
            let req = String::from_utf8_lossy(&buf[..n]).to_string();

            let body = if req.contains("\"getLatestLedger\"") {
                r#"{"jsonrpc":"2.0","id":1,"result":{"id":"test","sequence":100,"protocolVersion":20}}"#.to_string()
            } else if req.contains("\"getLedgerEntries\"") {
                if req.contains(&contract_data_key) {
                    format!(
                        r#"{{"jsonrpc":"2.0","id":1,"result":{{"entries":[{{"key":"{contract_data_key}","xdr":"{inspect_xdr}","lastModifiedLedgerSeq":1}}],"latestLedger":100}}}}"#
                    )
                } else if req.contains(&contract_code_key) {
                    format!(
                        r#"{{"jsonrpc":"2.0","id":1,"result":{{"entries":[{{"key":"{contract_code_key}","xdr":"{code_xdr}","lastModifiedLedgerSeq":1}}],"latestLedger":100}}}}"#
                    )
                } else {
                    r#"{"jsonrpc":"2.0","id":1,"result":{"entries":[],"latestLedger":100}}"#
                        .to_string()
                }
            } else {
                r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32601,"message":"method not found"}}"#
                    .to_string()
            };

            let resp = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                body.len(),
                body
            );
            let _ = sock.write_all(resp.as_bytes());
            let _ = sock.flush();
        }
    });

    url
}

fn sdkt_isolated(cache_dir: &std::path::Path, network_dir: &std::path::Path) -> Command {
    let mut cmd = Command::cargo_bin("sdkt").unwrap();
    cmd.env("SDKT_CACHE_DIR", cache_dir);
    cmd.env("SDKT_NETWORK_DIR", network_dir);
    cmd
}

#[test]
fn test_cli_network_conflicts_rejected() {
    let cache_dir = tempdir().unwrap();
    let network_dir = tempdir().unwrap();

    // 1. wasm metadata: --network with --rpc-url
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network",
            "mainnet",
            "--rpc-url",
            "http://127.0.0.1:1234",
        ])
        .assert()
        .failure()
        .stderr(
            predicates::str::contains("cannot be used with")
                .or(predicates::str::contains("conflicts with")),
        );

    // 2. wasm metadata: --network with --network-profile
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network",
            "testnet",
            "--network-profile",
            "mocknet",
        ])
        .assert()
        .failure()
        .stderr(
            predicates::str::contains("cannot be used with")
                .or(predicates::str::contains("conflicts with")),
        );

    // 3. verify: --network with --rpc-url
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "verify",
            "--contract",
            CONTRACT_ID,
            "--network",
            "mainnet",
            "--rpc-url",
            "http://127.0.0.1:1234",
        ])
        .assert()
        .failure()
        .stderr(
            predicates::str::contains("cannot be used with")
                .or(predicates::str::contains("conflicts with")),
        );

    // 4. health: --network with --network-profile
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "health",
            "--contract",
            CONTRACT_ID,
            "--network",
            "futurenet",
            "--network-profile",
            "mocknet",
        ])
        .assert()
        .failure()
        .stderr(
            predicates::str::contains("cannot be used with")
                .or(predicates::str::contains("conflicts with")),
        );
}

#[test]
fn test_cli_wasm_metadata_mock_rpc_cache_namespace() {
    let cache_dir = tempdir().unwrap();
    let network_dir = tempdir().unwrap();
    let mock_url = spawn_mock_rpc_server(WASM_FIXTURE);

    // Add a named network profile
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "network",
            "add",
            "profile_alpha",
            "--rpc-url",
            &mock_url,
            "--passphrase",
            "Test SDF Network ; September 2015",
        ])
        .assert()
        .success();

    // 1. First fetch: should be Cache Miss and write to wasm/profile_alpha/
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "profile_alpha",
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Cache Status: Miss"))
        .stdout(predicates::str::contains("Network: profile_alpha"));

    let cached_file = cache_dir
        .path()
        .join("wasm")
        .join("profile_alpha")
        .join(format!("{}.json", WASM_HASH_HEX));
    assert!(
        cached_file.exists(),
        "Cache file must exist at {:?}",
        cached_file
    );

    // Verify testnet cache namespace was NOT touched
    let testnet_dir = cache_dir.path().join("wasm").join("testnet");
    assert!(
        !testnet_dir.exists(),
        "testnet cache namespace must not be touched"
    );

    // 2. Second fetch: should be Cache Hit from profile_alpha cache
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "profile_alpha",
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Cache Status: Hit"))
        .stdout(predicates::str::contains("Network: profile_alpha"));
}

#[test]
fn test_cli_wasm_metadata_mock_rpc_reports_contract_metadata() {
    // #171: the on-chain `wasm metadata --contract` path must report the same
    // contractmetav0 entries the offline `wasm inspect` prints, when the WASM
    // bytes are available (here: served by the mock RPC).
    let cache_dir = tempdir().unwrap();
    let network_dir = tempdir().unwrap();
    let mock_url = spawn_mock_rpc_server(WASM_FIXTURE);

    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "network",
            "add",
            "profile_meta",
            "--rpc-url",
            &mock_url,
            "--passphrase",
            "Test SDF Network ; September 2015",
        ])
        .assert()
        .success();

    // Pretty output: decoded key = value entries, matching the fixture.
    let pretty = sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "profile_meta",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8_lossy(&pretty.get_output().stdout).clone();
    assert!(
        stdout.contains("Contract Metadata (3):"),
        "expected contractmetav0 entries on the on-chain path, got:\n{stdout}"
    );
    assert!(stdout.contains("rsver = 1.97.1"));
    assert!(stdout.contains("rssdkver = 22.0.11#"));
    assert!(stdout.contains("cliver = 27.1.0#"));

    // JSON output: additive top-level `contract_meta` array, and every
    // pre-existing inspection key still present and unrenamed.
    let json_out = sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "profile_meta",
            "--format",
            "json",
        ])
        .assert()
        .success();
    let json = String::from_utf8_lossy(&json_out.get_output().stdout).clone();
    let v: serde_json::Value =
        serde_json::from_str(&json).unwrap_or_else(|e| panic!("invalid JSON ({e}): {json}"));

    for key in [
        "contract_id",
        "wasm_hash",
        "wasm_size",
        "abi",
        "storage_summary",
        "ttl_info",
        "storage_keys",
        "contract_meta",
    ] {
        assert!(v.get(key).is_some(), "missing `{key}` in {v}");
    }

    let entries = v["contract_meta"]
        .as_array()
        .expect("contract_meta should be an array");
    assert_eq!(entries.len(), 3, "expected 3 entries, got {entries:?}");
    let keys: Vec<&str> = entries
        .iter()
        .filter_map(|e| e.get("key").and_then(|k| k.as_str()))
        .collect();
    assert_eq!(keys, vec!["rsver", "rssdkver", "cliver"]);
    assert_eq!(entries[0]["value"].as_str(), Some("1.97.1"));
}

#[test]
fn test_cli_cache_namespace_isolation_regression() {
    let cache_dir = tempdir().unwrap();
    let network_dir = tempdir().unwrap();
    let mock_url = spawn_mock_rpc_server(WASM_FIXTURE);

    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "network",
            "add",
            "profile_net1",
            "--rpc-url",
            &mock_url,
            "--passphrase",
            "Test SDF Network ; September 2015",
        ])
        .assert()
        .success();

    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "network",
            "add",
            "profile_net2",
            "--rpc-url",
            &mock_url,
            "--passphrase",
            "Test SDF Network ; September 2015",
        ])
        .assert()
        .success();

    // Run wasm metadata on profile_net1
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "profile_net1",
        ])
        .assert()
        .success();

    let net1_file = cache_dir
        .path()
        .join("wasm")
        .join("profile_net1")
        .join(format!("{}.json", WASM_HASH_HEX));
    assert!(net1_file.exists());

    // Plant a fake/poisoned cache entry in testnet
    let testnet_dir = cache_dir.path().join("wasm").join("testnet");
    std::fs::create_dir_all(&testnet_dir).unwrap();
    let testnet_poison_file = testnet_dir.join(format!("{}.json", WASM_HASH_HEX));
    std::fs::write(&testnet_poison_file, b"{\"poisoned\":true}").unwrap();

    // Query on profile_net2: must NOT read from testnet, must write to profile_net2
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "profile_net2",
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Cache Status: Miss"));

    let net2_file = cache_dir
        .path()
        .join("wasm")
        .join("profile_net2")
        .join(format!("{}.json", WASM_HASH_HEX));
    assert!(net2_file.exists());

    // The testnet planted file must remain untouched
    let testnet_content = std::fs::read(&testnet_poison_file).unwrap();
    assert_eq!(testnet_content, b"{\"poisoned\":true}");

    // Also assert offline --network mainnet failure does NOT touch testnet
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "wasm",
            "metadata",
            "--contract",
            CONTRACT_ID,
            "--network",
            "mainnet",
        ])
        .assert()
        .failure();

    let testnet_content_after = std::fs::read(&testnet_poison_file).unwrap();
    assert_eq!(testnet_content_after, b"{\"poisoned\":true}");
}

#[test]
fn test_cli_verify_and_health_network_labels_against_mock() {
    let cache_dir = tempdir().unwrap();
    let network_dir = tempdir().unwrap();
    let mock_url = spawn_mock_rpc_server(WASM_FIXTURE);

    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "network",
            "add",
            "custom_endpoint",
            "--rpc-url",
            &mock_url,
            "--passphrase",
            "Test SDF Network ; September 2015",
        ])
        .assert()
        .success();

    // 1. Verify with profile label
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "verify",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "custom_endpoint",
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Network     : custom_endpoint"));

    // 2. Verify with profile label in JSON format
    let assert_verify_json = sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "verify",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "custom_endpoint",
            "--format",
            "json",
        ])
        .assert()
        .success();
    let verify_val: serde_json::Value =
        serde_json::from_slice(&assert_verify_json.get_output().stdout).unwrap();
    assert_eq!(verify_val["network"], "custom_endpoint");

    // 3. Health with profile label
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "health",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "custom_endpoint",
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Network     : custom_endpoint"));

    // 4. Health with profile label in JSON format
    let assert_health_json = sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "health",
            "--contract",
            CONTRACT_ID,
            "--network-profile",
            "custom_endpoint",
            "--format",
            "json",
        ])
        .assert()
        .success();
    let health_val: serde_json::Value =
        serde_json::from_slice(&assert_health_json.get_output().stdout).unwrap();
    assert_eq!(health_val["network"], "custom_endpoint");

    // 5. Verify & Health with mainnet passphrase resolves to "mainnet" label
    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "verify",
            "--contract",
            CONTRACT_ID,
            "--rpc-url",
            &mock_url,
            "--network-passphrase",
            "Public Global Stellar Network ; September 2015",
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Network     : mainnet"));

    sdkt_isolated(cache_dir.path(), network_dir.path())
        .args([
            "health",
            "--contract",
            CONTRACT_ID,
            "--rpc-url",
            &mock_url,
            "--network-passphrase",
            "Public Global Stellar Network ; September 2015",
        ])
        .assert()
        .success()
        .stdout(predicates::str::contains("Network     : mainnet"));
}