alloy_sol_types/types/
error.rs

1use crate::{
2    abi::token::{PackedSeqToken, Token, TokenSeq, WordToken},
3    types::interface::RevertReason,
4    Result, SolType, Word,
5};
6use alloc::{string::String, vec::Vec};
7use alloy_primitives::U256;
8use core::{borrow::Borrow, fmt};
9
10/// A Solidity custom error.
11///
12/// # Implementer's Guide
13///
14/// It should not be necessary to implement this trait manually. Instead, use
15/// the [`sol!`](crate::sol!) procedural macro to parse Solidity syntax into
16/// types that implement this trait.
17pub trait SolError: Sized {
18    /// The underlying tuple type which represents the error's members.
19    ///
20    /// If the error has no arguments, this will be the unit type `()`
21    type Parameters<'a>: SolType<Token<'a> = Self::Token<'a>>;
22
23    /// The corresponding [`TokenSeq`] type.
24    type Token<'a>: TokenSeq<'a>;
25
26    /// The error's ABI signature.
27    const SIGNATURE: &'static str;
28
29    /// The error selector: `keccak256(SIGNATURE)[0..4]`
30    const SELECTOR: [u8; 4];
31
32    /// Convert from the tuple type used for ABI encoding and decoding.
33    fn new(tuple: <Self::Parameters<'_> as SolType>::RustType) -> Self;
34
35    /// Convert to the token type used for EIP-712 encoding and decoding.
36    fn tokenize(&self) -> Self::Token<'_>;
37
38    /// The size of the error params when encoded in bytes, **without** the
39    /// selector.
40    #[inline]
41    fn abi_encoded_size(&self) -> usize {
42        if let Some(size) = <Self::Parameters<'_> as SolType>::ENCODED_SIZE {
43            return size;
44        }
45
46        // `total_words` includes the first dynamic offset which we ignore.
47        let offset = <<Self::Parameters<'_> as SolType>::Token<'_> as Token>::DYNAMIC as usize * 32;
48        (self.tokenize().total_words() * Word::len_bytes()).saturating_sub(offset)
49    }
50
51    /// ABI decode this call's arguments from the given slice, **without** its
52    /// selector.
53    #[inline]
54    fn abi_decode_raw(data: &[u8]) -> Result<Self> {
55        <Self::Parameters<'_> as SolType>::abi_decode_sequence(data).map(Self::new)
56    }
57
58    /// ABI decode this error's arguments from the given slice, **without** its
59    /// selector, with validation.
60    ///
61    /// This is the same as [`abi_decode_raw`](Self::abi_decode_raw), but performs
62    /// validation checks on the decoded parameters tuple.
63    #[inline]
64    fn abi_decode_raw_validate(data: &[u8]) -> Result<Self> {
65        <Self::Parameters<'_> as SolType>::abi_decode_sequence_validate(data).map(Self::new)
66    }
67
68    /// ABI decode this error's arguments from the given slice, **with** the
69    /// selector.
70    #[inline]
71    fn abi_decode(data: &[u8]) -> Result<Self> {
72        let data = data
73            .strip_prefix(&Self::SELECTOR)
74            .ok_or_else(|| crate::Error::type_check_fail_sig(data, Self::SIGNATURE))?;
75        Self::abi_decode_raw(data)
76    }
77
78    /// ABI decode this error's arguments from the given slice, **with** the
79    /// selector, with validation.
80    ///
81    /// This is the same as [`abi_decode`](Self::abi_decode), but performs
82    /// validation checks on the decoded parameters tuple.
83    #[inline]
84    fn abi_decode_validate(data: &[u8]) -> Result<Self> {
85        let data = data
86            .strip_prefix(&Self::SELECTOR)
87            .ok_or_else(|| crate::Error::type_check_fail_sig(data, Self::SIGNATURE))?;
88        Self::abi_decode_raw_validate(data)
89    }
90
91    /// ABI encode the error to the given buffer **without** its selector.
92    #[inline]
93    fn abi_encode_raw(&self, out: &mut Vec<u8>) {
94        out.reserve(self.abi_encoded_size());
95        out.extend(crate::abi::encode_sequence(&self.tokenize()));
96    }
97
98    /// ABI encode the error to the given buffer **with** its selector.
99    #[inline]
100    fn abi_encode(&self) -> Vec<u8> {
101        let mut out = Vec::with_capacity(4 + self.abi_encoded_size());
102        out.extend(&Self::SELECTOR);
103        self.abi_encode_raw(&mut out);
104        out
105    }
106}
107
108/// Represents a standard Solidity revert. These are thrown by `revert(reason)`
109/// or `require(condition, reason)` statements in Solidity.
110#[derive(Clone, PartialEq, Eq, Hash)]
111pub struct Revert {
112    /// The reason string, provided by the Solidity contract.
113    pub reason: String,
114}
115
116impl fmt::Debug for Revert {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.debug_tuple("Revert").field(&self.reason).finish()
119    }
120}
121
122impl fmt::Display for Revert {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_str("revert: ")?;
125        f.write_str(self.reason())
126    }
127}
128
129impl core::error::Error for Revert {}
130
131impl AsRef<str> for Revert {
132    #[inline]
133    fn as_ref(&self) -> &str {
134        &self.reason
135    }
136}
137
138impl Borrow<str> for Revert {
139    #[inline]
140    fn borrow(&self) -> &str {
141        &self.reason
142    }
143}
144
145impl From<Revert> for String {
146    #[inline]
147    fn from(value: Revert) -> Self {
148        value.reason
149    }
150}
151
152impl From<String> for Revert {
153    #[inline]
154    fn from(reason: String) -> Self {
155        Self { reason }
156    }
157}
158
159impl From<&str> for Revert {
160    #[inline]
161    fn from(value: &str) -> Self {
162        Self { reason: value.into() }
163    }
164}
165
166impl SolError for Revert {
167    type Parameters<'a> = (crate::sol_data::String,);
168    type Token<'a> = (PackedSeqToken<'a>,);
169
170    const SIGNATURE: &'static str = "Error(string)";
171    const SELECTOR: [u8; 4] = [0x08, 0xc3, 0x79, 0xa0];
172
173    #[inline]
174    fn new(tuple: <Self::Parameters<'_> as SolType>::RustType) -> Self {
175        Self { reason: tuple.0 }
176    }
177
178    #[inline]
179    fn tokenize(&self) -> Self::Token<'_> {
180        (PackedSeqToken::from(self.reason.as_bytes()),)
181    }
182
183    #[inline]
184    fn abi_encoded_size(&self) -> usize {
185        64 + crate::utils::next_multiple_of_32(self.reason.len())
186    }
187
188    #[inline]
189    fn abi_decode_raw_validate(data: &[u8]) -> Result<Self> {
190        Self::abi_decode_raw(data)
191    }
192}
193
194impl Revert {
195    /// Returns the revert reason string, or `"<empty>"` if empty.
196    #[inline]
197    pub fn reason(&self) -> &str {
198        if self.reason.is_empty() {
199            "<empty>"
200        } else {
201            &self.reason
202        }
203    }
204}
205
206/// A [Solidity panic].
207///
208/// These are thrown by `assert(condition)` and by internal Solidity checks,
209/// such as arithmetic overflow or array bounds checks.
210///
211/// The list of all known panic codes can be found in the [PanicKind] enum.
212///
213/// [Solidity panic]: https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require
214#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
215pub struct Panic {
216    /// The [Solidity panic code].
217    ///
218    /// [Solidity panic code]: https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require
219    pub code: U256,
220}
221
222impl AsRef<U256> for Panic {
223    #[inline]
224    fn as_ref(&self) -> &U256 {
225        &self.code
226    }
227}
228
229impl Borrow<U256> for Panic {
230    #[inline]
231    fn borrow(&self) -> &U256 {
232        &self.code
233    }
234}
235
236impl From<PanicKind> for Panic {
237    #[inline]
238    fn from(value: PanicKind) -> Self {
239        Self { code: U256::from(value as u64) }
240    }
241}
242
243impl From<u64> for Panic {
244    #[inline]
245    fn from(value: u64) -> Self {
246        Self { code: U256::from(value) }
247    }
248}
249
250impl From<Panic> for U256 {
251    #[inline]
252    fn from(value: Panic) -> Self {
253        value.code
254    }
255}
256
257impl From<U256> for Panic {
258    #[inline]
259    fn from(value: U256) -> Self {
260        Self { code: value }
261    }
262}
263
264impl fmt::Debug for Panic {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        let mut debug = f.debug_tuple("Panic");
267        if let Some(kind) = self.kind() {
268            debug.field(&kind);
269        } else {
270            debug.field(&self.code);
271        }
272        debug.finish()
273    }
274}
275
276impl fmt::Display for Panic {
277    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
278        f.write_str("panic: ")?;
279
280        let kind = self.kind();
281        let msg = kind.map(PanicKind::as_str).unwrap_or("unknown code");
282        f.write_str(msg)?;
283
284        f.write_str(" (0x")?;
285        if let Some(kind) = kind {
286            write!(f, "{:02x}", kind as u32)
287        } else {
288            write!(f, "{:x}", self.code)
289        }?;
290        f.write_str(")")
291    }
292}
293
294impl core::error::Error for Panic {}
295
296impl SolError for Panic {
297    type Parameters<'a> = (crate::sol_data::Uint<256>,);
298    type Token<'a> = (WordToken,);
299
300    const SIGNATURE: &'static str = "Panic(uint256)";
301    const SELECTOR: [u8; 4] = [0x4e, 0x48, 0x7b, 0x71];
302
303    #[inline]
304    fn new(tuple: <Self::Parameters<'_> as SolType>::RustType) -> Self {
305        Self { code: tuple.0 }
306    }
307
308    #[inline]
309    fn tokenize(&self) -> Self::Token<'_> {
310        (WordToken::from(self.code),)
311    }
312
313    #[inline]
314    fn abi_encoded_size(&self) -> usize {
315        32
316    }
317}
318
319impl Panic {
320    /// Returns the [PanicKind] if this panic code is a known Solidity panic, as
321    /// described [in the Solidity documentation][ref].
322    ///
323    /// [ref]: https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require
324    pub fn kind(&self) -> Option<PanicKind> {
325        // use try_from to avoid copying by using the `&` impl
326        u32::try_from(&self.code).ok().and_then(PanicKind::from_number)
327    }
328}
329
330/// Represents a [Solidity panic].
331/// Same as the [Solidity definition].
332///
333/// [Solidity panic]: https://docs.soliditylang.org/en/latest/control-structures.html#panic-via-assert-and-error-via-require
334/// [Solidity definition]: https://github.com/ethereum/solidity/blob/9eaa5cebdb1458457135097efdca1a3573af17c8/libsolutil/ErrorCodes.h#L25-L37
335#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
336#[repr(u32)]
337#[non_exhaustive]
338pub enum PanicKind {
339    // Docs extracted from the Solidity definition and documentation, linked above.
340    /// Generic / unspecified error.
341    ///
342    /// Generic compiler inserted panics.
343    #[default]
344    Generic = 0x00,
345    /// Used by the `assert()` builtin.
346    ///
347    /// Thrown when you call `assert` with an argument that evaluates to
348    /// `false`.
349    Assert = 0x01,
350    /// Arithmetic underflow or overflow.
351    ///
352    /// Thrown when an arithmetic operation results in underflow or overflow
353    /// outside of an `unchecked { ... }` block.
354    UnderOverflow = 0x11,
355    /// Division or modulo by zero.
356    ///
357    /// Thrown when you divide or modulo by zero (e.g. `5 / 0` or `23 % 0`).
358    DivisionByZero = 0x12,
359    /// Enum conversion error.
360    ///
361    /// Thrown when you convert a value that is too big or negative into an enum
362    /// type.
363    EnumConversionError = 0x21,
364    /// Invalid encoding in storage.
365    ///
366    /// Thrown when you access a storage byte array that is incorrectly encoded.
367    StorageEncodingError = 0x22,
368    /// Empty array pop.
369    ///
370    /// Thrown when you call `.pop()` on an empty array.
371    EmptyArrayPop = 0x31,
372    /// Array out of bounds access.
373    ///
374    /// Thrown when you access an array, `bytesN` or an array slice at an
375    /// out-of-bounds or negative index (i.e. `x[i]` where `i >= x.length` or
376    /// `i < 0`).
377    ArrayOutOfBounds = 0x32,
378    /// Resource error (too large allocation or too large array).
379    ///
380    /// Thrown when you allocate too much memory or create an array that is too
381    /// large.
382    ResourceError = 0x41,
383    /// Calling invalid internal function.
384    ///
385    /// Thrown when you call a zero-initialized variable of internal function
386    /// type.
387    InvalidInternalFunction = 0x51,
388}
389
390impl fmt::Display for PanicKind {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        f.write_str(self.as_str())
393    }
394}
395
396impl PanicKind {
397    /// Returns the panic code for the given number if it is a known one.
398    pub const fn from_number(value: u32) -> Option<Self> {
399        match value {
400            0x00 => Some(Self::Generic),
401            0x01 => Some(Self::Assert),
402            0x11 => Some(Self::UnderOverflow),
403            0x12 => Some(Self::DivisionByZero),
404            0x21 => Some(Self::EnumConversionError),
405            0x22 => Some(Self::StorageEncodingError),
406            0x31 => Some(Self::EmptyArrayPop),
407            0x32 => Some(Self::ArrayOutOfBounds),
408            0x41 => Some(Self::ResourceError),
409            0x51 => Some(Self::InvalidInternalFunction),
410            _ => None,
411        }
412    }
413
414    /// Returns the panic code's string representation.
415    pub const fn as_str(self) -> &'static str {
416        // modified from the original Solidity comments:
417        // https://github.com/ethereum/solidity/blob/9eaa5cebdb1458457135097efdca1a3573af17c8/libsolutil/ErrorCodes.h#L25-L37
418        match self {
419            Self::Generic => "generic/unspecified error",
420            Self::Assert => "assertion failed",
421            Self::UnderOverflow => "arithmetic underflow or overflow",
422            Self::DivisionByZero => "division or modulo by zero",
423            Self::EnumConversionError => "failed to convert value into enum type",
424            Self::StorageEncodingError => "storage byte array incorrectly encoded",
425            Self::EmptyArrayPop => "called `.pop()` on an empty array",
426            Self::ArrayOutOfBounds => "array out-of-bounds access",
427            Self::ResourceError => "memory allocation error",
428            Self::InvalidInternalFunction => "called an invalid internal function",
429        }
430    }
431}
432
433/// Decodes and retrieves the reason for a revert from the provided output data.
434///
435/// This function attempts to decode the provided output data as a generic contract error
436/// or a UTF-8 string (for Vyper reverts) using the `RevertReason::decode` method.
437///
438/// If successful, it returns the decoded revert reason wrapped in an `Option`.
439///
440/// If both attempts fail, it returns `None`.
441pub fn decode_revert_reason(out: &[u8]) -> Option<String> {
442    RevertReason::decode(out).map(|x| x.to_string())
443}
444
445#[cfg(test)]
446mod tests {
447    use super::*;
448    use crate::{sol, types::interface::SolInterface};
449    use alloc::string::ToString;
450    use alloy_primitives::{address, hex, keccak256};
451
452    #[test]
453    fn revert_encoding() {
454        let revert = Revert::from("test");
455        let encoded = revert.abi_encode();
456        let decoded = Revert::abi_decode(&encoded).unwrap();
457        assert_eq!(encoded.len(), revert.abi_encoded_size() + 4);
458        assert_eq!(encoded.len(), 100);
459        assert_eq!(revert, decoded);
460    }
461
462    #[test]
463    fn panic_encoding() {
464        let panic = Panic { code: U256::ZERO };
465        assert_eq!(panic.kind(), Some(PanicKind::Generic));
466        let encoded = panic.abi_encode();
467        let decoded = Panic::abi_decode(&encoded).unwrap();
468
469        assert_eq!(encoded.len(), panic.abi_encoded_size() + 4);
470        assert_eq!(encoded.len(), 36);
471        assert_eq!(panic, decoded);
472    }
473
474    #[test]
475    fn selectors() {
476        assert_eq!(
477            Revert::SELECTOR,
478            &keccak256(b"Error(string)")[..4],
479            "Revert selector is incorrect"
480        );
481        assert_eq!(
482            Panic::SELECTOR,
483            &keccak256(b"Panic(uint256)")[..4],
484            "Panic selector is incorrect"
485        );
486    }
487
488    #[test]
489    fn decode_solidity_revert_reason() {
490        let revert = Revert::from("test_revert_reason");
491        let encoded = revert.abi_encode();
492        let decoded = decode_revert_reason(&encoded).unwrap();
493        assert_eq!(decoded, revert.to_string());
494    }
495
496    #[test]
497    fn decode_uniswap_revert() {
498        // Solc 0.5.X/0.5.16 adds a random 0x80 byte which makes reserialization check fail.
499        // https://github.com/Uniswap/v2-core/blob/ee547b17853e71ed4e0101ccfd52e70d5acded58/contracts/UniswapV2Pair.sol#L178
500        // https://github.com/paradigmxyz/evm-inspectors/pull/12
501        let bytes = hex!("08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000024556e697377617056323a20494e53554646494349454e545f494e5055545f414d4f554e5400000000000000000000000000000000000000000000000000000080");
502
503        let decoded = Revert::abi_decode(&bytes).unwrap();
504        assert_eq!(decoded.reason, "UniswapV2: INSUFFICIENT_INPUT_AMOUNT");
505
506        let decoded = decode_revert_reason(&bytes).unwrap();
507        assert_eq!(decoded, "revert: UniswapV2: INSUFFICIENT_INPUT_AMOUNT");
508    }
509
510    #[test]
511    fn decode_random_revert_reason() {
512        let revert_reason = String::from("test_revert_reason");
513        let decoded = decode_revert_reason(revert_reason.as_bytes()).unwrap();
514        assert_eq!(decoded, "test_revert_reason");
515    }
516
517    #[test]
518    fn decode_non_utf8_revert_reason() {
519        let revert_reason = [0xFF];
520        let decoded = decode_revert_reason(&revert_reason);
521        assert_eq!(decoded, None);
522    }
523
524    // https://github.com/alloy-rs/core/issues/382
525    #[test]
526    fn decode_solidity_no_interface() {
527        sol! {
528            interface C {
529                #[derive(Debug, PartialEq)]
530                error SenderAddressError(address);
531            }
532        }
533
534        let data = hex!("8758782b000000000000000000000000a48388222c7ee7daefde5d0b9c99319995c4a990");
535        assert_eq!(decode_revert_reason(&data), None);
536
537        let C::CErrors::SenderAddressError(decoded) =
538            C::CErrors::abi_decode_validate(&data).unwrap();
539        assert_eq!(
540            decoded,
541            C::SenderAddressError(address!("0xa48388222c7ee7daefde5d0b9c99319995c4a990"))
542        );
543    }
544}