alloy_json_rpc/response/
error.rs

1use alloy_primitives::Bytes;
2use alloy_sol_types::{SolError, SolInterface};
3use serde::{
4    de::{DeserializeOwned, MapAccess, Visitor},
5    Deserialize, Deserializer, Serialize,
6};
7use serde_json::{
8    value::{to_raw_value, RawValue},
9    Value,
10};
11use std::{
12    borrow::{Borrow, Cow},
13    fmt,
14    marker::PhantomData,
15};
16
17use crate::RpcSend;
18
19const INTERNAL_ERROR: Cow<'static, str> = Cow::Borrowed("Internal error");
20
21/// A JSON-RPC 2.0 error object.
22///
23/// This response indicates that the server received and handled the request,
24/// but that there was an error in the processing of it. The error should be
25/// included in the `message` field of the response payload.
26#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
27pub struct ErrorPayload<ErrData = Box<RawValue>> {
28    /// The error code.
29    pub code: i64,
30    /// The error message (if any).
31    pub message: Cow<'static, str>,
32    /// The error data (if any).
33    pub data: Option<ErrData>,
34}
35
36impl<E> ErrorPayload<E> {
37    /// Create a new error payload for a parse error.
38    pub const fn parse_error() -> Self {
39        Self { code: -32700, message: Cow::Borrowed("Parse error"), data: None }
40    }
41
42    /// Create a new error payload for an invalid request.
43    pub const fn invalid_request() -> Self {
44        Self { code: -32600, message: Cow::Borrowed("Invalid Request"), data: None }
45    }
46
47    /// Create a new error payload for a method not found error.
48    pub const fn method_not_found() -> Self {
49        Self { code: -32601, message: Cow::Borrowed("Method not found"), data: None }
50    }
51
52    /// Create a new error payload for an invalid params error.
53    pub const fn invalid_params() -> Self {
54        Self { code: -32602, message: Cow::Borrowed("Invalid params"), data: None }
55    }
56
57    /// Create a new error payload for an internal error.
58    pub const fn internal_error() -> Self {
59        Self { code: -32603, message: INTERNAL_ERROR, data: None }
60    }
61
62    /// Create a new error payload for an internal error with a custom message.
63    pub const fn internal_error_message(message: Cow<'static, str>) -> Self {
64        Self { code: -32603, message, data: None }
65    }
66
67    /// Create a new error payload for an internal error with a custom message
68    /// and additional data.
69    pub const fn internal_error_with_obj(data: E) -> Self
70    where
71        E: RpcSend,
72    {
73        Self { code: -32603, message: INTERNAL_ERROR, data: Some(data) }
74    }
75
76    /// Create a new error payload for an internal error with a custom message
77    pub const fn internal_error_with_message_and_obj(message: Cow<'static, str>, data: E) -> Self
78    where
79        E: RpcSend,
80    {
81        Self { code: -32603, message, data: Some(data) }
82    }
83
84    /// Analyzes the [ErrorPayload] and decides if the request should be
85    /// retried based on the error code or the message.
86    pub fn is_retry_err(&self) -> bool {
87        // alchemy throws it this way
88        if self.code == 429 {
89            return true;
90        }
91
92        // This is an infura error code for `exceeded project rate limit`
93        if self.code == -32005 {
94            return true;
95        }
96
97        // alternative alchemy error for specific IPs
98        if self.code == -32016 && self.message.contains("rate limit") {
99            return true;
100        }
101
102        // quick node error `"credits limited to 6000/sec"`
103        // <https://github.com/foundry-rs/foundry/pull/6712#issuecomment-1951441240>
104        if self.code == -32012 && self.message.contains("credits") {
105            return true;
106        }
107
108        // quick node rate limit error: `100/second request limit reached - reduce calls per second
109        // or upgrade your account at quicknode.com` <https://github.com/foundry-rs/foundry/issues/4894>
110        if self.code == -32007 && self.message.contains("request limit reached") {
111            return true;
112        }
113
114        // This is a websocket specific error for too many concurrent requests on the same
115        // connection <https://github.com/ithacaxyz/relay/issues/1352>
116        if self.code == 1008 {
117            return true;
118        }
119
120        match self.message.as_ref() {
121            // this is commonly thrown by infura and is apparently a load balancer issue, see also <https://github.com/MetaMask/metamask-extension/issues/7234>
122            "header not found" => true,
123            // also thrown by infura if out of budget for the day and ratelimited
124            "daily request count exceeded, request rate limited" => true,
125            msg => {
126                msg.contains("rate limit")
127                    || msg.contains("rate exceeded")
128                    || msg.contains("too many requests")
129                    || msg.contains("credits limited")
130                    || msg.contains("request limit")
131                    || msg.contains("maximum number of concurrent requests")
132            }
133        }
134    }
135}
136
137impl<T> From<T> for ErrorPayload<T>
138where
139    T: std::error::Error + RpcSend,
140{
141    fn from(value: T) -> Self {
142        Self { code: -32603, message: INTERNAL_ERROR, data: Some(value) }
143    }
144}
145
146impl<E> ErrorPayload<E>
147where
148    E: RpcSend,
149{
150    /// Serialize the inner data into a [`RawValue`].
151    pub fn serialize_payload(&self) -> serde_json::Result<ErrorPayload> {
152        Ok(ErrorPayload {
153            code: self.code,
154            message: self.message.clone(),
155            data: match self.data.as_ref() {
156                Some(data) => Some(to_raw_value(data)?),
157                None => None,
158            },
159        })
160    }
161}
162
163/// Recursively traverses the value, looking for hex data that it can extract.
164///
165/// Inspired by ethers-js logic:
166/// <https://github.com/ethers-io/ethers.js/blob/9f990c57f0486728902d4b8e049536f2bb3487ee/packages/providers/src.ts/json-rpc-provider.ts#L25-L53>
167fn spelunk_revert(value: &Value) -> Option<Bytes> {
168    match value {
169        Value::String(s) => s.parse().ok(),
170        Value::Object(o) => o.values().find_map(spelunk_revert),
171        _ => None,
172    }
173}
174
175impl<ErrData: fmt::Display> fmt::Display for ErrorPayload<ErrData> {
176    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
177        write!(
178            f,
179            "error code {}: {}{}",
180            self.code,
181            self.message,
182            self.data.as_ref().map(|data| format!(", data: {data}")).unwrap_or_default()
183        )
184    }
185}
186
187/// A [`ErrorPayload`] that has been partially deserialized, borrowing its
188/// contents from the deserializer. This is used primarily for intermediate
189/// deserialization. Most users will not require it.
190///
191/// See the [top-level docs] for more info.
192///
193/// [top-level docs]: crate
194pub type BorrowedErrorPayload<'a> = ErrorPayload<&'a RawValue>;
195
196impl BorrowedErrorPayload<'_> {
197    /// Convert this borrowed error payload into an owned payload by copying
198    /// the data from the deserializer (if necessary).
199    pub fn into_owned(self) -> ErrorPayload {
200        ErrorPayload {
201            code: self.code,
202            message: self.message,
203            data: self.data.map(|data| data.to_owned()),
204        }
205    }
206}
207
208impl<'de, ErrData: Deserialize<'de>> Deserialize<'de> for ErrorPayload<ErrData> {
209    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
210    where
211        D: Deserializer<'de>,
212    {
213        enum Field {
214            Code,
215            Message,
216            Data,
217            Unknown,
218        }
219
220        impl<'de> Deserialize<'de> for Field {
221            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
222            where
223                D: Deserializer<'de>,
224            {
225                struct FieldVisitor;
226
227                impl serde::de::Visitor<'_> for FieldVisitor {
228                    type Value = Field;
229
230                    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
231                        formatter.write_str("`code`, `message` and `data`")
232                    }
233
234                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
235                    where
236                        E: serde::de::Error,
237                    {
238                        match value {
239                            "code" => Ok(Field::Code),
240                            "message" => Ok(Field::Message),
241                            "data" => Ok(Field::Data),
242                            _ => Ok(Field::Unknown),
243                        }
244                    }
245                }
246                deserializer.deserialize_identifier(FieldVisitor)
247            }
248        }
249
250        struct ErrorPayloadVisitor<T>(PhantomData<T>);
251
252        impl<'de, Data> Visitor<'de> for ErrorPayloadVisitor<Data>
253        where
254            Data: Deserialize<'de>,
255        {
256            type Value = ErrorPayload<Data>;
257
258            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
259                write!(formatter, "a JSON-RPC 2.0 error object")
260            }
261
262            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
263            where
264                A: MapAccess<'de>,
265            {
266                let mut code = None;
267                let mut message = None;
268                let mut data = None;
269
270                while let Some(key) = map.next_key()? {
271                    match key {
272                        Field::Code => {
273                            if code.is_some() {
274                                return Err(serde::de::Error::duplicate_field("code"));
275                            }
276                            code = Some(map.next_value()?);
277                        }
278                        Field::Message => {
279                            if message.is_some() {
280                                return Err(serde::de::Error::duplicate_field("message"));
281                            }
282                            message = Some(map.next_value()?);
283                        }
284                        Field::Data => {
285                            if data.is_some() {
286                                return Err(serde::de::Error::duplicate_field("data"));
287                            }
288                            data = Some(map.next_value()?);
289                        }
290                        Field::Unknown => {
291                            let _: serde::de::IgnoredAny = map.next_value()?;
292                            // ignore
293                        }
294                    }
295                }
296                Ok(ErrorPayload {
297                    code: code.ok_or_else(|| serde::de::Error::missing_field("code"))?,
298                    message: message.unwrap_or_default(),
299                    data,
300                })
301            }
302        }
303
304        deserializer.deserialize_any(ErrorPayloadVisitor(PhantomData))
305    }
306}
307
308impl<'a, Data> ErrorPayload<Data>
309where
310    Data: Borrow<RawValue> + 'a,
311{
312    /// Deserialize the error's `data` field, borrowing from the data field if
313    /// necessary.
314    ///
315    /// # Returns
316    ///
317    /// - `None` if the error has no `data` field.
318    /// - `Some(Ok(data))` if the error has a `data` field that can be deserialized.
319    /// - `Some(Err(err))` if the error has a `data` field that can't be deserialized.
320    pub fn try_data_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
321        self.data.as_ref().map(|data| serde_json::from_str(data.borrow().get()))
322    }
323
324    /// Attempt to deserialize the data field.
325    ///
326    /// # Returns
327    ///
328    /// - `Ok(ErrorPayload<T>)` if the data field can be deserialized
329    /// - `Err(self)` if the data field can't be deserialized, or if there is no data field.
330    pub fn deser_data<T: DeserializeOwned>(self) -> Result<ErrorPayload<T>, Self> {
331        match self.try_data_as::<T>() {
332            Some(Ok(data)) => {
333                Ok(ErrorPayload { code: self.code, message: self.message, data: Some(data) })
334            }
335            _ => Err(self),
336        }
337    }
338
339    /// Attempt to extract revert data from the JSON-RPC error by recursively
340    /// traversing the error's data field
341    ///
342    /// Returns the first hex string found in the data object; behavior may change
343    /// with `serde_json` internal changes.
344    ///
345    /// If no hex value is found, returns `None` even if the message indicates a
346    /// revert.
347    ///
348    /// Inspired by ethers-js logic:
349    /// <https://github.com/ethers-io/ethers.js/blob/9f990c57f0486728902d4b8e049536f2bb3487ee/packages/providers/src.ts/json-rpc-provider.ts#L25-L53>
350    pub fn as_revert_data(&self) -> Option<Bytes> {
351        if self.message.contains("revert") {
352            let value = Value::deserialize(self.data.as_ref()?.borrow()).ok()?;
353            spelunk_revert(&value)
354        } else {
355            None
356        }
357    }
358
359    /// Extracts revert data and tries decoding it into given custom errors set present in the
360    /// [`SolInterface`].
361    pub fn as_decoded_interface_error<E: SolInterface>(&self) -> Option<E> {
362        self.as_revert_data().and_then(|data| E::abi_decode(&data).ok())
363    }
364
365    /// Extracts revert data and tries decoding it into custom [`SolError`].
366    pub fn as_decoded_error<E: SolError>(&self) -> Option<E> {
367        self.as_revert_data().and_then(|data| E::abi_decode(&data).ok())
368    }
369}
370
371#[cfg(test)]
372mod test {
373    use alloy_primitives::U256;
374    use alloy_sol_types::sol;
375
376    use super::BorrowedErrorPayload;
377    use crate::ErrorPayload;
378
379    #[test]
380    fn smooth_borrowing() {
381        let json = r#"{ "code": -32000, "message": "b", "data": null }"#;
382        let payload: BorrowedErrorPayload<'_> = serde_json::from_str(json).unwrap();
383
384        assert_eq!(payload.code, -32000);
385        assert_eq!(payload.message, "b");
386        assert_eq!(payload.data.unwrap().get(), "null");
387    }
388
389    #[test]
390    fn smooth_deser() {
391        #[derive(Debug, PartialEq, serde::Deserialize)]
392        struct TestData {
393            a: u32,
394            b: Option<String>,
395        }
396
397        let json = r#"{ "code": -32000, "message": "b", "data": { "a": 5, "b": null } }"#;
398
399        let payload: BorrowedErrorPayload<'_> = serde_json::from_str(json).unwrap();
400        let data: TestData = payload.try_data_as().unwrap().unwrap();
401        assert_eq!(data, TestData { a: 5, b: None });
402    }
403
404    #[test]
405    fn missing_data() {
406        let json = r#"{"code":-32007,"message":"20/second request limit reached - reduce calls per second or upgrade your account at quicknode.com"}"#;
407        let payload: ErrorPayload = serde_json::from_str(json).unwrap();
408
409        assert_eq!(payload.code, -32007);
410        assert_eq!(payload.message, "20/second request limit reached - reduce calls per second or upgrade your account at quicknode.com");
411        assert!(payload.data.is_none());
412    }
413
414    #[test]
415    fn custom_error_decoding() {
416        sol!(
417            #[derive(Debug, PartialEq, Eq)]
418            library Errors {
419                error SomeCustomError(uint256 a);
420            }
421        );
422
423        let json = r#"{"code":3,"message":"execution reverted: ","data":"0x810f00230000000000000000000000000000000000000000000000000000000000000001"}"#;
424        let payload: ErrorPayload = serde_json::from_str(json).unwrap();
425
426        let Errors::ErrorsErrors::SomeCustomError(value) =
427            payload.as_decoded_interface_error::<Errors::ErrorsErrors>().unwrap();
428
429        assert_eq!(value.a, U256::from(1));
430
431        let decoded_err = payload.as_decoded_error::<Errors::SomeCustomError>().unwrap();
432
433        assert_eq!(decoded_err, Errors::SomeCustomError { a: U256::from(1) });
434    }
435
436    #[test]
437    fn max_concurrent_requests() {
438        let json = r#"{"code":1008,"message":"You have exceeded the maximum number of concurrent requests on a single WebSocket. At most 200 concurrent requests are allowed per WebSocket."}"#;
439        let payload: ErrorPayload = serde_json::from_str(json).unwrap();
440        assert!(payload.is_retry_err());
441    }
442}