alloy_json_rpc/
result.rs

1use crate::{Response, ResponsePayload, RpcError, RpcRecv};
2use serde_json::value::RawValue;
3use std::borrow::Borrow;
4
5/// The result of a JSON-RPC request.
6///
7/// Either a success response, an error response, or a non-response error. The
8/// non-response error is intended to be used for errors returned by a
9/// transport, or serde errors.
10///
11/// The common cases are:
12/// - `Ok(T)` - The server returned a successful response.
13/// - `Err(RpcError::ErrorResponse(ErrResp))` - The server returned an error response.
14/// - `Err(RpcError::SerError(E))` - A serialization error occurred.
15/// - `Err(RpcError::DeserError { err: E, text: String })` - A deserialization error occurred.
16/// - `Err(RpcError::TransportError(E))` - Some client-side or communication error occurred.
17pub type RpcResult<T, E, ErrResp = Box<RawValue>> = Result<T, RpcError<E, ErrResp>>;
18
19/// A partially deserialized [`RpcResult`], borrowing from the deserializer.
20pub type BorrowedRpcResult<'a, E> = RpcResult<&'a RawValue, E, &'a RawValue>;
21
22/// Transform a transport response into an [`RpcResult`], discarding the [`Id`].
23///
24/// [`Id`]: crate::Id
25pub fn transform_response<T, E, ErrResp>(response: Response<T, ErrResp>) -> RpcResult<T, E, ErrResp>
26where
27    ErrResp: RpcRecv,
28{
29    match response {
30        Response { payload: ResponsePayload::Failure(err_resp), .. } => {
31            Err(RpcError::err_resp(err_resp))
32        }
33        Response { payload: ResponsePayload::Success(result), .. } => Ok(result),
34    }
35}
36
37/// Transform a transport outcome into an [`RpcResult`], discarding the [`Id`].
38///
39/// [`Id`]: crate::Id
40pub fn transform_result<T, E, ErrResp>(
41    response: Result<Response<T, ErrResp>, E>,
42) -> Result<T, RpcError<E, ErrResp>>
43where
44    ErrResp: RpcRecv,
45{
46    match response {
47        Ok(resp) => transform_response(resp),
48        Err(e) => Err(RpcError::Transport(e)),
49    }
50}
51
52/// Attempt to deserialize the `Ok(_)` variant of an [`RpcResult`].
53pub fn try_deserialize_ok<J, T, E, ErrResp>(
54    result: RpcResult<J, E, ErrResp>,
55) -> RpcResult<T, E, ErrResp>
56where
57    J: Borrow<RawValue>,
58    T: RpcRecv,
59    ErrResp: RpcRecv,
60{
61    let json = result?;
62    let json = json.borrow().get();
63    trace!(ty=%std::any::type_name::<T>(), %json, "deserializing response");
64    serde_json::from_str(json)
65        .inspect(|response| trace!(?response, "deserialized response"))
66        .inspect_err(|err| trace!(?err, "failed to deserialize response"))
67        .map_err(|err| RpcError::deser_err(err, json))
68}