use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::error::SdkError;
pub const JSONRPC_VERSION: &str = "2.0";
#[derive(Debug, Clone, Serialize)]
pub struct JsonRpcRequest<'a> {
pub jsonrpc: &'static str,
pub method: &'a str,
pub params: Value,
pub id: u64,
}
impl<'a> JsonRpcRequest<'a> {
#[must_use]
pub fn new(id: u64, method: &'a str, params: Value) -> Self {
Self {
jsonrpc: JSONRPC_VERSION,
method,
params,
id,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct JsonRpcResponse {
#[serde(default)]
pub jsonrpc: Option<String>,
#[serde(default)]
pub id: Option<Value>,
#[serde(default)]
pub result: Option<Value>,
#[serde(default)]
pub error: Option<JsonRpcError>,
}
impl JsonRpcResponse {
pub fn into_result(self) -> Result<Value, SdkError> {
if let Some(err) = self.error {
return Err(err.into_sdk_error());
}
Ok(self.result.unwrap_or(Value::Null))
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct JsonRpcError {
pub code: i64,
pub message: String,
#[serde(default)]
pub data: Option<Value>,
}
impl JsonRpcError {
#[must_use]
pub fn into_sdk_error(self) -> SdkError {
match self.code {
-32602 => SdkError::InvalidArgument(self.message),
_ => SdkError::Rpc(format!("[{}] {}", self.code, self.message)),
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct JsonRpcNotification {
pub jsonrpc: String,
pub method: String,
pub params: Value,
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use serde_json::json;
#[test]
fn request_serialises_canonical_shape() {
let req = JsonRpcRequest::new(7, "pyde_chainId", json!([]));
let s = serde_json::to_string(&req).unwrap();
let v: Value = serde_json::from_str(&s).unwrap();
assert_eq!(v["jsonrpc"], "2.0");
assert_eq!(v["method"], "pyde_chainId");
assert_eq!(v["id"], 7);
assert_eq!(v["params"], json!([]));
}
#[test]
fn response_into_result_unwraps_success() {
let resp: JsonRpcResponse =
serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"result":"0x1"}"#).unwrap();
let v = resp.into_result().unwrap();
assert_eq!(v, json!("0x1"));
}
#[test]
fn response_into_result_surfaces_error() {
let resp: JsonRpcResponse = serde_json::from_str(
r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"bad params"}}"#,
)
.unwrap();
let err = resp.into_result().unwrap_err();
assert!(matches!(err, SdkError::InvalidArgument(_)));
}
#[test]
fn response_into_result_null_when_no_result_or_error() {
let resp: JsonRpcResponse = serde_json::from_str(r#"{"jsonrpc":"2.0","id":1}"#).unwrap();
let v = resp.into_result().unwrap();
assert!(v.is_null());
}
#[test]
fn response_into_result_null_for_explicit_null_result() {
let resp: JsonRpcResponse =
serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"result":null}"#).unwrap();
let v = resp.into_result().unwrap();
assert!(v.is_null());
}
}