alloy_json_rpc/
request.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
use crate::{common::Id, RpcObject, RpcParam};
use alloy_primitives::{keccak256, B256};
use serde::{
    de::{DeserializeOwned, MapAccess},
    ser::SerializeMap,
    Deserialize, Serialize,
};
use serde_json::value::RawValue;
use std::{borrow::Cow, marker::PhantomData, mem::MaybeUninit};

/// `RequestMeta` contains the [`Id`] and method name of a request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RequestMeta {
    /// The method name.
    pub method: Cow<'static, str>,
    /// The request ID.
    pub id: Id,
    /// Whether the request is a subscription, other than `eth_subscribe`.
    is_subscription: bool,
}

impl RequestMeta {
    /// Create a new `RequestMeta`.
    pub const fn new(method: Cow<'static, str>, id: Id) -> Self {
        Self { method, id, is_subscription: false }
    }

    /// Returns `true` if the request is a subscription.
    pub fn is_subscription(&self) -> bool {
        self.is_subscription || self.method == "eth_subscribe"
    }

    /// Indicates that the request is a non-standard subscription (i.e. not
    /// "eth_subscribe").
    pub fn set_is_subscription(&mut self) {
        self.set_subscription_status(true);
    }

    /// Setter for `is_subscription`. Indicates to RPC clients that the request
    /// triggers a stream of notifications.
    pub fn set_subscription_status(&mut self, sub: bool) {
        self.is_subscription = sub;
    }
}

/// A JSON-RPC 2.0 request object.
///
/// This is a generic type that can be used to represent any JSON-RPC request.
/// The `Params` type parameter is used to represent the parameters of the
/// request, and the `method` field is used to represent the method name.
///
/// ### Note
///
/// The value of `method` should be known at compile time.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Request<Params> {
    /// The request metadata (ID and method).
    pub meta: RequestMeta,
    /// The request parameters.
    pub params: Params,
}

impl<Params> Request<Params> {
    /// Create a new `Request`.
    pub fn new(method: impl Into<Cow<'static, str>>, id: Id, params: Params) -> Self {
        Self { meta: RequestMeta::new(method.into(), id), params }
    }

    /// Returns `true` if the request is a subscription.
    pub fn is_subscription(&self) -> bool {
        self.meta.is_subscription()
    }

    /// Indicates that the request is a non-standard subscription (i.e. not
    /// "eth_subscribe").
    pub fn set_is_subscription(&mut self) {
        self.meta.set_is_subscription()
    }

    /// Setter for `is_subscription`. Indicates to RPC clients that the request
    /// triggers a stream of notifications.
    pub fn set_subscription_status(&mut self, sub: bool) {
        self.meta.set_subscription_status(sub);
    }

    /// Change type of the request parameters.
    pub fn map_params<NewParams>(
        self,
        map: impl FnOnce(Params) -> NewParams,
    ) -> Request<NewParams> {
        Request { meta: self.meta, params: map(self.params) }
    }
}

/// A [`Request`] that has been partially serialized.
///
/// The request parameters have been serialized, and are represented as a boxed [`RawValue`]. This
/// is useful for collections containing many requests, as it erases the `Param` type. It can be
/// created with [`Request::box_params()`].
///
/// See the [top-level docs] for more info.
///
/// [top-level docs]: crate
pub type PartiallySerializedRequest = Request<Box<RawValue>>;

impl<Params> Request<Params>
where
    Params: RpcParam,
{
    /// Serialize the request parameters as a boxed [`RawValue`].
    ///
    /// # Panics
    ///
    /// If serialization of the params fails.
    pub fn box_params(self) -> PartiallySerializedRequest {
        Request { meta: self.meta, params: serde_json::value::to_raw_value(&self.params).unwrap() }
    }

    /// Serialize the request, including the request parameters.
    pub fn serialize(self) -> serde_json::Result<SerializedRequest> {
        let request = serde_json::value::to_raw_value(&self)?;
        Ok(SerializedRequest { meta: self.meta, request })
    }
}

impl<Params> Request<&Params>
where
    Params: ToOwned,
    Params::Owned: RpcParam,
{
    /// Clone the request, including the request parameters.
    pub fn into_owned_params(self) -> Request<Params::Owned> {
        Request { meta: self.meta, params: self.params.to_owned() }
    }
}

impl<'a, Params> Request<Params>
where
    Params: AsRef<RawValue> + 'a,
{
    /// Attempt to deserialize the params.
    ///
    /// To borrow from the params via the deserializer, use
    /// [`Request::try_borrow_params_as`].
    ///
    /// # Returns
    /// - `Ok(T)` if the params can be deserialized as `T`
    /// - `Err(e)` if the params cannot be deserialized as `T`
    pub fn try_params_as<T: DeserializeOwned>(&self) -> serde_json::Result<T> {
        serde_json::from_str(self.params.as_ref().get())
    }

    /// Attempt to deserialize the params, borrowing from the params
    ///
    /// # Returns
    /// - `Ok(T)` if the params can be deserialized as `T`
    /// - `Err(e)` if the params cannot be deserialized as `T`
    pub fn try_borrow_params_as<T: Deserialize<'a>>(&'a self) -> serde_json::Result<T> {
        serde_json::from_str(self.params.as_ref().get())
    }
}

// manually implemented to avoid adding a type for the protocol-required
// `jsonrpc` field
impl<Params> Serialize for Request<Params>
where
    Params: RpcParam,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let sized_params = std::mem::size_of::<Params>() != 0;

        let mut map = serializer.serialize_map(Some(3 + sized_params as usize))?;
        map.serialize_entry("method", &self.meta.method[..])?;

        // Params may be omitted if it is 0-sized
        if sized_params {
            map.serialize_entry("params", &self.params)?;
        }

        map.serialize_entry("id", &self.meta.id)?;
        map.serialize_entry("jsonrpc", "2.0")?;
        map.end()
    }
}

impl<'de, Params> Deserialize<'de> for Request<Params>
where
    Params: RpcObject,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Visitor<Params>(PhantomData<Params>);
        impl<'de, Params> serde::de::Visitor<'de> for Visitor<Params>
        where
            Params: RpcObject,
        {
            type Value = Request<Params>;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(
                    formatter,
                    "a JSON-RPC 2.0 request object with params of type {}",
                    std::any::type_name::<Params>()
                )
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut id = None;
                let mut params = None;
                let mut method = None;
                let mut jsonrpc = None;

                while let Some(key) = map.next_key()? {
                    match key {
                        "id" => {
                            if id.is_some() {
                                return Err(serde::de::Error::duplicate_field("id"));
                            }
                            id = Some(map.next_value()?);
                        }
                        "params" => {
                            if params.is_some() {
                                return Err(serde::de::Error::duplicate_field("params"));
                            }
                            params = Some(map.next_value()?);
                        }
                        "method" => {
                            if method.is_some() {
                                return Err(serde::de::Error::duplicate_field("method"));
                            }
                            method = Some(map.next_value()?);
                        }
                        "jsonrpc" => {
                            let version: String = map.next_value()?;
                            if version != "2.0" {
                                return Err(serde::de::Error::custom(format!(
                                    "unsupported JSON-RPC version: {}",
                                    version
                                )));
                            }
                            jsonrpc = Some(());
                        }
                        other => {
                            return Err(serde::de::Error::unknown_field(
                                other,
                                &["id", "params", "method", "jsonrpc"],
                            ));
                        }
                    }
                }
                if jsonrpc.is_none() {
                    return Err(serde::de::Error::missing_field("jsonrpc"));
                }
                if method.is_none() {
                    return Err(serde::de::Error::missing_field("method"));
                }

                if params.is_none() {
                    if std::mem::size_of::<Params>() == 0 {
                        // SAFETY: params is a ZST, so it's safe to fail to initialize it
                        unsafe { params = Some(MaybeUninit::<Params>::zeroed().assume_init()) }
                    } else {
                        return Err(serde::de::Error::missing_field("params"));
                    }
                }

                Ok(Request {
                    meta: RequestMeta::new(method.unwrap(), id.unwrap_or(Id::None)),
                    params: params.unwrap(),
                })
            }
        }

        deserializer.deserialize_map(Visitor(PhantomData))
    }
}

/// A JSON-RPC 2.0 request object that has been serialized, with its [`Id`] and
/// method preserved.
///
/// This struct is used to represent a request that has been serialized, but
/// not yet sent. It is used by RPC clients to build batch requests and manage
/// in-flight requests.
#[derive(Clone, Debug)]
pub struct SerializedRequest {
    meta: RequestMeta,
    request: Box<RawValue>,
}

impl<Params> std::convert::TryFrom<Request<Params>> for SerializedRequest
where
    Params: RpcParam,
{
    type Error = serde_json::Error;

    fn try_from(value: Request<Params>) -> Result<Self, Self::Error> {
        value.serialize()
    }
}

impl SerializedRequest {
    /// Returns the request metadata (ID and Method).
    pub const fn meta(&self) -> &RequestMeta {
        &self.meta
    }

    /// Returns the request ID.
    pub const fn id(&self) -> &Id {
        &self.meta.id
    }

    /// Returns the request method.
    pub fn method(&self) -> &str {
        &self.meta.method
    }

    /// Mark the request as a non-standard subscription (i.e. not
    /// `eth_subscribe`)
    pub fn set_is_subscription(&mut self) {
        self.meta.set_is_subscription();
    }

    /// Returns `true` if the request is a subscription.
    pub fn is_subscription(&self) -> bool {
        self.meta.is_subscription()
    }

    /// Returns the serialized request.
    pub const fn serialized(&self) -> &RawValue {
        &self.request
    }

    /// Consume the serialized request, returning the underlying [`RawValue`].
    pub fn into_serialized(self) -> Box<RawValue> {
        self.request
    }

    /// Consumes the serialized request, returning the underlying
    /// [`RequestMeta`] and the [`RawValue`].
    pub fn decompose(self) -> (RequestMeta, Box<RawValue>) {
        (self.meta, self.request)
    }

    /// Take the serialized request, consuming the [`SerializedRequest`].
    pub fn take_request(self) -> Box<RawValue> {
        self.request
    }

    /// Get a reference to the serialized request's params.
    ///
    /// This partially deserializes the request, and should be avoided if
    /// possible.
    pub fn params(&self) -> Option<&RawValue> {
        #[derive(Deserialize)]
        struct Req<'a> {
            #[serde(borrow)]
            params: Option<&'a RawValue>,
        }

        let req: Req<'_> = serde_json::from_str(self.request.get()).unwrap();
        req.params
    }

    /// Get the hash of the serialized request's params.
    ///
    /// This partially deserializes the request, and should be avoided if
    /// possible.
    pub fn params_hash(&self) -> B256 {
        self.params().map_or_else(|| keccak256(""), |params| keccak256(params.get()))
    }
}

impl Serialize for SerializedRequest {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.request.serialize(serializer)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    fn test_inner<T: RpcObject + PartialEq>(t: T) {
        let ser = serde_json::to_string(&t).unwrap();
        let de: T = serde_json::from_str(&ser).unwrap();
        let reser = serde_json::to_string(&de).unwrap();
        assert_eq!(de, t, "deser error for {}", std::any::type_name::<T>());
        assert_eq!(ser, reser, "reser error for {}", std::any::type_name::<T>());
    }

    #[test]
    fn test_ser_deser() {
        test_inner(Request::<()>::new("test", 1.into(), ()));
        test_inner(Request::<u64>::new("test", "hello".to_string().into(), 1));
        test_inner(Request::<String>::new("test", Id::None, "test".to_string()));
        test_inner(Request::<Vec<u64>>::new("test", u64::MAX.into(), vec![1, 2, 3]));
    }
}