foundry_evm_core/
decode.rs1use crate::abi::{Vm, console};
4use alloy_dyn_abi::JsonAbiExt;
5use alloy_json_abi::{Error, JsonAbi};
6use alloy_primitives::{Log, Selector, hex, map::HashMap};
7use alloy_sol_types::{
8 ContractError::Revert, RevertReason, RevertReason::ContractError, SolEventInterface,
9 SolInterface, SolValue,
10};
11use evm2::interpreter::InstrStop;
12use foundry_common::SELECTOR_LEN;
13use itertools::Itertools;
14use std::{fmt, sync::OnceLock};
15
16pub const EMPTY_REVERT_DATA: &str = "<empty revert data>";
18
19pub const ASSERTION_FAILED_PREFIX: &str = "assertion failed";
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct SkipReason(pub Option<String>);
25
26impl SkipReason {
27 pub fn decode(raw_result: &[u8]) -> Option<Self> {
29 raw_result.strip_prefix(crate::constants::MAGIC_SKIP).map(|reason| {
30 let reason = String::from_utf8_lossy(reason).into_owned();
31 Self((!reason.is_empty()).then_some(reason))
32 })
33 }
34
35 pub fn decode_self(s: &str) -> Option<Self> {
39 s.strip_prefix("skipped").map(|rest| Self(rest.strip_prefix(": ").map(ToString::to_string)))
40 }
41}
42
43impl fmt::Display for SkipReason {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.write_str("skipped")?;
46 if let Some(reason) = &self.0 {
47 f.write_str(": ")?;
48 f.write_str(reason)?;
49 }
50 Ok(())
51 }
52}
53
54pub fn decode_console_logs(logs: &[Log]) -> Vec<String> {
56 logs.iter().filter_map(decode_console_log).collect()
57}
58
59pub fn decode_console_log(log: &Log) -> Option<String> {
64 console::ds::ConsoleEvents::decode_log(log).ok().map(|decoded| decoded.to_string())
65}
66
67#[derive(Clone, Debug, Default)]
69pub struct RevertDecoder {
70 errors: HashMap<Selector, Vec<Error>>,
72}
73
74impl Default for &RevertDecoder {
75 fn default() -> Self {
76 static EMPTY: OnceLock<RevertDecoder> = OnceLock::new();
77 EMPTY.get_or_init(RevertDecoder::new)
78 }
79}
80
81impl RevertDecoder {
82 pub fn new() -> Self {
84 Self::default()
85 }
86
87 pub fn with_abis<'a>(mut self, abi: impl IntoIterator<Item = &'a JsonAbi>) -> Self {
91 self.extend_from_abis(abi);
92 self
93 }
94
95 pub fn with_abi(mut self, abi: &JsonAbi) -> Self {
99 self.extend_from_abi(abi);
100 self
101 }
102
103 fn extend_from_abis<'a>(&mut self, abi: impl IntoIterator<Item = &'a JsonAbi>) {
105 for abi in abi {
106 self.extend_from_abi(abi);
107 }
108 }
109
110 fn extend_from_abi(&mut self, abi: &JsonAbi) {
112 for error in abi.errors() {
113 self.push_error(error.clone());
114 }
115 }
116
117 pub fn push_error(&mut self, error: Error) {
119 self.errors.entry(error.selector()).or_default().push(error);
120 }
121
122 pub fn decode(&self, err: &[u8], status: Option<InstrStop>) -> String {
127 self.maybe_decode(err, status).unwrap_or_else(|| {
128 if err.is_empty() { EMPTY_REVERT_DATA.to_string() } else { trimmed_hex(err) }
129 })
130 }
131
132 pub fn maybe_decode(&self, err: &[u8], status: Option<InstrStop>) -> Option<String> {
136 self.maybe_decode_known(err)
137 .or_else(|| decode_as_non_empty_string(err))
138 .or_else(|| Self::maybe_decode_fallback(err, status))
139 }
140
141 pub fn maybe_decode_known(&self, err: &[u8]) -> Option<String> {
148 if let Some(ContractError(Revert(revert))) = RevertReason::decode(err) {
150 return Some(revert.reason);
151 }
152
153 if let Ok(e) = alloy_sol_types::ContractError::<Vm::VmErrors>::abi_decode(err) {
155 return Some(e.to_string());
156 }
157
158 if let Some((selector, data)) = err.split_first_chunk::<SELECTOR_LEN>()
160 && let Some(errors) = self.errors.get(selector)
161 {
162 for error in errors {
163 if let Ok(decoded) = error.abi_decode_input(data) {
165 return Some(format!(
166 "{}({})",
167 error.name,
168 decoded.iter().map(foundry_common::fmt::format_token).format(", ")
169 ));
170 }
171 }
172 }
173
174 None
175 }
176
177 fn maybe_decode_fallback(err: &[u8], status: Option<InstrStop>) -> Option<String> {
179 if let Some((selector, data)) = err.split_first_chunk::<SELECTOR_LEN>() {
181 return Some({
182 let mut s = format!("custom error {}", hex::encode_prefixed(selector));
183 if !data.is_empty() {
184 s.push_str(": ");
185 match std::str::from_utf8(data) {
188 Ok(data) if is_printable(data) => s.push_str(data),
189 _ => s.push_str(&hex::encode(data)),
190 }
191 }
192 s
193 });
194 }
195
196 if let Some(status) = status
197 && !status.is_success()
198 {
199 return Some(format!("EvmError: {status:?}"));
200 }
201 if err.is_empty() {
202 None
203 } else {
204 Some(format!("custom error bytes {}", hex::encode_prefixed(err)))
205 }
206 }
207}
208
209fn decode_as_non_empty_string(err: &[u8]) -> Option<String> {
211 if let Ok(s) = String::abi_decode(err)
213 && !s.is_empty()
214 {
215 return Some(s);
216 }
217
218 if err.is_ascii() {
220 let mut msg = std::str::from_utf8(err).unwrap();
221 if err.len().is_multiple_of(32) {
225 msg = msg.trim_end_matches('\0');
226 }
227 if !msg.is_empty() && is_printable(msg) {
228 return Some(msg.to_owned());
229 }
230 }
231
232 None
233}
234
235fn is_printable(s: &str) -> bool {
238 !s.chars().any(|c| c.is_control() && !matches!(c, '\n' | '\r' | '\t'))
239}
240
241fn trimmed_hex(s: &[u8]) -> String {
242 let n = 32;
243 if s.len() <= n {
244 hex::encode(s)
245 } else {
246 format!(
247 "{}…{} ({} bytes)",
248 hex::encode(&s[..n / 2]),
249 hex::encode(&s[s.len() - n / 2..]),
250 s.len(),
251 )
252 }
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
260 fn test_trimmed_hex() {
261 assert_eq!(trimmed_hex(&hex::decode("1234567890").unwrap()), "1234567890");
262 assert_eq!(
263 trimmed_hex(&hex::decode("492077697368207275737420737570706F72746564206869676865722D6B696E646564207479706573").unwrap()),
264 "49207769736820727573742073757070…6865722d6b696e646564207479706573 (41 bytes)"
265 );
266 }
267
268 #[test]
270 fn partial_decode() {
271 let mut decoder = RevertDecoder::new();
276 decoder.push_error("ValidationFailed(bytes)".parse().unwrap());
277
278 let data = &hex!(
282 "0xe17594de"
283 "756688fe00000000000000000000000000000000000000000000000000000000"
284 );
285 assert_eq!(
286 decoder.decode(data, None),
287 "custom error 0xe17594de: 756688fe00000000000000000000000000000000000000000000000000000000"
288 );
289
290 let data = &hex!(
294 "0xe17594de"
295 "0000000000000000000000000000000000000000000000000000000000000020"
296 "0000000000000000000000000000000000000000000000000000000000000004"
297 "756688fe00000000000000000000000000000000000000000000000000000000"
298 );
299 assert_eq!(decoder.decode(data, None), "ValidationFailed(0x756688fe)");
300 }
301
302 #[test]
303 fn maybe_decode_magic_skip_is_not_skip_marker() {
304 let decoder = RevertDecoder::new();
305 let reason = decoder.maybe_decode(crate::constants::MAGIC_SKIP, None).unwrap();
306
307 assert_eq!(reason, "FOUNDRY::SKIP");
308 assert!(SkipReason::decode_self(&reason).is_none());
309 }
310
311 #[test]
312 fn unknown_custom_error_with_abi_arguments_is_hex() {
313 let data = &hex!(
315 "0xe94fe3af"
316 "0000000000000000000000000000000000000000000000000000000000000005"
317 "000000000000000000000000000000000000000000000000000000000000000a"
318 );
319 assert_eq!(
320 RevertDecoder::new().decode(data, None),
321 "custom error 0xe94fe3af: \
322 0000000000000000000000000000000000000000000000000000000000000005\
323 000000000000000000000000000000000000000000000000000000000000000a"
324 );
325
326 let data = &hex!(
328 "0x12345678"
329 "0000000000000000000000000000000000000000000000000000000000000005"
330 );
331 assert_eq!(
332 RevertDecoder::new().decode(data, None),
333 "custom error 0x12345678: \
334 0000000000000000000000000000000000000000000000000000000000000005"
335 );
336
337 let data = b"\xde\xad\xbe\xefnot enough balance";
339 assert_eq!(
340 RevertDecoder::new().decode(data, None),
341 "custom error 0xdeadbeef: not enough balance"
342 );
343 }
344
345 #[test]
346 fn plain_string_is_not_a_known_error() {
347 let decoder = RevertDecoder::new();
348 let data = b".,Bo";
349
350 assert_eq!(decoder.maybe_decode_known(data), None);
351 assert_eq!(decoder.maybe_decode(data, None).as_deref(), Some(".,Bo"));
352
353 let mut data = b"insufficient balance".to_vec();
355 data.resize(32, 0);
356 assert_eq!(decoder.maybe_decode_known(&data), None);
357 assert_eq!(decoder.maybe_decode(&data, None).as_deref(), Some("insufficient balance"));
358
359 let data = &hex!(
361 "0x2e2c426f"
362 "0000000000000000000000000000000000000000000000000000000000000000"
363 );
364 assert_eq!(
365 decoder.maybe_decode(data, None).as_deref(),
366 Some(
367 "custom error 0x2e2c426f: \
368 0000000000000000000000000000000000000000000000000000000000000000"
369 )
370 );
371 }
372}