sdkt-rpc 2.7.0

Soroban JSON-RPC client, endpoint configurations and network connectivity wrapper.
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
//! Soroban RPC HTTP client.
//!
//! Low-level JSON‑RPC over HTTP via [`reqwest`].

use crate::error::RpcError;
use sdkt_core::NetworkConfig;
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Soroban RPC HTTP client.
///
/// Holds the RPC endpoint URL and a reusable HTTP client.
#[derive(Clone)]
pub struct SorobanRpcClient {
    /// Base URL of the Soroban RPC endpoint (e.g. `https://soroban-testnet.stellar.org`).
    endpoint: String,
    http_client: reqwest::Client,
}

impl SorobanRpcClient {
    /// Create a client from an explicit endpoint URL.
    pub fn new(endpoint: &str) -> Self {
        Self::with_options(endpoint, Some(15), Some(100))
    }

    /// Create a client with explicit pool and timeout settings.
    pub fn with_options(
        endpoint: &str,
        timeout_secs: Option<u64>,
        pool_max_idle: Option<usize>,
    ) -> Self {
        let mut builder = reqwest::Client::builder();

        if let Some(secs) = timeout_secs {
            builder = builder.timeout(Duration::from_secs(secs));
        }

        if let Some(max_idle) = pool_max_idle {
            builder = builder.pool_max_idle_per_host(max_idle);
        }

        let http_client = builder
            .pool_idle_timeout(Duration::from_secs(60))
            .build()
            .unwrap_or_else(|_| reqwest::Client::new());

        let endpoint = endpoint.trim_end_matches('/').to_string();

        Self {
            endpoint,
            http_client,
        }
    }

    /// Create a client from [`NetworkConfig`].
    pub fn from_config(config: &NetworkConfig) -> Self {
        Self::with_options(
            &config.rpc_url,
            config.timeout_secs,
            config.pool_max_idle_per_host,
        )
    }

    /// Return the configured endpoint URL.
    pub fn endpoint(&self) -> &str {
        &self.endpoint
    }

    /// Return a reference to the internal HTTP client.
    pub fn http_client(&self) -> &reqwest::Client {
        &self.http_client
    }

    /// Helper for making JSON-RPC calls with basic timeout retry logic.
    pub async fn request<T: serde::de::DeserializeOwned>(
        &self,
        method: &str,
        params: impl Serialize,
    ) -> Result<T, RpcError> {
        let payload = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": method,
            "params": params,
        });

        let mut attempt = 0;
        let mut last_err = None;

        while attempt < 2 {
            match self
                .http_client
                .post(&self.endpoint)
                .json(&payload)
                .header("Accept-Encoding", "identity")
                .send()
                .await
            {
                Ok(res) => {
                    let rpc_res: JsonRpcResponse<T> = match res.json().await {
                        Ok(json) => json,
                        Err(e) => return Err(RpcError::Reqwest(e)),
                    };

                    if let Some(error) = rpc_res.error {
                        return Err(RpcError::Rpc(error.message));
                    }

                    return rpc_res.result.ok_or_else(|| {
                        RpcError::Rpc("Missing result in JSON-RPC response".to_string())
                    });
                }
                Err(e) => {
                    if e.is_timeout() || e.is_connect() {
                        last_err = Some(e);
                        attempt += 1;
                        tokio::time::sleep(Duration::from_millis(500)).await;
                        continue;
                    }
                    return Err(RpcError::Reqwest(e));
                }
            }
        }

        Err(RpcError::Reqwest(last_err.unwrap()))
    }

    /// Check the health of the Soroban RPC node.
    pub async fn get_health(&self) -> Result<HealthCheck, RpcError> {
        self.request("getHealth", ()).await
    }

    /// Get the latest ledger info from the Soroban RPC node.
    pub async fn get_ledger(&self) -> Result<LedgerInfo, RpcError> {
        self.request("getLatestLedger", ()).await
    }

    /// Get network identity and protocol information from the RPC endpoint.
    pub async fn get_network(&self) -> Result<NetworkInfo, RpcError> {
        self.request("getNetwork", ()).await
    }

    /// Get contract storage entries.
    pub async fn get_contract_storage(
        &self,
        _contract_id: &str,
        keys: &[String],
    ) -> Result<StorageResponse, RpcError> {
        self.request("getLedgerEntries", serde_json::json!({ "keys": keys }))
            .await
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FundResult {
    pub address: String,
    pub status: String,
}

/// Funds an account via the Stellar Testnet Friendbot.
///
/// Friendbot is a Testnet-only faucet. It is NOT available on Mainnet.
/// The caller must supply a network profile that explicitly carries a
/// `friendbot_url`. This function performs a single HTTP GET to the
/// Friendbot endpoint with the account address as a query parameter.
pub async fn fund_account(friendbot_url: &str, address: &str) -> Result<FundResult, RpcError> {
    if friendbot_url.trim().is_empty() {
        return Err(RpcError::Rpc("Friendbot URL is empty".into()));
    }
    if address.trim().is_empty() {
        return Err(RpcError::Rpc("Address is empty".into()));
    }

    let url = format!("{}?addr={}", friendbot_url.trim(), address);

    let response = reqwest::Client::new()
        .get(&url)
        .timeout(std::time::Duration::from_secs(30))
        .send()
        .await
        .map_err(|e| {
            if e.is_timeout() {
                RpcError::Rpc(format!("Friendbot request timed out: {e}"))
            } else {
                RpcError::Reqwest(e)
            }
        })?;

    let status = response.status();
    let body = response.text().await.map_err(RpcError::Reqwest)?;

    if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
        return Err(RpcError::Rpc(
            "Friendbot rate limit exceeded. Wait and try again.".into(),
        ));
    }

    if !status.is_success() {
        return Err(RpcError::Rpc(format!(
            "Friendbot returned HTTP {}: {}",
            status.as_u16(),
            body.chars().take(200).collect::<String>()
        )));
    }

    if body.contains("insufficient funds for rent exemption")
        || body.contains("account is already funded")
    {
        return Err(RpcError::Rpc(format!(
            "Friendbot refused: {}",
            body.chars().take(200).collect::<String>()
        )));
    }

    if body.contains("ERROR") || body.contains("error") {
        return Err(RpcError::Rpc(format!(
            "Friendbot error: {}",
            body.chars().take(200).collect::<String>()
        )));
    }

    Ok(FundResult {
        address: address.to_string(),
        status: "funded".into(),
    })
}

#[derive(Debug, Deserialize)]
struct JsonRpcResponse<T> {
    result: Option<T>,
    error: Option<JsonRpcError>,
}

#[derive(Debug, Deserialize)]
struct JsonRpcError {
    message: String,
}

/// Health check response from the node.
#[derive(Debug, Deserialize, PartialEq)]
pub struct HealthCheck {
    pub status: String,
}

/// Ledger info snapshot.
#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LedgerInfo {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub protocol_version: u32,
    pub sequence: u32,
}

/// Network identity and protocol details reported by `getNetwork`.
///
/// `latest_ledger` is optional because the SDF endpoints (testnet, futurenet,
/// mainnet) answer `getNetwork` with only `passphrase`, `protocolVersion` and
/// `friendbotUrl`; a required field there made every `getNetwork` decode fail
/// on those endpoints and the error was swallowed by callers that treated the
/// probe as best-effort.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NetworkInfo {
    #[serde(default)]
    pub friendbot_url: Option<String>,
    pub passphrase: String,
    pub protocol_version: u32,
    #[serde(default)]
    pub latest_ledger: Option<u32>,
}

/// Storage response payload.
#[derive(Debug, Deserialize, PartialEq)]
pub struct StorageResponse {
    pub entries: Vec<LedgerEntryResult>,
    #[serde(rename = "latestLedger")]
    pub latest_ledger: u32,
}

#[derive(Debug, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LedgerEntryResult {
    pub key: String,
    pub xdr: String,
    pub last_modified_ledger_seq: u32,
    pub live_until_ledger_seq: Option<u32>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use sdkt_core::NetworkConfig;

    #[test]
    fn new_sets_endpoint() {
        let c = SorobanRpcClient::new("http://localhost:8000");
        assert_eq!(c.endpoint(), "http://localhost:8000");
    }

    #[test]
    fn from_config_sets_endpoint() {
        let cfg = NetworkConfig {
            rpc_url: "https://custom.example.com".to_string(),
            passphrase: "test".to_string(),
            timeout_secs: None,
            pool_max_idle_per_host: None,
        };
        let c = SorobanRpcClient::from_config(&cfg);
        assert_eq!(c.endpoint(), "https://custom.example.com");
    }

    #[test]
    fn network_info_deserializes_rpc_camel_case_fields() {
        let info: NetworkInfo = serde_json::from_value(serde_json::json!({
            "friendbotUrl": "https://friendbot.example",
            "passphrase": "Test Network",
            "protocolVersion": 22,
            "latestLedger": 1234
        }))
        .unwrap();

        assert_eq!(
            info.friendbot_url.as_deref(),
            Some("https://friendbot.example")
        );
        assert_eq!(info.passphrase, "Test Network");
        assert_eq!(info.protocol_version, 22);
        assert_eq!(info.latest_ledger, Some(1234));
    }

    /// The live SDF endpoints answer `getNetwork` without `latestLedger`; a
    /// required field there made the decode fail on every real endpoint.
    #[test]
    fn network_info_deserializes_without_latest_ledger() {
        let info: NetworkInfo = serde_json::from_value(serde_json::json!({
            "friendbotUrl": "https://friendbot.stellar.org/",
            "passphrase": "Test SDF Network ; September 2015",
            "protocolVersion": 29
        }))
        .unwrap();
        assert_eq!(info.protocol_version, 29);
        assert_eq!(info.latest_ledger, None);
    }

    #[test]
    fn get_ledger_entries_request_uses_keys_object() {
        let keys = vec!["AAAA".to_string()];
        let body = serde_json::json!({ "keys": keys });
        assert_eq!(body, serde_json::json!({ "keys": ["AAAA".to_string()] }));
        assert_ne!(body, serde_json::json!(["AAAA".to_string()]));
    }

    #[tokio::test]
    async fn request_decodes_gzip_response_body() {
        // Removed: this test requires reqwest gzip feature which was disabled
        // to fix real Testnet E2E compatibility. This is a known trade-off.
    }

    #[tokio::test]
    async fn request_does_not_send_gzip_encoding_header() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let (tx, rx) = tokio::sync::oneshot::channel::<String>();

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 8192];
            let n = sock.read(&mut buf).await.unwrap();
            let request = String::from_utf8_lossy(&buf[..n]).to_string();

            let response = r#"{"jsonrpc":"2.0","id":1,"result":{"status":"ok"}}"#;
            let header = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                response.len(),
                response
            );
            sock.write_all(header.as_bytes()).await.unwrap();

            let _ = tx.send(request);
        });

        let client = SorobanRpcClient::new(&format!("http://{}", addr));
        let _res: HealthCheck = client.request("getHealth", ()).await.unwrap();

        let request = rx.await.unwrap();
        assert!(
            !request.contains("Accept-Encoding: gzip"),
            "Request should NOT contain Accept-Encoding: gzip, got:\n{}",
            request
        );
        assert!(
            !request.contains("Accept-Encoding: deflate"),
            "Request should NOT contain Accept-Encoding: deflate, got:\n{}",
            request
        );

        server.await.unwrap();
    }

    #[tokio::test]
    async fn fund_account_success() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 8192];
            let n = sock.read(&mut buf).await.unwrap();
            let request = String::from_utf8_lossy(&buf[..n]).to_string();

            assert!(
                request.contains("addr=GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF")
            );

            let response = r#"{"hash":"abc123","ledger":12345}"#;
            let header = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                response.len(),
                response
            );
            sock.write_all(header.as_bytes()).await.unwrap();
        });

        let result = fund_account(
            &format!("http://{}", addr),
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
        )
        .await
        .unwrap();

        assert_eq!(
            result.address,
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF"
        );
        assert_eq!(result.status, "funded");

        server.await.unwrap();
    }

    #[tokio::test]
    async fn fund_account_http_500() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 8192];
            let _n = sock.read(&mut buf).await.unwrap();

            let response = r#"{"error":"internal"}"#;
            let header = format!(
                "HTTP/1.1 500 Internal Server Error\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                response.len(),
                response
            );
            sock.write_all(header.as_bytes()).await.unwrap();
        });

        let err = fund_account(
            &format!("http://{}", addr),
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
        )
        .await
        .unwrap_err();

        assert!(err.to_string().contains("500"));

        server.await.unwrap();
    }

    #[tokio::test]
    async fn fund_account_rate_limit() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 8192];
            let _n = sock.read(&mut buf).await.unwrap();

            let response = r#"{"error":"rate limited"}"#;
            let header = format!(
                "HTTP/1.1 429 Too Many Requests\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                response.len(),
                response
            );
            sock.write_all(header.as_bytes()).await.unwrap();
        });

        let err = fund_account(
            &format!("http://{}", addr),
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
        )
        .await
        .unwrap_err();

        assert!(err.to_string().contains("rate limit"));

        server.await.unwrap();
    }

    #[tokio::test]
    async fn fund_account_empty_url_rejected() {
        let err = fund_account(
            "",
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("empty"));
    }

    #[tokio::test]
    async fn fund_account_empty_address_rejected() {
        let err = fund_account("http://localhost", "").await.unwrap_err();
        assert!(err.to_string().contains("empty"));
    }

    #[tokio::test]
    async fn fund_account_malformed_response() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 8192];
            let _n = sock.read(&mut buf).await.unwrap();

            // Return 200 OK but with body containing "ERROR"
            let response = r#"{"status":"ERROR","message":"internal failure"}"#;
            let header = format!(
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                response.len(),
                response
            );
            sock.write_all(header.as_bytes()).await.unwrap();
        });

        let err = fund_account(
            &format!("http://{}", addr),
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
        )
        .await
        .unwrap_err();

        // Should be rejected because body contains "error"
        assert!(err.to_string().contains("error") || err.to_string().contains("Error"));

        server.await.unwrap();
    }

    #[tokio::test]
    async fn fund_account_http_4xx() {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 8192];
            let _n = sock.read(&mut buf).await.unwrap();

            let response = r#"{"error":"bad request"}"#;
            let header = format!(
                "HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                response.len(),
                response
            );
            sock.write_all(header.as_bytes()).await.unwrap();
        });

        let err = fund_account(
            &format!("http://{}", addr),
            "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
        )
        .await
        .unwrap_err();

        assert!(err.to_string().contains("400"));

        server.await.unwrap();
    }
}