quicknode-cli 0.6.0

Command-line interface for the Quicknode SDK
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
//! Integration tests for `qn rpc`.
//!
//! The in-process harness injects `--api-key test`; the token cache is keyed by
//! account id via a `sha256(key) -> account_id -> token` lookup. Tests that
//! exercise the cache pass `--config-file` so `tokens.toml` lands in a tempdir
//! rather than the real home.

mod common;

use common::run_qn;
use serde_json::json;
use std::sync::atomic::{AtomicUsize, Ordering};
use wiremock::matchers::{body_partial_json, method, path};
use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};

// SHA-256 of "test" (the harness-injected API key).
const TEST_KEY_HASH: &str = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";

// The account id used across the cache tests.
const TEST_ACCOUNT_ID: i64 = 12345;

// A far-future ISO timestamp so a freshly minted token is never near expiry.
const FUTURE_ISO: &str = "2099-01-01T00:00:00.000Z";
// Matching far-future unix seconds for a seeded token.
const FUTURE_UNIX: i64 = 4_070_908_800;

/// Writes a `tokens.toml` in the new two-level shape: `key_hash -> account_id`
/// and `account_id -> token`. A hit on `key_hash` resolves the account offline.
fn write_token_cache(dir: &tempfile::TempDir, endpoint_url: &str, key_hash: &str, account_id: i64) {
    let path = dir.path().join("tokens.toml");
    let body = format!(
        "[keys]\n\"{key_hash}\" = {account_id}\n\n\
         [tokens.{account_id}]\nendpoint_url = \"{endpoint_url}\"\n\
         token = \"seeded.jwt\"\nexp_unix = {FUTURE_UNIX}\n"
    );
    std::fs::write(&path, body).unwrap();
}

/// Mounts a `GET /v0/account/info` returning `TEST_ACCOUNT_ID`, asserting it is
/// called exactly `times`. Cache misses need it (to key the write-back by
/// account); cache hits must never call it.
async fn mount_account_info(server: &MockServer, times: u64) {
    Mock::given(method("GET"))
        .and(path("/v0/account/info"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "id": TEST_ACCOUNT_ID,
                "name": "Acme Inc",
                "created_at": "2024-01-01T00:00:00Z",
                "billing_version": "v6",
                "subscription": null
            }
        })))
        .expect(times)
        .mount(server)
        .await;
}

fn cfg_path(dir: &tempfile::TempDir) -> String {
    // Provide an API key via the config file so the cache parent dir is the
    // tempdir. The harness still injects --api-key test, which wins, so the
    // cache key_hash matches TEST_KEY_HASH.
    let path = dir.path().join("config.toml");
    std::fs::write(&path, "[api]\nkey = \"test\"\n").unwrap();
    path.to_str().unwrap().to_string()
}

#[tokio::test]
async fn seeded_token_skips_mint() {
    let server = MockServer::start().await;
    // RPC endpoint returns a result. The mint route is intentionally NOT
    // mounted: if the SDK tried to mint, the call would 404 and fail.
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .and(body_partial_json(json!({ "method": "eth_blockNumber" })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0x1335f9a"
        })))
        .expect(1)
        .mount(&server)
        .await;
    // A cache hit must resolve the account offline: account_info is never called.
    mount_account_info(&server, 0).await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/rpc", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &["--config-file", &cfg, "rpc", "call", "eth_blockNumber"],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

// An already-enabled call must NOT incur the post-enable provisioning wait,
// even with --yes. --yes only matters if Tooling Access is disabled; here the
// seeded token works on the first attempt, so the ~1s wait must not fire.
#[tokio::test]
async fn already_enabled_yes_does_not_wait() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0x1"
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/rpc", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let started = std::time::Instant::now();
    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--yes",
        ],
    )
    .await;
    let elapsed = started.elapsed();
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
    // The post-enable initial wait is 1s; a happy-path call must be far faster.
    assert!(
        elapsed < std::time::Duration::from_millis(500),
        "already-enabled --yes should not wait, took {elapsed:?}"
    );
}

#[tokio::test]
async fn no_cache_mints_then_calls() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v0/tooling-access/token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "endpoint_url": format!("{}/rpc", server.uri()),
                "token": "minted.jwt",
                "expires_at": FUTURE_ISO
            },
            "error": null
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0xabc"
        })))
        .expect(1)
        .mount(&server)
        .await;
    // A miss (unknown key) learns the account id once to key the write-back.
    mount_account_info(&server, 1).await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    let out = run_qn(
        &server.uri(),
        &["--config-file", &cfg, "rpc", "call", "eth_blockNumber"],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);

    // The minted token should have been written back under the account id, with
    // the key -> account mapping recorded, and never the API key itself.
    let cached = std::fs::read_to_string(dir.path().join("tokens.toml")).unwrap();
    assert!(cached.contains("minted.jwt"), "cache: {cached}");
    assert!(
        cached.contains(&format!("[tokens.{TEST_ACCOUNT_ID}]")),
        "token keyed by account id: {cached}"
    );
    assert!(
        cached.contains(TEST_KEY_HASH),
        "key mapping recorded: {cached}"
    );
    assert!(
        !cached.contains("\"test\""),
        "api key must not be stored: {cached}"
    );
}

#[tokio::test]
async fn json_rpc_error_exits_nonzero() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1,
            "error": { "code": -32602, "message": "invalid params" }
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/rpc", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_getBalance",
            "[\"bad\"]",
        ],
    )
    .await;
    // SdkError::Rpc is neither Api nor Http → generic exit 1.
    assert_eq!(out.exit_code, 1, "stderr={}", out.stderr);
}

#[tokio::test]
async fn not_enabled_without_yes_is_actionable_error() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v0/tooling-access/token"))
        .respond_with(ResponseTemplate::new(400).set_body_json(json!({
            "data": null,
            "error": "Tooling access is not enabled. Enable it first."
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    // No --yes, and the harness sets --no-input, so we can't prompt → the
    // command should fail with the actionable "run 'qn tooling-access enable'".
    let out = run_qn(
        &server.uri(),
        &["--config-file", &cfg, "rpc", "call", "eth_blockNumber"],
    )
    .await;
    assert_eq!(out.exit_code, 1, "stderr={}", out.stderr);
    assert!(
        out.stderr.contains("tooling-access enable"),
        "stderr={}",
        out.stderr
    );
}

#[tokio::test]
async fn not_enabled_with_yes_auto_enables_and_retries() {
    let server = MockServer::start().await;

    // Mint: first call 400 (not enabled), subsequent calls succeed.
    struct MintSeq {
        calls: AtomicUsize,
        url: String,
    }
    impl Respond for MintSeq {
        fn respond(&self, _: &Request) -> ResponseTemplate {
            let n = self.calls.fetch_add(1, Ordering::SeqCst);
            if n == 0 {
                ResponseTemplate::new(400).set_body_json(json!({
                    "data": null,
                    "error": "Tooling access is not enabled. Enable it first."
                }))
            } else {
                ResponseTemplate::new(200).set_body_json(json!({
                    "data": { "endpoint_url": self.url, "token": "minted.jwt", "expires_at": FUTURE_ISO },
                    "error": null
                }))
            }
        }
    }

    Mock::given(method("POST"))
        .and(path("/v0/tooling-access/token"))
        .respond_with(MintSeq {
            calls: AtomicUsize::new(0),
            url: format!("{}/rpc", server.uri()),
        })
        .mount(&server)
        .await;
    // enable_tooling_access PATCH.
    Mock::given(method("PATCH"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": true, "endpoint_url": format!("{}/rpc", server.uri()) },
            "error": null
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0xok"
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--yes",
        ],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

#[tokio::test]
async fn unknown_key_mints_and_preserves_other_account() {
    let server = MockServer::start().await;
    // The cache holds a token for a DIFFERENT key/account. Our key isn't in
    // `[keys]`, so this is a miss: mint, learn our account id, and store under it
    // without disturbing the other account's entry.
    Mock::given(method("POST"))
        .and(path("/v0/tooling-access/token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "endpoint_url": format!("{}/rpc", server.uri()),
                "token": "minted.jwt",
                "expires_at": FUTURE_ISO
            },
            "error": null
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0xok"
        })))
        .mount(&server)
        .await;
    // A miss learns our account id once.
    mount_account_info(&server, 1).await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    // Pre-seed a different account (id 999) under a different key hash.
    let other_id = 999;
    write_token_cache(&dir, &format!("{}/rpc", server.uri()), "deadbeef", other_id);

    let out = run_qn(
        &server.uri(),
        &["--config-file", &cfg, "rpc", "call", "eth_blockNumber"],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);

    // Both accounts now coexist in the shared file: ours (freshly minted) and
    // the pre-existing one (untouched).
    let cached = std::fs::read_to_string(dir.path().join("tokens.toml")).unwrap();
    assert!(
        cached.contains(&format!("[tokens.{TEST_ACCOUNT_ID}]")),
        "our account cached: {cached}"
    );
    assert!(
        cached.contains(&format!("[tokens.{other_id}]")),
        "other account preserved: {cached}"
    );
}

// A cached token pointing at an unreachable (disabled) endpoint yields a
// connect failure; the CLI probes status, sees disabled, clears the stale
// token, and routes into the same enable flow as the mint-400 path. In the
// harness (non-TTY + --no-input, no --yes) that flow can't prompt, so it ends
// in the actionable "run qn tooling-access enable" error.
#[tokio::test]
async fn connect_failure_with_disabled_status_prompts_to_enable() {
    let server = MockServer::start().await;
    // Status probe reports disabled.
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": false, "endpoint_url": null, "endpoint_id": 3 },
            "error": null
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    // Seed a still-valid token whose endpoint_url refuses connections fast
    // (loopback, almost-certainly-closed high port) so the RPC POST returns a
    // connect error promptly rather than waiting out the timeout.
    write_token_cache(
        &dir,
        "http://127.0.0.1:9/rpc",
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--retries",
            "0",
        ],
    )
    .await;
    assert_ne!(out.exit_code, 0, "should fail");
    // Same actionable message as the mint-400 path (both converge on enable).
    assert!(
        out.stderr.contains("tooling-access enable"),
        "expected enable guidance, got: {}",
        out.stderr
    );
    // The stale token entry for this account should have been dropped before the
    // enable attempt, while the file (and its key -> account mapping) remains.
    let cached = std::fs::read_to_string(dir.path().join("tokens.toml")).unwrap();
    assert!(
        !cached.contains(&format!("[tokens.{TEST_ACCOUNT_ID}]")),
        "stale account token should be cleared: {cached}"
    );
    assert!(
        cached.contains(TEST_KEY_HASH),
        "key mapping preserved: {cached}"
    );
}

// With --yes, the connect-failure-disabled path auto-enables and retries the
// call against the (now re-enabled) endpoint, minting a fresh token.
#[tokio::test]
async fn connect_failure_with_disabled_status_auto_enables_with_yes() {
    let server = MockServer::start().await;
    // Status reports disabled (drives the connect-failure path into enable).
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": false, "endpoint_url": null, "endpoint_id": 3 },
            "error": null
        })))
        .mount(&server)
        .await;
    // enable() PATCH succeeds.
    Mock::given(method("PATCH"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": true, "endpoint_url": format!("{}/rpc", server.uri()), "endpoint_id": 3 },
            "error": null
        })))
        .expect(1)
        .mount(&server)
        .await;
    // After enabling, the retry re-mints (the stale token was cleared) and the
    // fresh token points at the reachable /rpc mock.
    Mock::given(method("POST"))
        .and(path("/v0/tooling-access/token"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "endpoint_url": format!("{}/rpc", server.uri()), "token": "minted.jwt", "expires_at": FUTURE_ISO },
            "error": null
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0xok"
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        "http://127.0.0.1:9/rpc",
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--retries",
            "0",
            "--yes",
        ],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

// --network: status returns an id, get_endpoint_urls returns the per-network
// map, and the RPC call routes to the mapped (solana) URL, not the default.
#[tokio::test]
async fn network_routes_to_mapped_url() {
    let server = MockServer::start().await;
    let solana_url = format!("{}/solana", server.uri());

    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": true, "endpoint_url": format!("{}/default", server.uri()), "endpoint_id": 3 },
            "error": null
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v0/endpoints/3/urls"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "http_url": format!("{}/default", server.uri()),
                "wss_url": null,
                "multichain_urls": {
                    "solana-mainnet": { "http_url": solana_url, "wss_url": null }
                }
            },
            "error": null
        })))
        .mount(&server)
        .await;
    // The call must hit /solana. /default is not mounted, so a misroute 404s.
    Mock::given(method("POST"))
        .and(path("/solana"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "12345"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/default", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "getSlot",
            "--network",
            "solana-mainnet",
        ],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);

    // networks.toml was written for reuse.
    let cached = std::fs::read_to_string(dir.path().join("networks.toml")).unwrap();
    assert!(cached.contains("solana-mainnet"), "cache: {cached}");
}

// --network when Tooling Access is disabled routes through the enable gate.
// In the harness (non-TTY + --no-input) without --yes that gate can't prompt,
// so it ends in the actionable "run qn tooling-access enable" error (exit 5)
// and no URL-map fetch or RPC call is made.
#[tokio::test]
async fn network_when_disabled_without_yes_prompts_to_enable() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": false, "endpoint_url": null, "endpoint_id": null },
            "error": null
        })))
        .mount(&server)
        .await;
    // No enable, no URL-map fetch, no RPC call should be reached.
    Mock::given(method("PATCH"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v0/endpoints/3/urls"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "getSlot",
            "--network",
            "solana-mainnet",
        ],
    )
    .await;
    assert_ne!(out.exit_code, 0, "should fail");
    // Same actionable message as the default lane's mint-400 path.
    assert!(
        out.stderr.contains("tooling-access enable"),
        "expected enable hint, got: {}",
        out.stderr
    );
}

// --network when disabled + --yes: enable, re-fetch status (now enabled with an
// id), fetch the per-network map, and route the call to the mapped URL.
#[tokio::test]
async fn network_when_disabled_with_yes_enables_and_routes() {
    let server = MockServer::start().await;
    let solana_url = format!("{}/solana", server.uri());

    // Status flips to enabled after the enable PATCH: first GET reports disabled,
    // subsequent GETs report enabled with an id.
    struct StatusSeq {
        calls: AtomicUsize,
        default_url: String,
    }
    impl wiremock::Respond for StatusSeq {
        fn respond(&self, _: &wiremock::Request) -> ResponseTemplate {
            let n = self.calls.fetch_add(1, Ordering::SeqCst);
            if n == 0 {
                ResponseTemplate::new(200).set_body_json(json!({
                    "data": { "enabled": false, "endpoint_url": null, "endpoint_id": null },
                    "error": null
                }))
            } else {
                ResponseTemplate::new(200).set_body_json(json!({
                    "data": { "enabled": true, "endpoint_url": self.default_url, "endpoint_id": 3 },
                    "error": null
                }))
            }
        }
    }
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(StatusSeq {
            calls: AtomicUsize::new(0),
            default_url: format!("{}/default", server.uri()),
        })
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": true, "endpoint_url": format!("{}/default", server.uri()) },
            "error": null
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v0/endpoints/3/urls"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "http_url": format!("{}/default", server.uri()),
                "wss_url": null,
                "multichain_urls": {
                    "solana-mainnet": { "http_url": solana_url, "wss_url": null }
                }
            },
            "error": null
        })))
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/solana"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "12345"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    // Seed a cached token so the call uses it rather than minting (the enable
    // flow, not token acquisition, is what this test exercises).
    write_token_cache(
        &dir,
        &format!("{}/default", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "getSlot",
            "--network",
            "solana-mainnet",
            "--yes",
        ],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

// --list-networks prints the available keys without making an RPC call.
#[tokio::test]
async fn list_networks_prints_keys() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": true, "endpoint_url": format!("{}/default", server.uri()), "endpoint_id": 3 },
            "error": null
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v0/endpoints/3/urls"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "http_url": format!("{}/default", server.uri()),
                "multichain_urls": {
                    "solana-mainnet": { "http_url": "https://x/sol", "wss_url": null },
                    "polygon": { "http_url": "https://x/matic", "wss_url": null }
                }
            },
            "error": null
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/default", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &["--config-file", &cfg, "rpc", "list-networks"],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

// Unknown --network surfaces a CLI error that points at `qn rpc list-networks`
// (the SDK's raw "unknown network" message is intercepted and re-rendered).
#[tokio::test]
async fn unknown_network_errors() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": { "enabled": true, "endpoint_url": format!("{}/default", server.uri()), "endpoint_id": 3 },
            "error": null
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v0/endpoints/3/urls"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": {
                "http_url": format!("{}/default", server.uri()),
                "multichain_urls": {
                    "solana-mainnet": { "http_url": "https://x/sol", "wss_url": null }
                }
            },
            "error": null
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/default", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "getSlot",
            "--network",
            "nope-mainnet",
        ],
    )
    .await;
    assert_ne!(out.exit_code, 0, "should fail on unknown network");
    // The CLI-rendered message keeps the available-keys list and points the
    // user at the discovery command, dropping the SDK-internal seeding hint.
    assert!(
        out.stderr.contains("qn rpc list-networks"),
        "expected list-networks hint, got: {}",
        out.stderr
    );
    assert!(
        out.stderr.contains("solana-mainnet"),
        "expected available keys, got: {}",
        out.stderr
    );
}

// A custom --endpoint-url sends the call straight to that URL. No token is
// minted (the mint route is not mounted, so a stray mint would 404) and the
// call succeeds against the custom host.
#[tokio::test]
async fn endpoint_url_flag_routes_call_without_minting() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/custom/rpc"))
        .and(body_partial_json(json!({ "method": "eth_blockNumber" })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0xcafe"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    let url = format!("{}/custom/rpc", server.uri());
    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--endpoint-url",
            &url,
        ],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);

    // Custom-URL lane never mints, so nothing is written to the token cache.
    assert!(
        !dir.path().join("tokens.toml").exists(),
        "custom-URL call must not write a token cache"
    );
}

// `[rpc] endpoint_url` in the config file routes a call there with no flag.
#[tokio::test]
async fn config_endpoint_url_routes_call() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/from-config/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0x1"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let url = format!("{}/from-config/rpc", server.uri());
    std::fs::write(
        &path,
        format!("[api]\nkey = \"test\"\n\n[rpc]\nendpoint_url = \"{url}\"\n"),
    )
    .unwrap();
    let cfg = path.to_str().unwrap();

    let out = run_qn(
        &server.uri(),
        &["--config-file", cfg, "rpc", "call", "eth_blockNumber"],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

// A per-call --endpoint-url overrides the config-file default.
#[tokio::test]
async fn flag_endpoint_url_overrides_config() {
    let server = MockServer::start().await;
    // Only the flag's URL is mounted; the config URL would 404 if used.
    Mock::given(method("POST"))
        .and(path("/flag/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0x1"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("config.toml");
    let cfg_url = format!("{}/config/rpc", server.uri());
    std::fs::write(
        &path,
        format!("[api]\nkey = \"test\"\n\n[rpc]\nendpoint_url = \"{cfg_url}\"\n"),
    )
    .unwrap();
    let cfg = path.to_str().unwrap();
    let flag_url = format!("{}/flag/rpc", server.uri());

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--endpoint-url",
            &flag_url,
        ],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

// A failing custom-URL call surfaces the error directly: it must NOT probe
// Tooling Access status or attempt to enable it. Both admin endpoints assert
// zero hits.
#[tokio::test]
async fn custom_url_failure_bypasses_enable_recovery() {
    let server = MockServer::start().await;
    // The custom endpoint returns a JSON-RPC error (a real, non-transport failure).
    Mock::given(method("POST"))
        .and(path("/custom/rpc"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1,
            "error": { "code": -32601, "message": "method not found" }
        })))
        .mount(&server)
        .await;
    // The Tooling Access status probe and enable must never be reached.
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    let url = format!("{}/custom/rpc", server.uri());
    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--endpoint-url",
            &url,
        ],
    )
    .await;
    assert_ne!(out.exit_code, 0, "custom-URL JSON-RPC error should fail");
}

// A malformed --endpoint-url is rejected before any request is made.
#[tokio::test]
async fn endpoint_url_rejects_bad_scheme() {
    let server = MockServer::start().await;
    // Nothing should be requested.
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--endpoint-url",
            "ftp://example.com/rpc",
        ],
    )
    .await;
    assert_ne!(out.exit_code, 0, "bad scheme should be rejected");
    assert!(
        out.stderr.contains("http or https"),
        "stderr={}",
        out.stderr
    );
}

// --endpoint-url and --network are mutually exclusive at the clap layer; the
// parse error fires before any request.
#[tokio::test]
async fn endpoint_url_conflicts_with_network() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/v0/tooling-access"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_blockNumber",
            "--endpoint-url",
            "https://x/rpc",
            "--network",
            "solana-mainnet",
        ],
    )
    .await;
    assert_ne!(out.exit_code, 0, "conflicting flags should fail to parse");
}

// --params-file reads the JSON params from a file; the parsed params reach the
// request body just like an inline positional value would.
#[tokio::test]
async fn params_file_reads_json_from_file() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .and(body_partial_json(json!({
            "method": "eth_getBalance",
            "params": ["0xabc", "latest"]
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "jsonrpc": "2.0", "id": 1, "result": "0x0"
        })))
        .expect(1)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/rpc", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );
    let params_path = dir.path().join("params.json");
    std::fs::write(&params_path, r#"["0xabc", "latest"]"#).unwrap();
    let params_file = params_path.to_str().unwrap();

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_getBalance",
            "--params-file",
            params_file,
        ],
    )
    .await;
    assert_eq!(out.exit_code, 0, "stderr={}", out.stderr);
}

// A missing --params-file path fails with an actionable error before any call.
#[tokio::test]
async fn params_file_missing_path_errors() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/rpc", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );
    let missing = dir.path().join("does-not-exist.json");

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_getBalance",
            "-f",
            missing.to_str().unwrap(),
        ],
    )
    .await;
    assert_ne!(out.exit_code, 0, "missing params file should fail");
    assert!(
        out.stderr.contains("could not read params file"),
        "stderr={}",
        out.stderr
    );
}

// The positional params and --params-file are mutually exclusive at the clap
// layer; passing both fails to parse before any request.
#[tokio::test]
async fn params_positional_and_file_conflict() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/rpc"))
        .respond_with(ResponseTemplate::new(200))
        .expect(0)
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().unwrap();
    let cfg = cfg_path(&dir);
    write_token_cache(
        &dir,
        &format!("{}/rpc", server.uri()),
        TEST_KEY_HASH,
        TEST_ACCOUNT_ID,
    );
    let params_path = dir.path().join("params.json");
    std::fs::write(&params_path, "[]").unwrap();

    let out = run_qn(
        &server.uri(),
        &[
            "--config-file",
            &cfg,
            "rpc",
            "call",
            "eth_getBalance",
            "[\"inline\"]",
            "--params-file",
            params_path.to_str().unwrap(),
        ],
    )
    .await;
    assert_ne!(
        out.exit_code, 0,
        "positional + --params-file should conflict"
    );
}