Skip to content

Commit 8a9d9f7

Browse files
committed
Improve jsonrpc async client
Add a JSONRPC_VERSION constant to remove magic number in code. Add the same version check to batch responses.
1 parent d1f0181 commit 8a9d9f7

1 file changed

Lines changed: 12 additions & 2 deletions

File tree

jsonrpc/src/client_async.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ use serde_json::Value;
1919
use crate::error::Error;
2020
use crate::{Request, Response};
2121

22+
const JSONRPC_VERSION: &str = "2.0";
23+
2224
/// Boxed future type used by async transports.
2325
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
2426

@@ -55,7 +57,12 @@ impl Client {
5557
/// [`crate::arg`] or [`crate::try_arg`].
5658
pub fn build_request<'a>(&self, method: &'a str, params: Option<&'a RawValue>) -> Request<'a> {
5759
let nonce = self.nonce.fetch_add(1, atomic::Ordering::Relaxed);
58-
Request { method, params, id: serde_json::Value::from(nonce), jsonrpc: Some("2.0") }
60+
Request {
61+
method,
62+
params,
63+
id: serde_json::Value::from(nonce),
64+
jsonrpc: Some(JSONRPC_VERSION),
65+
}
5966
}
6067

6168
/// Sends a request to a client.
@@ -92,6 +99,9 @@ impl Client {
9299
// First index responses by ID and catch duplicate IDs.
93100
let mut by_id = HashMap::with_capacity(requests.len());
94101
for resp in responses.into_iter() {
102+
if resp.jsonrpc.is_some() && resp.jsonrpc.as_deref() != Some(JSONRPC_VERSION) {
103+
return Err(Error::VersionMismatch);
104+
}
95105
let id = HashableValue(Cow::Owned(resp.id.clone()));
96106
if let Some(dup) = by_id.insert(id, resp) {
97107
return Err(Error::BatchDuplicateResponseId(dup.id));
@@ -123,7 +133,7 @@ impl Client {
123133
let id = request.id.clone();
124134

125135
let response = self.send_request(request).await?;
126-
if response.jsonrpc.is_some() && response.jsonrpc != Some(From::from("2.0")) {
136+
if response.jsonrpc.is_some() && response.jsonrpc.as_deref() != Some(JSONRPC_VERSION) {
127137
return Err(Error::VersionMismatch);
128138
}
129139
if response.id != id {

0 commit comments

Comments
 (0)