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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use crate::{provider::ProviderError, JsonRpcClient};
use async_trait::async_trait;
use reqwest::{Client, Error as ReqwestError};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
fmt,
str::FromStr,
sync::atomic::{AtomicU64, Ordering},
};
use thiserror::Error;
use url::Url;
#[derive(Debug)]
pub struct Provider {
id: AtomicU64,
client: Client,
url: Url,
}
#[derive(Error, Debug)]
pub enum ClientError {
#[error(transparent)]
ReqwestError(#[from] ReqwestError),
#[error(transparent)]
JsonRpcError(#[from] errors::JsonRpcError),
}
impl From<ClientError> for ProviderError {
fn from(src: ClientError) -> Self {
ProviderError::JsonRpcClientError(Box::new(src))
}
}
#[async_trait]
impl JsonRpcClient for Provider {
type Error = ClientError;
async fn request<T: Serialize + Send + Sync, R: for<'a> Deserialize<'a>>(
&self,
method: &str,
params: T,
) -> Result<R, ClientError> {
let next_id = self.id.load(Ordering::SeqCst) + 1;
self.id.store(next_id, Ordering::SeqCst);
let payload = Request::new(next_id, method, params);
let res = self
.client
.post(self.url.as_ref())
.json(&payload)
.send()
.await?;
let res = res.json::<Response<R>>().await?;
Ok(res.data.into_result()?)
}
}
impl Provider {
pub fn new(url: impl Into<Url>) -> Self {
Self {
id: AtomicU64::new(0),
client: Client::new(),
url: url.into(),
}
}
}
impl FromStr for Provider {
type Err = url::ParseError;
fn from_str(src: &str) -> Result<Self, Self::Err> {
let url = Url::parse(src)?;
Ok(Provider::new(url))
}
}
impl Clone for Provider {
fn clone(&self) -> Self {
Self {
id: AtomicU64::new(0),
client: self.client.clone(),
url: self.url.clone(),
}
}
}
mod errors {
use super::*;
#[derive(Serialize, Deserialize, Debug, Clone, Error)]
pub struct JsonRpcError {
pub code: i64,
pub message: String,
pub data: Option<Value>,
}
impl fmt::Display for JsonRpcError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"(code: {}, message: {}, data: {:?})",
self.code, self.message, self.data
)
}
}
}
#[derive(Serialize, Deserialize, Debug)]
struct Request<'a, T> {
id: u64,
jsonrpc: &'a str,
method: &'a str,
params: T,
}
impl<'a, T> Request<'a, T> {
fn new(id: u64, method: &'a str, params: T) -> Self {
Self {
id,
jsonrpc: "2.0",
method,
params,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
struct Response<T> {
id: u64,
jsonrpc: String,
#[serde(flatten)]
data: ResponseData<T>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
enum ResponseData<R> {
Error { error: errors::JsonRpcError },
Success { result: R },
}
impl<R> ResponseData<R> {
fn into_result(self) -> Result<R, errors::JsonRpcError> {
match self {
ResponseData::Success { result } => Ok(result),
ResponseData::Error { error } => Err(error),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn response() {
let response: Response<u64> =
serde_json::from_str(r#"{"jsonrpc": "2.0", "result": 19, "id": 1}"#).unwrap();
assert_eq!(response.id, 1);
assert_eq!(response.data.into_result().unwrap(), 19);
}
}