quicknode-sdk 0.8.0

Core library for 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
//! x402 credit drawdown lane for `rpc.call`.
//!
//! Distinct from the per-request 402 loop in the parent module: instead of
//! signing a fresh settlement per call, the caller authenticates once with a
//! SIWX (Sign-In-With-X) message and receives a session JWT. Each drawdown call
//! then presents `Authorization: Bearer <JWT>` and draws 1 credit per successful
//! response — no per-call signing.
//!
//! The flow:
//! 1. [`authenticate`] — build a SIWE (EIP-4361) message, sign it with the
//!    payment key, POST `/auth`, and cache the returned [`GatewaySession`].
//! 2. [`drawdown_call`] — POST `/:network` with the Bearer JWT; returns the raw
//!    JSON-RPC envelope text.
//! 3. [`credits`] — GET `/credits` with the Bearer JWT → the current balance.
//! 4. [`drip`] — POST `/drip` (testnet faucet, once per account) — funds the
//!    wallet, not the credit ledger.
//!
//! [`buy_credits`] settles a credit block by signing the gateway's credit-tier
//! offer. It is reachable only where that offer's construction is signable; see
//! [`super::authorize_x402_credit`].
//!
//! State (the JWT) is held by the caller: the SDK is stateless here, so a host
//! persists [`GatewaySession`] between runs exactly as it does the tooling
//! [`crate::config::CachedToken`].

use serde::Deserialize;
use serde_json::Value;

use crate::admin::tooling_access::parse_rfc3339_to_unix;
use crate::errors::SdkError;

use super::{now_unix, random_nonce, ResolvedPayment};

/// A gateway session JWT plus its expiry and the account it authenticates.
/// This is the unit the drawdown lane caches; a host (the CLI) persists it
/// between processes and re-seeds it next run, the same pattern as
/// [`crate::config::CachedToken`].
///
/// `token` is a live bearer credential and is redacted in `Debug`.
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct GatewaySession {
    /// The session JWT, presented as `Authorization: Bearer <token>`.
    pub token: String,
    /// JWT expiry in unix seconds (from the gateway's `expiresAt`).
    pub exp_unix: i64,
    /// The CAIP-10 account the JWT authenticates (the payer's address on the
    /// pay chain). Used as the cache key so distinct wallets don't collide.
    pub account_id: String,
}

// Never print the live JWT.
impl std::fmt::Debug for GatewaySession {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GatewaySession")
            .field("token", &"[redacted]")
            .field("exp_unix", &self.exp_unix)
            .field("account_id", &self.account_id)
            .finish()
    }
}

impl GatewaySession {
    /// Whether the session is still valid `margin_secs` before its expiry.
    /// A caller re-authenticates when this is false.
    pub fn is_fresh(&self, margin_secs: i64) -> bool {
        now_unix() as i64 + margin_secs < self.exp_unix
    }
}

/// The gateway `/auth` response.
#[derive(Deserialize)]
struct AuthResponse {
    token: String,
    #[serde(rename = "expiresAt")]
    expires_at: String,
    #[serde(rename = "accountId")]
    account_id: String,
}

/// The gateway `/credits` response.
#[derive(Deserialize)]
struct CreditsResponse {
    #[serde(rename = "accountId")]
    account_id: String,
    credits: u64,
}

/// The current credit balance for an account.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CreditBalance {
    pub account_id: String,
    pub credits: u64,
}

// The /auth endpoint requires this statement verbatim.
const SIWX_STATEMENT: &str =
    "I accept the Quicknode Terms of Service: https://www.quicknode.com/terms";

/// Authenticates against the x402 gateway with a SIWE (EIP-4361) message and
/// returns a cached [`GatewaySession`]. Free — no funds move — so a caller may
/// (re)auth transparently on a missing/expired session without user consent.
///
/// EVM signers only (SIWE). An SVM signer errors — SIWS is a separate
/// construction.
pub async fn authenticate(
    client: &reqwest::Client,
    payment: &ResolvedPayment,
) -> Result<GatewaySession, SdkError> {
    let base = super::PaymentScheme::X402.host_base(payment.base_url_override.as_deref());
    // SIWE compares the recovered address case-sensitively.
    let address = to_checksum_address(&payment.signer.address()?);
    // SIWE requires the decimal EIP-155 id, not the CAIP-2 string.
    let chain_id = eip155_chain_id(&payment.pay_network)?;

    // Build the gateway's fixed SIWE message with a fresh nonce and timestamp.
    let host = host_only(base);
    let nonce = hex::encode(&random_nonce()[..8]);
    let issued_at = rfc3339_now();
    let message = siwe_message(
        &host,
        &address,
        chain_id,
        &nonce,
        &issued_at,
        SIWX_STATEMENT,
    );
    let signature = payment.signer.sign_siwe(&message)?;

    let url = format!("{}/auth", base.trim_end_matches('/'));
    let resp = client
        .post(&url)
        .json(&serde_json::json!({
            "type": "siwx",
            "message": message,
            "signature": signature,
        }))
        .send()
        .await
        .map_err(SdkError::Http)?;

    let status = resp.status();
    let body = resp.text().await.map_err(SdkError::Http)?;
    if !status.is_success() {
        return Err(SdkError::Api { status, body });
    }
    let parsed: AuthResponse =
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })?;
    let exp_unix = parse_rfc3339_to_unix(&parsed.expires_at)?;
    Ok(GatewaySession {
        token: parsed.token,
        exp_unix,
        account_id: parsed.account_id,
    })
}

/// Makes one drawdown JSON-RPC call against `/:query_network` with the session
/// JWT as a Bearer token, drawing 1 credit on success. Returns the raw
/// JSON-RPC envelope text for the caller to parse.
///
/// Never retries on its own: the caller decides, and a paid lane never
/// blind-retries. A 401/403 surfaces as [`SdkError::Api`] so the caller can
/// map `token_expired` → re-auth and `monthly_limit_reached` → an actionable
/// error.
pub async fn drawdown_call(
    client: &reqwest::Client,
    payment: &ResolvedPayment,
    session: &GatewaySession,
    query_network: &str,
    body: &Value,
) -> Result<String, SdkError> {
    let base = super::PaymentScheme::X402.host_base(payment.base_url_override.as_deref());
    let url = format!("{}/{}", base.trim_end_matches('/'), query_network);
    let resp = client
        .post(&url)
        .bearer_auth(&session.token)
        .json(body)
        .send()
        .await
        .map_err(SdkError::Http)?;
    let status = resp.status();
    let text = resp.text().await.map_err(SdkError::Http)?;
    if !status.is_success() {
        return Err(SdkError::Api { status, body: text });
    }
    Ok(text)
}

/// Fetches the account's current credit balance (GET `/credits`, Bearer JWT).
pub async fn credits(
    client: &reqwest::Client,
    payment: &ResolvedPayment,
    session: &GatewaySession,
) -> Result<CreditBalance, SdkError> {
    let base = super::PaymentScheme::X402.host_base(payment.base_url_override.as_deref());
    let url = format!("{}/credits", base.trim_end_matches('/'));
    let resp = client
        .get(&url)
        .bearer_auth(&session.token)
        .send()
        .await
        .map_err(SdkError::Http)?;
    let status = resp.status();
    let body = resp.text().await.map_err(SdkError::Http)?;
    if !status.is_success() {
        return Err(SdkError::Api { status, body });
    }
    let parsed: CreditsResponse =
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })?;
    Ok(CreditBalance {
        account_id: parsed.account_id,
        credits: parsed.credits,
    })
}

/// The faucet drip result: the on-chain funding transaction. The gateway's
/// `/drip` returns the settlement tx, not a credit balance — call [`credits`]
/// afterwards to read the updated balance.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DripReceipt {
    pub account_id: String,
    /// The faucet funding transaction hash.
    pub transaction_hash: String,
}

/// Requests testnet tokens from the faucet (POST `/drip`, Bearer JWT). The
/// gateway allows this once per account on Base Sepolia and returns the funding
/// transaction (NOT a balance).
pub async fn drip(
    client: &reqwest::Client,
    payment: &ResolvedPayment,
    session: &GatewaySession,
) -> Result<DripReceipt, SdkError> {
    let base = super::PaymentScheme::X402.host_base(payment.base_url_override.as_deref());
    let url = format!("{}/drip", base.trim_end_matches('/'));
    let resp = client
        .post(&url)
        .bearer_auth(&session.token)
        .send()
        .await
        .map_err(SdkError::Http)?;
    let status = resp.status();
    let body = resp.text().await.map_err(SdkError::Http)?;
    if !status.is_success() {
        return Err(SdkError::Api { status, body });
    }
    #[derive(Deserialize)]
    struct DripBody {
        #[serde(rename = "accountId")]
        account_id: String,
        #[serde(rename = "transactionHash")]
        transaction_hash: String,
    }
    let parsed: DripBody =
        serde_json::from_str(&body).map_err(|source| SdkError::Decode { source, body })?;
    Ok(DripReceipt {
        account_id: parsed.account_id,
        transaction_hash: parsed.transaction_hash,
    })
}

/// Buys a block of credits: POST `/credits` with the Bearer JWT, settle the
/// `402` credit offer with the SAME x402 signer construction as the
/// per-request lane, and resend exactly once. Returns the balance after the
/// purchase settles.
///
/// The amount is chosen by the gateway's offer (bounded by `payment.max_amount`
/// like every signed payment); the caller does not name it. A second 402 is a
/// terminal [`SdkError::PaymentRejected`]; a lost response after the paid
/// resend is [`SdkError::PaymentIndeterminate`] — never blind-retry.
pub async fn buy_credits(
    client: &reqwest::Client,
    payment: &ResolvedPayment,
    session: &GatewaySession,
    query_network: &str,
) -> Result<CreditBalance, SdkError> {
    use crate::errors::HttpKind;

    // Credit purchases use a network-scoped RPC request; the balance is read
    // separately from GET /credits.
    let base = super::PaymentScheme::X402.host_base(payment.base_url_override.as_deref());
    let url = format!("{}/{}", base.trim_end_matches('/'), query_network);
    let rpc_body = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "eth_chainId", "params": []
    });

    // Probe the offer. A non-402 means no purchase is needed.
    let first = client
        .post(&url)
        .bearer_auth(&session.token)
        .json(&rpc_body)
        .send()
        .await
        .map_err(SdkError::Http)?;
    let status = first.status();
    if status.as_u16() != 402 {
        if !status.is_success() {
            let body = first.text().await.unwrap_or_default();
            return Err(SdkError::Api { status, body });
        }
        return credits(client, payment, session).await;
    }

    // Select and settle only the credit tier; never fall back to per-request.
    let challenge_body = first.text().await.map_err(SdkError::Http)?;
    let authorized = super::authorize_x402_credit(client, payment, &challenge_body).await?;
    let header = authorized
        .x402_header()
        .ok_or_else(|| SdkError::Config("credit purchase produced no x402 credential".into()))?;

    // Resend once. A lost response makes the purchase indeterminate.
    let paid = match client
        .post(&url)
        .bearer_auth(&session.token)
        .header("PAYMENT-SIGNATURE", header)
        .json(&rpc_body)
        .send()
        .await
    {
        Ok(resp) => resp,
        Err(e) => {
            let err = SdkError::Http(e);
            return Err(match err.http_kind() {
                Some(HttpKind::Connect) => err,
                _ => SdkError::PaymentIndeterminate,
            });
        }
    };
    let paid_status = paid.status().as_u16();
    if !(200..300).contains(&paid_status) {
        let body = paid.text().await.unwrap_or_default();
        return Err(SdkError::PaymentRejected {
            status: paid_status,
            body,
        });
    }
    // Drain the response, then read the funded balance.
    let _ = paid.text().await;
    credits(client, payment, session).await
}

// ── SIWE message construction ────────────────────────────────────────────────

/// Build a Sign-In-With-Ethereum (EIP-4361) message. The gateway pins the
/// domain/uri to its own host and requires the ToS `statement`; `chain_id` is
/// the caller's CAIP-2 pay network. Deterministic given its inputs so the
/// message tests are byte-exact.
pub(super) fn siwe_message(
    host: &str,
    address: &str,
    chain_id: u64,
    nonce: &str,
    issued_at: &str,
    statement: &str,
) -> String {
    // EIP-4361 field order and the decimal chain id are fixed.
    format!(
        "{host} wants you to sign in with your Ethereum account:\n\
         {address}\n\
         \n\
         {statement}\n\
         \n\
         URI: https://{host}\n\
         Version: 1\n\
         Chain ID: {chain_id}\n\
         Nonce: {nonce}\n\
         Issued At: {issued_at}"
    )
}

// Apply the EIP-55 checksum required by SIWE.
fn to_checksum_address(addr: &str) -> String {
    use sha3::{Digest, Keccak256};
    let lower = addr.strip_prefix("0x").unwrap_or(addr).to_lowercase();
    let hash = Keccak256::digest(lower.as_bytes());
    let mut out = String::with_capacity(42);
    out.push_str("0x");
    for (i, c) in lower.chars().enumerate() {
        if c.is_ascii_digit() {
            out.push(c);
        } else {
            // nibble i of the hash: high nibble for even i, low for odd.
            let nibble = if i % 2 == 0 {
                hash[i / 2] >> 4
            } else {
                hash[i / 2] & 0x0f
            };
            if nibble >= 8 {
                out.push(c.to_ascii_uppercase());
            } else {
                out.push(c);
            }
        }
    }
    out
}

// Parse the EIP-155 id required by SIWE.
fn eip155_chain_id(pay_network: &str) -> Result<u64, SdkError> {
    pay_network
        .strip_prefix("eip155:")
        .and_then(|s| s.parse().ok())
        .ok_or_else(|| {
            SdkError::Config(format!(
                "x402 drawdown requires an eip155 pay network (e.g. eip155:84532), got {pay_network:?}"
            ))
        })
}

// Return the gateway host used by SIWE domain and URI fields.
fn host_only(base: &str) -> String {
    base.trim_end_matches('/')
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .to_string()
}

// Build an RFC-3339 UTC timestamp without adding a date dependency.
fn rfc3339_now() -> String {
    let secs = now_unix() as i64;
    let days = secs.div_euclid(86_400);
    let rem = secs.rem_euclid(86_400);
    let (hour, min, sec) = (rem / 3600, (rem % 3600) / 60, rem % 60);
    let (year, month, day) = civil_from_days(days);
    // SIWE expects millisecond precision.
    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{min:02}:{sec:02}.000Z")
}

// Days-since-epoch → (year, month, day), Howard Hinnant's civil_from_days.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
    let m = (if mp < 10 { mp + 3 } else { mp - 9 }) as u32;
    (if m <= 2 { y + 1 } else { y }, m, d)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use secrecy::SecretString;
    use serde_json::json;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use wiremock::matchers::{body_partial_json, header, method, path};
    use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};

    // anvil key #0 (public throwaway, never funded).
    const EVM_KEY: &str = "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
    const EVM_ADDR: &str = "0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266";
    const USDC: &str = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";

    fn evm_payment(base: &str) -> ResolvedPayment {
        ResolvedPayment {
            scheme: super::super::PaymentScheme::X402,
            signer: super::super::signer::Signer::Evm(SecretString::new(EVM_KEY.to_string())),
            pay_network: "eip155:84532".into(),
            asset: USDC.into(),
            max_amount: 10_000_000,
            base_url_override: Some(base.to_string()),
            svm_rpc_url: None,
        }
    }

    fn x402_credit_offer(amount: &str) -> Value {
        json!({
            "x402Version": 2,
            "accepts": [{
                "scheme": "exact",
                "network": "eip155:84532",
                "amount": amount,
                "payTo": "0x000000000000000000000000000000000000dEaD",
                "maxTimeoutSeconds": 60,
                "asset": USDC,
                "extra": { "name": "USDC", "version": "2" }
            }]
        })
    }

    #[test]
    fn siwe_message_is_byte_exact() {
        let msg = siwe_message(
            "x402.quicknode.com",
            EVM_ADDR,
            84532,
            "abc12345",
            "2026-07-17T12:00:00Z",
            SIWX_STATEMENT,
        );
        let expected = "x402.quicknode.com wants you to sign in with your Ethereum account:\n\
             0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266\n\
             \n\
             I accept the Quicknode Terms of Service: https://www.quicknode.com/terms\n\
             \n\
             URI: https://x402.quicknode.com\n\
             Version: 1\n\
             Chain ID: 84532\n\
             Nonce: abc12345\n\
             Issued At: 2026-07-17T12:00:00Z";
        assert_eq!(msg, expected);
    }

    // Verify the generated timestamp uses the gateway's millisecond format.
    #[test]
    fn issued_at_carries_millisecond_precision() {
        let iso = rfc3339_now();
        assert!(iso.ends_with(".000Z"), "issued_at was {iso}");
        assert_eq!(
            iso.len(),
            24,
            "expected YYYY-MM-DDTHH:MM:SS.000Z, got {iso}"
        );

        let msg = siwe_message(
            "x402.quicknode.com",
            EVM_ADDR,
            84532,
            "abc12345",
            &iso,
            SIWX_STATEMENT,
        );
        assert!(msg.ends_with(&format!("Issued At: {iso}")));
    }

    #[test]
    fn rfc3339_now_round_trips_through_the_parser() {
        // Generated timestamps must round-trip through the parser.
        let iso = rfc3339_now();
        let back = parse_rfc3339_to_unix(&iso).unwrap();
        let now = now_unix() as i64;
        assert!((now - back).abs() <= 1, "iso={iso} back={back} now={now}");
    }

    #[test]
    fn checksum_address_matches_eip55() {
        // Known-good EIP-55 checksum.
        assert_eq!(
            to_checksum_address("0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"),
            "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
        );
        // Idempotent on already-checksummed input.
        assert_eq!(
            to_checksum_address("0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"),
            "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
        );
    }

    #[test]
    fn host_only_strips_scheme_and_slash() {
        assert_eq!(
            host_only("https://x402.quicknode.com/"),
            "x402.quicknode.com"
        );
        assert_eq!(host_only("http://127.0.0.1:8080"), "127.0.0.1:8080");
    }

    #[test]
    fn session_freshness() {
        let s = GatewaySession {
            token: "t".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        assert!(s.is_fresh(60));
        let stale = GatewaySession {
            token: "t".into(),
            exp_unix: now_unix() as i64 + 10,
            account_id: "a".into(),
        };
        assert!(!stale.is_fresh(60));
    }

    #[test]
    fn session_debug_redacts_the_jwt() {
        let s = GatewaySession {
            token: "super-secret-jwt".into(),
            exp_unix: 0,
            account_id: "a".into(),
        };
        let rendered = format!("{s:?}");
        assert!(rendered.contains("[redacted]"));
        assert!(!rendered.contains("super-secret-jwt"));
    }

    #[tokio::test]
    async fn authenticate_posts_siwx_and_caches_session() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/auth"))
            .and(body_partial_json(json!({ "type": "siwx" })))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "token": "jwt-abc",
                "expiresAt": "2099-01-01T00:00:00Z",
                "accountId": "eip155:84532:0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266"
            })))
            .expect(1)
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let client = reqwest::Client::new();
        let session = authenticate(&client, &payment).await.unwrap();
        assert_eq!(session.token, "jwt-abc");
        assert!(session.account_id.contains("0xf39fd6e5"));
        assert!(session.is_fresh(60));
    }

    #[tokio::test]
    async fn authenticate_error_surfaces_as_api() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/auth"))
            .respond_with(ResponseTemplate::new(401).set_body_json(json!({
                "error": "invalid_signature", "message": "bad SIWX signature"
            })))
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let client = reqwest::Client::new();
        let err = authenticate(&client, &payment).await.unwrap_err();
        assert!(matches!(err, SdkError::Api { status, .. } if status == 401));
    }

    #[tokio::test]
    async fn drawdown_call_attaches_bearer_and_returns_envelope() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/base-sepolia"))
            .and(header("authorization", "Bearer jwt-abc"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "jsonrpc": "2.0", "id": 1, "result": "0x1335f9a"
            })))
            .expect(1)
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let body = json!({ "jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": [] });
        let client = reqwest::Client::new();
        let text = drawdown_call(&client, &payment, &session, "base-sepolia", &body)
            .await
            .unwrap();
        assert!(text.contains("0x1335f9a"));
    }

    #[tokio::test]
    async fn drawdown_call_403_monthly_limit_is_api_error() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/base-sepolia"))
            .respond_with(ResponseTemplate::new(403).set_body_json(json!({
                "error": "monthly_limit_reached", "message": "monthly credit limit reached"
            })))
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let body = json!({ "jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": [] });
        let client = reqwest::Client::new();
        let err = drawdown_call(&client, &payment, &session, "base-sepolia", &body)
            .await
            .unwrap_err();
        assert!(
            matches!(&err, SdkError::Api { status, body } if *status == 403 && body.contains("monthly_limit_reached"))
        );
    }

    #[tokio::test]
    async fn credits_reads_the_balance() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/credits"))
            .and(header("authorization", "Bearer jwt-abc"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "accountId": "eip155:84532:0xabc", "credits": 1_000_095u64
            })))
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let client = reqwest::Client::new();
        let bal = credits(&client, &payment, &session).await.unwrap();
        assert_eq!(bal.credits, 1_000_095);
    }

    #[tokio::test]
    async fn drip_returns_the_funding_transaction() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/drip"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "accountId": "eip155:84532:0xabc",
                "walletAddress": "0xabc",
                "transactionHash": "0xfeed"
            })))
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let client = reqwest::Client::new();
        let receipt = drip(&client, &payment, &session).await.unwrap();
        assert_eq!(receipt.transaction_hash, "0xfeed");
        assert_eq!(receipt.account_id, "eip155:84532:0xabc");
    }

    // Menu with credit, per-request, and nanopayment tiers.
    fn gateway_menu() -> Value {
        let mut nanopayment = x402_credit_offer("100")
            .pointer("/accepts/0")
            .cloned()
            .unwrap();
        nanopayment["maxTimeoutSeconds"] = json!(604_900);
        nanopayment["extra"] = json!({
            "name": "GatewayWalletBatched",
            "version": "1",
            "verifyingContract": "0x0077777d7EBA4688BDeF3E311b846F25870A19B9"
        });
        json!({
            "x402Version": 2,
            "accepts": [
                x402_credit_offer("1000000").pointer("/accepts/0").cloned().unwrap(),
                x402_credit_offer("1000").pointer("/accepts/0").cloned().unwrap(),
                nanopayment,
            ]
        })
    }

    // Select and settle the regular credit tier; do not fall back to the
    // cheaper per-request or nanopayment tiers.
    #[tokio::test]
    async fn buy_credits_settles_the_regular_credit_tier() {
        let server = MockServer::start().await;
        struct BuySeq {
            calls: AtomicUsize,
        }
        impl Respond for BuySeq {
            fn respond(&self, req: &Request) -> ResponseTemplate {
                let n = self.calls.fetch_add(1, Ordering::SeqCst);
                if n == 0 && !req.headers.contains_key("payment-signature") {
                    ResponseTemplate::new(402).set_body_json(gateway_menu())
                } else {
                    use base64::Engine;
                    let header = req
                        .headers
                        .get("payment-signature")
                        .expect("paid resend must include a payment signature")
                        .to_str()
                        .unwrap();
                    let envelope: Value = serde_json::from_slice(
                        &base64::engine::general_purpose::STANDARD
                            .decode(header)
                            .unwrap(),
                    )
                    .unwrap();
                    assert_eq!(envelope["accepted"]["amount"], "1000000");
                    ResponseTemplate::new(200).set_body_json(json!({
                        "jsonrpc": "2.0", "id": 1, "result": "0x1"
                    }))
                }
            }
        }
        Mock::given(method("POST"))
            .and(path("/base-sepolia"))
            .respond_with(BuySeq {
                calls: AtomicUsize::new(0),
            })
            .expect(2)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/credits"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "accountId": "eip155:84532:0xabc", "credits": 100_000u64
            })))
            .expect(1)
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let client = reqwest::Client::new();
        let balance = buy_credits(&client, &payment, &session, "base-sepolia")
            .await
            .unwrap();
        assert_eq!(balance.credits, 100_000);
    }

    #[tokio::test]
    async fn buy_credits_does_not_downgrade_when_credit_tier_exceeds_ceiling() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/base-sepolia"))
            .respond_with(ResponseTemplate::new(402).set_body_json(gateway_menu()))
            .expect(1)
            .mount(&server)
            .await;

        let mut payment = evm_payment(&server.uri());
        payment.max_amount = 1_000;
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let client = reqwest::Client::new();
        let err = buy_credits(&client, &payment, &session, "base-sepolia")
            .await
            .unwrap_err();
        assert!(
            matches!(&err, SdkError::PaymentUnsupported { offered }
                if offered.contains("above max_amount 1000")),
            "unexpected error: {err:?}"
        );
    }

    // No credit tier means refusal, not per-request fallback.
    #[tokio::test]
    async fn buy_credits_without_a_credit_offer_settles_nothing() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/base-sepolia"))
            .respond_with(ResponseTemplate::new(402).set_body_json(x402_credit_offer("1000")))
            .expect(1)
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let client = reqwest::Client::new();
        let err = buy_credits(&client, &payment, &session, "base-sepolia")
            .await
            .unwrap_err();
        assert!(
            matches!(&err, SdkError::PaymentUnsupported { offered }
                if offered.contains("no credit-drawdown offer")),
            "unexpected error: {err:?}"
        );
    }

    // A non-402 probe means no purchase is needed.
    #[tokio::test]
    async fn buy_credits_with_existing_credits_reads_the_balance() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/base-sepolia"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "jsonrpc": "2.0", "id": 1, "result": "0x1"
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/credits"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "accountId": "eip155:84532:0xabc", "credits": 42u64
            })))
            .mount(&server)
            .await;

        let payment = evm_payment(&server.uri());
        let session = GatewaySession {
            token: "jwt-abc".into(),
            exp_unix: now_unix() as i64 + 3600,
            account_id: "a".into(),
        };
        let client = reqwest::Client::new();
        let bal = buy_credits(&client, &payment, &session, "base-sepolia")
            .await
            .unwrap();
        assert_eq!(bal.credits, 42);
    }
}