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        match self.message.as_ref() {
115            // this is commonly thrown by infura and is apparently a load balancer issue, see also <https://github.com/MetaMask/metamask-extension/issues/7234>
116            "header not found" => true,
117            // also thrown by infura if out of budget for the day and ratelimited
118            "daily request count exceeded, request rate limited" => true,
119            msg => {
120                msg.contains("rate limit")
121                    || msg.contains("rate exceeded")
122                    || msg.contains("too many requests")
123                    || msg.contains("credits limited")
124                    || msg.contains("request limit")
125            }
126        }
127    }
128}
129
130impl<T> From<T> for ErrorPayload<T>
131where
132    T: std::error::Error + RpcSend,
133{
134    fn from(value: T) -> Self {
135        Self { code: -32603, message: INTERNAL_ERROR, data: Some(value) }
136    }
137}
138
139impl<E> ErrorPayload<E>
140where
141    E: RpcSend,
142{
143    /// Serialize the inner data into a [`RawValue`].
144    pub fn serialize_payload(&self) -> serde_json::Result<ErrorPayload> {
145        Ok(ErrorPayload {
146            code: self.code,
147            message: self.message.clone(),
148            data: match self.data.as_ref() {
149                Some(data) => Some(to_raw_value(data)?),
150                None => None,
151            },
152        })
153    }
154}
155
156/// Recursively traverses the value, looking for hex data that it can extract.
157///
158/// Inspired by ethers-js logic:
159/// <https://github.com/ethers-io/ethers.js/blob/9f990c57f0486728902d4b8e049536f2bb3487ee/packages/providers/src.ts/json-rpc-provider.ts#L25-L53>
160fn spelunk_revert(value: &Value) -> Option<Bytes> {
161    match value {
162        Value::String(s) => s.parse().ok(),
163        Value::Object(o) => o.values().find_map(spelunk_revert),
164        _ => None,
165    }
166}
167
168impl<ErrData: fmt::Display> fmt::Display for ErrorPayload<ErrData> {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        write!(
171            f,
172            "error code {}: {}{}",
173            self.code,
174            self.message,
175            self.data.as_ref().map(|data| format!(", data: {data}")).unwrap_or_default()
176        )
177    }
178}
179
180/// A [`ErrorPayload`] that has been partially deserialized, borrowing its
181/// contents from the deserializer. This is used primarily for intermediate
182/// deserialization. Most users will not require it.
183///
184/// See the [top-level docs] for more info.
185///
186/// [top-level docs]: crate
187pub type BorrowedErrorPayload<'a> = ErrorPayload<&'a RawValue>;
188
189impl BorrowedErrorPayload<'_> {
190    /// Convert this borrowed error payload into an owned payload by copying
191    /// the data from the deserializer (if necessary).
192    pub fn into_owned(self) -> ErrorPayload {
193        ErrorPayload {
194            code: self.code,
195            message: self.message,
196            data: self.data.map(|data| data.to_owned()),
197        }
198    }
199}
200
201impl<'de, ErrData: Deserialize<'de>> Deserialize<'de> for ErrorPayload<ErrData> {
202    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
203    where
204        D: Deserializer<'de>,
205    {
206        enum Field {
207            Code,
208            Message,
209            Data,
210            Unknown,
211        }
212
213        impl<'de> Deserialize<'de> for Field {
214            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
215            where
216                D: Deserializer<'de>,
217            {
218                struct FieldVisitor;
219
220                impl serde::de::Visitor<'_> for FieldVisitor {
221                    type Value = Field;
222
223                    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
224                        formatter.write_str("`code`, `message` and `data`")
225                    }
226
227                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
228                    where
229                        E: serde::de::Error,
230                    {
231                        match value {
232                            "code" => Ok(Field::Code),
233                            "message" => Ok(Field::Message),
234                            "data" => Ok(Field::Data),
235                            _ => Ok(Field::Unknown),
236                        }
237                    }
238                }
239                deserializer.deserialize_identifier(FieldVisitor)
240            }
241        }
242
243        struct ErrorPayloadVisitor<T>(PhantomData<T>);
244
245        impl<'de, Data> Visitor<'de> for ErrorPayloadVisitor<Data>
246        where
247            Data: Deserialize<'de>,
248        {
249            type Value = ErrorPayload<Data>;
250
251            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
252                write!(formatter, "a JSON-RPC 2.0 error object")
253            }
254
255            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
256            where
257                A: MapAccess<'de>,
258            {
259                let mut code = None;
260                let mut message = None;
261                let mut data = None;
262
263                while let Some(key) = map.next_key()? {
264                    match key {
265                        Field::Code => {
266                            if code.is_some() {
267                                return Err(serde::de::Error::duplicate_field("code"));
268                            }
269                            code = Some(map.next_value()?);
270                        }
271                        Field::Message => {
272                            if message.is_some() {
273                                return Err(serde::de::Error::duplicate_field("message"));
274                            }
275                            message = Some(map.next_value()?);
276                        }
277                        Field::Data => {
278                            if data.is_some() {
279                                return Err(serde::de::Error::duplicate_field("data"));
280                            }
281                            data = Some(map.next_value()?);
282                        }
283                        Field::Unknown => {
284                            let _: serde::de::IgnoredAny = map.next_value()?;
285                            // ignore
286                        }
287                    }
288                }
289                Ok(ErrorPayload {
290                    code: code.ok_or_else(|| serde::de::Error::missing_field("code"))?,
291                    message: message.unwrap_or_default(),
292                    data,
293                })
294            }
295        }
296
297        deserializer.deserialize_any(ErrorPayloadVisitor(PhantomData))
298    }
299}
300
301impl<'a, Data> ErrorPayload<Data>
302where
303    Data: Borrow<RawValue> + 'a,
304{
305    /// Deserialize the error's `data` field, borrowing from the data field if
306    /// necessary.
307    ///
308    /// # Returns
309    ///
310    /// - `None` if the error has no `data` field.
311    /// - `Some(Ok(data))` if the error has a `data` field that can be deserialized.
312    /// - `Some(Err(err))` if the error has a `data` field that can't be deserialized.
313    pub fn try_data_as<T: Deserialize<'a>>(&'a self) -> Option<serde_json::Result<T>> {
314        self.data.as_ref().map(|data| serde_json::from_str(data.borrow().get()))
315    }
316
317    /// Attempt to deserialize the data field.
318    ///
319    /// # Returns
320    ///
321    /// - `Ok(ErrorPayload<T>)` if the data field can be deserialized
322    /// - `Err(self)` if the data field can't be deserialized, or if there is no data field.
323    pub fn deser_data<T: DeserializeOwned>(self) -> Result<ErrorPayload<T>, Self> {
324        match self.try_data_as::<T>() {
325            Some(Ok(data)) => {
326                Ok(ErrorPayload { code: self.code, message: self.message, data: Some(data) })
327            }
328            _ => Err(self),
329        }
330    }
331
332    /// Attempt to extract revert data from the JsonRpcError be recursively
333    /// traversing the error's data field
334    ///
335    /// This returns the first hex it finds in the data object, and its
336    /// behavior may change with `serde_json` internal changes.
337    ///
338    /// If no hex object is found, it will return an empty bytes IFF the error
339    /// is a revert
340    ///
341    /// Inspired by ethers-js logic:
342    /// <https://github.com/ethers-io/ethers.js/blob/9f990c57f0486728902d4b8e049536f2bb3487ee/packages/providers/src.ts/json-rpc-provider.ts#L25-L53>
343    pub fn as_revert_data(&self) -> Option<Bytes> {
344        if self.message.contains("revert") {
345            let value = Value::deserialize(self.data.as_ref()?.borrow()).ok()?;
346            spelunk_revert(&value)
347        } else {
348            None
349        }
350    }
351
352    /// Extracts revert data and tries decoding it into given custom errors set present in the
353    /// [`SolInterface`].
354    pub fn as_decoded_interface_error<E: SolInterface>(&self) -> Option<E> {
355        self.as_revert_data().and_then(|data| E::abi_decode(&data).ok())
356    }
357
358    /// Extracts revert data and tries decoding it into custom [`SolError`].
359    pub fn as_decoded_error<E: SolError>(&self) -> Option<E> {
360        self.as_revert_data().and_then(|data| E::abi_decode(&data).ok())
361    }
362}
363
364#[cfg(test)]
365mod test {
366    use alloy_primitives::U256;
367    use alloy_sol_types::sol;
368
369    use super::BorrowedErrorPayload;
370    use crate::ErrorPayload;
371
372    #[test]
373    fn smooth_borrowing() {
374        let json = r#"{ "code": -32000, "message": "b", "data": null }"#;
375        let payload: BorrowedErrorPayload<'_> = serde_json::from_str(json).unwrap();
376
377        assert_eq!(payload.code, -32000);
378        assert_eq!(payload.message, "b");
379        assert_eq!(payload.data.unwrap().get(), "null");
380    }
381
382    #[test]
383    fn smooth_deser() {
384        #[derive(Debug, PartialEq, serde::Deserialize)]
385        struct TestData {
386            a: u32,
387            b: Option<String>,
388        }
389
390        let json = r#"{ "code": -32000, "message": "b", "data": { "a": 5, "b": null } }"#;
391
392        let payload: BorrowedErrorPayload<'_> = serde_json::from_str(json).unwrap();
393        let data: TestData = payload.try_data_as().unwrap().unwrap();
394        assert_eq!(data, TestData { a: 5, b: None });
395    }
396
397    #[test]
398    fn missing_data() {
399        let json = r#"{"code":-32007,"message":"20/second request limit reached - reduce calls per second or upgrade your account at quicknode.com"}"#;
400        let payload: ErrorPayload = serde_json::from_str(json).unwrap();
401
402        assert_eq!(payload.code, -32007);
403        assert_eq!(payload.message, "20/second request limit reached - reduce calls per second or upgrade your account at quicknode.com");
404        assert!(payload.data.is_none());
405    }
406
407    #[test]
408    fn custom_error_decoding() {
409        sol!(
410            #[derive(Debug, PartialEq, Eq)]
411            library Errors {
412                error SomeCustomError(uint256 a);
413            }
414        );
415
416        let json = r#"{"code":3,"message":"execution reverted: ","data":"0x810f00230000000000000000000000000000000000000000000000000000000000000001"}"#;
417        let payload: ErrorPayload = serde_json::from_str(json).unwrap();
418
419        let Errors::ErrorsErrors::SomeCustomError(value) =
420            payload.as_decoded_interface_error::<Errors::ErrorsErrors>().unwrap();
421
422        assert_eq!(value.a, U256::from(1));
423
424        let decoded_err = payload.as_decoded_error::<Errors::SomeCustomError>().unwrap();
425
426        assert_eq!(decoded_err, Errors::SomeCustomError { a: U256::from(1) });
427    }
428}