lampo_jsonrpc/
json_rpc2.rs

1use serde::{Deserialize, Serialize};
2
3use crate::errors::{Error, RpcError};
4
5#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
6#[serde(untagged)]
7pub enum Id {
8    Str(String),
9    Int(u16),
10}
11
12impl From<&str> for Id {
13    fn from(value: &str) -> Self {
14        Id::Str(value.to_owned())
15    }
16}
17
18impl From<u64> for Id {
19    fn from(value: u64) -> Self {
20        Id::Str(format!("{value}"))
21    }
22}
23
24#[allow(clippy::derive_partial_eq_without_eq)]
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26/// A standard JSONRPC request object
27pub struct Request<T: Serialize> {
28    /// The name of the RPC method call
29    pub method: String,
30    /// Parameters to the RPC method call
31    pub params: T,
32    /// Identifier for this Request, which should appear in the response
33    #[serde(skip_serializing_if = "Option::is_none")]
34    pub id: Option<Id>,
35    /// jsonrpc field, MUST be "2.0"
36    pub jsonrpc: String,
37}
38
39impl<T: Serialize> Request<T> {
40    pub fn new(method: &str, args: T) -> Self {
41        Request {
42            method: method.to_owned(),
43            params: args,
44            id: Some("lampo/jsonrpc/1".into()),
45            jsonrpc: "2.0".to_owned(),
46        }
47    }
48}
49
50#[allow(clippy::derive_partial_eq_without_eq)]
51#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
52/// A standard JSONRPC response object
53pub struct Response<T> {
54    /// A result if there is one, or null
55    pub result: Option<T>,
56    /// An error if there is one, or null
57    pub error: Option<RpcError>,
58    /// Identifier for this Request, which should match that of the request
59    pub id: Id,
60    /// jsonrpc field, MUST be "2.0"
61    pub jsonrpc: String,
62}
63
64impl<T> Response<T> {
65    /// Extract the result from a response, consuming the response
66    pub fn into_result(self) -> Result<T, Error> {
67        if let Some(e) = self.error {
68            return Err(Error::Rpc(e));
69        }
70
71        self.result.ok_or(Error::NoErrorOrResult)
72    }
73
74    /// Returns whether or not the `result` field is empty
75    pub fn is_none(&self) -> bool {
76        self.result.is_none()
77    }
78}