Skip to main content

foundry_cheatcodes/
error.rs

1use crate::Vm;
2use alloy_primitives::{Bytes, hex};
3use alloy_signer::Error as SignerError;
4use alloy_signer_local::LocalSignerError;
5use alloy_sol_types::SolError;
6use foundry_common::errors::FsPathError;
7use foundry_config::UnresolvedEnvVarError;
8use foundry_evm_core::backend::{BackendError, DatabaseError};
9use foundry_wallets::error::WalletSignerError;
10use k256::ecdsa::signature::Error as SignatureError;
11use std::{borrow::Cow, fmt};
12
13/// Cheatcode result type.
14///
15/// Type alias with a default Ok type of [`Vec<u8>`], and default Err type of [`Error`].
16pub type Result<T = Vec<u8>, E = Error> = std::result::Result<T, E>;
17
18macro_rules! fmt_err {
19    ($msg:literal $(,)?) => {
20        $crate::Error::fmt(::std::format_args!($msg))
21    };
22    ($err:expr $(,)?) => {
23        <$crate::Error as ::std::convert::From<_>>::from($err)
24    };
25    ($fmt:expr, $($arg:tt)*) => {
26        $crate::Error::fmt(::std::format_args!($fmt, $($arg)*))
27    };
28}
29
30macro_rules! bail {
31    ($msg:literal $(,)?) => {
32        return ::std::result::Result::Err(fmt_err!($msg))
33    };
34    ($err:expr $(,)?) => {
35        return ::std::result::Result::Err(fmt_err!($err))
36    };
37    ($fmt:expr, $($arg:tt)*) => {
38        return ::std::result::Result::Err(fmt_err!($fmt, $($arg)*))
39    };
40}
41
42macro_rules! ensure {
43    ($cond:expr $(,)?) => {
44        if !$cond {
45            return ::std::result::Result::Err($crate::Error::custom(
46                ::std::concat!("Condition failed: `", ::std::stringify!($cond), "`")
47            ));
48        }
49    };
50    ($cond:expr, $msg:literal $(,)?) => {
51        if !$cond {
52            return ::std::result::Result::Err(fmt_err!($msg));
53        }
54    };
55    ($cond:expr, $err:expr $(,)?) => {
56        if !$cond {
57            return ::std::result::Result::Err(fmt_err!($err));
58        }
59    };
60    ($cond:expr, $fmt:expr, $($arg:tt)*) => {
61        if !$cond {
62            return ::std::result::Result::Err(fmt_err!($fmt, $($arg)*));
63        }
64    };
65}
66
67/// Error thrown by cheatcodes.
68// This uses a custom repr to minimize the size of the error.
69// The repr is basically `enum { Cow<'static, str>, Cow<'static, [u8]> }`
70pub struct Error {
71    /// If true, encode `data` as `Error(string)`, otherwise encode it directly as `bytes`.
72    is_str: bool,
73    /// Whether this was constructed from an owned byte vec, which means we have to drop the data
74    /// in `impl Drop`.
75    drop: bool,
76    /// The error data. Always a valid pointer, and never modified.
77    data: *const [u8],
78}
79
80impl std::error::Error for Error {}
81
82impl fmt::Debug for Error {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str("Error::")?;
85        self.kind().fmt(f)
86    }
87}
88
89impl fmt::Display for Error {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        self.kind().fmt(f)
92    }
93}
94
95/// Kind of cheatcode errors.
96///
97/// Constructed by [`Error::kind`].
98#[derive(Debug)]
99pub enum ErrorKind<'a> {
100    /// A string error, ABI-encoded as `CheatcodeError(string)`.
101    String(&'a str),
102    /// A raw bytes error. Does not get encoded.
103    Bytes(&'a [u8]),
104}
105
106impl fmt::Display for ErrorKind<'_> {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        match *self {
109            Self::String(ss) => f.write_str(ss),
110            Self::Bytes(b) => f.write_str(&hex::encode_prefixed(b)),
111        }
112    }
113}
114
115impl Error {
116    /// Creates a new error and ABI encodes it as `CheatcodeError(string)`.
117    pub fn encode(error: impl Into<Self>) -> Bytes {
118        error.into().abi_encode().into()
119    }
120
121    /// Creates a new error with a custom message.
122    pub fn display(msg: impl fmt::Display) -> Self {
123        Self::fmt(format_args!("{msg}"))
124    }
125
126    /// Creates a new error with a custom [`fmt::Arguments`] message.
127    pub fn fmt(args: fmt::Arguments<'_>) -> Self {
128        match args.as_str() {
129            Some(s) => Self::new_str(s),
130            None => Self::new_string(std::fmt::format(args)),
131        }
132    }
133
134    /// ABI-encodes this error as `CheatcodeError(string)` if the inner message is a string,
135    /// otherwise returns the raw bytes.
136    pub fn abi_encode(&self) -> Vec<u8> {
137        match self.kind() {
138            ErrorKind::String(string) => Vm::CheatcodeError { message: string.into() }.abi_encode(),
139            ErrorKind::Bytes(bytes) => bytes.into(),
140        }
141    }
142
143    /// Returns the kind of this error.
144    pub fn kind(&self) -> ErrorKind<'_> {
145        let data = self.data();
146        if self.is_str {
147            debug_assert!(std::str::from_utf8(data).is_ok());
148            ErrorKind::String(unsafe { std::str::from_utf8_unchecked(data) })
149        } else {
150            ErrorKind::Bytes(data)
151        }
152    }
153
154    /// Returns the raw data of this error.
155    pub const fn data(&self) -> &[u8] {
156        unsafe { &*self.data }
157    }
158
159    /// Returns `true` if this error is a human-readable string.
160    pub const fn is_str(&self) -> bool {
161        self.is_str
162    }
163
164    /// Prefixes a string error with the name of the cheatcode that produced it.
165    pub(crate) fn with_cheatcode_name(self, cheat: &spec::Cheatcode<'static>) -> Self {
166        let name = cheat.func.signature.split('(').next().unwrap();
167        // Skip showing the cheatcode name for:
168        // - assertions: too verbose, and can already be inferred from the error message
169        // - `rpcUrl`: forge-std relies on it in `getChainWithUpdatedRpcUrl`
170        if self.is_str && !name.contains("assert") && name != "rpcUrl" {
171            fmt_err!("vm.{name}: {self}")
172        } else {
173            self
174        }
175    }
176
177    fn new_str(data: &'static str) -> Self {
178        Self::_new(true, false, data.as_bytes())
179    }
180
181    fn new_string(data: String) -> Self {
182        Self::_new(true, true, Box::into_raw(data.into_boxed_str().into_boxed_bytes()))
183    }
184
185    fn new_bytes(data: &'static [u8]) -> Self {
186        Self::_new(false, false, data)
187    }
188
189    fn new_vec(data: Vec<u8>) -> Self {
190        Self::_new(false, true, Box::into_raw(data.into_boxed_slice()))
191    }
192
193    fn _new(is_str: bool, drop: bool, data: *const [u8]) -> Self {
194        debug_assert!(!data.is_null());
195        Self { is_str, drop, data }
196    }
197}
198
199impl Drop for Error {
200    fn drop(&mut self) {
201        if self.drop {
202            drop(unsafe { Box::<[u8]>::from_raw(self.data.cast_mut()) });
203        }
204    }
205}
206
207impl From<Cow<'static, str>> for Error {
208    fn from(value: Cow<'static, str>) -> Self {
209        match value {
210            Cow::Borrowed(str) => Self::new_str(str),
211            Cow::Owned(string) => Self::new_string(string),
212        }
213    }
214}
215
216impl From<String> for Error {
217    fn from(value: String) -> Self {
218        Self::new_string(value)
219    }
220}
221
222impl From<&'static str> for Error {
223    fn from(value: &'static str) -> Self {
224        Self::new_str(value)
225    }
226}
227
228impl From<Cow<'static, [u8]>> for Error {
229    fn from(value: Cow<'static, [u8]>) -> Self {
230        match value {
231            Cow::Borrowed(bytes) => Self::new_bytes(bytes),
232            Cow::Owned(vec) => Self::new_vec(vec),
233        }
234    }
235}
236
237impl From<&'static [u8]> for Error {
238    fn from(value: &'static [u8]) -> Self {
239        Self::new_bytes(value)
240    }
241}
242
243impl<const N: usize> From<&'static [u8; N]> for Error {
244    fn from(value: &'static [u8; N]) -> Self {
245        Self::new_bytes(value)
246    }
247}
248
249impl From<Vec<u8>> for Error {
250    fn from(value: Vec<u8>) -> Self {
251        Self::new_vec(value)
252    }
253}
254
255impl From<Bytes> for Error {
256    fn from(value: Bytes) -> Self {
257        Self::new_vec(value.into())
258    }
259}
260
261// So we can use `?` on `Result<_, Error>`.
262macro_rules! impl_from {
263    ($($t:ty),* $(,)?) => {$(
264        impl From<$t> for Error {
265            fn from(value: $t) -> Self {
266                Self::display(value)
267            }
268        }
269    )*};
270}
271
272impl_from!(
273    alloy_sol_types::Error,
274    alloy_dyn_abi::Error,
275    alloy_primitives::SignatureError,
276    alloy_consensus::crypto::RecoveryError,
277    FsPathError,
278    hex::FromHexError,
279    BackendError,
280    DatabaseError,
281    jsonpath_lib::JsonPathError,
282    serde_json::Error,
283    SignatureError,
284    std::io::Error,
285    std::num::TryFromIntError,
286    std::str::Utf8Error,
287    std::string::FromUtf8Error,
288    UnresolvedEnvVarError,
289    LocalSignerError,
290    SignerError,
291    WalletSignerError,
292);
293
294impl From<evm2::DatabaseError> for Error {
295    fn from(err: evm2::DatabaseError) -> Self {
296        Self::display(BackendError::from(err))
297    }
298}
299
300impl From<evm2::ExecutionError> for Error {
301    fn from(err: evm2::ExecutionError) -> Self {
302        Self::new_string(format!("{err:?}"))
303    }
304}
305
306impl From<eyre::Report> for Error {
307    fn from(err: eyre::Report) -> Self {
308        Self::new_string(foundry_common::errors::display_chain(&err))
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn encode() {
318        let error = Vm::CheatcodeError { message: "hello".into() }.abi_encode();
319        assert_eq!(Error::from("hello").abi_encode(), error);
320        assert_eq!(Error::encode("hello"), error);
321
322        assert_eq!(Error::from(b"hello").abi_encode(), b"hello");
323        assert_eq!(Error::encode(b"hello"), b"hello"[..]);
324    }
325}