1use crate::http::HTTPBody;
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4
5#[cfg(feature = "jsonrpc")]
6#[derive(Debug, Serialize, Deserialize)]
7pub struct JsonRpcRequest {
8 pub jsonrpc: &'static str,
9 pub id: JsonRpcId,
10 pub method: &'static str,
11 pub params: Vec<Value>,
12}
13
14#[cfg(feature = "jsonrpc")]
15impl JsonRpcRequest {
16 pub fn new(method: &'static str, params: Vec<Value>, id: u64) -> Self {
17 Self {
18 jsonrpc: "2.0",
19 id: JsonRpcId::Integer(id),
20 method,
21 params,
22 }
23 }
24}
25
26#[cfg(feature = "jsonrpc")]
27impl From<JsonRpcRequest> for reqwest::Body {
28 fn from(val: JsonRpcRequest) -> Self {
29 serde_json::to_vec(&val).unwrap().into()
30 }
31}
32
33#[cfg(feature = "jsonrpc")]
34impl From<JsonRpcRequest> for HTTPBody {
35 fn from(val: JsonRpcRequest) -> Self {
36 HTTPBody::from(&val)
37 }
38}
39
40#[cfg(feature = "jsonrpc")]
41#[derive(Debug, Serialize, Deserialize)]
42pub struct JsonRpcResponse<T> {
43 pub id: JsonRpcId,
44 pub jsonrpc: String,
45 pub result: T,
46}
47
48#[cfg(feature = "jsonrpc")]
49#[derive(Debug, Serialize, Deserialize)]
50pub struct JsonRpcErrorResponse {
51 pub jsonrpc: String,
52 pub id: JsonRpcId,
53 pub error: JsonRpcError,
54}
55
56#[cfg(feature = "jsonrpc")]
57#[derive(Debug, Serialize, Deserialize)]
58pub struct JsonRpcError {
59 pub code: i64,
60 pub message: String,
61}
62
63#[cfg(feature = "jsonrpc")]
64impl std::error::Error for JsonRpcError {}
65
66#[cfg(feature = "jsonrpc")]
67impl From<reqwest::Error> for JsonRpcError {
68 fn from(err: reqwest::Error) -> Self {
69 JsonRpcError {
70 code: -32603,
71 message: format!("Internal error ({})", err),
72 }
73 }
74}
75
76#[cfg(feature = "jsonrpc")]
77impl std::fmt::Display for JsonRpcError {
78 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79 write!(f, "{} ({})", self.message, self.code)
80 }
81}
82
83#[cfg(feature = "jsonrpc")]
84#[derive(Debug, Serialize, Deserialize)]
85#[serde(untagged)]
86pub enum JsonRpcResult<T> {
87 Value(JsonRpcResponse<T>),
88 Error(JsonRpcErrorResponse),
89}
90
91#[cfg(feature = "jsonrpc")]
92#[derive(Debug, Serialize, Deserialize)]
93#[serde(untagged)]
94pub enum JsonRpcId {
95 Integer(u64),
96 String(String),
97}