Skip to main content

simulator_client/
rpc.rs

1//! Calls to the session's RPC endpoint that `solana_client` does not cover.
2//!
3//! For standard Solana RPC methods, use the `RpcClient` from
4//! [`ManagedBacktestSession::rpc`](crate::ManagedBacktestSession::rpc).
5
6use simulator_api::AccountModifications;
7
8use crate::{BacktestClientError, BacktestClientResult, endpoint::without_query};
9
10/// Modify accounts on a session RPC endpoint via the custom `modifyAccounts` JSON-RPC method.
11///
12/// Returns the number of accounts modified on success.
13///
14/// # Errors
15///
16/// - [`BacktestClientError::HttpStatus`] when the endpoint answers with a non-2xx status.
17/// - [`BacktestClientError::Http`] when the request fails, the body does not decode, or the
18///   server returns a JSON-RPC error.
19pub async fn modify_accounts(
20    rpc_url: &str,
21    modifications: &AccountModifications,
22) -> BacktestClientResult<usize> {
23    let count = modifications.0.len();
24    let body = serde_json::json!({
25        "jsonrpc": "2.0",
26        "id": 1,
27        "method": "modifyAccounts",
28        "params": [modifications],
29    });
30
31    let url = without_query(rpc_url);
32    let resp = reqwest::Client::new()
33        .post(rpc_url)
34        .json(&body)
35        .send()
36        .await
37        .map_err(|e| BacktestClientError::Http {
38            url: url.to_string(),
39            source: Box::new(e.without_url()),
40        })?;
41    let status = resp.status();
42    if !status.is_success() {
43        return Err(BacktestClientError::HttpStatus {
44            url: url.to_string(),
45            status,
46            body: resp.text().await.unwrap_or_default(),
47        });
48    }
49    let resp: serde_json::Value = resp.json().await.map_err(|e| BacktestClientError::Http {
50        url: url.to_string(),
51        source: Box::new(e.without_url()),
52    })?;
53
54    if let Some(error) = resp.get("error") {
55        return Err(BacktestClientError::Http {
56            url: url.to_string(),
57            source: format!("modifyAccounts RPC error: {error}").into(),
58        });
59    }
60
61    Ok(count)
62}