miden-client-cli 0.14.7

The official command line client for interacting with the Miden network
Documentation
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
use std::env::{self, temp_dir};
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::Result;
use assert_cmd::Command;
use assert_cmd::cargo::cargo_bin_cmd;
use miden_client::account::{AccountId, AccountStorageMode};
use miden_client::address::AddressInterface;
use miden_client::auth::{RPO_FALCON_SCHEME_ID, TransactionAuthenticator};
use miden_client::builder::ClientBuilder;
use miden_client::crypto::{FeltRng, RandomCoin};
use miden_client::keystore::Keystore;
use miden_client::note::{
    Note,
    NoteAssets,
    NoteFile,
    NoteId,
    NoteMetadata,
    NoteRecipient,
    NoteStorage,
    NoteTag,
    NoteType,
};
use miden_client::note_transport::NOTE_TRANSPORT_TESTNET_ENDPOINT;
use miden_client::rpc::Endpoint;
use miden_client::testing::account_id::ACCOUNT_ID_PRIVATE_SENDER;
use miden_client::testing::common::{
    ACCOUNT_ID_REGULAR,
    FilesystemKeyStore,
    create_test_store_path,
    execute_tx_and_sync,
    insert_new_wallet,
};
use miden_client::transaction::TransactionRequestBuilder;
use miden_client::utils::Serializable;
use miden_client::{self, Client, DebugMode, Felt};
use miden_client_cli::MIDEN_DIR;
use miden_client_cli::config::Network;
use miden_client_sqlite_store::SqliteStore;
use predicates::str::contains;
use rand::Rng;

// CLI TESTS
// ================================================================================================

/// This Module contains integration tests that test against the miden CLI directly. In order to do
/// that we use [assert_cmd](https://github.com/assert-rs/assert_cmd?tab=readme-ov-file) which aids
/// in the process of spawning commands.
///
/// Tests added here should only interact with the CLI through `assert_cmd`, with the exception of
/// reading data from the client's store since it would be quite tedious to parse the CLI output
/// for that and is more error prone.
///
/// Note that each client has to run in its own directory so you'll need to create a random
/// temporary directory (check existing tests to see how). You'll also need to make the commands
/// run as if they were spawned on that directory. `std::env::set_current_dir` shouldn't be used as
/// it impacts on other tests and instead you should use `assert_cmd::Command::current_dir`.

// INIT TESTS
// ================================================================================================

#[test]
fn init_without_params() {
    let temp_dir = init_cli().1;

    // Trying to init twice should result in an error
    let mut init_cmd = cargo_bin_cmd!("miden-client");
    init_cmd.args(["init", "--local"]);
    init_cmd.current_dir(&temp_dir).assert().failure();
}

#[test]
fn init_with_params() {
    let store_path = create_test_store_path();
    let endpoint = Endpoint::devnet();
    let temp_dir = init_cli_with_store_path(&store_path, &endpoint);

    // Assert the config file contains the specified contents
    let mut config_path = temp_dir.clone();
    config_path.push(MIDEN_DIR);
    config_path.push("miden-client.toml");
    let mut config_file = File::open(config_path).unwrap();
    let mut config_file_str = String::new();
    config_file.read_to_string(&mut config_file_str).unwrap();

    assert!(config_file_str.contains(store_path.to_str().unwrap()));
    assert!(config_file_str.contains("devnet"));

    // Trying to init twice should result in an error
    let mut init_cmd = cargo_bin_cmd!("miden-client");
    init_cmd.args([
        "init",
        "--local",
        "--network",
        "devnet",
        "--store-path",
        store_path.to_str().unwrap(),
    ]);
    init_cmd.current_dir(&temp_dir).assert().failure();
}

#[test]
#[serial_test::file_serial]
fn silent_initialization_uses_default_values() {
    let miden_home = set_isolated_miden_home();

    let temp_dir = temp_dir().join(format!("cli-test-{}", rand::rng().random::<u64>()));
    std::fs::create_dir_all(&temp_dir).unwrap();

    // Run any command to trigger silent initialization (should create global config)
    let mut account_cmd = cargo_bin_cmd!("miden-client");
    account_cmd.args(["account"]);
    account_cmd.current_dir(&temp_dir).assert().success();

    // Read and verify the global config file contents
    let global_config_path = miden_home.join("miden-client.toml");
    let config_content = std::fs::read_to_string(&global_config_path).unwrap();

    // Verify default values are used
    assert!(config_content.contains("testnet"), "Should use testnet as default network");
    assert!(
        config_content.contains("store.sqlite3"),
        "Should use default store path (relative to config file)"
    );
    assert!(
        config_content.contains("keystore"),
        "Should use default keystore directory (relative to config file)"
    );
    // Verify note transport defaults to the testnet endpoint
    assert!(
        config_content.contains("[note_transport]"),
        "Silent init should write a [note_transport] section"
    );
    assert!(
        config_content.contains(NOTE_TRANSPORT_TESTNET_ENDPOINT),
        "Silent init should default note transport to the testnet endpoint"
    );
    // Verify that the paths don't have the .miden prefix in the config
    // (they're relative to the config file location now)
    assert!(
        !config_content.contains(&format!("{MIDEN_DIR}/store.sqlite3")),
        "Paths should be relative to config file, not include {MIDEN_DIR}/ prefix"
    );

    // Verify no local config was created
    let local_config_path = temp_dir.join(MIDEN_DIR).join("miden-client.toml");
    assert!(
        !local_config_path.exists(),
        "Should not create local config during silent initialization"
    );
}

#[test]
fn miden_directory_structure_creation() {
    let temp_dir = temp_dir().join(format!("cli-test-{}", rand::rng().random::<u64>()));
    std::fs::create_dir_all(&temp_dir).unwrap();

    // Run init command to create .miden directory structure
    let mut init_cmd = cargo_bin_cmd!("miden-client");
    init_cmd.args(["init", "--local"]);
    init_cmd.current_dir(&temp_dir).assert().success();

    let miden_dir = temp_dir.join(MIDEN_DIR);

    // Verify .miden directory exists
    assert!(miden_dir.exists(), ".miden directory should be created");
    assert!(miden_dir.is_dir(), ".miden should be a directory");

    // Verify expected files that are created during init
    let config_file = miden_dir.join("miden-client.toml");
    assert!(config_file.exists(), "config file should be created");
    assert!(config_file.is_file(), "config should be a file");

    // Verify packages directory is created with template files
    let packages_dir = miden_dir.join("packages");
    assert!(packages_dir.exists(), "packages directory should be created");
    assert!(packages_dir.is_dir(), "packages should be a directory");

    // Check that expected package files exist
    let basic_wallet_package = packages_dir.join("basic-wallet.masp");
    assert!(basic_wallet_package.exists(), "basic-wallet package should be created");

    let basic_auth_package = packages_dir.join("auth/basic-auth.masp");
    assert!(basic_auth_package.exists(), "basic-auth package should be created");

    let ecdsa_auth_package = packages_dir.join("auth/ecdsa-auth.masp");
    assert!(ecdsa_auth_package.exists(), "ecdsa-auth package should be created");

    let basic_faucet_package = packages_dir.join("basic-fungible-faucet.masp");
    assert!(basic_faucet_package.exists(), "basic-fungible-faucet package should be created");

    // Verify config file contains correct paths relative to config file location
    let config_content = std::fs::read_to_string(&config_file).unwrap();
    assert!(
        config_content.contains("store.sqlite3"),
        "Config should reference store path relative to config file"
    );
    assert!(
        config_content.contains("keystore"),
        "Config should reference keystore path relative to config file"
    );
    assert!(
        config_content.contains("packages"),
        "Config should reference packages path relative to config file"
    );
    assert!(
        config_content.contains("token_symbol_map.toml"),
        "Config should reference token symbol map path relative to config file"
    );
    // Verify that the paths don't have the .miden prefix (they're relative to config file now)
    assert!(
        !config_content.contains(&format!("{MIDEN_DIR}/store.sqlite3")),
        "Paths should be relative to config file, not include {MIDEN_DIR}/ prefix"
    );

    // Verify default RPC endpoint is set
    assert!(
        config_content.contains("https://rpc.testnet.miden.io"),
        "Config should have default testnet RPC endpoint"
    );

    // Test that keystore directory doesn't exist initially (created on demand)
    let keystore_dir = miden_dir.join("keystore");
    assert!(!keystore_dir.exists(), "keystore directory should not exist until first use");

    // Test that token symbol map file doesn't exist initially (created on demand)
    let token_map_file = miden_dir.join("token_symbol_map.toml");
    assert!(!token_map_file.exists(), "token symbol map should not exist until first use");

    // Test that running any command after init creates keystore directory on-demand
    let mut account_cmd = cargo_bin_cmd!("miden-client");
    account_cmd.args(["account"]);
    account_cmd.current_dir(&temp_dir).assert().success();

    // Now keystore directory should exist
    let keystore_dir = miden_dir.join("keystore");
    assert!(keystore_dir.exists(), "keystore directory should be created on first use");
    assert!(keystore_dir.is_dir(), "keystore should be a directory");
}

#[test]
fn silent_initialization_does_not_override_existing_config() {
    let temp_dir = temp_dir().join(format!("cli-test-{}", rand::rng().random::<u64>()));
    std::fs::create_dir_all(&temp_dir).unwrap();

    // Create the MIDEN_DIR directory and manual configuration file
    let miden_dir = temp_dir.join(MIDEN_DIR);
    std::fs::create_dir_all(&miden_dir).unwrap();
    let config_path = miden_dir.join("miden-client.toml");
    // Manual configuration file
    let custom_config = format!(
        r#"
        store_filepath = "{MIDEN_DIR}/custom-store.sqlite3"
        secret_keys_directory = "{MIDEN_DIR}/custom-keystore"
        token_symbol_map_filepath = "{MIDEN_DIR}/custom-tokens.toml"
        package_directory = "{MIDEN_DIR}/custom-templates"

        [rpc]
        endpoint = "https://custom-endpoint.com"
        timeout_ms = 5000

        [remote_prover_timeout]
        secs = 20
        nanos = 0
        "#
    );
    std::fs::write(&config_path, custom_config).unwrap();

    // Run command without explicitly initializing
    let mut account_cmd = cargo_bin_cmd!("miden-client");
    account_cmd.args(["account"]);
    account_cmd.current_dir(&temp_dir).assert().success();

    // Verify original config remains unchanged
    let config_content = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        config_content.contains("custom-endpoint.com"),
        "Config should not be overwritten"
    );
    assert!(
        config_content.contains("custom-store.sqlite3"),
        "Config should not be overwritten"
    );
}

// TX TESTS
// ================================================================================================

/// This test tries to run a mint TX using the CLI for an account that isn't tracked.
#[tokio::test]
async fn mint_with_untracked_account() -> Result<()> {
    let temp_dir = init_cli().1;

    // Create faucet account
    let fungible_faucet_account_id = new_faucet_cli(&temp_dir, AccountStorageMode::Private);

    sync_cli(&temp_dir);

    // Let's try and mint
    mint_cli(
        &temp_dir,
        &AccountId::try_from(ACCOUNT_ID_REGULAR).unwrap().to_hex(),
        &fungible_faucet_account_id,
    );

    // Wait until the faucet's mint transaction is committed on the node.
    // We sync for a committed transaction (not note) because the target account is untracked,
    // so the output note's tag won't be requested during sync and the note will never appear.
    sync_until_committed_transaction(&temp_dir);
    Ok(())
}

/// This test tries to run a mint TX using the CLI for an account that isn't tracked.
#[tokio::test]
async fn token_symbol_mapping() -> Result<()> {
    let (store_path, temp_dir, endpoint) = init_cli();

    // Create faucet account
    let fungible_faucet_account_id = new_faucet_cli(&temp_dir, AccountStorageMode::Private);

    // Create a token symbol mapping file in the MIDEN_DIR directory
    let token_symbol_map_path = temp_dir.join(MIDEN_DIR).join("token_symbol_map.toml");
    let token_symbol_map_content =
        format!(r#"BTC = {{ id = "{fungible_faucet_account_id}", decimals = 10 }}"#);
    fs::write(&token_symbol_map_path, token_symbol_map_content).unwrap();

    sync_cli(&temp_dir);

    let mut mint_cmd = cargo_bin_cmd!("miden-client");
    mint_cmd.args([
        "mint",
        "--target",
        AccountId::try_from(ACCOUNT_ID_REGULAR).unwrap().to_hex().as_str(),
        "--asset",
        "0.00001::BTC",
        "-n",
        "private",
        "--force",
    ]);

    let output = mint_cmd.current_dir(&temp_dir).output().unwrap();
    assert!(
        output.status.success(),
        "token_symbol mint failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let note_id = String::from_utf8(output.stdout)
        .unwrap()
        .split_whitespace()
        .skip_while(|&word| word != "Output")
        .find(|word| word.starts_with("0x"))
        .unwrap()
        .to_string();

    let note = {
        let (client, _) = create_rust_client_with_store_path(&store_path, endpoint).await?;
        client.get_output_note(NoteId::try_from_hex(&note_id)?).await?.unwrap()
    };

    assert_eq!(note.assets().num_assets(), 1);
    assert_eq!(note.assets().iter().next().unwrap().unwrap_fungible().amount(), 100_000);
    Ok(())
}

// IMPORT TESTS
// ================================================================================================

// Only one faucet is being created on the genesis block
const GENESIS_ACCOUNTS_FILENAMES: [&str; 1] = ["account.mac"];

// This tests that it's possible to import the genesis accounts and interact with them. To do so it:
//
// 1. Creates a new client
// 2. Imports the genesis account
// 3. Creates a wallet
// 4. Runs a mint tx and syncs until the transaction and note are committed
#[tokio::test]
#[ignore = "import genesis test gets ignored by default so integration tests can be ran with dockerized and remote nodes where we might not have the genesis data"]
async fn import_genesis_accounts_can_be_used_for_transactions() -> Result<()> {
    let (store_path, temp_dir, endpoint) = init_cli();

    for genesis_account_filename in GENESIS_ACCOUNTS_FILENAMES {
        let mut new_file_path = temp_dir.clone();
        new_file_path.push(genesis_account_filename);

        let cargo_workspace_dir =
            env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set");
        let source_path = format!("{cargo_workspace_dir}/../../data/{genesis_account_filename}");

        std::fs::copy(source_path, new_file_path).unwrap();
    }

    // Import genesis accounts
    let mut args = vec!["import"];
    for filename in GENESIS_ACCOUNTS_FILENAMES {
        args.push(filename);
    }
    let mut import_cmd = cargo_bin_cmd!("miden-client");
    import_cmd.args(&args);
    import_cmd.current_dir(&temp_dir).assert().success();

    sync_cli(&temp_dir);

    let fungible_faucet_account_id = {
        let (client, _) = create_rust_client_with_store_path(&store_path, endpoint).await?;
        let accounts = client.get_account_headers().await?;

        let account_ids = accounts.iter().map(|(acc, _seed)| acc.id()).collect::<Vec<_>>();
        let faucet_accounts = account_ids.iter().filter(|id| id.is_faucet()).collect::<Vec<_>>();

        assert_eq!(faucet_accounts.len(), 1);

        faucet_accounts[0].to_hex()
    };

    // Ensure they've been importing by showing them
    let args = vec!["account", "--show", &fungible_faucet_account_id];
    let mut show_cmd = cargo_bin_cmd!("miden-client");
    show_cmd.args(&args);
    show_cmd.current_dir(&temp_dir).assert().success();

    // Let's try and mint
    mint_cli(
        &temp_dir,
        &AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER).unwrap().to_hex(),
        &fungible_faucet_account_id,
    );

    // Wait until the mint transaction is committed on the node.
    // We sync for a committed transaction (not note) because the target account is untracked.
    sync_until_committed_transaction(&temp_dir);
    Ok(())
}

// This tests that it's possible to export and import notes into other CLIs. To do so it:
//
// 1. Creates a client A with a faucet
// 2. Creates a client B with a regular account
// 3. On client A runs a mint transaction, and exports the output note
// 4. On client B imports the note and consumes it
#[tokio::test]
async fn cli_export_import_note() -> Result<()> {
    const NOTE_FILENAME: &str = "test_note.mno";

    let temp_dir_1 = init_cli().1;
    let temp_dir_2 = init_cli().1;

    // Create wallet account
    let first_basic_account_id = new_wallet_cli(&temp_dir_2, AccountStorageMode::Private);

    // Create faucet account
    let fungible_faucet_account_id = new_faucet_cli(&temp_dir_1, AccountStorageMode::Private);

    sync_cli(&temp_dir_1);

    // Let's try and mint
    let note_to_export_id =
        mint_cli(&temp_dir_1, &first_basic_account_id, &fungible_faucet_account_id);

    // Export without type fails
    let mut export_cmd = cargo_bin_cmd!("miden-client");
    export_cmd.args(["export", &note_to_export_id, "--filename", NOTE_FILENAME]);
    export_cmd.current_dir(&temp_dir_1).assert().failure().code(1); // Code returned when the CLI handles an error

    // Export the note
    let mut export_cmd = cargo_bin_cmd!("miden-client");
    export_cmd.args([
        "export",
        &note_to_export_id,
        "--filename",
        NOTE_FILENAME,
        "--export-type",
        "partial",
    ]);
    export_cmd.current_dir(&temp_dir_1).assert().success();

    // Copy the note
    let mut client_1_note_file_path = temp_dir_1.clone();
    client_1_note_file_path.push(NOTE_FILENAME);
    let mut client_2_note_file_path = temp_dir_2.clone();
    client_2_note_file_path.push(NOTE_FILENAME);
    std::fs::copy(client_1_note_file_path, client_2_note_file_path).unwrap();

    // Import Note on second client
    let mut import_cmd = cargo_bin_cmd!("miden-client");
    import_cmd.args(["import", NOTE_FILENAME]);
    import_cmd.current_dir(&temp_dir_2).assert().success();

    // Wait until the note is committed on the node
    sync_until_committed_note(&temp_dir_2);

    show_note_cli(&temp_dir_2, &note_to_export_id, false);
    // Consume the note
    consume_note_cli(&temp_dir_2, &first_basic_account_id, &[&note_to_export_id]);

    // Test send command
    let mock_target_id: AccountId = AccountId::try_from(ACCOUNT_ID_PRIVATE_SENDER).unwrap();
    send_cli(
        &temp_dir_2,
        &first_basic_account_id,
        &mock_target_id.to_hex(),
        &fungible_faucet_account_id,
    );

    Ok(())
}

#[tokio::test]
async fn cli_export_import_account() -> Result<()> {
    const FAUCET_FILENAME: &str = "test_faucet.mac";
    const WALLET_FILENAME: &str = "test_wallet.wal";

    let (_, temp_dir_1, _) = init_cli();
    let (store_path_2, temp_dir_2, endpoint_2) = init_cli();

    // Create faucet account
    let faucet_id = new_faucet_cli(&temp_dir_1, AccountStorageMode::Private);

    // Create wallet account
    let wallet_id = new_wallet_cli(&temp_dir_1, AccountStorageMode::Private);

    // Export the accounts
    let mut export_cmd = cargo_bin_cmd!("miden-client");
    export_cmd.args(["export", &faucet_id, "--account", "--filename", FAUCET_FILENAME]);
    export_cmd.current_dir(&temp_dir_1).assert().success();
    let mut export_cmd = cargo_bin_cmd!("miden-client");
    export_cmd.args(["export", &wallet_id, "--account", "--filename", WALLET_FILENAME]);
    export_cmd.current_dir(&temp_dir_1).assert().success();

    // Copy the account files
    for filename in &[FAUCET_FILENAME, WALLET_FILENAME] {
        let mut client_1_file_path = temp_dir_1.clone();
        client_1_file_path.push(filename);
        let mut client_2_file_path = temp_dir_2.clone();
        client_2_file_path.push(filename);
        std::fs::copy(client_1_file_path, client_2_file_path).unwrap();
    }

    // Import the account from the second client
    let mut import_cmd = cargo_bin_cmd!("miden-client");
    import_cmd.args(["import", FAUCET_FILENAME]);
    import_cmd.current_dir(&temp_dir_2).assert().success();
    let mut import_cmd = cargo_bin_cmd!("miden-client");
    import_cmd.args(["import", WALLET_FILENAME]);
    import_cmd.current_dir(&temp_dir_2).assert().success();

    // Ensure the account was imported
    let (client_2, _) = create_rust_client_with_store_path(&store_path_2, endpoint_2).await?;
    let cli_keystore =
        FilesystemKeyStore::new(temp_dir_2.clone().join(MIDEN_DIR).join("keystore"))?;

    assert!(client_2.get_account(AccountId::from_hex(&faucet_id)?).await.is_ok());
    assert!(client_2.get_account(AccountId::from_hex(&wallet_id)?).await.is_ok());
    sync_cli(&temp_dir_2);

    let note_id = mint_cli(&temp_dir_2, &wallet_id, &faucet_id);

    // Wait until the note is committed on the node
    sync_until_committed_note(&temp_dir_2);

    // Consume the note
    consume_note_cli(&temp_dir_2, &wallet_id, &[&note_id]);

    // Since importing keys should also store a mapping from
    // the account id to its public key commitments, we should be able
    // to retrieve them via the Keystore trait.
    let faucet_pks = cli_keystore
        .get_account_key_commitments(&AccountId::from_hex(&faucet_id)?)
        .await?;

    for stored_pk_commitment in faucet_pks {
        let matching_secret_key = cli_keystore.get_key_sync(stored_pk_commitment).unwrap();
        assert!(matching_secret_key.is_some());
        assert_eq!(matching_secret_key.unwrap().public_key().to_commitment(), stored_pk_commitment);

        let public_key = cli_keystore.get_public_key(stored_pk_commitment).await;
        assert!(public_key.is_some());
        assert_eq!(public_key.unwrap().to_commitment(), stored_pk_commitment);
    }

    let wallet_pks = cli_keystore
        .get_account_key_commitments(&AccountId::from_hex(&wallet_id)?)
        .await?;

    for stored_pk_commitment in wallet_pks {
        let matching_secret_key = cli_keystore.get_key_sync(stored_pk_commitment).unwrap();
        assert!(matching_secret_key.is_some());
        assert_eq!(matching_secret_key.unwrap().public_key().to_commitment(), stored_pk_commitment);

        let public_key = cli_keystore.get_public_key(stored_pk_commitment).await;
        assert!(public_key.is_some());
        assert_eq!(public_key.unwrap().to_commitment(), stored_pk_commitment);
    }

    Ok(())
}

#[test]
fn cli_empty_commands() {
    let temp_dir = init_cli().1;

    let mut create_faucet_cmd = cargo_bin_cmd!("miden-client");
    assert_command_fails_but_does_not_panic(
        create_faucet_cmd.args(["new-account"]).current_dir(&temp_dir),
    );

    let mut import_cmd = cargo_bin_cmd!("miden-client");
    assert_command_fails_but_does_not_panic(import_cmd.args(["export"]).current_dir(&temp_dir));

    let mut mint_cmd = cargo_bin_cmd!("miden-client");
    assert_command_fails_but_does_not_panic(mint_cmd.args(["mint"]).current_dir(&temp_dir));

    let mut send_cmd = cargo_bin_cmd!("miden-client");
    assert_command_fails_but_does_not_panic(send_cmd.args(["send"]).current_dir(&temp_dir));

    let mut swam_cmd = cargo_bin_cmd!("miden-client");
    assert_command_fails_but_does_not_panic(swam_cmd.args(["swap"]).current_dir(&temp_dir));
}

#[tokio::test]
async fn consume_unauthenticated_note() -> Result<()> {
    let temp_dir = init_cli().1;

    // Create wallet account
    let wallet_account_id = new_wallet_cli(&temp_dir, AccountStorageMode::Public);

    // Create faucet account
    let fungible_faucet_account_id = new_faucet_cli(&temp_dir, AccountStorageMode::Public);

    sync_cli(&temp_dir);

    // Mint
    let note_id = mint_cli(&temp_dir, &wallet_account_id, &fungible_faucet_account_id);

    // Wait for the mint transaction to be committed on the node
    sync_until_committed_transaction(&temp_dir);

    // Consume the note, internally this checks that the note was consumed correctly
    consume_note_cli(&temp_dir, &wallet_account_id, &[&note_id]);
    Ok(())
}

// DEVNET & TESTNET TESTS
// ================================================================================================

#[tokio::test]
async fn init_with_devnet() -> Result<()> {
    let store_path = create_test_store_path();
    let endpoint = Endpoint::devnet();
    let temp_dir = init_cli_with_store_path(&store_path, &endpoint);

    // Check in the config file that the network is devnet
    let mut config_path = temp_dir.clone();
    config_path.push(MIDEN_DIR);
    config_path.push("miden-client.toml");
    let mut config_file = File::open(config_path).unwrap();
    let mut config_file_str = String::new();
    config_file.read_to_string(&mut config_file_str).unwrap();

    assert!(config_file_str.contains(&Endpoint::devnet().to_string()));
    Ok(())
}

#[tokio::test]
async fn init_with_testnet() -> Result<()> {
    let store_path = create_test_store_path();
    let endpoint = Endpoint::testnet();
    let temp_dir = init_cli_with_store_path(&store_path, &endpoint);

    // Check in the config file that the network is testnet
    let mut config_path = temp_dir.clone();
    config_path.push(MIDEN_DIR);
    config_path.push("miden-client.toml");
    let mut config_file = File::open(config_path).unwrap();
    let mut config_file_str = String::new();
    config_file.read_to_string(&mut config_file_str).unwrap();

    assert!(config_file_str.contains(&Endpoint::testnet().to_string()));
    Ok(())
}

#[tokio::test]
#[serial_test::file_serial]
async fn debug_mode_outputs_logs() -> Result<()> {
    // This test tries to execute a transaction with debug mode enabled and checks that the stack
    // state is printed. We need to use the CLI for this because the debug logs are always printed
    // to stdout and we can't capture them in a [`Client`] only test.
    // We use the [`Client`] to create a custom note that will print the stack state and consume it
    // using the CLI to check the stdout.
    const NOTE_FILENAME: &str = "test_note.mno";
    unsafe {
        env::set_var("MIDEN_DEBUG", "true");
    }

    // Create a Client and a custom note
    let (store_path, _, endpoint) = init_cli();
    let (mut client, authenticator) =
        create_rust_client_with_store_path(&store_path, endpoint).await?;
    let (account, ..) = insert_new_wallet(
        &mut client,
        AccountStorageMode::Private,
        &authenticator,
        RPO_FALCON_SCHEME_ID,
    )
    .await?;

    // Create the custom note with a script that will print the stack state
    let note_script = "
            @note_script
            pub proc main
                debug.stack
                assert_eq
            end
            ";
    let note_script = client.code_builder().compile_note_script(note_script).unwrap();
    let inputs = NoteStorage::new(vec![]).unwrap();
    let serial_num = client.rng().draw_word();
    let note_metadata = NoteMetadata::new(account.id(), NoteType::Private)
        .with_tag(NoteTag::with_account_target(account.id()));
    let note_assets = NoteAssets::new(vec![]).unwrap();
    let note_recipient = NoteRecipient::new(serial_num, note_script, inputs);
    let note = Note::new(note_assets, note_metadata, note_recipient);

    // Send transaction and wait for it to be committed
    client.sync_state().await?;
    let transaction_request =
        TransactionRequestBuilder::new().own_output_notes(vec![note.clone()]).build()?;
    execute_tx_and_sync(&mut client, account.id(), transaction_request).await?;

    // Export the note
    let note_file: NoteFile = NoteFile::NoteDetails {
        details: note.clone().into(),
        after_block_num: 0.into(),
        tag: Some(note.metadata().tag()),
    };

    // Import the note into the CLI
    let (_, temp_dir, _) = init_cli();

    // Serialize the note
    let note_path = temp_dir.join(NOTE_FILENAME);
    let mut file = File::create(note_path.clone()).unwrap();
    file.write_all(&note_file.to_bytes()).unwrap();

    // Import the note
    let mut import_cmd = cargo_bin_cmd!("miden-client");
    import_cmd.args(["import", note_path.to_str().unwrap()]);
    import_cmd.current_dir(&temp_dir).assert().success();

    sync_cli(&temp_dir);

    // Create wallet account
    let wallet_account_id = new_wallet_cli(&temp_dir, AccountStorageMode::Private);

    // Consume the note and check the output
    let mut consume_note_cmd = cargo_bin_cmd!("miden-client");
    let note_id = note.id().to_hex();
    let mut cli_args = vec!["consume-notes", "--account", &wallet_account_id, "--force"];
    cli_args.extend_from_slice(vec![note_id.as_str()].as_slice());
    consume_note_cmd.args(&cli_args);
    consume_note_cmd
        .current_dir(&temp_dir)
        .assert()
        .success()
        .stdout(contains("Stack state"));

    unsafe {
        env::remove_var("MIDEN_DEBUG");
    }

    Ok(())
}

// ADDRESSES TESTS
// ================================================================================================

#[tokio::test]
async fn list_addresses_add() -> Result<()> {
    let temp_dir = init_cli().1;

    // Create wallet account
    let basic_account_id = new_wallet_cli(&temp_dir, AccountStorageMode::Private);

    sync_cli(&temp_dir);

    let mut list_addresses_cmd = cargo_bin_cmd!("miden-client");
    list_addresses_cmd.args(["address", "list", &basic_account_id]);

    let output = list_addresses_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());
    let formatted_output = String::from_utf8(output.stdout).unwrap();
    assert!(formatted_output.contains(&basic_account_id));
    assert!(formatted_output.contains("Unspecified"));
    assert!(!formatted_output.contains("BasicWallet"));

    // Add a basic wallet address to the account
    let mut add_address_cmd = cargo_bin_cmd!("miden-client");
    let custom_note_tag_len = "10";
    add_address_cmd.args([
        "address",
        "add",
        &basic_account_id,
        &AddressInterface::BasicWallet.to_string(),
        custom_note_tag_len,
    ]);
    let output = add_address_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());

    // List of addresses for created account should now contain a BasicWallet address
    sync_cli(&temp_dir);
    let output = list_addresses_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());
    let formatted_output = String::from_utf8(output.stdout).unwrap();
    assert!(formatted_output.contains(&basic_account_id));
    assert_eq!(formatted_output.matches("Unspecified").count(), 1);
    assert_eq!(formatted_output.matches("BasicWallet").count(), 1);

    // Add another basic wallet address to the account
    let mut add_address_cmd = cargo_bin_cmd!("miden-client");
    let custom_note_tag_len = "5";
    add_address_cmd.args([
        "address",
        "add",
        &basic_account_id,
        &AddressInterface::BasicWallet.to_string(),
        custom_note_tag_len,
    ]);
    let output = add_address_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());

    // List of addresses for created account should now contain two BasicWallet addresses
    sync_cli(&temp_dir);
    let output = list_addresses_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());
    let formatted_output = String::from_utf8(output.stdout).unwrap();
    assert!(formatted_output.contains(&basic_account_id));
    assert_eq!(formatted_output.matches("Unspecified").count(), 1);
    assert_eq!(formatted_output.matches("BasicWallet").count(), 2);

    Ok(())
}

#[tokio::test]
async fn list_addresses_remove() -> Result<()> {
    let temp_dir = init_cli().1;

    // Create wallet account
    let basic_account_id = new_wallet_cli(&temp_dir, AccountStorageMode::Private);

    sync_cli(&temp_dir);

    // List of addresses for created account should contain an Unspecified address
    let mut list_addresses_cmd = cargo_bin_cmd!("miden-client");
    list_addresses_cmd.args(["address", "list", &basic_account_id]);
    let output = list_addresses_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());
    let formatted_output = String::from_utf8(output.stdout).unwrap();
    assert!(formatted_output.contains(&basic_account_id));
    assert_eq!(formatted_output.matches("Unspecified").count(), 1);

    // Remove the Unspecified wallet from the account
    let mut remove_address_cmd = cargo_bin_cmd!("miden-client");
    // Match any bech32 Miden address (HRP varies by network: mlcl, mdev, mtst, mm, etc.)
    let unspecified_wallet_address = regex::Regex::new(r"m[a-z]{1,4}1[0-9a-z]+")
        .unwrap()
        .find(&formatted_output)
        .unwrap()
        .as_str();
    remove_address_cmd.args(["address", "remove", &basic_account_id, unspecified_wallet_address]);
    let output = remove_address_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());

    // List of addresses for created account should now contain one BasicWallet address
    sync_cli(&temp_dir);
    let output = list_addresses_cmd.current_dir(temp_dir.clone()).output().unwrap();
    assert!(output.status.success());
    let formatted_output = String::from_utf8(output.stdout).unwrap();
    assert!(formatted_output.contains(&basic_account_id));
    assert_eq!(formatted_output.matches("Unspecified").count(), 0);

    Ok(())
}

#[tokio::test]
async fn new_wallet_with_deploy_flag() -> Result<()> {
    let (store_path, temp_dir, endpoint) = init_cli();

    sync_cli(&temp_dir);

    let mut create_wallet_cmd = cargo_bin_cmd!("miden-client");
    create_wallet_cmd.args(["new-wallet", "-s", "public", "--deploy"]);

    let output = create_wallet_cmd.current_dir(&temp_dir).output().unwrap();
    assert!(
        output.status.success(),
        "Failed to create and deploy wallet: {}",
        String::from_utf8(output.stderr).unwrap()
    );

    // Extract the account ID from the output
    let output_str = std::str::from_utf8(&output.stdout).unwrap();
    let account_id_str = output_str
        .split_whitespace()
        .skip_while(|&word| word != "-s")
        .nth(1)
        .expect("Failed to extract account ID from output");

    // Sync to ensure the transaction is committed
    sync_cli(&temp_dir);

    // Create a client and retrieve the account to verify the nonce
    let (client, _) = create_rust_client_with_store_path(&store_path, endpoint).await?;
    let account_id = AccountId::from_hex(account_id_str)?;
    let nonce = client.account_reader(account_id).nonce().await?;

    // Verify that the nonce is non-zero (account was deployed)
    // By convention, a nonce of 0 indicates an undeployed account
    assert!(
        nonce.as_canonical_u64() > 0,
        "Account nonce should be non-zero after deployment, but got: {nonce}"
    );

    Ok(())
}

// HELPERS
// ================================================================================================

/// Initializes a CLI with the network in the config file and returns the store path and the temp
/// directory where the CLI is running.
fn init_cli() -> (PathBuf, PathBuf, Endpoint) {
    // Try to read from env first or default to localhost.
    // Accepts "devnet", "testnet", "localhost", or a custom RPC endpoint string.
    let network: Network = std::env::var("TEST_MIDEN_NETWORK")
        .unwrap_or_else(|_| "localhost".to_string())
        .parse()
        .unwrap();
    let endpoint = Endpoint::try_from(network.to_rpc_endpoint().as_str()).unwrap();

    let store_path = create_test_store_path();
    let temp_dir = init_cli_with_store_path(&store_path, &endpoint);
    (store_path, temp_dir, endpoint)
}

/// Initializes a CLI with the given network and store path and returns the temp directory where
/// the CLI is running.
fn init_cli_with_store_path(store_path: &Path, endpoint: &Endpoint) -> PathBuf {
    let temp_dir = temp_dir().join(format!("cli-test-{}", rand::rng().random::<u64>()));
    std::fs::create_dir_all(&temp_dir).unwrap();

    // Init and create basic wallet on second client
    let mut init_cmd = cargo_bin_cmd!("miden-client");
    init_cmd.args([
        "init",
        "--local", // Use local mode to maintain test isolation
        "--network",
        endpoint.to_string().as_str(),
        "--store-path",
        store_path.to_str().unwrap(),
    ]);
    init_cmd.current_dir(&temp_dir).assert().success();

    temp_dir
}

/// Creates an isolated temporary directory and sets `MIDEN_CLIENT_HOME` to point to it.
/// This prevents tests from touching the real `~/.miden` directory.
/// Tests using this MUST use `#[serial_test::file_serial]`.
fn set_isolated_miden_home() -> PathBuf {
    let path = temp_dir().join(format!("miden-home-{}", rand::rng().random::<u64>()));
    std::fs::create_dir_all(&path).unwrap();
    // SAFETY: Tests using this are serialized via #[serial_test::file_serial]
    // These don't need to be executed in parallel as they aren't a bottleneck at all.
    unsafe {
        env::set_var("MIDEN_CLIENT_HOME", &path);
    }
    path
}

struct SyncResult {
    committed_notes: u64,
    committed_transactions: u64,
}

// Syncs CLI on directory. It'll try syncing until the command executes successfully. If it never
// executes successfully, eventually the test will time out (provided the nextest config has a
// timeout set). It returns the number of committed notes and transactions after the sync.
fn sync_cli(cli_path: &Path) -> SyncResult {
    loop {
        let mut sync_cmd = cargo_bin_cmd!("miden-client");
        sync_cmd.args(["sync"]);

        let output = sync_cmd.current_dir(cli_path).output().unwrap();

        if output.status.success() {
            let stdout = String::from_utf8(output.stdout).unwrap();

            let committed_notes = stdout
                .lines()
                .find_map(|line| {
                    line.strip_prefix("Committed notes: ")
                        .and_then(|rest| rest.trim().parse::<u64>().ok())
                })
                .unwrap();

            let committed_transactions = stdout
                .lines()
                .find_map(|line| {
                    line.strip_prefix("Committed transactions: ")
                        .and_then(|rest| rest.trim().parse::<u64>().ok())
                })
                .unwrap();

            return SyncResult { committed_notes, committed_transactions };
        }
        std::thread::sleep(std::time::Duration::from_secs(3));
    }
}

/// Mints 100 units of the corresponding faucet using the cli and checks that the command runs
/// successfully given account using the CLI given by `cli_path`.
fn mint_cli(cli_path: &Path, target_account_id: &str, faucet_id: &str) -> String {
    let mut mint_cmd = cargo_bin_cmd!("miden-client");
    mint_cmd.env("MIDEN_DEBUG", "true");
    mint_cmd.args([
        "mint",
        "--target",
        target_account_id,
        "--asset",
        &format!("100::{faucet_id}"),
        "-n",
        "private",
        "--force",
    ]);

    let output = mint_cmd.current_dir(cli_path).output().unwrap();
    assert!(
        output.status.success(),
        "mint_cli failed.\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    String::from_utf8(output.stdout)
        .unwrap()
        .split_whitespace()
        .skip_while(|&word| word != "Output")
        .find(|word| word.starts_with("0x"))
        .unwrap()
        .to_string()
}

/// Shows note details using the cli and checks that the command runs
/// successfully given account using the CLI given by `cli_path`.
fn show_note_cli(cli_path: &Path, note_id: &str, should_fail: bool) {
    let mut show_note_cmd = cargo_bin_cmd!("miden-client");
    show_note_cmd.args(["notes", "--show", note_id]);

    if should_fail {
        show_note_cmd.current_dir(cli_path).assert().failure();
    } else {
        show_note_cmd.current_dir(cli_path).assert().success();
    }
}

/// Sends 25 units of the corresponding faucet and checks that the command runs successfully given
/// account using the CLI given by `cli_path`.
fn send_cli(cli_path: &Path, from_account_id: &str, to_account_id: &str, faucet_id: &str) {
    let mut send_cmd = cargo_bin_cmd!("miden-client");
    send_cmd.args([
        "send",
        "--sender",
        from_account_id,
        "--target",
        to_account_id,
        "--asset",
        &format!("25::{faucet_id}"),
        "-n",
        "private",
        "--force",
    ]);
    send_cmd.current_dir(cli_path).assert().success();
}

/// Syncs until a tracked note gets committed.
fn sync_until_committed_note(cli_path: &Path) {
    while sync_cli(cli_path).committed_notes == 0 {
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}

/// Syncs until a tracked transaction gets committed.
fn sync_until_committed_transaction(cli_path: &Path) {
    while sync_cli(cli_path).committed_transactions == 0 {
        std::thread::sleep(std::time::Duration::from_secs(1));
    }
}

/// Consumes a series of notes with a given account using the CLI given by `cli_path`.
fn consume_note_cli(cli_path: &Path, account_id: &str, note_ids: &[&str]) {
    let mut consume_note_cmd = cargo_bin_cmd!("miden-client");
    let mut cli_args = vec!["consume-notes", "--account", &account_id, "--force"];
    cli_args.extend_from_slice(note_ids);
    consume_note_cmd.args(&cli_args);
    consume_note_cmd.current_dir(cli_path).assert().success();
}

/// Creates a new faucet account using the CLI given by `cli_path`.
fn new_faucet_cli(cli_path: &Path, storage_mode: AccountStorageMode) -> String {
    const INIT_DATA_FILENAME: &str = "init_data.toml";
    let mut create_faucet_cmd = cargo_bin_cmd!("miden-client");

    // Create a TOML file with the InitStorageData
    let init_storage_data_toml = r#"
        ["miden::standards::fungible_faucets::metadata"]
        decimals="10"
        max_supply="10000000"
        symbol="BTC"
        "#;
    let file_path = cli_path.join(INIT_DATA_FILENAME);
    fs::write(&file_path, init_storage_data_toml).unwrap();

    create_faucet_cmd.args([
        "new-account",
        "-s",
        storage_mode.to_string().as_str(),
        "--account-type",
        "fungible-faucet",
        "-p",
        "basic-fungible-faucet",
        "-i",
        INIT_DATA_FILENAME,
    ]);
    create_faucet_cmd.current_dir(cli_path).assert().success();

    let output = create_faucet_cmd.current_dir(cli_path).output().unwrap();
    assert!(output.status.success());

    std::str::from_utf8(&output.stdout)
        .unwrap()
        .split_whitespace()
        .skip_while(|&word| word != "-s")
        .nth(1)
        .unwrap()
        .to_string()
}

/// Creates a new wallet account using the CLI given by `cli_path`.
fn new_wallet_cli(cli_path: &Path, storage_mode: AccountStorageMode) -> String {
    let mut create_wallet_cmd = cargo_bin_cmd!("miden-client");
    create_wallet_cmd.args(["new-wallet", "-s", storage_mode.to_string().as_str()]);

    let output = create_wallet_cmd.current_dir(cli_path).output().unwrap();
    assert!(
        output.status.success(),
        "Failed to create wallet {}",
        String::from_utf8(output.stderr)
            .map_or(". Also failed to access the Command's stderr".to_string(), |err_msg| format!(
                "with error: {err_msg}"
            ))
    );

    std::str::from_utf8(&output.stdout)
        .unwrap()
        .split_whitespace()
        .skip_while(|&word| word != "-s")
        .nth(1)
        .unwrap()
        .to_string()
}

pub type TestClient = Client<FilesystemKeyStore>;

/// Creates a new [`Client`] with a given store. Also returns the keystore associated with it.
async fn create_rust_client_with_store_path(
    store_path: &Path,
    endpoint: Endpoint,
) -> Result<(TestClient, FilesystemKeyStore)> {
    let store = {
        let sqlite_store = SqliteStore::new(PathBuf::from(store_path)).await?;
        std::sync::Arc::new(sqlite_store)
    };

    let mut rng = rand::rng();
    let coin_seed: [u64; 4] = rng.random();

    let rng = Box::new(RandomCoin::new(coin_seed.map(Felt::new).into()));

    let keystore = FilesystemKeyStore::new(temp_dir())?;

    let client = ClientBuilder::new()
        .grpc_client(&endpoint, Some(10_000))
        .rng(rng)
        .store(store)
        .authenticator(Arc::new(keystore.clone()))
        .in_debug_mode(DebugMode::Enabled)
        .build()
        .await?;

    Ok((client, keystore))
}

/// Executes a command and asserts that it fails but does not panic.
fn assert_command_fails_but_does_not_panic(command: &mut Command) {
    let output_error = command.ok().unwrap_err();
    let exit_code = output_error.as_output().unwrap().status.code().unwrap();
    assert_ne!(exit_code, 0); // Command failed
    assert_ne!(exit_code, 101); // Command didn't panic
}

// COMMANDS TESTS
// ================================================================================================

#[test]
fn exec_parse() {
    let failure_script =
        fs::canonicalize("tests/files/test_cli_advice_inputs_expect_failure.masm").unwrap();
    let success_script =
        fs::canonicalize("tests/files/test_cli_advice_inputs_expect_success.masm").unwrap();
    let toml_path = fs::canonicalize("tests/files/test_cli_advice_inputs_input.toml").unwrap();

    let temp_dir = init_cli().1;

    // Create wallet account
    let basic_account_id = new_wallet_cli(&temp_dir, AccountStorageMode::Private);

    sync_cli(&temp_dir);
    let mut success_cmd = cargo_bin_cmd!("miden-client");
    success_cmd.args([
        "exec",
        "-s",
        success_script.to_str().unwrap(),
        "-a",
        &basic_account_id,
        "-i",
        toml_path.to_str().unwrap(),
    ]);

    success_cmd.current_dir(&temp_dir).assert().success();

    let mut failure_cmd = cargo_bin_cmd!("miden-client");
    failure_cmd.args([
        "exec",
        "-s",
        failure_script.to_str().unwrap(),
        "-a",
        &basic_account_id,
        "-i",
        toml_path.to_str().unwrap(),
    ]);

    failure_cmd.current_dir(&temp_dir).assert().failure();
}

// AUTH COMPONENT TESTS
// ================================================================================================

/// Tests creating an account with the no-auth component.
#[test]
fn create_account_with_no_auth() {
    let temp_dir = init_cli().1;

    let mut create_account_cmd = cargo_bin_cmd!("miden-client");
    create_account_cmd.args([
        "new-account",
        "-s",
        "private",
        "--account-type",
        "regular-account-updatable-code",
        "-p",
        "basic-wallet",
        "-p",
        "auth/no-auth",
    ]);

    create_account_cmd.current_dir(&temp_dir).assert().success();
}

/// Tests creating an account with the multisig-auth component.
#[test]
fn create_account_with_multisig_auth() {
    let temp_dir = init_cli().1;

    // Create init storage data file for multisig
    // threshold_config is a value slot with [threshold, num_approvers, 0, 0]
    // approver_public_keys and procedure_thresholds are map slots
    let init_storage_data_toml = r#"
        "miden::standards::auth::multisig::threshold_config.threshold" = "2"
        "miden::standards::auth::multisig::threshold_config.num_approvers" = "3"

        "miden::standards::auth::multisig::approver_public_keys" = [
            { key = ["0", "0", "0", "0"], value = "0x0000000000000000000000000000000000000000000000000000000000000001" },
            { key = ["1", "0", "0", "0"], value = "0x0000000000000000000000000000000000000000000000000000000000000002" },
            { key = ["2", "0", "0", "0"], value = "0x0000000000000000000000000000000000000000000000000000000000000003" }
        ]

        "miden::standards::auth::multisig::approver_schemes" = [
            { key = ["0", "0", "0", "0"], value = ["2", "0", "0", "0"] },
            { key = ["1", "0", "0", "0"], value = ["2", "0", "0", "0"] },
            { key = ["2", "0", "0", "0"], value = ["2", "0", "0", "0"] }
        ]

        "miden::standards::auth::multisig::procedure_thresholds" = [
            { key = "0xd2d1b6229d7cfb9f2ada31c5cb61453cf464f91828e124437c708eec55b9cd07", value = "1" }
        ]
        "#;
    let file_path = temp_dir.join("multisig_init_data.toml");
    fs::write(&file_path, init_storage_data_toml).unwrap();

    let mut create_account_cmd = cargo_bin_cmd!("miden-client");
    create_account_cmd.args([
        "new-account",
        "-s",
        "private",
        "--account-type",
        "regular-account-updatable-code",
        "-p",
        "basic-wallet",
        "-p",
        "auth/multisig-auth",
        "-i",
        "multisig_init_data.toml",
    ]);

    create_account_cmd.current_dir(&temp_dir).assert().success();
}

/// Tests creating an account with the acl-auth component.
#[test]
fn create_account_with_acl_auth() {
    let temp_dir = init_cli().1;

    // Create init storage data file for acl-auth with a test public key
    let init_storage_data_toml = r#"
        "miden::standards::auth::singlesig_acl::pub_key" = "0x0000000000000000000000000000000000000000000000000000000000000001"
        "miden::standards::auth::singlesig_acl::scheme" = "Falcon512Poseidon2"
        "miden::standards::auth::singlesig_acl::config.num_trigger_procs" = "1"
        "miden::standards::auth::singlesig_acl::config.allow_unauthorized_output_notes" = "0"
        "miden::standards::auth::singlesig_acl::config.allow_unauthorized_input_notes" = "0"

        "miden::standards::auth::singlesig_acl::trigger_procedure_roots" = [
            { key = ["0", "0", "0", "0"], value = "0xd2d1b6229d7cfb9f2ada31c5cb61453cf464f91828e124437c708eec55b9cd07" }
        ]
        "#;
    let file_path = temp_dir.join("acl_init_data.toml");
    fs::write(&file_path, init_storage_data_toml).unwrap();

    let mut create_account_cmd = cargo_bin_cmd!("miden-client");
    create_account_cmd.args([
        "new-account",
        "-s",
        "private",
        "--account-type",
        "regular-account-updatable-code",
        "-p",
        "basic-wallet",
        "-p",
        "auth/acl-auth",
        "-i",
        "acl_init_data.toml",
    ]);

    create_account_cmd.current_dir(&temp_dir).assert().success();
}

// Tests creating an account with the acl-auth component.
#[test]
fn create_account_with_ecdsa_auth() {
    let temp_dir = init_cli().1;

    // Create init storage data file for ecdsa-auth with a test public key and scheme
    let init_storage_data_toml = r#"
        "miden::standards::auth::singlesig::pub_key" = "0x0000000000000000000000000000000000000000000000000000000000000001"
        "miden::standards::auth::singlesig::scheme" = "EcdsaK256Keccak"
        "#;
    let file_path = temp_dir.join("ecdsa_init_data.toml");
    fs::write(&file_path, init_storage_data_toml).unwrap();

    let mut create_account_cmd = cargo_bin_cmd!("miden-client");
    create_account_cmd.args([
        "new-account",
        "-s",
        "private",
        "--account-type",
        "regular-account-updatable-code",
        "-p",
        "basic-wallet",
        "-p",
        "auth/ecdsa-auth",
        "-i",
        "ecdsa_init_data.toml",
    ]);

    create_account_cmd.current_dir(&temp_dir).assert().success();
}

// CLICLIENT::NEW TESTS
// ================================================================================================
/// Tests that `CliClient::new()` successfully creates a client with the same
/// configuration as the CLI tool when a local config exists.
#[tokio::test]
#[serial_test::file_serial]
async fn test_new_with_local_config() -> Result<()> {
    // Initialize a local CLI configuration
    let (store_path, temp_dir, _endpoint) = init_cli();

    // Use isolated global miden directory to ensure no global config interferes
    let _miden_home = set_isolated_miden_home();

    // Change to the temp directory where local .miden config exists
    let original_dir = env::current_dir().unwrap();
    env::set_current_dir(&temp_dir)?;

    // Create a client using new - should pick up local config
    let client_result = miden_client_cli::CliClient::new(DebugMode::Disabled).await;

    // Restore original directory
    env::set_current_dir(original_dir)?;

    // Assert the client was created successfully
    assert!(
        client_result.is_ok(),
        "Failed to create client from local config: {:?}",
        client_result.err()
    );

    // Verify that the local config was actually used by checking which store file was created.
    // The local store should exist, indicating the local config was used.
    assert!(
        store_path.exists(),
        "Local store file should exist at {store_path:?}, indicating local config was used"
    );

    Ok(())
}

/// Tests that `CliClient::new()` silently initializes with default config
/// when no configuration exists.
#[tokio::test]
#[serial_test::file_serial]
async fn test_new_silent_init() -> Result<()> {
    // Create a temporary directory with no .miden configuration
    let temp_dir = temp_dir().join(format!("cli-test-silent-init-{}", rand::rng().random::<u64>()));
    std::fs::create_dir_all(&temp_dir)?;

    // Use isolated global miden directory
    let miden_home = set_isolated_miden_home();

    // Verify no config exists before we start
    let global_config_path = miden_home.join("miden-client.toml");
    assert!(!global_config_path.exists(), "Global config should not exist before test");

    // Change to the temp directory
    let original_dir = env::current_dir().unwrap();
    env::set_current_dir(&temp_dir)?;

    // Create a client - should succeed via silent initialization
    let client_result = miden_client_cli::CliClient::new(DebugMode::Disabled).await;

    // Restore original directory
    env::set_current_dir(original_dir)?;

    // Assert the client was created successfully
    assert!(
        client_result.is_ok(),
        "Expected client to be created via silent initialization, but got error: {:?}",
        client_result.err()
    );

    // Verify that a global config was created by the silent initialization
    assert!(
        global_config_path.exists(),
        "Expected global config to be created at {global_config_path:?} by silent initialization"
    );

    Ok(())
}

/// Tests that `CliConfig::load()` prioritizes local config over global config.
#[tokio::test]
#[serial_test::file_serial]
async fn test_load_local_priority() -> Result<()> {
    // Use isolated global miden directory
    let _miden_home = set_isolated_miden_home();

    // Create a global config with testnet endpoint
    let global_store_path = create_test_store_path();
    let global_endpoint = Endpoint::testnet();

    let temp_dir_for_global =
        temp_dir().join(format!("cli-test-global-init-{}", rand::rng().random::<u64>()));
    std::fs::create_dir_all(&temp_dir_for_global)?;

    let mut init_global_cmd = cargo_bin_cmd!("miden-client");
    init_global_cmd.args([
        "init",
        "--network",
        global_endpoint.to_string().as_str(),
        "--store-path",
        global_store_path.to_str().unwrap(),
    ]);
    init_global_cmd.current_dir(&temp_dir_for_global).assert().success();

    // Create a local config with localhost endpoint
    let local_store_path = create_test_store_path();
    let local_endpoint = Endpoint::localhost();
    let local_temp_dir = init_cli_with_store_path(&local_store_path, &local_endpoint);

    // Load config from the specific local directory (no need to change working directory!)
    let local_miden_dir = local_temp_dir.join(MIDEN_DIR);
    let config = miden_client_cli::CliConfig::from_dir(&local_miden_dir)?;

    // Create client with local config
    let client = miden_client_cli::CliClient::from_config(config, DebugMode::Disabled).await;

    // Assert client was created with local config
    assert!(client.is_ok(), "Failed to create client with local config: {:?}", client.err());

    // Verify that the local config was actually used by checking which store file was created

    // The local store should exist
    assert!(
        local_store_path.exists(),
        "Local store file should exist at {local_store_path:?}, indicating local config was used"
    );

    // The global store should NOT exist
    assert!(
        !global_store_path.exists(),
        "Global store file should NOT exist at {global_store_path:?}, as global config should not have been used"
    );

    Ok(())
}