alloy_dyn_abi/dynamic/
error.rs

1use crate::{DynSolType, DynSolValue, Error, Result};
2use alloc::vec::Vec;
3use alloy_primitives::Selector;
4use alloy_sol_types::SolError;
5
6/// See [alloy_sol_types::Panic] for signature details.
7const PANIC_SELECTOR: Selector = Selector::new(alloy_sol_types::Panic::SELECTOR);
8/// See [alloy_sol_types::Revert] for signature details.
9const REVERT_SELECTOR: Selector = Selector::new(alloy_sol_types::Revert::SELECTOR);
10
11/// A dynamic ABI error.
12///
13/// This is a representation of a Solidity error, which can be used to decode
14/// error events.
15#[derive(Clone, Debug, PartialEq)]
16pub struct DynSolError {
17    /// Error selector.
18    pub(crate) selector: Selector,
19    /// Error body types. MUST be a tuple.
20    pub(crate) body: DynSolType,
21}
22
23impl DynSolError {
24    /// Represents a standard Solidity revert. These are thrown by
25    /// `revert(reason)` or `require(condition, reason)` statements in Solidity.
26    ///
27    /// **Note**: Usage of this instantiator is not recommended. It is better to
28    /// use [alloy_sol_types::Revert] in almost all cases.
29    pub fn revert() -> Self {
30        Self { selector: REVERT_SELECTOR, body: DynSolType::Tuple(vec![DynSolType::String]) }
31    }
32
33    /// A [Solidity panic].
34    ///
35    /// **Note**: Usage of this instantiator is not recommended. It is better to
36    /// use [alloy_sol_types::Panic] in almost all cases.
37    ///
38    /// These are thrown by `assert(condition)` and by internal Solidity checks,
39    /// such as arithmetic overflow or array bounds checks.
40    ///
41    /// The list of all known panic codes can be found in the [PanicKind] enum.
42    ///
43    /// [Solidity panic]: https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require
44    /// [PanicKind]: alloy_sol_types::PanicKind
45    pub fn panic() -> Self {
46        Self { selector: PANIC_SELECTOR, body: DynSolType::Tuple(vec![DynSolType::Uint(256)]) }
47    }
48
49    /// Creates a new error, without length-checking the body. This allows
50    /// creation of invalid errors.
51    pub const fn new_unchecked(selector: Selector, body: DynSolType) -> Self {
52        Self { selector, body }
53    }
54
55    /// Creates a new error from a selector.
56    pub fn new(selector: Selector, body: DynSolType) -> Option<Self> {
57        let _ = body.as_tuple()?;
58        Some(Self::new_unchecked(selector, body))
59    }
60
61    /// Error selector is the first 4 bytes of the keccak256 hash of the error
62    /// declaration.
63    pub const fn selector(&self) -> Selector {
64        self.selector
65    }
66
67    /// Error body types.
68    pub fn body(&self) -> &[DynSolType] {
69        self.body.as_tuple().expect("body is a tuple")
70    }
71
72    /// Decode the error from the given data, which must already be stripped of
73    /// its selector.
74    fn decode_error_body(&self, data: &[u8]) -> Result<DecodedError> {
75        let body = self.body.abi_decode_sequence(data)?.into_fixed_seq().expect("body is a tuple");
76        Ok(DecodedError { body })
77    }
78
79    /// Decode the error from the given data.
80    pub fn decode_error(&self, data: &[u8]) -> Result<DecodedError> {
81        // Check selector validity.
82        if !data.starts_with(self.selector.as_slice()) {
83            return Err(Error::SelectorMismatch {
84                expected: self.selector,
85                actual: Selector::from_slice(&data[0..4]),
86            });
87        }
88
89        // will not panic, as we've already checked the length with starts_with
90        let data = data.split_at(4).1;
91        self.decode_error_body(data)
92    }
93}
94
95/// A decoded dynamic ABI error.
96#[derive(Clone, Debug, PartialEq)]
97pub struct DecodedError {
98    /// The decoded error body.
99    pub body: Vec<DynSolValue>,
100}
101
102#[cfg(test)]
103mod test {
104    use super::DynSolError;
105    use crate::DynSolValue;
106    use alloy_primitives::hex;
107
108    #[test]
109    fn decode_revert_message() {
110        let error = DynSolError::revert();
111        let data = hex!("08c379a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000042020202000000000000000000000000000000000000000000000000000000000");
112
113        let decoded = error.decode_error(&data).unwrap();
114        assert_eq!(decoded.body, vec!(DynSolValue::String("    ".into())));
115    }
116
117    #[test]
118    fn decode_panic() {
119        let error = DynSolError::panic();
120        let data = hex!("4e487b710000000000000000000000000000000000000000000000000000000000000001");
121
122        let decoded = error.decode_error(&data).unwrap();
123        assert_eq!(decoded.body, vec![DynSolValue::Uint(alloy_primitives::Uint::from(1), 256)]);
124    }
125}