From ca2ec0aaddbb8f07980a94c7294ef12f83ea79b2 Mon Sep 17 00:00:00 2001 From: James Prestwich <10149425+prestwich@users.noreply.github.com> Date: Tue, 18 Aug 2020 07:12:47 -0700 Subject: [PATCH] bug #55: prevent request from serializing ZSTs as null (#57) * bug #55: prevent request from serializing ZSTs as null * chore: cargo fmt Co-authored-by: Georgios Konstantopoulos --- ethers-providers/src/transports/common.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/ethers-providers/src/transports/common.rs b/ethers-providers/src/transports/common.rs index d65b7d65..e99dbbbf 100644 --- a/ethers-providers/src/transports/common.rs +++ b/ethers-providers/src/transports/common.rs @@ -25,12 +25,17 @@ impl fmt::Display for JsonRpcError { } } +fn is_zst(_t: &T) -> bool { + std::mem::size_of::() == 0 +} + #[derive(Serialize, Deserialize, Debug)] /// A JSON-RPC request pub struct Request<'a, T> { id: u64, jsonrpc: &'a str, method: &'a str, + #[serde(skip_serializing_if = "is_zst")] params: T, } @@ -76,10 +81,25 @@ mod tests { use super::*; #[test] - fn response() { + fn deser_response() { let response: Response = 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); } + + #[test] + fn ser_request() { + let request: Request<()> = Request::new(300, "method_name", ()); + assert_eq!( + &serde_json::to_string(&request).unwrap(), + r#"{"id":300,"jsonrpc":"2.0","method":"method_name"}"# + ); + + let request: Request = Request::new(300, "method_name", 1); + assert_eq!( + &serde_json::to_string(&request).unwrap(), + r#"{"id":300,"jsonrpc":"2.0","method":"method_name","params":1}"# + ); + } }