Skip to main content

anvil_rpc/
response.rs

1use crate::{
2    error::RpcError,
3    request::{Id, Version},
4};
5use serde::Serialize;
6use serde_json::value::RawValue;
7
8/// Response of a _single_ rpc call
9#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
10pub struct RpcResponse {
11    // JSON RPC version
12    jsonrpc: Version,
13    id: Id,
14    #[serde(flatten)]
15    result: ResponseResult,
16}
17
18impl From<RpcError> for RpcResponse {
19    fn from(e: RpcError) -> Self {
20        Self { jsonrpc: Version::V2, id: Id::Null, result: ResponseResult::Error(e) }
21    }
22}
23
24impl RpcResponse {
25    pub fn new(id: Id, content: impl Into<ResponseResult>) -> Self {
26        Self { jsonrpc: Version::V2, id, result: content.into() }
27    }
28
29    pub fn invalid_request(id: Id) -> Self {
30        Self::new(id, RpcError::invalid_request())
31    }
32}
33
34/// Represents the result of a call either success or error
35#[derive(Clone, Debug, Serialize)]
36pub enum ResponseResult {
37    #[serde(rename = "result")]
38    Success(Box<RawValue>),
39    #[serde(rename = "error")]
40    Error(RpcError),
41}
42
43impl ResponseResult {
44    pub fn success<S>(content: S) -> Self
45    where
46        S: Serialize + 'static,
47    {
48        Self::Success(serde_json::value::to_raw_value(&content).unwrap())
49    }
50
51    pub const fn error(error: RpcError) -> Self {
52        Self::Error(error)
53    }
54}
55
56impl PartialEq for ResponseResult {
57    fn eq(&self, other: &Self) -> bool {
58        match (self, other) {
59            (Self::Success(a), Self::Success(b)) => a.get() == b.get(),
60            (Self::Error(a), Self::Error(b)) => a == b,
61            _ => false,
62        }
63    }
64}
65
66impl Eq for ResponseResult {}
67
68impl From<RpcError> for ResponseResult {
69    fn from(err: RpcError) -> Self {
70        Self::error(err)
71    }
72}
73/// Synchronous response
74#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
75#[serde(untagged)]
76pub enum Response {
77    /// single json rpc response
78    Single(RpcResponse),
79    /// batch of several responses
80    Batch(Vec<RpcResponse>),
81}
82
83impl Response {
84    /// Creates new [`Response`] with the given [`RpcError`].
85    pub fn error(error: RpcError) -> Self {
86        RpcResponse::new(Id::Null, ResponseResult::Error(error)).into()
87    }
88}
89
90impl From<RpcError> for Response {
91    fn from(err: RpcError) -> Self {
92        Self::error(err)
93    }
94}
95
96impl From<RpcResponse> for Response {
97    fn from(resp: RpcResponse) -> Self {
98        Self::Single(resp)
99    }
100}