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
//! A [JsonRpcClient] implementation that serves as a wrapper around two different [JsonRpcClient]
//! and uses a dedicated client for read and the other for write operations

use crate::{errors::ProviderError, JsonRpcClient};
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use thiserror::Error;

/// A client containing two clients.
///
/// One is used for _read_ operations
/// One is used for _write_ operations that consume gas `["eth_sendTransaction",
/// "eth_sendRawTransaction"]`
///
/// **Note**: if the method is unknown this client falls back to the _read_ client
// # Example
#[derive(Debug, Clone)]
pub struct RwClient<Read, Write> {
    /// client used to read
    r: Read,
    /// client used to write
    w: Write,
}

impl<Read, Write> RwClient<Read, Write> {
    /// Creates a new client using two different clients
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use url::Url;
    ///  async fn t(){
    /// use ethers_providers::{Http, RwClient, Ws};
    /// let http = Http::new(Url::parse("http://localhost:8545").unwrap());
    /// let ws = Ws::connect("ws://localhost:8545").await.unwrap();
    /// let rw = RwClient::new(http, ws);
    /// # }
    /// ```
    pub fn new(r: Read, w: Write) -> RwClient<Read, Write> {
        Self { r, w }
    }

    /// Returns the client used for read operations
    pub fn read_client(&self) -> &Read {
        &self.r
    }

    /// Returns the client used for write operations
    pub fn write_client(&self) -> &Write {
        &self.w
    }

    /// Returns a new `RwClient` with transposed clients
    pub fn transpose(self) -> RwClient<Write, Read> {
        let RwClient { r, w } = self;
        RwClient::new(w, r)
    }

    /// Consumes the client and returns the underlying clients
    pub fn split(self) -> (Read, Write) {
        let RwClient { r, w } = self;
        (r, w)
    }
}

#[derive(Error, Debug)]
/// Error thrown when using either read or write client
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,
{
    /// Thrown if the _read_ request failed
    #[error(transparent)]
    Read(Read::Error),
    #[error(transparent)]
    /// Thrown if the _write_ request failed
    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>;

    /// Sends a POST request with the provided method and the params serialized as JSON
    /// over HTTP
    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),
        }
    }
}