use std::{
collections::{HashMap, HashSet},
marker::PhantomData,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use reqwest::{Client, header::HeaderMap};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use url::Url;
use crate::{
ErpcError, JsonRpcErrorObject, Result,
error::{invalid_response, rpc_error, timeout},
};
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[serde(untagged)]
pub enum JsonRpcId {
Number(u64),
String(String),
}
#[derive(Clone, Debug, Serialize)]
pub struct RpcBatchCall {
pub method: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
impl RpcBatchCall {
pub fn new(method: impl Into<String>, params: impl Serialize) -> Result<Self> {
Ok(Self {
method: method.into(),
params: Some(serde_json::to_value(params).map_err(|_| {
ErpcError::Config("RPC parameters could not be serialized".to_owned())
})?),
})
}
#[must_use]
pub fn without_params(method: impl Into<String>) -> Self {
Self {
method: method.into(),
params: None,
}
}
}
#[derive(Clone, Debug, Default)]
pub struct RequestOptions {
pub cancellation: Option<CancellationToken>,
}
#[derive(Clone)]
pub struct HttpTransportConfig {
pub api_key: String,
pub endpoint: Url,
pub headers: HeaderMap,
pub max_batch_size: usize,
pub timeout: Duration,
pub client: Client,
}
pub struct HttpJsonRpcTransport {
api_key: String,
endpoint: Url,
headers: HeaderMap,
max_batch_size: usize,
timeout: Duration,
client: Client,
next_id: AtomicU64,
}
impl HttpJsonRpcTransport {
#[must_use]
pub fn new(config: HttpTransportConfig) -> Self {
let mut endpoint = config.endpoint;
endpoint.set_query(None);
endpoint.set_fragment(None);
Self {
api_key: config.api_key,
endpoint,
headers: config.headers,
max_batch_size: config.max_batch_size,
timeout: config.timeout,
client: config.client,
next_id: AtomicU64::new(1),
}
}
#[must_use]
pub fn endpoint(&self) -> String {
self.endpoint.to_string()
}
#[must_use]
pub const fn max_batch_size(&self) -> usize {
self.max_batch_size
}
pub async fn request<T: DeserializeOwned>(
&self,
method: &str,
params: Option<Value>,
options: &RequestOptions,
) -> Result<T> {
let id = self.id();
let request = WireRequest {
jsonrpc: "2.0",
id: id.clone(),
method,
params,
};
let response = self.post(&request, options).await?;
self.unwrap(&response, &id)
}
pub async fn batch(
&self,
calls: &[RpcBatchCall],
options: &RequestOptions,
) -> Result<Vec<Value>> {
if calls.is_empty() {
return Ok(Vec::new());
}
if calls.len() > self.max_batch_size {
return Err(invalid_response(format!(
"A batch may contain at most {} calls",
self.max_batch_size
)));
}
let requests: Vec<_> = calls
.iter()
.map(|call| WireRequest {
jsonrpc: "2.0",
id: self.id(),
method: call.method.as_str(),
params: call.params.clone(),
})
.collect();
let response = self.post(&requests, options).await?;
let Value::Array(responses) = response else {
if let Ok(failure) = serde_json::from_value::<WireFailure>(response) {
return Err(rpc_error(failure.error, &self.api_key));
}
return Err(invalid_response("ERPC returned a non-array batch response"));
};
let mut by_id = HashMap::new();
for response in responses {
let id = response
.get("id")
.cloned()
.ok_or_else(|| invalid_response("ERPC returned an invalid batch item"))?;
let id: JsonRpcId = serde_json::from_value(id)
.map_err(|_| invalid_response("ERPC returned an invalid batch id"))?;
if by_id.insert(id, response).is_some() {
return Err(invalid_response("ERPC returned a duplicate batch id"));
}
}
let results = requests
.iter()
.map(|request| {
let response = by_id.remove(&request.id).ok_or_else(|| {
invalid_response(format!("ERPC omitted batch response id {}", request.id))
})?;
self.unwrap(&response, &request.id)
})
.collect::<Result<Vec<_>>>()?;
if !by_id.is_empty() {
return Err(invalid_response(
"ERPC returned an unexpected batch response id",
));
}
Ok(results)
}
fn id(&self) -> JsonRpcId {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
if id == u64::MAX {
self.next_id.store(1, Ordering::Relaxed);
}
JsonRpcId::Number(id)
}
async fn post(&self, body: &impl Serialize, options: &RequestOptions) -> Result<Value> {
let mut url = self.endpoint.clone();
url.query_pairs_mut().append_pair("api-key", &self.api_key);
let operation = async {
let response = self
.client
.post(url)
.headers(self.headers.clone())
.json(body)
.send()
.await
.map_err(|_| ErpcError::Transport("Unable to reach ERPC".to_owned()))?;
if !response.status().is_success() {
return Err(ErpcError::Http {
status: response.status().as_u16(),
});
}
let text = response
.text()
.await
.map_err(|_| ErpcError::Transport("Unable to read ERPC response".to_owned()))?;
serde_json::from_str(&text)
.map_err(|_| invalid_response("ERPC returned malformed JSON"))
};
let timed = tokio::time::timeout(self.timeout, operation);
let result = if let Some(cancellation) = &options.cancellation {
tokio::select! {
biased;
() = cancellation.cancelled() => return Err(ErpcError::Aborted),
result = timed => result,
}
} else {
timed.await
};
result.map_err(|_| timeout(self.timeout))?
}
fn unwrap<T: DeserializeOwned>(&self, response: &Value, expected: &JsonRpcId) -> Result<T> {
let object = response
.as_object()
.ok_or_else(|| invalid_response("ERPC returned an invalid response"))?;
let id: JsonRpcId = serde_json::from_value(
object
.get("id")
.cloned()
.ok_or_else(|| invalid_response("ERPC returned an invalid response"))?,
)
.map_err(|_| invalid_response("ERPC returned an invalid response id"))?;
if &id != expected {
return Err(invalid_response("ERPC returned an unexpected response id"));
}
if let Some(error) = object.get("error") {
let error: JsonRpcErrorObject = serde_json::from_value(error.clone())
.map_err(|_| invalid_response("ERPC returned an invalid RPC error"))?;
return Err(rpc_error(error, &self.api_key));
}
let result = object
.get("result")
.cloned()
.ok_or_else(|| invalid_response("ERPC returned an invalid response"))?;
serde_json::from_value(result)
.map_err(|_| invalid_response("ERPC returned an unexpected result shape"))
}
}
impl std::fmt::Display for JsonRpcId {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Number(id) => id.fmt(formatter),
Self::String(id) => id.fmt(formatter),
}
}
}
#[derive(Serialize)]
struct WireRequest<'a> {
jsonrpc: &'static str,
id: JsonRpcId,
method: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
params: Option<Value>,
}
#[derive(Deserialize)]
struct WireFailure {
error: JsonRpcErrorObject,
}
pub struct PendingRpcRequest<T> {
transport: Arc<HttpJsonRpcTransport>,
method: String,
params: Option<Value>,
marker: PhantomData<fn() -> T>,
}
impl<T: DeserializeOwned> PendingRpcRequest<T> {
pub async fn send(self) -> Result<T> {
self.send_with(RequestOptions::default()).await
}
pub async fn send_with(self, options: RequestOptions) -> Result<T> {
self.transport
.request(&self.method, self.params, &options)
.await
}
}
pub struct PendingRpcBatchRequest {
transport: Arc<HttpJsonRpcTransport>,
calls: Vec<RpcBatchCall>,
}
impl PendingRpcBatchRequest {
pub async fn send(self) -> Result<Vec<Value>> {
self.send_with(RequestOptions::default()).await
}
pub async fn send_with(self, options: RequestOptions) -> Result<Vec<Value>> {
self.transport.batch(&self.calls, &options).await
}
}
#[derive(Clone, Copy)]
pub(crate) enum BatchPolicy {
Any,
SolanaStandard,
Unsupported,
}
#[derive(Clone)]
pub struct RpcNamespace {
transport: Arc<HttpJsonRpcTransport>,
policy: BatchPolicy,
}
impl RpcNamespace {
pub(crate) const fn new(transport: Arc<HttpJsonRpcTransport>, policy: BatchPolicy) -> Self {
Self { transport, policy }
}
#[must_use]
pub fn endpoint(&self) -> String {
self.transport.endpoint()
}
pub fn request<T: DeserializeOwned>(
&self,
method: impl Into<String>,
params: impl Serialize,
) -> Result<PendingRpcRequest<T>> {
Ok(PendingRpcRequest {
transport: Arc::clone(&self.transport),
method: method.into(),
params: Some(serde_json::to_value(params).map_err(|_| {
ErpcError::Config("RPC parameters could not be serialized".to_owned())
})?),
marker: PhantomData,
})
}
#[must_use]
pub fn request_without_params<T: DeserializeOwned>(
&self,
method: impl Into<String>,
) -> PendingRpcRequest<T> {
PendingRpcRequest {
transport: Arc::clone(&self.transport),
method: method.into(),
params: None,
marker: PhantomData,
}
}
pub fn raw<T: DeserializeOwned>(
&self,
method: impl Into<String>,
params: Option<Value>,
) -> PendingRpcRequest<T> {
PendingRpcRequest {
transport: Arc::clone(&self.transport),
method: method.into(),
params,
marker: PhantomData,
}
}
pub fn batch(&self, calls: Vec<RpcBatchCall>) -> Result<PendingRpcBatchRequest> {
if matches!(self.policy, BatchPolicy::Unsupported) {
if !calls.is_empty() {
return Err(ErpcError::BatchPolicy(
"Leader RPC methods do not support batching".to_owned(),
));
}
} else if matches!(self.policy, BatchPolicy::SolanaStandard) {
validate_solana_standard_batch(&calls)?;
}
Ok(PendingRpcBatchRequest {
transport: Arc::clone(&self.transport),
calls,
})
}
}
fn validate_solana_standard_batch(calls: &[RpcBatchCall]) -> Result<()> {
let heavy: HashSet<&str> = [
"getPriorityFeeEstimate",
"getProgramAccounts",
"getProgramAccountsV2",
"getTokenLargestAccounts",
]
.into_iter()
.collect();
let contains_heavy = calls
.iter()
.any(|call| heavy.contains(call.method.as_str()));
let contains_standard = calls
.iter()
.any(|call| !heavy.contains(call.method.as_str()));
if contains_heavy && contains_standard {
return Err(ErpcError::BatchPolicy(
"Solana indexed and standard RPC methods cannot share a batch".to_owned(),
));
}
Ok(())
}