simulator-client 0.31.0

Async WebSocket client for the Solana simulator backtest API
Documentation
//! Calls to the session's RPC endpoint that `solana_client` does not cover.
//!
//! For standard Solana RPC methods, use the `RpcClient` from
//! [`ManagedBacktestSession::rpc`](crate::ManagedBacktestSession::rpc).

use std::time::Duration;

use simulator_api::AccountModifications;

use crate::{BacktestClientError, BacktestClientResult, endpoint::without_query};

const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const READ_TIMEOUT: Duration = Duration::from_secs(60);

/// Modify accounts on a session RPC endpoint via the custom `modifyAccounts` JSON-RPC method.
///
/// Returns the number of accounts modified on success.
///
/// # Errors
///
/// - [`BacktestClientError::HttpStatus`] when the endpoint answers with a non-2xx status.
/// - [`BacktestClientError::Http`] when the request fails, the body does not decode, or the
///   server returns a JSON-RPC error.
pub async fn modify_accounts(
    rpc_url: &str,
    modifications: &AccountModifications,
) -> BacktestClientResult<usize> {
    let count = modifications.0.len();
    let body = serde_json::json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "modifyAccounts",
        "params": [modifications],
    });

    let url = without_query(rpc_url);
    let http_error = |e: reqwest::Error| BacktestClientError::Http {
        url: url.to_string(),
        source: Box::new(e.without_url()),
    };
    let resp = reqwest::Client::builder()
        .connect_timeout(CONNECT_TIMEOUT)
        .read_timeout(READ_TIMEOUT)
        .build()
        .map_err(http_error)?
        .post(rpc_url)
        .json(&body)
        .send()
        .await
        .map_err(http_error)?;
    let status = resp.status();
    if !status.is_success() {
        return Err(BacktestClientError::HttpStatus {
            url: url.to_string(),
            status,
            body: resp.text().await.unwrap_or_default(),
        });
    }
    let resp: serde_json::Value = resp.json().await.map_err(|e| BacktestClientError::Http {
        url: url.to_string(),
        source: Box::new(e.without_url()),
    })?;

    if let Some(error) = resp.get("error") {
        return Err(BacktestClientError::Http {
            url: url.to_string(),
            source: format!("modifyAccounts RPC error: {error}").into(),
        });
    }

    Ok(count)
}