lampo_jsonrpc/
json_rpc2.rs1use 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)]
26pub struct Request<T: Serialize> {
28 pub method: String,
30 pub params: T,
32 #[serde(skip_serializing_if = "Option::is_none")]
34 pub id: Option<Id>,
35 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)]
52pub struct Response<T> {
54 pub result: Option<T>,
56 pub error: Option<RpcError>,
58 pub id: Id,
60 pub jsonrpc: String,
62}
63
64impl<T> Response<T> {
65 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 pub fn is_none(&self) -> bool {
76 self.result.is_none()
77 }
78}