Skip to main content

clightningrpc_common/
types.rs

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