Skip to main content

foundry_evm_traces/
lib.rs

1//! # foundry-evm-traces
2//!
3//! EVM trace identifying and decoding.
4
5#![cfg_attr(not(test), warn(unused_crate_dependencies))]
6#![cfg_attr(docsrs, feature(doc_cfg))]
7
8#[macro_use]
9extern crate foundry_common;
10
11#[macro_use]
12extern crate tracing;
13
14use evm2::interpreter::opcode::OpCode;
15use evm2_inspectors::ColorChoice;
16use foundry_common::{
17    contracts::{ContractsByAddress, ContractsByArtifact},
18    shell,
19};
20use foundry_config::{Chain, Config};
21use foundry_evm_hardforks::{FoundryHardfork, TempoHardfork};
22use foundry_evm_networks::NetworkConfigs;
23use serde::{Deserialize, Serialize};
24use std::{
25    borrow::Cow,
26    collections::{BTreeMap, BTreeSet},
27    fmt,
28    ops::{Deref, DerefMut},
29};
30
31use alloy_primitives::{Address, Bytes, U256, map::HashMap};
32use tempo_contracts::precompiles::TIP20_CHANNEL_RESERVE_ADDRESS;
33
34/// Network context used to identify and decode execution traces.
35#[derive(Clone, Copy, Debug)]
36pub struct TraceContext {
37    chain: Chain,
38    networks: NetworkConfigs,
39    hardfork: Option<FoundryHardfork>,
40}
41
42impl TraceContext {
43    pub const fn new(
44        chain: Chain,
45        networks: NetworkConfigs,
46        hardfork: Option<FoundryHardfork>,
47    ) -> Self {
48        Self { chain, networks, hardfork }
49    }
50
51    pub const fn chain(self) -> Chain {
52        self.chain
53    }
54
55    pub const fn networks(self) -> NetworkConfigs {
56        self.networks
57    }
58
59    pub const fn hardfork(self) -> Option<FoundryHardfork> {
60        self.hardfork
61    }
62
63    pub const fn with_hardfork(mut self, hardfork: Option<FoundryHardfork>) -> Self {
64        self.hardfork = hardfork;
65        self
66    }
67
68    /// Completes metadata for a remotely executed trace before decoding.
69    /// Locally executed traces must use [`Self::hardfork`] directly, including `None`, so a
70    /// configured hardfork cannot replace an explicit execution-spec override.
71    pub fn decoding_hardfork(self, config: &Config) -> Option<FoundryHardfork> {
72        let execution_network = self.networks.execution_network();
73        let mut hardfork = self
74            .hardfork
75            .or(config.hardfork)
76            .filter(|hardfork| hardfork.namespace() == execution_network.hardfork_namespace());
77        if hardfork.is_none() && execution_network.is_tempo() {
78            hardfork = Some(config.evm_spec_id::<TempoHardfork>().into());
79        }
80        #[cfg(feature = "monad")]
81        if hardfork.is_none() && execution_network.is_monad() {
82            hardfork = Some(config.evm_spec_id::<foundry_evm_hardforks::MonadHardfork>().into());
83        }
84        hardfork
85    }
86}
87
88pub use evm2_inspectors::tracing::{
89    CallTraceArena, FourByteInspector, GethTraceBuilder, ParityTraceBuilder, StackSnapshotType,
90    TraceWriter, TracingInspector, TracingInspectorConfig,
91    types::{
92        CallKind, CallLog, CallTrace, CallTraceNode, CallTraceStep, DecodedCallData,
93        DecodedCallLog, DecodedCallTrace, DecodedInternalCall, DecodedTraceStep, RecordedMemory,
94        StorageChange, StorageChangeReason, TraceMemberOrder,
95    },
96};
97
98/// Call trace address identifiers.
99///
100/// Identifiers figure out what ABIs and labels belong to all the addresses of the trace.
101pub mod identifier;
102use identifier::LocalTraceIdentifier;
103
104mod decoder;
105pub use decoder::{CallTraceDecoder, CallTraceDecoderBuilder, DecodedEvent};
106
107pub mod debug;
108pub use debug::DebugTraceIdentifier;
109
110pub mod folded_stack_trace;
111
112pub mod backtrace;
113pub mod speedscope;
114
115pub mod erc8021;
116
117pub type Traces = Vec<(TraceKind, SparsedTraceArena)>;
118
119/// Presentation-only detail for an otherwise empty EVM revert.
120#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
121pub enum RevertDiagnostic {
122    /// A call targeted an address without code.
123    CallToNonContract(Address),
124    /// A delegate call targeted an address without code.
125    DelegateCallToNonContract(Address),
126}
127
128impl fmt::Display for RevertDiagnostic {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        match self {
131            Self::CallToNonContract(addr) => write!(f, "call to non-contract address {addr}"),
132            Self::DelegateCallToNonContract(addr) => write!(
133                f,
134                "delegatecall to non-contract address {addr} (usually an unliked library)"
135            ),
136        }
137    }
138}
139
140/// Trace arena keeping track of ignored trace items.
141#[derive(Debug, Clone, Deserialize)]
142pub struct SparsedTraceArena {
143    /// Full trace arena.
144    #[serde(flatten)]
145    pub arena: CallTraceArena,
146    /// Ranges of trace steps to ignore in format (start_node, start_step) -> (end_node, end_step).
147    /// See `foundry_cheatcodes::utils::IgnoredTraces` for more information.
148    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
149    pub ignored: HashMap<(usize, usize), (usize, usize)>,
150    /// Presentation-only revert diagnostics, keyed by trace node index.
151    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
152    pub diagnostics: HashMap<usize, RevertDiagnostic>,
153    /// The opcode steps recorded for the debugger, if a debug recorder ran.
154    #[serde(skip)]
155    pub debug_steps: Option<debug::DebugRecording>,
156}
157
158impl Serialize for SparsedTraceArena {
159    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
160    where
161        S: serde::Serializer,
162    {
163        #[derive(Serialize)]
164        struct ResolvedArena<'a> {
165            #[serde(flatten)]
166            arena: &'a CallTraceArena,
167            #[serde(skip_serializing_if = "HashMap::is_empty")]
168            ignored: &'a HashMap<(usize, usize), (usize, usize)>,
169        }
170
171        ResolvedArena { arena: &self.resolve_diagnostics(), ignored: &self.ignored }
172            .serialize(serializer)
173    }
174}
175
176impl SparsedTraceArena {
177    /// Applies presentation-only diagnostics to the provided arena.
178    fn apply_diagnostics(&self, arena: &mut CallTraceArena) {
179        for (&node_idx, diagnostic) in &self.diagnostics {
180            if let Some(node) = arena.nodes_mut().get_mut(node_idx) {
181                node.trace.decoded.get_or_insert_default().return_data =
182                    Some(diagnostic.to_string());
183            }
184        }
185    }
186
187    /// Applies presentation-only diagnostics without consuming ignored trace ranges.
188    fn resolve_diagnostics(&self) -> Cow<'_, CallTraceArena> {
189        if self.diagnostics.is_empty() {
190            Cow::Borrowed(&self.arena)
191        } else {
192            let mut arena = self.arena.clone();
193            self.apply_diagnostics(&mut arena);
194            Cow::Owned(arena)
195        }
196    }
197
198    /// Goes over entire trace arena and removes ignored trace items.
199    fn resolve_arena(&self) -> Cow<'_, CallTraceArena> {
200        if self.ignored.is_empty() {
201            self.resolve_diagnostics()
202        } else {
203            let mut arena = self.arena.clone();
204
205            fn clear_node(
206                nodes: &mut [CallTraceNode],
207                node_idx: usize,
208                ignored: &HashMap<(usize, usize), (usize, usize)>,
209                cur_ignore_end: &mut Option<(usize, usize)>,
210            ) {
211                let mut internal_calls = Vec::new();
212                let mut items_to_remove = BTreeSet::new();
213                // Item 0 is an additional None item before the ordering to handle the beginning
214                // of the trace. The ordering of this node only changes after the loop.
215                for item_idx in 0..=nodes[node_idx].ordering.len() {
216                    let item = item_idx.checked_sub(1).map(|idx| nodes[node_idx].ordering[idx]);
217                    if let Some(end_node) = ignored.get(&(node_idx, item_idx)) {
218                        *cur_ignore_end = Some(*end_node);
219                    }
220
221                    let mut remove = cur_ignore_end.is_some() & item.is_some();
222
223                    match item {
224                        // we only remove calls if they did not start/pause tracing
225                        Some(TraceMemberOrder::Call(child_idx)) => {
226                            clear_node(
227                                nodes,
228                                nodes[node_idx].children[child_idx],
229                                ignored,
230                                cur_ignore_end,
231                            );
232                            remove &= cur_ignore_end.is_some();
233                        }
234                        // we only remove decoded internal calls if they did not start/pause tracing
235                        Some(TraceMemberOrder::Step(step_idx)) => {
236                            // If this is an internal call beginning, track it in `internal_calls`
237                            if let Some(decoded) = &nodes[node_idx].trace.steps[step_idx].decoded
238                                && let DecodedTraceStep::InternalCall(_, end_step_idx) = &**decoded
239                            {
240                                internal_calls.push((item_idx, remove, *end_step_idx));
241                                // we decide if we should remove it later
242                                remove = false;
243                            }
244                            // Handle ends of internal calls
245                            internal_calls.retain(|(start_item_idx, remove_start, end_idx)| {
246                                if *end_idx != step_idx {
247                                    return true;
248                                }
249                                // only remove start if end should be removed as well
250                                if *remove_start && remove {
251                                    items_to_remove.insert(*start_item_idx);
252                                } else {
253                                    remove = false;
254                                }
255
256                                false
257                            });
258                        }
259                        _ => {}
260                    }
261
262                    if remove {
263                        items_to_remove.insert(item_idx);
264                    }
265
266                    if let Some((end_node, end_step_idx)) = cur_ignore_end
267                        && node_idx == *end_node
268                        && item_idx == *end_step_idx
269                    {
270                        *cur_ignore_end = None;
271                    }
272                }
273
274                for (offset, item_idx) in items_to_remove.into_iter().enumerate() {
275                    nodes[node_idx].ordering.remove(item_idx - offset - 1);
276                }
277            }
278
279            clear_node(arena.nodes_mut(), 0, &self.ignored, &mut None);
280
281            self.apply_diagnostics(&mut arena);
282
283            Cow::Owned(arena)
284        }
285    }
286
287    /// Makes a single top-level call that ran below the transaction the root node, one level up.
288    ///
289    /// A transaction handler can run the top-level calls one level below the transaction, such as
290    /// Tempo's for the calls of an AA transaction. The tracer then keeps an empty root node above
291    /// them. With more than one top-level call, that root groups the calls and stays.
292    ///
293    /// The debug recorder already records the steps of a single such call one level up, so only
294    /// its frames move here.
295    pub fn lift_single_top_level_call(&mut self) {
296        let nodes = self.arena.nodes_mut();
297        if nodes.len() < 2 || nodes[0].children.len() != 1 || nodes[0].trace != CallTrace::default()
298        {
299            return;
300        }
301        nodes.remove(0);
302        for node in nodes {
303            node.idx -= 1;
304            node.parent = node.parent.and_then(|parent| parent.checked_sub(1));
305            node.children.iter_mut().for_each(|child| *child -= 1);
306            node.trace.depth -= 1;
307        }
308        self.ignored = std::mem::take(&mut self.ignored)
309            .into_iter()
310            .map(|((start_node, start_step), (end_node, end_step))| {
311                ((start_node.saturating_sub(1), start_step), (end_node.saturating_sub(1), end_step))
312            })
313            .collect();
314        self.diagnostics = std::mem::take(&mut self.diagnostics)
315            .into_iter()
316            .filter_map(|(node_idx, diagnostic)| Some((node_idx.checked_sub(1)?, diagnostic)))
317            .collect();
318        if let Some(debug_steps) = &mut self.debug_steps {
319            debug_steps.frames.remove(0);
320            debug_steps.frames.iter_mut().for_each(|frame| frame.depth -= 1);
321        }
322    }
323
324    /// Returns the arena with only the data that a gas report reads.
325    ///
326    /// A gas report keeps every sampled run of a test until its suite is reported. Logs, the
327    /// return data of calls and spare node capacity are not read, and they add up over the
328    /// samples. The output of a create stays, because it is the runtime code that identifies the
329    /// created contract.
330    pub fn into_gas_report_arena(self) -> CallTraceArena {
331        let mut arena = self.arena;
332        let nodes = arena.nodes_mut();
333        for node in nodes.iter_mut() {
334            node.logs = Vec::new();
335            node.ordering = Vec::new();
336            if !node.trace.kind.is_any_create() {
337                node.trace.output = Bytes::new();
338            }
339        }
340        nodes.shrink_to_fit();
341        arena
342    }
343}
344
345impl Deref for SparsedTraceArena {
346    type Target = CallTraceArena;
347
348    fn deref(&self) -> &Self::Target {
349        &self.arena
350    }
351}
352
353impl DerefMut for SparsedTraceArena {
354    fn deref_mut(&mut self) -> &mut Self::Target {
355        &mut self.arena
356    }
357}
358
359/// Decode a collection of call traces.
360///
361/// The traces will be decoded using the given decoder, if possible.
362pub async fn decode_trace_arena(arena: &mut CallTraceArena, decoder: &CallTraceDecoder) {
363    decoder.prefetch_signatures(arena.nodes()).await;
364    decoder.populate_traces(arena.nodes_mut()).await;
365}
366
367/// Render a collection of call traces to a string.
368pub fn render_trace_arena(arena: &SparsedTraceArena) -> String {
369    render_trace_arena_inner(arena, false, false)
370}
371
372/// Prunes trace depth if depth is provided as an argument.
373pub fn prune_trace_depth(arena: &mut CallTraceArena, depth: usize) {
374    for node in arena.nodes_mut() {
375        if node.trace.depth >= depth {
376            node.ordering.clear();
377        }
378    }
379}
380
381/// Returns a serializable trace arena containing only nodes visible at `depth`.
382pub fn trace_arena_at_depth(arena: &SparsedTraceArena, depth: usize) -> SparsedTraceArena {
383    let mut arena = arena.resolve_arena().into_owned();
384    let nodes = arena.nodes_mut();
385    let mut reachable = vec![false; nodes.len()];
386    let mut pending = vec![0];
387    while let Some(node_idx) = pending.pop() {
388        if reachable[node_idx] {
389            continue;
390        }
391        reachable[node_idx] = true;
392        let node = &nodes[node_idx];
393        if node.trace.depth < depth {
394            pending.extend(node.ordering.iter().filter_map(|item| match item {
395                TraceMemberOrder::Call(child_idx) => Some(node.children[*child_idx]),
396                _ => None,
397            }));
398        }
399    }
400
401    let mut remapped = vec![None; nodes.len()];
402    for (next_idx, node) in nodes.iter_mut().filter(|node| reachable[node.idx]).enumerate() {
403        remapped[node.idx] = Some(next_idx);
404        if node.trace.depth >= depth {
405            node.ordering.clear();
406            node.children.clear();
407        } else {
408            let mut child_positions = vec![None; node.children.len()];
409            let mut children = Vec::with_capacity(node.children.len());
410            for (old_position, child) in node.children.iter().copied().enumerate() {
411                if reachable[child] {
412                    child_positions[old_position] = Some(children.len());
413                    children.push(child);
414                }
415            }
416            node.children = children;
417            node.ordering = std::mem::take(&mut node.ordering)
418                .into_iter()
419                .filter_map(|item| match item {
420                    TraceMemberOrder::Call(child_idx) => {
421                        Some(TraceMemberOrder::Call(child_positions[child_idx]?))
422                    }
423                    item => Some(item),
424                })
425                .collect();
426        }
427    }
428
429    nodes.retain(|node| reachable[node.idx]);
430    for node in nodes {
431        node.idx = remapped[node.idx].expect("retained trace node has a remapped index");
432        node.parent = node.parent.and_then(|parent| remapped[parent]);
433        for child in &mut node.children {
434            *child = remapped[*child].expect("retained trace child has a remapped index");
435        }
436    }
437
438    SparsedTraceArena {
439        arena,
440        ignored: Default::default(),
441        diagnostics: Default::default(),
442        debug_steps: None,
443    }
444}
445
446/// Render a collection of call traces to a string optionally including contract creation bytecodes
447/// and in JSON format.
448pub fn render_trace_arena_inner(
449    arena: &SparsedTraceArena,
450    with_bytecodes: bool,
451    with_storage_changes: bool,
452) -> String {
453    if shell::is_json() {
454        return serde_json::to_string(&arena.resolve_arena()).expect("Failed to serialize traces");
455    }
456
457    let mut resolved = arena.resolve_arena();
458
459    let mut tempo_changes = None;
460    if with_storage_changes {
461        tempo_changes = tempo_channel_storage_decodes(&resolved);
462
463        let needs_dedup = resolved.as_ref().nodes().iter().any(|node| {
464            node.trace.steps.iter().any(|step| {
465                step.storage_change.is_some()
466                    && matches!(step.decoded.as_deref(), Some(DecodedTraceStep::Line(_)))
467            })
468        });
469        if needs_dedup {
470            // Remove storage text that is already represented by an opcode line.
471            for node in resolved.to_mut().nodes_mut() {
472                for step in &mut node.trace.steps {
473                    if step.storage_change.is_some()
474                        && matches!(step.decoded.as_deref(), Some(DecodedTraceStep::Line(_)))
475                    {
476                        step.storage_change = None;
477                    }
478                }
479            }
480        }
481    }
482
483    let mut w = TraceWriter::new(Vec::<u8>::new())
484        .color_cheatcodes(true)
485        .use_colors(convert_color_choice(shell::color_choice()))
486        .write_bytecodes(with_bytecodes)
487        .with_storage_changes(with_storage_changes);
488    w.write_arena(resolved.as_ref()).expect("Failed to write traces");
489    let mut rendered =
490        String::from_utf8(w.into_writer()).expect("trace writer wrote invalid UTF-8");
491    if let Some(tempo_changes) = tempo_changes {
492        if !rendered.ends_with('\n') {
493            rendered.push('\n');
494        }
495        rendered.push_str(&tempo_changes);
496    }
497
498    rendered
499}
500
501fn tempo_channel_storage_decodes(arena: &CallTraceArena) -> Option<String> {
502    let decoded_changes = arena
503        .nodes()
504        .iter()
505        .filter(|node| node.trace.address == TIP20_CHANNEL_RESERVE_ADDRESS)
506        .flat_map(compact_channel_storage_changes)
507        .collect::<Vec<_>>();
508
509    if decoded_changes.is_empty() {
510        return None;
511    }
512
513    let mut rendered = String::new();
514    rendered.push_str("Decoded TIP20ChannelReserve storage:\n");
515    for (slot, before, after) in decoded_changes {
516        rendered.push_str(&format!(
517            "  @ {}: {} -> {}\n",
518            format_storage_word(slot),
519            format_channel_state(before),
520            format_channel_state(after),
521        ));
522    }
523    Some(rendered)
524}
525
526fn compact_channel_storage_changes(node: &CallTraceNode) -> Vec<(U256, U256, U256)> {
527    let mut changes_map = BTreeMap::new();
528    for step in &node.trace.steps {
529        if let Some(change) = &step.storage_change
530            && change.had_value.is_some()
531        {
532            let (_first, last) = changes_map.entry(change.key).or_insert((&**change, &**change));
533            *last = &**change;
534        }
535    }
536
537    changes_map
538        .into_iter()
539        .filter_map(|(key, (first, last))| {
540            let before = first.had_value.unwrap_or_default();
541            let after = last.value;
542            (before != after).then_some((key, before, after))
543        })
544        .collect()
545}
546
547fn format_channel_state(value: U256) -> String {
548    let (settled, deposit, close_requested_at) = decode_channel_state(value);
549    format!("{{settled: {settled}, deposit: {deposit}, closeRequestedAt: {close_requested_at}}}")
550}
551
552fn decode_channel_state(value: U256) -> (U256, U256, u32) {
553    let mask96 = (U256::ONE << 96) - U256::ONE;
554    let mask32 = (U256::ONE << 32) - U256::ONE;
555    let settled: U256 = value & mask96;
556    let deposit: U256 = (value >> 96usize) & mask96;
557    let close_requested_at_word: U256 = (value >> 192usize) & mask32;
558    let close_requested_at = close_requested_at_word.to::<u32>();
559    (settled, deposit, close_requested_at)
560}
561
562fn format_storage_word(value: U256) -> String {
563    if value < U256::from(1_000_000u64) { value.to_string() } else { format!("{value:#x}") }
564}
565
566const fn convert_color_choice(choice: shell::ColorChoice) -> ColorChoice {
567    match choice {
568        shell::ColorChoice::Auto => ColorChoice::Auto,
569        shell::ColorChoice::Always => ColorChoice::Always,
570        shell::ColorChoice::Never => ColorChoice::Never,
571    }
572}
573
574/// Specifies the kind of trace.
575#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
576pub enum TraceKind {
577    Deployment,
578    Setup,
579    Execution,
580}
581
582impl TraceKind {
583    /// Returns `true` if the trace kind is [`Deployment`].
584    ///
585    /// [`Deployment`]: TraceKind::Deployment
586    #[must_use]
587    pub const fn is_deployment(self) -> bool {
588        matches!(self, Self::Deployment)
589    }
590
591    /// Returns `true` if the trace kind is [`Setup`].
592    ///
593    /// [`Setup`]: TraceKind::Setup
594    #[must_use]
595    pub const fn is_setup(self) -> bool {
596        matches!(self, Self::Setup)
597    }
598
599    /// Returns `true` if the trace kind is [`Execution`].
600    ///
601    /// [`Execution`]: TraceKind::Execution
602    #[must_use]
603    pub const fn is_execution(self) -> bool {
604        matches!(self, Self::Execution)
605    }
606}
607
608/// Given a list of traces and artifacts, it returns a map connecting address to abi
609pub fn load_contracts<'a>(
610    traces: impl IntoIterator<Item = &'a CallTraceArena>,
611    known_contracts: &ContractsByArtifact,
612) -> ContractsByAddress {
613    let mut local_identifier = LocalTraceIdentifier::new(known_contracts);
614    let decoder = CallTraceDecoder::new();
615    let mut contracts = ContractsByAddress::new();
616    for trace in traces {
617        for address in decoder.identify_addresses(trace, &mut local_identifier) {
618            if let (Some(contract), Some(abi)) = (address.contract, address.abi) {
619                contracts.insert(address.address, (contract, abi.into_owned()));
620            }
621        }
622    }
623    contracts
624}
625
626/// Different kinds of internal functions tracing.
627#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
628pub enum InternalTraceMode {
629    #[default]
630    None,
631    /// Traces internal functions without decoding inputs/outputs from memory.
632    Simple,
633    /// Same as `Simple`, but also tracks memory snapshots.
634    Full,
635}
636
637/// Opcode step recording granularity.
638#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
639pub enum StepRecording {
640    /// No opcode steps.
641    #[default]
642    None,
643    /// Record only JUMP/JUMPDEST steps.
644    Jumps,
645    /// Record all opcode steps.
646    All,
647}
648
649impl StepRecording {
650    const fn merge(self, other: Self) -> Self {
651        match (self, other) {
652            (Self::All, _) | (_, Self::All) => Self::All,
653            (Self::Jumps, _) | (_, Self::Jumps) => Self::Jumps,
654            (Self::None, Self::None) => Self::None,
655        }
656    }
657}
658
659/// Trace data requirements composed across independent feature axes.
660#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
661pub struct TraceRequirements {
662    calls: bool,
663    steps: StepRecording,
664    memory_snapshots: bool,
665    stack_snapshots: bool,
666    returndata_snapshots: bool,
667    immediate_bytes: bool,
668    state_diff: bool,
669    bytecode: bool,
670    debug_recording: bool,
671}
672
673impl TraceRequirements {
674    pub const fn none() -> Self {
675        Self {
676            calls: false,
677            steps: StepRecording::None,
678            memory_snapshots: false,
679            stack_snapshots: false,
680            returndata_snapshots: false,
681            immediate_bytes: false,
682            state_diff: false,
683            bytecode: false,
684            debug_recording: false,
685        }
686    }
687
688    pub const fn with_calls(mut self, yes: bool) -> Self {
689        self.calls |= yes;
690        self
691    }
692
693    pub const fn merge(mut self, other: Self) -> Self {
694        self.calls |= other.calls;
695        self.steps = self.steps.merge(other.steps);
696        self.memory_snapshots |= other.memory_snapshots;
697        self.stack_snapshots |= other.stack_snapshots;
698        self.returndata_snapshots |= other.returndata_snapshots;
699        self.immediate_bytes |= other.immediate_bytes;
700        self.state_diff |= other.state_diff;
701        self.bytecode |= other.bytecode;
702        self.debug_recording |= other.debug_recording;
703        self
704    }
705
706    pub const fn with_steps(mut self, steps: StepRecording) -> Self {
707        self.steps = self.steps.merge(steps);
708        self
709    }
710
711    pub const fn with_memory_snapshots(mut self, yes: bool) -> Self {
712        self.memory_snapshots |= yes;
713        self
714    }
715
716    pub const fn with_stack_snapshots(mut self, yes: bool) -> Self {
717        self.stack_snapshots |= yes;
718        self
719    }
720
721    pub const fn with_debug(mut self, yes: bool) -> Self {
722        if yes {
723            self.calls = true;
724            self.steps = StepRecording::All;
725            self.memory_snapshots = true;
726            self.stack_snapshots = true;
727            self.returndata_snapshots = true;
728            self.immediate_bytes = true;
729            self.state_diff = true;
730            self.bytecode = true;
731        }
732        self
733    }
734
735    /// Records the debugger's opcode steps with a debug recorder instead of the tracer.
736    ///
737    /// The tracer keeps the call trace and the bytecode of each call; the steps go straight into
738    /// one step table, see [`debug::DebugRecording`].
739    pub const fn with_debug_recording(mut self, yes: bool) -> Self {
740        if yes {
741            self.calls = true;
742            self.bytecode = true;
743            self.debug_recording = true;
744        }
745        self
746    }
747
748    /// Whether a debug recorder records the opcode steps.
749    pub const fn debug_recording(&self) -> bool {
750        self.debug_recording
751    }
752
753    pub const fn with_decode_internal(self, mode: InternalTraceMode) -> Self {
754        match mode {
755            InternalTraceMode::None => self,
756            InternalTraceMode::Simple => {
757                self.with_calls(true).with_steps(StepRecording::Jumps).with_stack_snapshots(true)
758            }
759            InternalTraceMode::Full => self
760                .with_calls(true)
761                .with_steps(StepRecording::Jumps)
762                .with_memory_snapshots(true)
763                .with_stack_snapshots(true),
764        }
765    }
766
767    pub const fn with_all_steps(self, yes: bool) -> Self {
768        if yes { self.with_calls(true).with_steps(StepRecording::All) } else { self }
769    }
770
771    pub const fn with_state_changes(mut self, yes: bool) -> Self {
772        self.state_diff |= yes;
773        if yes {
774            self.calls = true;
775        }
776        self
777    }
778
779    pub const fn with_verbosity(self, verbosity: u8) -> Self {
780        match verbosity {
781            0..3 => self,
782            3..=4 => self.with_calls(true),
783            _ if matches!(self.steps, StepRecording::All) || self.debug_recording => {
784                self.with_calls(true)
785            }
786            _ => self.with_state_changes(true),
787        }
788    }
789
790    pub fn into_config(self) -> Option<TracingInspectorConfig> {
791        if !self.calls && self.steps == StepRecording::None && !self.state_diff {
792            return None;
793        }
794
795        let steps = if self.state_diff { StepRecording::All } else { self.steps };
796        TracingInspectorConfig {
797            record_steps: steps != StepRecording::None,
798            record_inputs: true,
799            record_bytecode: self.bytecode,
800            step_limit: None,
801            record_memory_snapshots: self.memory_snapshots,
802            record_stack_snapshots: if self.stack_snapshots {
803                StackSnapshotType::Full
804            } else {
805                StackSnapshotType::None
806            },
807            record_logs: true,
808            record_state_diff: self.state_diff,
809            record_returndata_snapshots: self.returndata_snapshots,
810            record_opcodes_filter: match steps {
811                StepRecording::None | StepRecording::All => None,
812                StepRecording::Jumps => {
813                    Some([OpCode::JUMP, OpCode::JUMPDEST].into_iter().map(OpCode::get).collect())
814                }
815            },
816            record_precompile_calls: false,
817            record_immediate_bytes: self.immediate_bytes,
818            record_step_deltas: false,
819        }
820        .into()
821    }
822}
823
824#[cfg(test)]
825mod tests {
826    use super::*;
827    use alloy_network::TransactionBuilder;
828    use evm2::{
829        bytecode::Bytecode,
830        evm::{AccountInfo, InMemoryDB},
831        interpreter::InstrStop,
832    };
833    use foundry_evm_core::evm::{
834        EvmEnv, EvmFactoryFor, FoundryEvmFactory, FoundryEvmNetwork, FoundryTxConversion, SpecFor,
835        TransactionRequestFor, TypesFor,
836    };
837    use snapbox::{assert_data_eq, str};
838
839    /// Traces a call to a contract whose sub-call reverts without data on `FEN`'s default spec, and
840    /// renders the decoded trace.
841    async fn render_reverting_subcall<FEN: FoundryEvmNetwork>() -> String
842    where
843        TransactionRequestFor<FEN>: Default,
844    {
845        let (caller, target, reverter) = (
846            Address::with_last_byte(0xCA),
847            Address::with_last_byte(0xC0),
848            Address::with_last_byte(0xC1),
849        );
850        // `call(gas(), reverter, 0, 0, 0, 0, 0); stop`.
851        let mut code = [0x60, 0x00].repeat(5);
852        code.push(0x73);
853        code.extend_from_slice(reverter.as_slice());
854        code.extend([0x5a, 0xf1, 0x00]);
855        let mut db = InMemoryDB::default();
856        db.insert_account_info(&caller, AccountInfo::default().with_balance(U256::from(1e18)));
857        for (address, code) in [(target, &code[..]), (reverter, &[0x60, 0x00, 0x60, 0x00, 0xfd])] {
858            let code = Bytecode::new_legacy(Bytes::copy_from_slice(code));
859            db.insert_account_info(&address, AccountInfo::default().with_code(code));
860        }
861        let factory = EvmFactoryFor::<FEN>::default();
862        let spec = SpecFor::<FEN>::default();
863        let env = EvmEnv::new(spec, factory.version(spec, 31337), Default::default());
864        let mut evm = factory.create_evm(db, env);
865        evm.set_inspector(TracingInspector::new(TracingInspectorConfig::default_parity()));
866        let request = TransactionRequestFor::<FEN>::default()
867            .with_from(caller)
868            .with_to(target)
869            .with_nonce(0)
870            .with_chain_id(31337)
871            .with_gas_limit(1_000_000)
872            .with_max_fee_per_gas(0)
873            .with_max_priority_fee_per_gas(0);
874        let tx = TypesFor::<FEN>::tx_from_request(request).unwrap();
875        assert!(evm.transact(&tx).unwrap().commit().status);
876
877        let mut arena = evm.clear_inspector_as::<TracingInspector>().unwrap().into_traces();
878        decode_trace_arena(&mut arena, &CallTraceDecoder::new().clone()).await;
879        render_trace_arena(&SparsedTraceArena {
880            arena,
881            ignored: Default::default(),
882            diagnostics: Default::default(),
883            debug_steps: None,
884        })
885    }
886
887    async fn tracing_suite<FEN: FoundryEvmNetwork>()
888    where
889        TransactionRequestFor<FEN>: Default,
890    {
891        assert_data_eq!(
892            render_reverting_subcall::<FEN>().await,
893            str![[r#"
894  [..] 0x00000000000000000000000000000000000000C0::fallback()
895    ├─ [..] 0x00000000000000000000000000000000000000C1::fallback()
896    │   └─ ← [Revert] EvmError: Revert
897    └─ ← [Stop]
898
899"#]]
900        );
901    }
902
903    #[tokio::test]
904    async fn tracing() {
905        tracing_suite::<foundry_evm_core::evm::EthEvmNetwork>().await;
906        tracing_suite::<foundry_evm_core::evm::TempoEvmNetwork>().await;
907        #[cfg(feature = "optimism")]
908        tracing_suite::<foundry_evm_core::evm::OpEvmNetwork>().await;
909        #[cfg(feature = "base")]
910        tracing_suite::<foundry_evm_core::evm::BaseEvmNetwork>().await;
911        #[cfg(feature = "monad")]
912        tracing_suite::<foundry_evm_core::evm::MonadEvmNetwork>().await;
913    }
914
915    #[test]
916    fn trace_context_uses_the_execution_network_hardfork_namespace() {
917        let config = Config {
918            hardfork: Some(FoundryHardfork::Ethereum(
919                foundry_evm_hardforks::EthereumHardfork::Cancun,
920            )),
921            ..Default::default()
922        };
923        let context = TraceContext::new(Chain::tempo_mainnet(), NetworkConfigs::with_tempo(), None);
924
925        assert!(matches!(context.decoding_hardfork(&config), Some(FoundryHardfork::Tempo(_))));
926    }
927
928    #[test]
929    fn trace_depth_projection_removes_and_reindexes_nodes() {
930        let mut arena = CallTraceArena::default();
931        arena.nodes_mut().extend([
932            CallTraceNode {
933                parent: Some(0),
934                children: vec![2],
935                idx: 1,
936                trace: CallTrace { depth: 1, ..Default::default() },
937                ordering: vec![TraceMemberOrder::Call(0)],
938                ..Default::default()
939            },
940            CallTraceNode {
941                parent: Some(1),
942                idx: 2,
943                trace: CallTrace { depth: 2, ..Default::default() },
944                ..Default::default()
945            },
946            CallTraceNode {
947                parent: Some(0),
948                idx: 3,
949                trace: CallTrace { depth: 1, ..Default::default() },
950                ..Default::default()
951            },
952        ]);
953        let root = &mut arena.nodes_mut()[0];
954        root.children = vec![1, 3];
955        root.ordering = vec![TraceMemberOrder::Call(0), TraceMemberOrder::Call(1)];
956        let arena = SparsedTraceArena {
957            arena,
958            ignored: Default::default(),
959            diagnostics: Default::default(),
960            debug_steps: None,
961        };
962
963        let arena = trace_arena_at_depth(&arena, 1);
964
965        assert_eq!(arena.nodes().len(), 3);
966        assert_eq!(arena.nodes()[0].children, [1, 2]);
967        assert_eq!(arena.nodes()[1].idx, 1);
968        assert!(arena.nodes()[1].children.is_empty());
969        assert!(arena.nodes()[1].ordering.is_empty());
970        assert_eq!(arena.nodes()[2].idx, 2);
971        assert_eq!(arena.nodes()[2].parent, Some(0));
972        assert!(arena.ignored.is_empty());
973    }
974
975    #[test]
976    fn decodes_tip1034_packed_channel_state() {
977        let settled = U256::from(123u64);
978        let deposit = U256::from(456u64);
979        let close_requested_at = U256::from(1_780_495_200u64);
980        let packed = settled | (deposit << 96usize) | (close_requested_at << 192usize);
981
982        assert_eq!(decode_channel_state(packed), (settled, deposit, 1_780_495_200));
983        assert_eq!(
984            format_channel_state(packed),
985            "{settled: 123, deposit: 456, closeRequestedAt: 1780495200}"
986        );
987    }
988
989    #[test]
990    fn tempo_storage_decodes_do_not_insert_extra_blank_line() {
991        let mut arena = CallTraceArena::default();
992        let root = &mut arena.nodes_mut()[0];
993        root.ordering.push(TraceMemberOrder::Step(0));
994        root.trace = CallTrace {
995            address: TIP20_CHANNEL_RESERVE_ADDRESS,
996            success: true,
997            steps: vec![CallTraceStep {
998                pc: 0,
999                op: OpCode::SSTORE,
1000                stack: None,
1001                push_stack: None,
1002                memory: None,
1003                returndata: Bytes::new(),
1004                gas_remaining: 0,
1005                gas_refund_counter: 0,
1006                gas_cost: 0,
1007                state_gas_cost: None,
1008                state_gas_reservoir: None,
1009                state_gas_spent: 0,
1010                storage_change: Some(Box::new(StorageChange {
1011                    key: U256::ONE,
1012                    value: U256::from(2),
1013                    had_value: Some(U256::ONE),
1014                    reason: StorageChangeReason::SSTORE,
1015                })),
1016                status: Some(InstrStop::Stop),
1017                immediate_bytes: None,
1018                decoded: None,
1019            }],
1020            ..Default::default()
1021        };
1022
1023        let rendered = render_trace_arena_inner(
1024            &SparsedTraceArena {
1025                arena,
1026                ignored: Default::default(),
1027                diagnostics: Default::default(),
1028                debug_steps: None,
1029            },
1030            false,
1031            true,
1032        );
1033
1034        assert!(rendered.contains("\nDecoded TIP20ChannelReserve storage:\n"));
1035        assert!(!rendered.contains("\n\nDecoded TIP20ChannelReserve storage:\n"));
1036    }
1037
1038    #[test]
1039    fn revert_diagnostic_only_changes_resolved_trace() {
1040        let traces = SparsedTraceArena {
1041            arena: CallTraceArena::default(),
1042            ignored: Default::default(),
1043            diagnostics: HashMap::from_iter([(
1044                0,
1045                RevertDiagnostic::CallToNonContract(alloy_primitives::Address::ZERO),
1046            )]),
1047            debug_steps: None,
1048        };
1049
1050        let resolved = traces.resolve_arena();
1051        assert_eq!(
1052            resolved.nodes()[0].trace.decoded.as_ref().unwrap().return_data.as_deref(),
1053            Some("call to non-contract address 0x0000000000000000000000000000000000000000")
1054        );
1055        assert!(resolved.nodes()[0].trace.output.is_empty());
1056        assert!(traces.arena.nodes()[0].trace.decoded.is_none());
1057        assert!(traces.arena.nodes()[0].trace.output.is_empty());
1058    }
1059
1060    #[test]
1061    fn serialization_resolves_diagnostics_without_consuming_ignored_ranges() {
1062        let mut arena = CallTraceArena::default();
1063        let root = &mut arena.nodes_mut()[0];
1064        root.logs = vec![CallLog::default(), CallLog::default(), CallLog::default()];
1065        root.ordering =
1066            vec![TraceMemberOrder::Log(0), TraceMemberOrder::Log(1), TraceMemberOrder::Log(2)];
1067
1068        let traces = SparsedTraceArena {
1069            arena,
1070            ignored: HashMap::from_iter([((0, 1), (0, 2))]),
1071            diagnostics: HashMap::from_iter([(
1072                0,
1073                RevertDiagnostic::CallToNonContract(alloy_primitives::Address::ZERO),
1074            )]),
1075            debug_steps: None,
1076        };
1077
1078        let serialized = ron::to_string(&traces).unwrap();
1079        let deserialized: SparsedTraceArena = ron::from_str(&serialized).unwrap();
1080        assert_eq!(
1081            deserialized.arena.nodes()[0].ordering,
1082            [TraceMemberOrder::Log(0), TraceMemberOrder::Log(1), TraceMemberOrder::Log(2)]
1083        );
1084        assert_eq!(deserialized.ignored, traces.ignored);
1085        assert!(deserialized.diagnostics.is_empty());
1086        assert_eq!(
1087            deserialized.arena.nodes()[0].trace.decoded.as_ref().unwrap().return_data.as_deref(),
1088            Some("call to non-contract address 0x0000000000000000000000000000000000000000")
1089        );
1090        assert!(deserialized.arena.nodes()[0].trace.output.is_empty());
1091
1092        let resolved = deserialized.resolve_arena();
1093        assert_eq!(resolved.nodes()[0].ordering, [TraceMemberOrder::Log(2)]);
1094        assert_eq!(
1095            resolved.nodes()[0].trace.decoded.as_ref().unwrap().return_data.as_deref(),
1096            Some("call to non-contract address 0x0000000000000000000000000000000000000000")
1097        );
1098        assert!(render_trace_arena(&deserialized).contains("call to non-contract address"));
1099    }
1100
1101    #[test]
1102    fn verbosity_0_through_2_is_noop() {
1103        for v in 0..=2 {
1104            assert_eq!(
1105                TraceRequirements::none().with_verbosity(v),
1106                TraceRequirements::none(),
1107                "v={v}"
1108            );
1109            assert_eq!(
1110                TraceRequirements::none().with_calls(true).with_verbosity(v),
1111                TraceRequirements::none().with_calls(true),
1112                "v={v}"
1113            );
1114            assert_eq!(
1115                TraceRequirements::none().with_debug(true).with_verbosity(v),
1116                TraceRequirements::none().with_debug(true),
1117                "v={v}"
1118            );
1119        }
1120    }
1121
1122    #[test]
1123    fn verbosity_3_and_4_raises_to_call() {
1124        for v in 3..=4 {
1125            assert_eq!(
1126                TraceRequirements::none().with_verbosity(v),
1127                TraceRequirements::none().with_calls(true),
1128                "v={v}"
1129            );
1130            assert_eq!(
1131                TraceRequirements::none().with_debug(true).with_verbosity(v),
1132                TraceRequirements::none().with_debug(true),
1133                "v={v}"
1134            );
1135            assert_eq!(
1136                TraceRequirements::none().with_state_changes(true).with_verbosity(v),
1137                TraceRequirements::none().with_state_changes(true),
1138                "v={v}"
1139            );
1140        }
1141    }
1142
1143    #[test]
1144    fn verbosity_5_raises_to_record_state_diff() {
1145        let state_changes = TraceRequirements::none().with_state_changes(true);
1146
1147        assert_eq!(TraceRequirements::none().with_verbosity(5), state_changes);
1148        assert_eq!(TraceRequirements::none().with_calls(true).with_verbosity(5), state_changes);
1149        let cfg = TraceRequirements::none()
1150            .with_calls(true)
1151            .with_steps(StepRecording::Jumps)
1152            .with_verbosity(5)
1153            .into_config()
1154            .unwrap();
1155        assert!(cfg.record_state_diff);
1156        assert!(cfg.record_opcodes_filter.is_none());
1157        assert_eq!(
1158            TraceRequirements::none().with_debug(true).with_verbosity(5),
1159            TraceRequirements::none().with_debug(true)
1160        );
1161        assert_eq!(
1162            TraceRequirements::none().with_state_changes(true).with_verbosity(5),
1163            state_changes
1164        );
1165    }
1166
1167    #[test]
1168    fn config_at_verbosity_0_is_none() {
1169        assert!(TraceRequirements::none().with_verbosity(0).into_config().is_none());
1170    }
1171
1172    #[test]
1173    fn config_at_verbosity_3_records_calls_only() {
1174        let cfg = TraceRequirements::none().with_verbosity(3).into_config().unwrap();
1175        assert!(!cfg.record_steps, "verbosity 3 should not record steps");
1176        assert!(!cfg.record_state_diff, "verbosity 3 should not record state diff");
1177        assert!(cfg.record_logs, "verbosity 3 should record logs");
1178    }
1179
1180    #[test]
1181    fn config_at_verbosity_5_records_steps_and_state_diff() {
1182        let cfg = TraceRequirements::none().with_verbosity(5).into_config().unwrap();
1183        assert!(cfg.record_steps, "verbosity 5 must record steps for backtraces");
1184        assert!(cfg.record_state_diff, "verbosity 5 must record state diff");
1185        assert!(cfg.record_logs, "verbosity 5 must record logs");
1186        // RecordStateDiff should NOT enable expensive debug-level features.
1187        assert!(!cfg.record_memory_snapshots, "verbosity 5 should not record memory snapshots");
1188        assert_eq!(
1189            cfg.record_stack_snapshots,
1190            StackSnapshotType::None,
1191            "verbosity 5 should not record stack snapshots"
1192        );
1193        // State diff requires all opcodes to capture SLOAD/SSTORE, so no filter.
1194        assert!(
1195            cfg.record_opcodes_filter.is_none(),
1196            "verbosity 5 needs unfiltered opcodes for state diff"
1197        );
1198    }
1199
1200    #[test]
1201    fn config_debug_mode_unchanged() {
1202        // Debug mode must still enable full recording for the debugger.
1203        let cfg = TraceRequirements::none().with_debug(true).into_config().unwrap();
1204        assert!(cfg.record_steps);
1205        assert!(cfg.record_memory_snapshots, "Debug must record memory snapshots");
1206        assert_eq!(
1207            cfg.record_stack_snapshots,
1208            StackSnapshotType::Full,
1209            "Debug must record full stack snapshots"
1210        );
1211        assert!(cfg.record_returndata_snapshots, "Debug must record returndata");
1212        assert!(cfg.record_immediate_bytes, "Debug must record immediate bytes");
1213        assert!(cfg.record_opcodes_filter.is_none(), "Debug must record all opcodes (no filter)");
1214        assert!(cfg.record_state_diff, "Debug should record storage accesses for the debugger");
1215    }
1216
1217    #[test]
1218    fn requirements_preserve_internal_decode_with_state_diff() {
1219        let cfg = TraceRequirements::none()
1220            .with_decode_internal(InternalTraceMode::Full)
1221            .with_state_changes(true)
1222            .into_config()
1223            .unwrap();
1224
1225        assert!(cfg.record_steps, "requirements should record opcode steps");
1226        assert!(cfg.record_memory_snapshots, "Full internal decoding needs memory snapshots");
1227        assert_eq!(
1228            cfg.record_stack_snapshots,
1229            StackSnapshotType::Full,
1230            "internal decoding needs stack snapshots"
1231        );
1232        assert!(cfg.record_state_diff, "state changes should be recorded");
1233        assert!(cfg.record_opcodes_filter.is_none(), "state diff needs unfiltered opcodes");
1234    }
1235
1236    #[test]
1237    fn requirements_all_steps_avoid_debug_snapshots() {
1238        let cfg =
1239            TraceRequirements::none().with_all_steps(true).with_verbosity(5).into_config().unwrap();
1240
1241        assert!(cfg.record_steps, "all steps must record opcode steps");
1242        assert!(cfg.record_opcodes_filter.is_none(), "all steps must record every opcode step");
1243        assert!(!cfg.record_memory_snapshots, "all steps should not record memory snapshots");
1244        assert_eq!(
1245            cfg.record_stack_snapshots,
1246            StackSnapshotType::None,
1247            "all steps should not record stack snapshots"
1248        );
1249        assert!(!cfg.record_returndata_snapshots, "all steps should not record returndata");
1250        assert!(!cfg.record_immediate_bytes, "all steps should not record immediate bytes");
1251        assert!(!cfg.record_state_diff, "all steps should not record state diffs");
1252    }
1253}