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
//! Data-plane JSON-RPC client.
//!
//! Makes JSON-RPC calls directly against the account's provisioned Tooling
//! Access endpoint, authenticating with a short-lived session JWT. The JWT is
//! minted via the Admin control plane ([`crate::admin::AdminApiClient::mint_tooling_token`]),
//! cached in memory, and refreshed proactively before expiry (or reactively on
//! a 401). The signing key never leaves the server; this client only ever holds
//! a minted JWT.
//!
//! A host that outlives a single process (e.g. the CLI) can persist the cached
//! token between runs by seeding [`crate::config::RpcConfig::seed`] on startup
//! and snapshotting [`RpcApiClient::current_token`] afterwards.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
use serde_json::Value;
#[cfg(feature = "payments")]
pub mod payment;
#[cfg(feature = "payments")]
pub use crate::config::PaymentConfig;
#[cfg(feature = "payments")]
pub use payment::drawdown::{CreditBalance, DripReceipt, GatewaySession};
#[cfg(feature = "payments-tempo")]
pub use payment::session::{ChannelState, ChannelStatus};
#[cfg(feature = "payments")]
pub use payment::signer::{generate_payment_wallet, ChainKind, GeneratedWallet};
#[cfg(feature = "payments")]
pub use payment::{PaymentReceipt, PaymentScheme};
use crate::admin::AdminApiClient;
use crate::config::{CachedToken, RpcConfig};
use crate::errors::SdkError;
use crate::SdkConfig;
// Default seconds before `exp` at which we proactively refresh. Also absorbs
// clock skew between client and endpoint.
const DEFAULT_REFRESH_MARGIN_SECS: i64 = 60;
/// JSON-RPC client for the Tooling Access endpoint.
#[derive(Clone)]
pub struct RpcApiClient {
// Used to mint/refresh session tokens against the control plane.
admin: AdminApiClient,
config: SdkConfig,
refresh_margin_secs: i64,
// Current cached token. Guarded by a std Mutex held only for synchronous
// read/write — never across an await.
cache: Arc<Mutex<Option<CachedToken>>>,
// Serializes refreshes so concurrent callers that all see an expired token
// trigger a single mint, not a stampede. Held across the mint await, hence
// an async mutex.
refresh_lock: Arc<tokio::sync::Mutex<()>>,
// Per-network URL map for multichain routing: key (e.g. "solana-mainnet")
// -> full http_url. The endpoint is multichain by subdomain and the URLs
// are not derivable by string munging, so callers seed this map (from
// `admin.get_endpoint_urls`). `None` until seeded; a `call` with a network
// then errors with a clear message.
networks: Arc<Mutex<Option<HashMap<String, String>>>>,
// Client-wide default custom endpoint URL. When set, calls bypass the
// Tooling Access endpoint and the JWT entirely (see `RpcConfig::endpoint_url`).
// A per-call `endpoint_url` overrides this. Immutable after construction.
endpoint_url: Option<String>,
// Crypto-micropayment lane config. When set, `call`/`call_with_receipt`
// pay per request against the x402/MPP gateways instead of minting a JWT.
// Resolved to the internal Signer at call time so a malformed config
// (bad max_amount, unknown scheme) surfaces as a clear `Config` error.
#[cfg(feature = "payments")]
payment: Option<Arc<crate::config::PaymentConfig>>,
}
/// The result of a JSON-RPC call plus an optional settlement receipt. Returned
/// by [`RpcApiClient::call_with_receipt`]; `payment_receipt` is `Some` only for
/// the MPP payment lane and `None` for x402 and the non-payment lanes.
#[cfg(feature = "payments")]
#[derive(Debug, Clone)]
pub struct RpcCallResponse {
pub result: Value,
pub payment_receipt: Option<payment::PaymentReceipt>,
}
impl std::fmt::Debug for RpcApiClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Never print the cached JWT.
f.debug_struct("RpcApiClient")
.field("refresh_margin_secs", &self.refresh_margin_secs)
.field(
"has_cached_token",
&self.cache.lock().is_ok_and(|c| c.is_some()),
)
.finish()
}
}
impl RpcApiClient {
pub fn new(config: SdkConfig, rpc_config: Option<&RpcConfig>) -> Self {
let refresh_margin_secs = rpc_config
.and_then(|c| c.refresh_margin_secs)
.filter(|&m| m >= 0)
.unwrap_or(DEFAULT_REFRESH_MARGIN_SECS);
// Seed is advisory: a stale/expired seed simply produces a cache miss on
// the first call and is replaced by a fresh mint.
let seed = rpc_config.and_then(|c| c.seed.clone());
let networks = rpc_config.and_then(|c| c.networks.clone());
let endpoint_url = rpc_config.and_then(|c| c.endpoint_url.clone());
// Hold the plain-data payment config; resolve it to the internal enum
// Signer at call time so a malformed config surfaces as a clear
// `Config` error (keeps `new` infallible).
#[cfg(feature = "payments")]
let payment = rpc_config.and_then(|c| c.payment.clone()).map(Arc::new);
Self {
admin: AdminApiClient::new(config.clone()),
config,
refresh_margin_secs,
cache: Arc::new(Mutex::new(seed)),
refresh_lock: Arc::new(tokio::sync::Mutex::new(())),
networks: Arc::new(Mutex::new(networks)),
endpoint_url,
#[cfg(feature = "payments")]
payment,
}
}
/// Seeds (or replaces) the per-network URL map used for multichain routing.
/// The map is `network key -> full http_url`, typically built from
/// `admin.get_endpoint_urls(endpoint_id).multichain_urls`. A host that
/// didn't seed it via [`RpcConfig`] can install it here before calling with
/// a `network`.
pub fn set_networks(&self, networks: HashMap<String, String>) {
if let Ok(mut guard) = self.networks.lock() {
*guard = Some(networks);
}
}
/// Returns a snapshot of the current cached token, if any. Hosts use this to
/// persist the token between processes. Returns `None` if no token has been
/// minted (or seeded) yet.
pub fn current_token(&self) -> Option<CachedToken> {
self.cache.lock().ok().and_then(|c| c.clone())
}
/// Discards the in-memory cached token, forcing the next call to mint a
/// fresh one. Use when the cached token is known stale beyond expiry — e.g.
/// the endpoint was disabled and re-enabled out of band.
pub fn clear_cached_token(&self) {
self.invalidate();
}
/// Makes a JSON-RPC call. `params` defaults to an empty array when `None`;
/// it accepts both a positional array and a by-name object.
///
/// `endpoint_url` sends this call to a custom HTTP URL, bypassing the
/// Tooling Access endpoint and the session JWT entirely — the URL is treated
/// as self-authenticating and gets no Authorization header. It overrides the
/// client-wide [`RpcConfig::endpoint_url`] default for this call. Because a
/// custom URL is not multichain-routed, passing both `endpoint_url` and
/// `network` is a [`SdkError::Config`] error.
///
/// `network` selects which chain to route to on a multichain endpoint: it
/// is a key in the seeded network map (e.g. `"solana-mainnet"`, `"polygon"`).
/// When `None`, the call goes to the endpoint's default network. When `Some`,
/// the map must be seeded (via [`RpcConfig`] or [`Self::set_networks`]) and
/// contain the key, otherwise a [`SdkError::Config`] is returned.
///
/// Returns the unwrapped `result`. A JSON-RPC `error` member is surfaced as
/// [`SdkError::Rpc`].
pub async fn call(
&self,
method: &str,
params: Option<Value>,
network: Option<String>,
endpoint_url: Option<String>,
) -> Result<Value, SdkError> {
// Payment lane wins when configured (see the precedence rules in
// `run_payment_lane`); it returns the bare result and discards any
// receipt. Every other caller keeps today's behavior unchanged.
#[cfg(feature = "payments")]
if self.payment.is_some() {
return self
.run_payment_lane(method, ¶ms, network.as_deref(), endpoint_url.as_deref())
.await
.map(|(result, _receipt)| result);
}
// Precedence: a per-call custom URL wins; then a per-call network; then
// the client-wide custom URL default; then the tooling default endpoint.
// A per-call URL and network are mutually exclusive (custom URLs are not
// multichain-routed).
if endpoint_url.is_some() && network.is_some() {
return Err(SdkError::Config(
"`endpoint_url` and `network` are mutually exclusive: a custom \
URL is not multichain-routed"
.into(),
));
}
let custom_url = endpoint_url.or_else(|| self.endpoint_url.clone());
// Custom mode: no token minted or attached; the URL authenticates itself.
// There is no JWT to refresh, so no reactive-401 retry path.
if let Some(url) = custom_url {
let resp = self.send(None, &url, method, ¶ms).await?;
return Self::parse_rpc(resp);
}
// Tooling mode: mint/refresh the JWT and route via the token/network map.
let token = self.valid_token().await?;
let url = self.resolve_url(&token, network.as_deref())?;
let resp = self.send(Some(&token), &url, method, ¶ms).await?;
// Reactive refresh: a 401 means the token was rejected (expired at the
// edge, revoked, clock skew past the margin). Discard, mint once, retry
// once. A second 401 surfaces as an Api error.
if resp.status == 401 {
self.invalidate();
let token = self.refresh().await?;
let url = self.resolve_url(&token, network.as_deref())?;
let retry = self.send(Some(&token), &url, method, ¶ms).await?;
return Self::parse_rpc(retry);
}
Self::parse_rpc(resp)
}
/// Like [`Self::call`], but also returns the settlement receipt for the
/// crypto-micropayment lane. `payment_receipt` is `Some` only on the MPP
/// happy path; it is `None` for x402 and for every non-payment lane (which
/// behave exactly like [`Self::call`]).
#[cfg(feature = "payments")]
pub async fn call_with_receipt(
&self,
method: &str,
params: Option<Value>,
network: Option<String>,
endpoint_url: Option<String>,
) -> Result<RpcCallResponse, SdkError> {
if self.payment.is_some() {
let (result, payment_receipt) = self
.run_payment_lane(method, ¶ms, network.as_deref(), endpoint_url.as_deref())
.await?;
return Ok(RpcCallResponse {
result,
payment_receipt,
});
}
// No payment lane: delegate to the ordinary call and report no receipt.
let result = self.call(method, params, network, endpoint_url).await?;
Ok(RpcCallResponse {
result,
payment_receipt: None,
})
}
// Payment-lane precedence + dispatch. Called only when `self.payment` is set.
//
// Precedence rules (mutually-exclusive with the self-auth URL lanes):
// - a per-call `endpoint_url` + payment => Config error;
// - a client-wide `endpoint_url` + payment => Config error (a custom
// self-auth URL and a payment lane are mutually exclusive);
// - payment present => `network` (the QUERY chain) is required and routed to
// the gateway path slug (NOT looked up in the tooling network map).
#[cfg(feature = "payments")]
async fn run_payment_lane(
&self,
method: &str,
params: &Option<Value>,
network: Option<&str>,
endpoint_url: Option<&str>,
) -> Result<(Value, Option<payment::PaymentReceipt>), SdkError> {
if endpoint_url.is_some() {
return Err(SdkError::Config(
"`endpoint_url` and a payment lane are mutually exclusive: a \
self-authenticating URL does not use per-request payment"
.into(),
));
}
if self.endpoint_url.is_some() {
return Err(SdkError::Config(
"a client-wide `endpoint_url` and a payment lane are mutually \
exclusive: configure one or the other"
.into(),
));
}
let query_network = network.ok_or_else(|| {
SdkError::Config(
"the payment lane requires `network` (the query chain, e.g. \
\"base-sepolia\" or \"solana-mainnet\")"
.into(),
)
})?;
// Resolve the plain-data config to the internal Signer here so a
// malformed config (bad max_amount, unknown scheme) surfaces as a
// clear `Config` error rather than being silently dropped.
let config = self
.payment
.as_ref()
.ok_or_else(|| SdkError::Config("no payment lane configured".into()))?;
// `resolved` is only mutated on the SVM RPC-source step below, which is
// compiled out without `payments-svm`.
#[cfg_attr(not(feature = "payments-svm"), allow(unused_mut))]
let mut resolved = payment::ResolvedPayment::from_config(config)?;
// SVM RPC source precedence: an explicit override (already applied in
// from_config) wins; otherwise, if the tooling lane is enabled and its
// network map resolves the pay-chain's Solana network, read through the
// caller's own Quicknode endpoint; else the public default (best-effort
// — no API key just means skip to public, never an error).
#[cfg(feature = "payments-svm")]
if resolved.svm_rpc_url.is_some() && config.svm_rpc_url.is_none() {
if let Some(tooling_url) = self.tooling_svm_url(&resolved.pay_network) {
resolved.svm_rpc_url = Some(tooling_url);
}
}
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params.clone().unwrap_or_else(|| Value::Array(vec![])),
});
let (text, receipt) = payment::pay_and_call(
self.config.rpc_http_client(),
&resolved,
query_network,
&body,
)
.await?;
let result = Self::parse_rpc(RawResponse { status: 200, text })?;
Ok((result, receipt))
}
// Resolve the plain-data payment config to the internal Signer + selector,
// applying the same SVM RPC-source precedence as `run_payment_lane`. Shared
// by the x402 drawdown lifecycle methods below. Errors (bad max_amount,
// unknown scheme) surface as a clear `Config` error.
#[cfg(feature = "payments")]
fn resolve_payment(&self) -> Result<payment::ResolvedPayment, SdkError> {
let config = self
.payment
.as_ref()
.ok_or_else(|| SdkError::Config("no payment lane configured".into()))?;
#[cfg_attr(not(feature = "payments-svm"), allow(unused_mut))]
let mut resolved = payment::ResolvedPayment::from_config(config)?;
#[cfg(feature = "payments-svm")]
if resolved.svm_rpc_url.is_some() && config.svm_rpc_url.is_none() {
if let Some(tooling_url) = self.tooling_svm_url(&resolved.pay_network) {
resolved.svm_rpc_url = Some(tooling_url);
}
}
Ok(resolved)
}
/// The configured payment wallet's on-chain address (EVM/Tempo `0x…` hex,
/// Solana base58), derived offline from the key. A host uses this to key a
/// gateway-session cache by wallet without a network round trip.
#[cfg(feature = "payments")]
pub fn payment_address(&self) -> Result<String, SdkError> {
self.resolve_payment()?.signer.address()
}
/// Authenticates against the x402 gateway with a SIWX message and returns a
/// [`payment::drawdown::GatewaySession`] (the session JWT). Free — no funds
/// move — so a host may (re)auth transparently before a drawdown call. The
/// host persists the session and re-seeds it next run, exactly as it does
/// the tooling [`crate::config::CachedToken`].
#[cfg(feature = "payments")]
pub async fn gateway_authenticate(
&self,
) -> Result<payment::drawdown::GatewaySession, SdkError> {
let resolved = self.resolve_payment()?;
payment::drawdown::authenticate(self.config.rpc_http_client(), &resolved).await
}
/// Buys a block of credits against the x402 gateway, settling the offered
/// `402` with the same signer construction as the per-request lane. Returns
/// the post-purchase [`payment::drawdown::CreditBalance`]. Single-attempt:
/// a paid lane never blind-retries.
#[cfg(feature = "payments")]
pub async fn gateway_buy_credits(
&self,
session: &payment::drawdown::GatewaySession,
network: &str,
) -> Result<payment::drawdown::CreditBalance, SdkError> {
let resolved = self.resolve_payment()?;
payment::drawdown::buy_credits(self.config.rpc_http_client(), &resolved, session, network)
.await
}
/// Reads the account's current x402 credit balance (GET `/credits`).
#[cfg(feature = "payments")]
pub async fn gateway_credits(
&self,
session: &payment::drawdown::GatewaySession,
) -> Result<payment::drawdown::CreditBalance, SdkError> {
let resolved = self.resolve_payment()?;
payment::drawdown::credits(self.config.rpc_http_client(), &resolved, session).await
}
/// Requests testnet tokens from the x402 faucet (POST `/drip`). Allowed once
/// per account on Base Sepolia. Returns the funding transaction (not a
/// balance — call [`Self::gateway_credits`] afterwards for the balance).
#[cfg(feature = "payments")]
pub async fn gateway_drip(
&self,
session: &payment::drawdown::GatewaySession,
) -> Result<payment::drawdown::DripReceipt, SdkError> {
let resolved = self.resolve_payment()?;
payment::drawdown::drip(self.config.rpc_http_client(), &resolved, session).await
}
/// Makes one x402 drawdown JSON-RPC call against `network` with the session
/// JWT as a Bearer token, drawing 1 credit on success. Returns the
/// unwrapped JSON-RPC `result`. Single-attempt; the caller decides whether
/// to re-auth on a `token_expired` (surfaced as [`SdkError::Api`] 401/403).
#[cfg(feature = "payments")]
pub async fn gateway_drawdown_call(
&self,
method: &str,
params: Option<Value>,
network: &str,
session: &payment::drawdown::GatewaySession,
) -> Result<Value, SdkError> {
let resolved = self.resolve_payment()?;
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params.unwrap_or_else(|| Value::Array(vec![])),
});
let text = payment::drawdown::drawdown_call(
self.config.rpc_http_client(),
&resolved,
session,
network,
&body,
)
.await?;
Self::parse_rpc(RawResponse { status: 200, text })
}
/// Opens an MPP payment channel by depositing `deposit` base units into the
/// escrow and returns the new [`payment::session::ChannelState`]. Moves real
/// funds; single-attempt.
///
/// The channel is scoped by the configured pay network and asset, not by any
/// queried chain: one open channel funds paid calls to every supported
/// network, so this takes no query network.
#[cfg(feature = "payments-tempo")]
pub async fn mpp_open(
&self,
deposit: u128,
) -> Result<payment::session::ChannelState, SdkError> {
let resolved = self.resolve_payment()?;
payment::session::open(self.config.rpc_http_client(), &resolved, deposit).await
}
/// Adds `additional_deposit` base units to an open MPP channel. Moves real
/// funds; single-attempt. Scoped by the configured pay network and asset.
#[cfg(feature = "payments-tempo")]
pub async fn mpp_top_up(
&self,
channel: &payment::session::ChannelState,
additional_deposit: u128,
) -> Result<payment::session::ChannelState, SdkError> {
let resolved = self.resolve_payment()?;
payment::session::top_up(
self.config.rpc_http_client(),
&resolved,
channel,
additional_deposit,
)
.await
}
/// Cooperatively closes an MPP channel: settles the final cumulative spend
/// on-chain and refunds the unused deposit. Single-attempt. Scoped by the
/// configured pay network and asset.
#[cfg(feature = "payments-tempo")]
pub async fn mpp_close(
&self,
channel: &payment::session::ChannelState,
) -> Result<(), SdkError> {
let resolved = self.resolve_payment()?;
payment::session::close(self.config.rpc_http_client(), &resolved, channel).await
}
/// Fetches the gateway's view of the channel (accepted cumulative + spent).
///
/// **This costs one request unit.** The gateway prices every session POST as
/// a chargeable request and computes the available balance from the *new*
/// spend a voucher authorizes, so the probe advances `cumulative_spent` by
/// `per_call` exactly like a session RPC call. The caller must persist the
/// returned state on success. Returns [`SdkError::PaymentUnsupported`]
/// before any network I/O when the channel has no room left for the probe.
///
/// Scoped by the configured pay network and asset; takes no query network.
#[cfg(feature = "payments-tempo")]
pub async fn mpp_status(
&self,
channel: &payment::session::ChannelState,
) -> Result<payment::session::ChannelStatus, SdkError> {
let resolved = self.resolve_payment()?;
payment::session::status(self.config.rpc_http_client(), &resolved, channel).await
}
/// Makes one MPP session-lane JSON-RPC call, authorizing it with a
/// cumulative voucher for `new_cumulative` (the running total after this
/// call). Returns the unwrapped JSON-RPC `result`. Single-attempt; the caller
/// advances the persisted `cumulative_spent` after a success.
#[cfg(feature = "payments-tempo")]
pub async fn mpp_session_call(
&self,
method: &str,
params: Option<Value>,
network: &str,
channel: &payment::session::ChannelState,
new_cumulative: u128,
) -> Result<Value, SdkError> {
let resolved = self.resolve_payment()?;
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params.unwrap_or_else(|| Value::Array(vec![])),
});
let text = payment::session::voucher_call(
self.config.rpc_http_client(),
&resolved,
network,
channel,
new_cumulative,
&body,
)
.await?;
Self::parse_rpc(RawResponse { status: 200, text })
}
// Best-effort tooling-endpoint lookup for the pay-chain's Solana network.
// Returns None (skip to the public default) when no map / no matching key —
// never an error. The seeded map is itself the effective API-key gate: it's
// built from `admin.get_endpoint_urls`, which a keyless SDK cannot call, so
// a keyless instance never has a map here and falls through to the public
// default exactly as the precedence requires.
#[cfg(feature = "payments-svm")]
fn tooling_svm_url(&self, pay_network: &str) -> Option<String> {
// Map the CAIP-2 solana cluster to its tooling network key. Devnet is
// identified by its genesis-hash prefix (the literal "devnet" never
// appears in a CAIP-2 id — see payment::solana_pay_network_is_devnet).
let key = if payment::solana_pay_network_is_devnet(pay_network) {
"solana-devnet"
} else {
"solana-mainnet"
};
let guard = self.networks.lock().ok()?;
guard.as_ref()?.get(key).cloned()
}
// Resolve the target URL for a call. `None` network -> the token's default
// endpoint_url. `Some(key)` -> the mapped per-network URL; errors if no map
// is seeded or the key is unknown (listing available keys).
fn resolve_url(&self, token: &CachedToken, network: Option<&str>) -> Result<String, SdkError> {
let Some(key) = network else {
return Ok(token.endpoint_url.clone());
};
let guard = self
.networks
.lock()
.map_err(|_| SdkError::Config("network map lock poisoned".into()))?;
let Some(map) = guard.as_ref() else {
return Err(SdkError::Config(format!(
"network '{key}' requested but no network map is available; \
seed it via RpcConfig.networks or set_networks()"
)));
};
match map.get(key) {
Some(url) => Ok(url.clone()),
None => {
let mut keys: Vec<&str> = map.keys().map(String::as_str).collect();
keys.sort_unstable();
Err(SdkError::Config(format!(
"unknown network '{key}'. Available: {}",
keys.join(", ")
)))
}
}
}
// ── Token lifecycle ──────────────────────────────────────────────────────
// Returns a token that is valid past the refresh margin, minting if needed.
async fn valid_token(&self) -> Result<CachedToken, SdkError> {
if let Some(tok) = self.cached_if_fresh() {
return Ok(tok);
}
self.refresh().await
}
// Returns the cached token only if present and not within the refresh margin.
fn cached_if_fresh(&self) -> Option<CachedToken> {
let now = now_unix();
let guard = self.cache.lock().ok()?;
guard
.as_ref()
.filter(|t| now + self.refresh_margin_secs < t.exp_unix)
.cloned()
}
// Single-flight refresh: only one caller mints at a time; others re-check
// the cache after acquiring the lock and reuse the just-minted token.
async fn refresh(&self) -> Result<CachedToken, SdkError> {
let _guard = self.refresh_lock.lock().await;
// Another caller may have refreshed while we waited for the lock.
if let Some(tok) = self.cached_if_fresh() {
return Ok(tok);
}
let fresh = self.admin.mint_tooling_token().await?;
if let Ok(mut guard) = self.cache.lock() {
*guard = Some(fresh.clone());
}
Ok(fresh)
}
fn invalidate(&self) {
if let Ok(mut guard) = self.cache.lock() {
*guard = None;
}
}
// ── Transport ─────────────────────────────────────────────────────────────
// Sends the JSON-RPC request. `token` is `Some` in tooling mode (attaches a
// Bearer JWT) and `None` for a custom endpoint URL, which is treated as
// self-authenticating and gets no Authorization header. Either way the
// request goes through the keyless `rpc_http_client`, so the account
// `x-api-key` never reaches the data plane.
async fn send(
&self,
token: Option<&CachedToken>,
target_url: &str,
method: &str,
params: &Option<Value>,
) -> Result<RawResponse, SdkError> {
let url = reqwest::Url::parse(target_url).map_err(|e| SdkError::Config(e.to_string()))?;
let body = serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params.clone().unwrap_or_else(|| Value::Array(vec![])),
});
let mut req = self.config.rpc_http_client().post(url).json(&body);
if let Some(token) = token {
req = req.bearer_auth(&token.token);
}
let resp = req.send().await.map_err(SdkError::Http)?;
let status = resp.status().as_u16();
let text = resp.text().await.map_err(SdkError::Http)?;
Ok(RawResponse { status, text })
}
// Parse a JSON-RPC envelope: surface `error` as SdkError::Rpc, else return
// `result`. Non-2xx HTTP without a usable JSON-RPC body is an Api error.
fn parse_rpc(resp: RawResponse) -> Result<Value, SdkError> {
// Try to decode the JSON-RPC envelope regardless of HTTP status — some
// endpoints return a JSON-RPC error with a 200, others with 4xx.
let parsed: Result<JsonRpcEnvelope, _> = serde_json::from_str(&resp.text);
match parsed {
Ok(env) => {
if let Some(err) = env.error {
return Err(SdkError::Rpc {
code: err.code,
message: err.message,
});
}
if let Some(result) = env.result {
return Ok(result);
}
// No result and no error: if the HTTP status was a failure,
// surface it; otherwise return null.
if !(200..300).contains(&resp.status) {
return Err(SdkError::Api {
status: status_code(resp.status),
body: resp.text,
});
}
Ok(Value::Null)
}
Err(source) => {
if !(200..300).contains(&resp.status) {
Err(SdkError::Api {
status: status_code(resp.status),
body: resp.text,
})
} else {
Err(SdkError::Decode {
source,
body: resp.text,
})
}
}
}
}
}
struct RawResponse {
status: u16,
text: String,
}
#[derive(serde::Deserialize)]
struct JsonRpcEnvelope {
#[serde(default)]
result: Option<Value>,
#[serde(default)]
error: Option<JsonRpcError>,
}
#[derive(serde::Deserialize)]
struct JsonRpcError {
code: i64,
message: String,
}
fn now_unix() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
// Pre-epoch system clock is implausible; treat as 0 so a fresh token is
// always considered valid rather than panicking.
.map_or(0, |d| d.as_secs() as i64)
}
fn status_code(status: u16) -> reqwest::StatusCode {
reqwest::StatusCode::from_u16(status).unwrap_or(reqwest::StatusCode::BAD_GATEWAY)
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use crate::config::{AdminConfig, SdkFullConfig};
use crate::QuicknodeSdk;
use std::sync::atomic::{AtomicUsize, Ordering};
use wiremock::matchers::{body_partial_json, header, method, path};
use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
// A future exp so seeded tokens are considered fresh.
fn future_exp() -> i64 {
now_unix() + 3600
}
fn token_body(endpoint_url: &str, exp: i64) -> serde_json::Value {
// The mint route returns an ISO timestamp; build one far in the future.
// We feed exp directly via seed in most tests, but mint tests use this.
let _ = exp;
serde_json::json!({
"data": {
"endpoint_url": endpoint_url,
"token": "minted.jwt.value",
"expires_at": "2099-01-01T00:00:00.000Z"
},
"error": null
})
}
fn sdk_with_seed(admin_base: &str, rpc_endpoint: &str) -> QuicknodeSdk {
let mut cfg = SdkFullConfig::from_api_key("test-key".to_string());
cfg.admin = Some(AdminConfig {
base_url: Some(format!("{admin_base}/")),
});
cfg.rpc = Some(RpcConfig {
endpoint_url: None,
seed: Some(CachedToken {
endpoint_url: rpc_endpoint.to_string(),
token: "seeded.jwt".to_string(),
exp_unix: future_exp(),
}),
refresh_margin_secs: None,
networks: None,
payment: None,
});
QuicknodeSdk::new(&cfg).unwrap()
}
#[tokio::test]
async fn call_uses_seed_without_minting() {
let server = MockServer::start().await;
// RPC endpoint returns a result.
Mock::given(method("POST"))
.and(path("/"))
.and(body_partial_json(
serde_json::json!({ "method": "eth_blockNumber" }),
))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "0x1335f9a"
})))
.mount(&server)
.await;
// Use the same server for both admin and rpc; if mint were called it
// would 404 (no mock for /tooling-access/token) and the test would fail.
let sdk = sdk_with_seed(&server.uri(), &server.uri());
let result = sdk
.rpc
.call("eth_blockNumber", None, None, None)
.await
.unwrap();
assert_eq!(result, serde_json::json!("0x1335f9a"));
}
#[tokio::test]
async fn call_sends_bearer_jwt_but_not_account_api_key() {
let server = MockServer::start().await;
// Match only requests that carry the Bearer JWT and omit the account
// key: the data-plane client must never leak `x-api-key`. If the key
// were present this mock would not match and the call would 404.
Mock::given(method("POST"))
.and(path("/"))
.and(header("authorization", "Bearer seeded.jwt"))
.and(|req: &Request| !req.headers.contains_key("x-api-key"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "0xok"
})))
.mount(&server)
.await;
let sdk = sdk_with_seed(&server.uri(), &server.uri());
let result = sdk
.rpc
.call("eth_blockNumber", None, None, None)
.await
.unwrap();
assert_eq!(result, serde_json::json!("0xok"));
}
// Builds an SDK whose RPC client has a client-wide custom `endpoint_url` and
// NO seed. The admin base points at a dead address, so any attempt to mint a
// tooling token would fail — proving custom mode never touches the JWT path.
fn sdk_with_custom_url(endpoint_url: &str) -> QuicknodeSdk {
let mut cfg = SdkFullConfig::from_api_key("test-key".to_string());
cfg.admin = Some(AdminConfig {
base_url: Some("http://127.0.0.1:1/".to_string()),
});
cfg.rpc = Some(RpcConfig {
endpoint_url: Some(endpoint_url.to_string()),
seed: None,
refresh_margin_secs: None,
networks: None,
payment: None,
});
QuicknodeSdk::new(&cfg).unwrap()
}
#[tokio::test]
async fn config_endpoint_url_bypasses_jwt_and_minting() {
let server = MockServer::start().await;
// Custom endpoint must receive the call with NO Authorization header and
// NO account key. If minting were attempted it would fail against the
// dead admin base and the call would error instead.
Mock::given(method("POST"))
.and(path("/custom"))
.and(|req: &Request| {
!req.headers.contains_key("authorization") && !req.headers.contains_key("x-api-key")
})
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "0xcustom"
})))
.mount(&server)
.await;
let sdk = sdk_with_custom_url(&format!("{}/custom", server.uri()));
let result = sdk
.rpc
.call("eth_blockNumber", None, None, None)
.await
.unwrap();
assert_eq!(result, serde_json::json!("0xcustom"));
// No token was ever minted or cached.
assert!(sdk.rpc.current_token().is_none());
}
#[tokio::test]
async fn per_call_endpoint_url_overrides_config_default() {
let server = MockServer::start().await;
// The per-call URL points here; the config default points at /wrong,
// which has no mock and would 404.
Mock::given(method("POST"))
.and(path("/override"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "0xoverride"
})))
.mount(&server)
.await;
let sdk = sdk_with_custom_url(&format!("{}/wrong", server.uri()));
let result = sdk
.rpc
.call(
"eth_blockNumber",
None,
None,
Some(format!("{}/override", server.uri())),
)
.await
.unwrap();
assert_eq!(result, serde_json::json!("0xoverride"));
}
#[tokio::test]
async fn endpoint_url_and_network_together_is_config_error() {
let sdk = sdk_with_custom_url("https://example.invalid/rpc");
let err = sdk
.rpc
.call(
"eth_blockNumber",
None,
Some("solana-mainnet".to_string()),
Some("https://example.invalid/other".to_string()),
)
.await
.unwrap_err();
assert!(matches!(err, SdkError::Config(msg) if msg.contains("mutually exclusive")));
}
#[tokio::test]
async fn json_rpc_error_maps_to_rpc_error() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1,
"error": { "code": -32602, "message": "invalid params" }
})))
.mount(&server)
.await;
let sdk = sdk_with_seed(&server.uri(), &server.uri());
let err = sdk
.rpc
.call("eth_getBalance", None, None, None)
.await
.unwrap_err();
match err {
SdkError::Rpc { code, message } => {
assert_eq!(code, -32602);
assert!(message.contains("invalid params"));
}
other => panic!("expected Rpc error, got {other:?}"),
}
}
#[tokio::test]
async fn reactive_401_refreshes_and_retries_once() {
let server = MockServer::start().await;
// First RPC call returns 401, second (after refresh) returns a result.
struct Sequence {
calls: AtomicUsize,
}
impl Respond for Sequence {
fn respond(&self, _: &Request) -> ResponseTemplate {
let n = self.calls.fetch_add(1, Ordering::SeqCst);
if n == 0 {
ResponseTemplate::new(401).set_body_string("unauthorized")
} else {
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "0xokay"
}))
}
}
}
// RPC endpoint lives at /rpc; mint route at /tooling-access/token.
Mock::given(method("POST"))
.and(path("/rpc"))
.respond_with(Sequence {
calls: AtomicUsize::new(0),
})
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/tooling-access/token"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(token_body(&format!("{}/rpc", server.uri()), future_exp())),
)
.mount(&server)
.await;
let sdk = sdk_with_seed(&server.uri(), &format!("{}/rpc", server.uri()));
let result = sdk
.rpc
.call("eth_blockNumber", None, None, None)
.await
.unwrap();
assert_eq!(result, serde_json::json!("0xokay"));
}
#[tokio::test]
async fn second_401_surfaces_as_api_error() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/rpc"))
.respond_with(ResponseTemplate::new(401).set_body_string("nope"))
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/tooling-access/token"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(token_body(&format!("{}/rpc", server.uri()), future_exp())),
)
.mount(&server)
.await;
let sdk = sdk_with_seed(&server.uri(), &format!("{}/rpc", server.uri()));
let err = sdk
.rpc
.call("eth_blockNumber", None, None, None)
.await
.unwrap_err();
assert!(matches!(err, SdkError::Api { status, .. } if status.as_u16() == 401));
}
#[tokio::test]
async fn expired_seed_triggers_mint() {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/tooling-access/token"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(token_body(&format!("{}/rpc", server.uri()), future_exp())),
)
.mount(&server)
.await;
Mock::given(method("POST"))
.and(path("/rpc"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "0xfresh"
})))
.mount(&server)
.await;
// Seed an already-expired token.
let mut cfg = SdkFullConfig::from_api_key("test-key".to_string());
cfg.admin = Some(AdminConfig {
base_url: Some(format!("{}/", server.uri())),
});
cfg.rpc = Some(RpcConfig {
endpoint_url: None,
seed: Some(CachedToken {
endpoint_url: format!("{}/rpc", server.uri()),
token: "expired.jwt".to_string(),
exp_unix: now_unix() - 10,
}),
refresh_margin_secs: None,
networks: None,
payment: None,
});
let sdk = QuicknodeSdk::new(&cfg).unwrap();
let result = sdk
.rpc
.call("eth_blockNumber", None, None, None)
.await
.unwrap();
assert_eq!(result, serde_json::json!("0xfresh"));
// current_token now reflects the minted token.
assert_eq!(sdk.rpc.current_token().unwrap().token, "minted.jwt.value");
}
#[tokio::test]
async fn network_routes_to_mapped_url() {
let server = MockServer::start().await;
// The default endpoint is /default; the "solana-mainnet" network maps to
// /solana. A call with that network must POST to /solana, not /default.
Mock::given(method("POST"))
.and(path("/solana"))
.respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "12345"
})))
.mount(&server)
.await;
let mut cfg = SdkFullConfig::from_api_key("test-key".to_string());
cfg.admin = Some(AdminConfig {
base_url: Some(format!("{}/", server.uri())),
});
let mut networks = std::collections::HashMap::new();
networks.insert(
"solana-mainnet".to_string(),
format!("{}/solana", server.uri()),
);
cfg.rpc = Some(RpcConfig {
endpoint_url: None,
seed: Some(CachedToken {
endpoint_url: format!("{}/default", server.uri()),
token: "seeded.jwt".to_string(),
exp_unix: future_exp(),
}),
refresh_margin_secs: None,
networks: Some(networks),
payment: None,
});
let sdk = QuicknodeSdk::new(&cfg).unwrap();
let result = sdk
.rpc
.call("getSlot", None, Some("solana-mainnet".to_string()), None)
.await
.unwrap();
assert_eq!(result, serde_json::json!("12345"));
}
#[tokio::test]
async fn unknown_network_is_config_error_listing_keys() {
let server = MockServer::start().await;
let sdk = sdk_with_seed(&server.uri(), &server.uri());
// sdk_with_seed seeds no network map.
sdk.rpc.set_networks(std::collections::HashMap::from([(
"solana-mainnet".to_string(),
"https://x/solana".to_string(),
)]));
let err = sdk
.rpc
.call("getSlot", None, Some("polygon".to_string()), None)
.await
.unwrap_err();
match err {
SdkError::Config(msg) => {
assert!(msg.contains("unknown network 'polygon'"), "msg: {msg}");
assert!(
msg.contains("solana-mainnet"),
"msg should list keys: {msg}"
);
}
other => panic!("expected Config error, got {other:?}"),
}
}
#[tokio::test]
async fn network_without_seeded_map_errors() {
let server = MockServer::start().await;
let sdk = sdk_with_seed(&server.uri(), &server.uri());
let err = sdk
.rpc
.call("getSlot", None, Some("solana-mainnet".to_string()), None)
.await
.unwrap_err();
assert!(matches!(err, SdkError::Config(msg) if msg.contains("no network map")));
}
}
#[cfg(all(test, feature = "payments"))]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod payment_lane_tests {
use super::*;
use crate::config::{PaymentConfig, SdkFullConfig};
use crate::QuicknodeSdk;
use std::sync::atomic::{AtomicUsize, Ordering};
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, Request, Respond, ResponseTemplate};
const EVM_KEY: &str = "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";
const USDC: &str = "0x036CbD53842c5426634e7929541eC2318f3dCF7e";
// A keyless SDK whose RPC client carries an x402/EVM payment lane pointed at
// the given mock gateway base.
fn keyless_x402_sdk(gateway_base: &str) -> QuicknodeSdk {
let mut cfg = SdkFullConfig::keyless();
cfg.rpc = Some(RpcConfig {
endpoint_url: None,
seed: None,
refresh_margin_secs: None,
networks: None,
payment: Some(PaymentConfig {
scheme: "x402".into(),
key: EVM_KEY.into(),
pay_network: "eip155:84532".into(),
asset: USDC.into(),
max_amount: "10000".into(),
svm_rpc_url: None,
base_url_override: Some(gateway_base.to_string()),
}),
});
QuicknodeSdk::new(&cfg).unwrap()
}
// Mock gateway: unpaid POST -> 402 menu; paid POST (has PAYMENT-SIGNATURE)
// -> 200 result.
async fn mount_x402_gateway(server: &MockServer) {
struct Seq {
calls: AtomicUsize,
}
impl Respond for Seq {
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(serde_json::json!({
"x402Version": 2,
"accepts": [{
"scheme": "exact", "network": "eip155:84532",
"amount": "1000", "payTo": "0x000000000000000000000000000000000000dEaD",
"maxTimeoutSeconds": 60, "asset": USDC,
"extra": { "name": "USDC", "version": "2" }
}]
}))
} else {
ResponseTemplate::new(200).set_body_json(serde_json::json!({
"jsonrpc": "2.0", "id": 1, "result": "0x1335f9a"
}))
}
}
}
Mock::given(method("POST"))
.respond_with(Seq {
calls: AtomicUsize::new(0),
})
.mount(server)
.await;
}
#[tokio::test]
async fn keyless_payment_call_returns_unwrapped_result() {
let server = MockServer::start().await;
mount_x402_gateway(&server).await;
let sdk = keyless_x402_sdk(&server.uri());
let result = sdk
.rpc
.call(
"eth_blockNumber",
None,
Some("base-sepolia".to_string()),
None,
)
.await
.unwrap();
assert_eq!(result, serde_json::json!("0x1335f9a"));
}
#[tokio::test]
async fn x402_call_with_receipt_has_no_receipt() {
let server = MockServer::start().await;
mount_x402_gateway(&server).await;
let sdk = keyless_x402_sdk(&server.uri());
let resp = sdk
.rpc
.call_with_receipt(
"eth_blockNumber",
None,
Some("base-sepolia".to_string()),
None,
)
.await
.unwrap();
assert_eq!(resp.result, serde_json::json!("0x1335f9a"));
assert!(resp.payment_receipt.is_none());
}
#[tokio::test]
async fn payment_lane_requires_network() {
let server = MockServer::start().await;
let sdk = keyless_x402_sdk(&server.uri());
let err = sdk
.rpc
.call("eth_blockNumber", None, None, None)
.await
.unwrap_err();
assert!(matches!(err, SdkError::Config(m) if m.contains("requires `network`")));
}
#[tokio::test]
async fn per_call_endpoint_url_plus_payment_is_config_error() {
let server = MockServer::start().await;
let sdk = keyless_x402_sdk(&server.uri());
let err = sdk
.rpc
.call(
"eth_blockNumber",
None,
None,
Some("https://example.invalid/rpc".to_string()),
)
.await
.unwrap_err();
assert!(matches!(err, SdkError::Config(m) if m.contains("mutually exclusive")));
}
#[tokio::test]
async fn bad_max_amount_is_config_error_at_call() {
let server = MockServer::start().await;
let mut cfg = SdkFullConfig::keyless();
cfg.rpc = Some(RpcConfig {
endpoint_url: None,
seed: None,
refresh_margin_secs: None,
networks: None,
payment: Some(PaymentConfig {
scheme: "x402".into(),
key: EVM_KEY.into(),
pay_network: "eip155:84532".into(),
asset: USDC.into(),
max_amount: "not-a-number".into(),
svm_rpc_url: None,
base_url_override: Some(server.uri()),
}),
});
let sdk = QuicknodeSdk::new(&cfg).unwrap();
let err = sdk
.rpc
.call(
"eth_blockNumber",
None,
Some("base-sepolia".to_string()),
None,
)
.await
.unwrap_err();
assert!(matches!(err, SdkError::Config(m) if m.contains("max_amount")));
}
}