use crate::{errors::ProviderError, JsonRpcClient};
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;
#[derive(Debug, Clone)]
pub struct RwClient<Read, Write> {
r: Read,
w: Write,
}
impl<Read, Write> RwClient<Read, Write> {
pub fn new(r: Read, w: Write) -> RwClient<Read, Write> {
Self { r, w }
}
pub fn read_client(&self) -> &Read {
&self.r
}
pub fn write_client(&self) -> &Write {
&self.w
}
pub fn transpose(self) -> RwClient<Write, Read> {
let RwClient { r, w } = self;
RwClient::new(w, r)
}
pub fn split(self) -> (Read, Write) {
let RwClient { r, w } = self;
(r, w)
}
}
#[derive(Error, Debug)]
pub enum RwClientError<Read, Write>
where
Read: JsonRpcClient,
<Read as JsonRpcClient>::Error: crate::RpcError + Sync + Send + 'static,
Write: JsonRpcClient,
<Write as JsonRpcClient>::Error: crate::RpcError + Sync + Send + 'static,
{
#[error(transparent)]
Read(Read::Error),
#[error(transparent)]
Write(Write::Error),
}
impl<Read, Write> crate::RpcError for RwClientError<Read, Write>
where
Read: JsonRpcClient,
<Read as JsonRpcClient>::Error: crate::RpcError + Sync + Send + 'static,
Write: JsonRpcClient,
<Write as JsonRpcClient>::Error: crate::RpcError + Sync + Send + 'static,
{
fn as_error_response(&self) -> Option<&super::JsonRpcError> {
match self {
RwClientError::Read(e) => e.as_error_response(),
RwClientError::Write(e) => e.as_error_response(),
}
}
fn as_serde_error(&self) -> Option<&serde_json::Error> {
match self {
RwClientError::Read(e) => e.as_serde_error(),
RwClientError::Write(e) => e.as_serde_error(),
}
}
}
impl<Read, Write> From<RwClientError<Read, Write>> for ProviderError
where
Read: JsonRpcClient + 'static,
<Read as JsonRpcClient>::Error: Sync + Send + 'static,
Write: JsonRpcClient + 'static,
<Write as JsonRpcClient>::Error: Sync + Send + 'static,
{
fn from(src: RwClientError<Read, Write>) -> Self {
ProviderError::JsonRpcClientError(Box::new(src))
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl<Read, Write> JsonRpcClient for RwClient<Read, Write>
where
Read: JsonRpcClient + 'static,
<Read as JsonRpcClient>::Error: Sync + Send + 'static,
Write: JsonRpcClient + 'static,
<Write as JsonRpcClient>::Error: Sync + Send + 'static,
{
type Error = RwClientError<Read, Write>;
async fn request<T, R>(&self, method: &str, params: T) -> Result<R, Self::Error>
where
T: std::fmt::Debug + Serialize + Send + Sync,
R: DeserializeOwned + Send,
{
match method {
"eth_sendTransaction" | "eth_sendRawTransaction" => {
self.w.request(method, params).await.map_err(RwClientError::Write)
}
_ => self.r.request(method, params).await.map_err(RwClientError::Read),
}
}
}