loom_broadcast_flashbots/client/
jsonrpc.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
use std::fmt;

use crate::client::BundleHash;
use alloy_primitives::U256;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;
// Code adapted from: https://github.com/althea-net/guac_rs/tree/master/web3/src/jsonrpc
// NOTE: This module only exists since there is no way to use the data structures
// in the `ethers-providers/src/transports/common.rs` from another crate.

/// A JSON-RPC 2.0 error
#[derive(Serialize, Deserialize, Debug, Clone, Error)]
pub struct JsonRpcError {
    /// The error code
    pub code: i64,
    /// The error message
    pub message: String,
    /// Additional data
    pub data: Option<Value>,
}

impl fmt::Display for JsonRpcError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "(code: {}, message: {}, data: {:?})", self.code, self.message, self.data)
    }
}

fn is_zst<T>(_t: &T) -> bool {
    std::mem::size_of::<T>() == 0
}

#[derive(Serialize, Deserialize, Debug)]
/// A JSON-RPC request
pub struct Request<'a, T> {
    id: u64,
    jsonrpc: &'a str,
    method: &'a str,
    #[serde(skip_serializing_if = "is_zst")]
    params: T,
}

#[derive(Serialize, Deserialize, Debug)]
/// A JSON-RPC Notifcation
pub struct Notification<R> {
    jsonrpc: String,
    method: String,
    pub params: Subscription<R>,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Subscription<R> {
    pub subscription: U256,
    pub result: R,
}

impl<'a, T> Request<'a, T> {
    /// Creates a new JSON RPC request
    pub fn new(id: u64, method: &'a str, params: T) -> Self {
        Self { id, jsonrpc: "2.0", method, params }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Response<T> {
    #[serde(default)]
    pub(crate) id: u64,
    #[serde(default)]
    jsonrpc: String,
    #[serde(flatten)]
    pub data: ResponseData<T>,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum ResponseData<R> {
    Error { error: JsonRpcError },
    Success { result: R },
}

impl<R> ResponseData<R> {
    /// Consume response and return value
    pub fn into_result(self) -> Result<R, JsonRpcError> {
        match self {
            ResponseData::Success { result } => Ok(result),
            ResponseData::Error { error } => Err(error),
        }
    }
}

#[derive(Deserialize, Debug, PartialEq, Eq, Hash)]
#[serde(untagged)]
pub enum SendBundleResponseType {
    Integer(u64),
    BundleHash(BundleHash),
    String(String),
    SendBundleResponse(SendBundleResponse),
    Null(Option<()>),
}

#[derive(Deserialize, Debug, PartialEq, Eq, Hash)]
#[serde(rename_all = "camelCase")]
pub struct SendBundleResponse {
    #[serde(default)]
    pub(crate) bundle_hash: Option<BundleHash>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloy_primitives::{hex, TxHash};

    #[test]
    fn deser_response() {
        let response: Response<u64> = serde_json::from_str(r#"{"jsonrpc": "2.0", "result": 19, "id": 1}"#).unwrap();
        assert_eq!(response.id, 1);
        assert_eq!(response.data.into_result().unwrap(), 19);
    }

    #[test]
    fn ser_request() {
        let request: Request<()> = Request::new(300, "method_name", ());
        assert_eq!(&serde_json::to_string(&request).unwrap(), r#"{"id":300,"jsonrpc":"2.0","method":"method_name"}"#);

        let request: Request<u32> = Request::new(300, "method_name", 1);
        assert_eq!(&serde_json::to_string(&request).unwrap(), r#"{"id":300,"jsonrpc":"2.0","method":"method_name","params":1}"#);
    }

    #[test]
    fn deser_response_enum() {
        let response: Response<SendBundleResponseType> = serde_json::from_str(r#"{"jsonrpc": "2.0", "result": 19, "id": 1}"#).unwrap();
        assert_eq!(response.id, 1);
        assert_eq!(response.data.into_result().unwrap(), SendBundleResponseType::Integer(19));
    }

    #[test]
    fn deser_response_result_null() {
        // https://rpc.penguinbuild.org
        let response: Response<SendBundleResponseType> = serde_json::from_str(r#"{"jsonrpc":"2.0","id":2,"result":null}"#).unwrap();
        assert_eq!(response.id, 2);
        assert_eq!(response.data.into_result().unwrap(), SendBundleResponseType::Null(None));
    }

    #[test]
    fn deser_response_result_string() {
        // https://rpc.lokibuilder.xyz
        // https://api.securerpc.com/v1
        let response: Response<SendBundleResponseType> = serde_json::from_str(r#"{"jsonrpc":"2.0","id":1,"result":"nil"}"#).unwrap();
        assert_eq!(response.id, 1);
        assert_eq!(response.data.into_result().unwrap(), SendBundleResponseType::String("nil".to_string()));
    }
    #[test]
    fn deser_response_result_send_bundle_response() {
        let response: Response<SendBundleResponseType> = serde_json::from_str(
            r#"{"id":1,"result":{"bundleHash":"0xcc6c61428c6516a252768859d167dc8f5c8c8c682334a184710f898e422530f8"},"jsonrpc":"2.0"}"#,
        )
        .unwrap();
        assert_eq!(response.id, 1);
        assert_eq!(
            response.data.into_result().unwrap(),
            SendBundleResponseType::SendBundleResponse(SendBundleResponse {
                bundle_hash: Some(TxHash::from(hex!("cc6c61428c6516a252768859d167dc8f5c8c8c682334a184710f898e422530f8")))
            })
        )
    }
    #[test]
    fn deser_response_result_bundle_hash_response() {
        let response: Response<SendBundleResponseType> = serde_json::from_str(
            r#"{"jsonrpc":"2.0","id":1,"result":"0xcc6c61428c6516a252768859d167dc8f5c8c8c682334a184710f898e422530f8"}"#,
        )
        .unwrap();
        assert_eq!(response.id, 1);
        assert_eq!(
            response.data.into_result().unwrap(),
            SendBundleResponseType::BundleHash(TxHash::from(hex!("cc6c61428c6516a252768859d167dc8f5c8c8c682334a184710f898e422530f8")))
        )
    }

    //
}