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
use crate::http::HTTPBody;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonRpcRequest {
    pub jsonrpc: &'static str,
    pub id: JsonRpcId,
    pub method: &'static str,
    pub params: Vec<Value>,
}

#[cfg(feature = "jsonrpc")]
impl JsonRpcRequest {
    pub fn new(method: &'static str, params: Vec<Value>, id: u64) -> Self {
        Self {
            jsonrpc: "2.0",
            id: JsonRpcId::Integer(id),
            method,
            params,
        }
    }
}

#[cfg(feature = "jsonrpc")]
impl From<JsonRpcRequest> for reqwest::Body {
    fn from(val: JsonRpcRequest) -> Self {
        serde_json::to_vec(&val).unwrap().into()
    }
}

#[cfg(feature = "jsonrpc")]
impl From<JsonRpcRequest> for HTTPBody {
    fn from(val: JsonRpcRequest) -> Self {
        HTTPBody::from(&val)
    }
}

#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonRpcResponse<T> {
    pub id: JsonRpcId,
    pub jsonrpc: String,
    pub result: T,
}

#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonRpcErrorResponse {
    pub jsonrpc: String,
    pub id: JsonRpcId,
    pub error: JsonRpcError,
}

#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonRpcError {
    pub code: i64,
    pub message: String,
}

#[cfg(feature = "jsonrpc")]
impl std::error::Error for JsonRpcError {}

#[cfg(feature = "jsonrpc")]
impl From<reqwest::Error> for JsonRpcError {
    fn from(err: reqwest::Error) -> Self {
        JsonRpcError {
            code: -32603,
            message: format!("Internal error ({})", err),
        }
    }
}

#[cfg(feature = "jsonrpc")]
impl std::fmt::Display for JsonRpcError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} ({})", self.message, self.code)
    }
}

#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum JsonRpcResult<T> {
    Value(JsonRpcResponse<T>),
    Error(JsonRpcErrorResponse),
}

#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum JsonRpcId {
    Integer(u64),
    String(String),
}